text
stringlengths 3
1.05M
|
|---|
import React from "react";
import styled from "styled-components";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { library } from '@fortawesome/fontawesome-svg-core';
import { fab } from '@fortawesome/free-brands-svg-icons';
import { StaticQuery, graphql } from "gatsby"
const SocialMediaLinkWhite = styled.a`
text-decoration: none;
background-color: transparent;
color: #f1f1f1;
&:hover, &:visited, &:active {
color: #f1f1f1;
}
`;
const SocialMediaLink = styled.a`
text-decoration: none;
background-color: transparent;
color: #171717;
&:hover, &:visited, &:active {
color: #171717;
}
`;
const SocialMedia = styled.div`
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-items: flex-end;
align-content: stretch;
text-align: right;
`;
const SocialMediaUl = styled.ul`
list-style: none;
display: inline-block;
margin: 0;
padding: 0;
`;
const SocialMediaLi = styled.li`
display: inline-block;
margin: 0 18px 0 18px;
padding: 0;
`;
class socialmedia extends React.Component {
render() {
const { className } = this.props;
const darkBackground = this.props.darkBackground | false;
library.add(fab);
return (
<StaticQuery
query={socialMediaQuery}
render={data => {
const { social } = data.site.siteMetadata;
const { socialUrl } = data;
return (
<SocialMedia className={`social-media ${className}`}>
<SocialMediaUl>
{Object.keys(social).map(site => (
<SocialMediaLi key={`social-media-${site}`}>
{darkBackground ? (
<SocialMediaLinkWhite href={`${socialUrl[site]}${social[site]}`}>
<FontAwesomeIcon icon={['fab', site]} size="lg" />
</SocialMediaLinkWhite>
) : (
<SocialMediaLink href={`${socialUrl[site]}${social[site]}`}>
<FontAwesomeIcon icon={['fab', site]} size="lg" />
</SocialMediaLink>
)}
</SocialMediaLi>
))}
</SocialMediaUl>
</SocialMedia>
);
}}
/>
);
}
}
const socialMediaQuery = graphql`
query SocialMediaQuery {
site {
siteMetadata {
social {
facebook
github
instagram
linkedin
}
}
}
socialUrl: dataJson {
facebook
github
instagram
linkedin
}
}
`
export default socialmedia;
|
'use strict';
module.exports = {
deleteResourceGroup () {
return this.provider.Login()
.then(() => this.provider.DeleteDeployment())
.then(() => this.provider.DeleteResourceGroup());
}
};
|
"use strict";var defaultDistrib="ubuntu";var defaultEngine="duckduckgo";var defaultLanguage="en";var distrib=Cookies.get("distrib")?Cookies.get("distrib"):defaultDistrib;var engine=Cookies.get("engine")?Cookies.get("engine"):defaultEngine;var language=Cookies.get("language")?Cookies.get("language"):defaultLanguage;var languages=[];function loadJSON(a,c){var b=new XMLHttpRequest();b.open("GET","data/"+a,true);b.onload=function(){if(this.status>=200&&this.status<400){c(JSON.parse(this.response))}else{alert("Unable to download json data...")}};b.onerror=function(){alert("Unable to download json data...")};b.send()}function createLinks(b){var a=document.querySelectorAll(".link");var c=b.hasOwnProperty(language)?language:defaultLanguage;Object.keys(b[c]).forEach(function(e,d){a[d].setAttribute("href",b[c][e]);a[d].textContent=e})}function changeDistrib(e){var g=document.getElementById("logo");if(distrib!==g.className){g.style.backgroundImage="url('img/"+distrib+"-logo.png')";g.className=distrib;document.getElementById("search").style.backgroundColor="#"+e[distrib].main_color;var b=document.querySelectorAll("#navbar a");for(var d=0;d<b.length;d++){b[d].style.color="#"+e[distrib].main_color}var c=document.querySelector(".website");c.setAttribute("href",e[distrib].website);var f=document.querySelector(".doc");f.setAttribute("href",e[distrib].doc);var a=document.querySelector(".distrowatch");a.setAttribute("href","https://distrowatch.com/"+distrib);Cookies.set("distrib",distrib,{expires:365,path:"/"})}}function changeEngine(b){var a=document.getElementById("engine");if(engine!==a.className){document.getElementById("form-search").setAttribute("action",b[engine].url);document.querySelector("input[type='search']").setAttribute("name",b[engine].parameter);a.className=engine;a.style.backgroundColor="#"+b[engine].colors.circle;a.style.color="#"+b[engine].colors.font;a.textContent=engine.charAt(0).toUpperCase();Cookies.set("engine",engine,{expires:365,path:"/"})}}function changeLanguage(b){var c=[];for(var a=0;a<languages.length;a++){c[languages[a]]=["option[value="+languages[a]+"]","textContent"]}c.placeholder=["#input-search input","placeholder"];c.doc=["#doc-text","textContent"];c.website=["#website-text","textContent"];c.distrowatch=["#distrowatch-text","textContent"];c.about=["#about-text","textContent"];c.author=["#author-text","textContent"];c.description=["#description-text","textContent"];c.license=["#license-text","textContent"];c.github=["#github-text","textContent"];c.thanks=["#thanks-text","textContent"];c.contributors=["#contributors-text","textContent"];c.close=["#close-text","textContent"];Object.keys(c).forEach(function(d){document.querySelector(c[d][0])[c[d][1]]=b[language][d]});Cookies.set("language",language,{expires:365,path:"/"})}function fillSelect(c){var a=document.querySelector("#"+c[0]);c[1].forEach(function(d){var e=document.createElement("option");e.value=d.toLowerCase().replace(" ","");e.textContent=d;a.appendChild(e)});var b=c[0].substr(0,c[0].length-1);a.value=window[b]}function initDistribs(a){var b=[];Object.keys(a).forEach(function(c){b.push(a[c].name)});fillSelect(["distribs",b]);changeDistrib(a)}function initEngines(a){var b=[];Object.keys(a).forEach(function(c){b.push(a[c].name)});fillSelect(["engines",b]);changeEngine(a)}function initLanguages(a){languages=[];Object.keys(a).forEach(function(b){languages.push(b)});fillSelect(["languages",languages]);changeLanguage(a)}loadJSON("links.min.json",createLinks);loadJSON("distribs.min.json",initDistribs);loadJSON("engines.min.json",initEngines);loadJSON("translations.min.json",initLanguages);document.getElementById("distribs").onchange=function(){distrib=this.value;loadJSON("distribs.min.json",changeDistrib)};document.getElementById("engines").onchange=function(){engine=this.value;loadJSON("engines.min.json",changeEngine)};document.getElementById("languages").onchange=function(){language=this.value;loadJSON("translations.min.json",changeLanguage);loadJSON("links.min.json",createLinks)};
|
'use strict';
class IComparable {
compare(other) {
return 0;
}
}
module.exports = IComparable;
|
/*
* RingBuffer.c
*
* Created: 29.11.2017 20:31:15
* Author: Lukasz
*/
#include <stdint.h>
#include <stdbool.h>
#include "stm32l1xx_hal.h"
#include <GPS/CB_UART.h>
inline _Bool CB_UART_IsEmpty(volatile CB_UART *cb)
{
return (cb->Count == 0);
}
inline _Bool CB_UART_IsFull(volatile CB_UART *cb)
{
return (cb->Count == CB_UART_SIZE);
}
enum bufferResult CB_UART_Add(volatile CB_UART *cb, char value)
{
uint16_t cb_end;
if (CB_UART_IsFull(cb)) return BUFFER_FULL;
cb_end = (cb->Begin + cb->Count) % CB_UART_SIZE;
cb->elements[cb_end] = value;
(cb->Count)++;
return BUFFER_OK;
}
char CB_UART_Read(volatile CB_UART *cb)
{
char value;
if (CB_UART_IsEmpty(cb)) return '\0';
value = cb->elements[cb->Begin];
cb->Begin = (cb->Begin + 1) % CB_UART_SIZE;
(cb->Count)--;
return value;
}
|
import logging
import mido
logger = logging.getLogger(__name__)
class BaseHandler():
def handle_msg(self, msg, *args, **kwargs):
'''
Trys to handle a mido message
'''
try:
handler_name = '_{}_handler'.format(msg.type)
if hasattr(self, handler_name):
handler = getattr(self, handler_name, default=self._handler_not_implemented)
return handler(msg, *args, **kwargs)
except:
return None
|
export function addLeafs(leaf, additional) {
let successMessage = "Successfully added the leaf";
if (additional.noOfLeafs>1) successMessage = "Successfully added the leaves";
return {
types: ['CREATE_LEAVES_FRONTEND','CREATE_LEAVES_SUCCESS_BACKEND','CREATE_LEAVES_FAILED_BACKEND'],
payload: {
request : {
url: `/leafs`,
method: 'post',
data: { leaf, additional },
successMessage,
errorMessage: "Ooops! Something went wrong"
}
},
isUndoable: true,
};
}
export function updateLeaf(leafID, leaf) {
return {
types: ['UPDATE_LEAF_FRONTEND','UPDATE_LEAF_SUCCESS_BACKEND','UPDATE_LEAF_FAILED_BACKEND'],
payload: {
request : {
url: `/leafs/${leafID}`,
method: 'put',
data: {leaf},
successMessage: "Successfully updated the leaf" ,
errorMessage: "Ooops! Something went wrong"
}
},
isUndoable: true,
};
}
export function updateLeafs(leafs, project_id) {
return {
types: ['UPDATE_LEAVES_FRONTEND','UPDATE_LEAVES_SUCCESS_BACKEND','UPDATE_LEAVES_FAILED_BACKEND'],
payload: {
request : {
url: `/leafs`,
method: 'put',
data: {leafs, project_id},
successMessage: "Successfully updated the leaves" ,
errorMessage: "Ooops! Something went wrong"
}
},
isUndoable: true,
};
}
/**
leafs: [
"59ea025c3b0eb7168e9591de",
"59ea025c3b0eb7168e9591de",
"59ea025c3b0eb7168e9591de",
"59ea025c3b0eb7168e9591de"
]
*/
export function autoConjoinLeafs(leafs) {
return {
types: ['AUTOCONJOIN_LEAFS_FRONTEND','AUTOCONJOIN_LEAFS_SUCCESS_BACKEND','AUTOCONJOIN_LEAFS_FAILED_BACKEND'],
payload: {
request : {
url: `/leafs/conjoin`,
method: 'put',
data: {leafs},
successMessage: "Successfully conjoined the leaves" ,
errorMessage: "Ooops! Something went wrong"
}
},
isUndoable: true,
};
}
export function deleteLeaf(leafID) {
return {
types: ['DELETE_LEAF_FRONTEND','DELETE_LEAF_SUCCESS_BACKEND','DELETE_LEAF_FAILED_BACKEND'],
payload: {
request : {
url: `/leafs/${leafID}`,
method: 'delete',
successMessage: "Successfully deleted the leaf" ,
errorMessage: "Ooops! Something went wrong"
}
},
isUndoable: true,
};
}
export function deleteLeafs(leafs) {
return {
types: ['DELETE_LEAVES_FRONTEND','DELETE_LEAFS_SUCCESS_BACKEND','DELETE_LEAFS_FAILED_BACKEND'],
payload: {
request : {
url: `/leafs`,
method: 'delete',
data: leafs,
successMessage: "Successfully deleted the leaves" ,
errorMessage: "Ooops! Something went wrong"
}
},
isUndoable: true,
};
}
export function generateFolioNumbers(startNumber, rectoIDs, versoIDs) {
return {
types: ['GENERATE_FOLIO_NUMBERS_FRONTEND','GENERATE_FOLIO_NUMBERS_SUCCESS_BACKEND','GENERATE_FOLIO_NUMBERS_FAILED_BACKEND'],
payload: {
request : {
url: `/sides/generateFolio`,
method: 'put',
data: {startNumber, rectoIDs, versoIDs},
successMessage: "Successfully generated the folio numbers" ,
errorMessage: "Ooops! Something went wrong"
}
},
isUndoable: true,
};
}
export function generatePageNumbers(startNumber, rectoIDs, versoIDs) {
return {
types: ['GENERATE_PAGE_NUMBERS_FRONTEND','GENERATE_PAGE_NUMBERS_SUCCESS_BACKEND','GENERATE_PAGE_NUMBERS_FAILED_BACKEND'],
payload: {
request : {
url: `/sides/generatePageNumber`,
method: 'put',
data: {startNumber, rectoIDs, versoIDs},
successMessage: "Successfully generated the page numbers" ,
errorMessage: "Ooops! Something went wrong"
}
},
isUndoable: true,
};
}
|
import pytest
@pytest.fixture
def given_any_message():
return "Hello world"
@pytest.fixture
def given_any_title():
return "This is a title"
@pytest.fixture
def given_any_info_petisco():
return {
"app_name": "test",
"app_version": "0.0.1",
"petisco_version": "0.0.1",
"environment": "Production",
}
@pytest.fixture
def given_any_exception():
return ValueError("Oops, something went wrong")
@pytest.fixture
def given_any_traceback():
return """Traceback (most recent call last):
File "e.py", line 7, in <module>
raise TypeError("Again !?!")
TypeError: Again !?!
"""
@pytest.fixture
def given_long_traceback():
return (
"""Traceback (most recent call last):
File "e.py", line 7, in <module>
raise TypeError("Again !?!")
TypeError: Again !?!
"""
* 500
)
@pytest.fixture
def given_any_input_parameters():
return {"parameter_1": 1, "parameter_2": 2}
|
"""Support for RFXtrx switches."""
import logging
import voluptuous as vol
from homeassistant.components import rfxtrx
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_NAME
from homeassistant.helpers import config_validation as cv
from . import (
CONF_AUTOMATIC_ADD,
CONF_DEVICES,
CONF_FIRE_EVENT,
CONF_SIGNAL_REPETITIONS,
DEFAULT_SIGNAL_REPETITIONS,
)
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_DEVICES, default={}): {
cv.string: vol.Schema(
{
vol.Required(CONF_NAME): cv.string,
vol.Optional(CONF_FIRE_EVENT, default=False): cv.boolean,
}
)
},
vol.Optional(CONF_AUTOMATIC_ADD, default=False): cv.boolean,
vol.Optional(
CONF_SIGNAL_REPETITIONS, default=DEFAULT_SIGNAL_REPETITIONS
): vol.Coerce(int),
}
)
def setup_platform(hass, config, add_entities_callback, discovery_info=None):
"""Set up the RFXtrx platform."""
import RFXtrx as rfxtrxmod
# Add switch from config file
switches = rfxtrx.get_devices_from_config(config, RfxtrxSwitch)
add_entities_callback(switches)
def switch_update(event):
"""Handle sensor updates from the RFXtrx gateway."""
if (
not isinstance(event.device, rfxtrxmod.LightingDevice)
or event.device.known_to_be_dimmable
or event.device.known_to_be_rollershutter
):
return
new_device = rfxtrx.get_new_device(event, config, RfxtrxSwitch)
if new_device:
add_entities_callback([new_device])
rfxtrx.apply_received_command(event)
# Subscribe to main RFXtrx events
if switch_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS:
rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(switch_update)
class RfxtrxSwitch(rfxtrx.RfxtrxDevice, SwitchDevice):
"""Representation of a RFXtrx switch."""
def turn_on(self, **kwargs):
"""Turn the device on."""
self._send_command("turn_on")
|
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const secrets = require('../../data/secrets/secret.js');
const Users = require('./user-model.js');
const router = express.Router();
const AuthMiddleware = require('../middleware/auth-middleware.js');
const ValidateMiddleware = require('../middleware/validate-middleware.js');
// GET ALL USERS
router.get('/', AuthMiddleware.restricted, async (req, res) => {
Users.find()
.then(users => {
res.status(200).json({
users: usersWithoutPassword(users),
/* decodedToken: req.decodedToken, */
});
})
.catch(error =>
res.status(500).json({
error:
'An error occurred during fetching all users. That one is on us!',
}),
);
});
// GET A USER BY ID
router.get(
'/:id',
AuthMiddleware.restricted,
ValidateMiddleware.validateUserId,
async (req, res) => {
try {
const {
user: { id },
} = req;
const user = await Users.findById(id);
res.status(200).json({
id: user.id,
email: user.email,
firstname: user.firstname,
lastname: user.lastname,
});
} catch (error) {
const {
user: { id },
} = req;
res.status(500).json({
error: `An error occurred during fetching an user with the id ${id}.`,
});
}
},
);
// ADD A NEW USER
router.post('/register', (req, res) => {
let { email, password, firstname, lastname } = req.body;
if (email && password && firstname && lastname) {
const hash = bcrypt.hashSync(password, 12);
password = hash;
Users.add({ email, password, firstname, lastname })
.then(newUser => {
res.status(201).json({
id: newUser.id,
email: newUser.email,
firstname: newUser.firstname,
lastname: newUser.lastname,
});
})
.catch(error => {
res.status(500).json({
error: 'An error occurred during the creation of a new user.',
});
});
} else {
res.status(400).json({
warning: 'Not all information were provided to create a new user.',
});
}
});
// LOGIN A USER
router.post('/login', (req, res) => {
let { email, password } = req.body;
Users.findByUserEmail(email)
.then(user => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = generateJWT(user);
res.status(200).json({
message: `The user ${user.email} successfully logged in!`,
user: {
id: user.id,
email: user.email,
firstname: user.firstname,
lastname: user.lastname,
},
token: token,
});
} else {
res.status(401).json({
warning: 'Invalid credentials submitted for the login of an user.',
});
}
})
.catch(error => {
res
.status(500)
.json({ error: 'An error occurred during logging in an user.' });
});
});
/* // DELETE A USER
router.delete(
'/:id',
AuthMiddleware.restricted,
ValidateMiddleware.validateUserId,
async (req, res) => {
try {
const {
user: { id },
} = req;
const deleteUser = await Users.remove(id);
res.status(200).json({
message: `The user with the id of ${id} was successfully deleted.`,
});
} catch (error) {
const {
user: { id },
} = req;
console.log(error);
res.status(500).json({
message: `The user with the id of ${id} could not be deleted.`,
});
}
},
); */
// UPDATE A USER
router.put(
'/:id',
AuthMiddleware.restricted,
ValidateMiddleware.validateUser,
ValidateMiddleware.validateUserId,
async (req, res) => {
console.log('middleware: ', req.user);
try {
const {
body: { email, password, firstname, lastname },
user: { id },
} = req;
const successFlag = await Users.update(id, {
email,
firstname,
lastname,
});
return successFlag > 0
? res.status(200).json({
message: `The user with the id ${id} has been successfully updated!`,
})
: res.status(500).json({
error: `An error occurred within the database thus the user with the id ${id} could not be updated.`,
});
} catch (error) {
const {
user: { id },
} = req;
res.status(500).json({
error:
`An error occurred during updating the user with the id ${id}.` +
error,
});
}
},
);
// GET ALL BILLS BY A USER ID
router.get(
'/:id/bills',
AuthMiddleware.restricted,
ValidateMiddleware.validateUserId,
async (req, res) => {
const {
user: { id },
} = req;
try {
const userBills = await Users.findUserBills(id);
if (userBills && userBills.length) {
res.status(200).json(userBills);
} else {
res.status(404).json({
info: `No bills are available for the user with the id ${id}.`,
});
}
} catch (error) {
const {
user: { id },
} = req;
res.status(500).json({
error: `An error occurred retrieving the bills for the user with the id ${id}.`,
});
}
},
);
// UTILITY FUNCTIONS
function usersWithoutPassword(users) {
return users.map(user => ({
id: user.id,
email: user.email,
firstname: user.firstname,
lastname: user.lastname,
}));
}
function generateJWT(user) {
const payload = {
subject: user.id,
email: user.email,
};
const options = {
expiresIn: '1h',
};
return jwt.sign(payload, secrets.jwtSecret, options);
}
module.exports = router;
|
export const Supporters = [
{
name: "ChaosNative",
logo: "/support/cn_logo.png",
desc: "ChaosNative is the original creator of Litmus and provides commercial support for Litmus.",
link: "https://www.chaosnative.com"
}
]
|
# 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.
# Recipe which runs the Skia infra tests.
PYTHON_VERSION_COMPATIBILITY = "PY3"
DEPS = [
'infra',
'recipe_engine/context',
'recipe_engine/file',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/step',
'run',
'vars',
]
def RunSteps(api):
api.vars.setup()
with api.context(env=api.infra.go_env):
api.step('hello', cmd=['echo', 'hello world'])
def GenTests(api):
yield (
api.test('infra_tests') +
api.properties(buildername='Housekeeper-PerCommit-InfraTests',
repository='https://skia.googlesource.com/skia.git',
revision='abc123',
path_config='kitchen',
swarm_out_dir='[SWARM_OUT_DIR]') +
api.path.exists(api.path['start_dir'].join('localpath'))
)
|
//// [baseIndexSignatureResolution.ts]
class Base { private a: string; }
class Derived extends Base { private b: string; }
// Note - commmenting "extends Foo" prevents the error
interface Foo {
[i: number]: Base;
}
interface FooOf<TBase extends Base> extends Foo {
[i: number]: TBase;
}
var x: FooOf<Derived> = null;
var y: Derived = x[0];
/*
// Note - the equivalent for normal interface methods works fine:
interface A {
foo(): Base;
}
interface B<TBase extends Base> extends A {
foo(): TBase;
}
var b: B<Derived> = null;
var z: Derived = b.foo();
*/
//// [baseIndexSignatureResolution.js]
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Base = /** @class */ (function () {
function Base() {
}
return Base;
}());
var Derived = /** @class */ (function (_super) {
__extends(Derived, _super);
function Derived() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Derived;
}(Base));
var x = null;
var y = x[0];
/*
// Note - the equivalent for normal interface methods works fine:
interface A {
foo(): Base;
}
interface B<TBase extends Base> extends A {
foo(): TBase;
}
var b: B<Derived> = null;
var z: Derived = b.foo();
*/
|
# -*- coding: utf-8 -*-
# Autogenerated on 19:52:29 2016/03/14
# flake8: noqa
import logging
from wbia.algo.preproc import preproc_annot
from wbia.algo.preproc import preproc_image
from wbia.algo.preproc import preproc_occurrence
from wbia.algo.preproc import preproc_residual
from wbia.algo.preproc import preproc_rvec
import utool
print, rrr, profile = utool.inject2(__name__, '[wbia.algo.preproc]')
logger = logging.getLogger('wbia')
def reassign_submodule_attributes(verbose=True):
"""
why reloading all the modules doesnt do this I don't know
"""
import sys
if verbose and '--quiet' not in sys.argv:
print('dev reimport')
# Self import
import wbia.algo.preproc
# Implicit reassignment.
seen_ = set([])
for tup in IMPORT_TUPLES:
if len(tup) > 2 and tup[2]:
continue # dont import package names
submodname, fromimports = tup[0:2]
submod = getattr(wbia.algo.preproc, submodname)
for attr in dir(submod):
if attr.startswith('_'):
continue
if attr in seen_:
# This just holds off bad behavior
# but it does mimic normal util_import behavior
# which is good
continue
seen_.add(attr)
setattr(wbia.algo.preproc, attr, getattr(submod, attr))
def reload_subs(verbose=True):
""" Reloads wbia.algo.preproc and submodules """
if verbose:
print('Reloading submodules')
rrr(verbose=verbose)
def wrap_fbrrr(mod):
def fbrrr(*args, **kwargs):
""" fallback reload """
if verbose:
print('No fallback relaod for mod=%r' % (mod,))
# Breaks ut.Pref (which should be depricated anyway)
# import imp
# imp.reload(mod)
return fbrrr
def get_rrr(mod):
if hasattr(mod, 'rrr'):
return mod.rrr
else:
return wrap_fbrrr(mod)
def get_reload_subs(mod):
return getattr(mod, 'reload_subs', wrap_fbrrr(mod))
get_rrr(preproc_annot)(verbose=verbose)
get_rrr(preproc_image)(verbose=verbose)
get_rrr(preproc_occurrence)(verbose=verbose)
get_rrr(preproc_residual)(verbose=verbose)
get_rrr(preproc_rvec)(verbose=verbose)
rrr(verbose=verbose)
try:
# hackish way of propogating up the new reloaded submodule attributes
reassign_submodule_attributes(verbose=verbose)
except Exception as ex:
print(ex)
rrrr = reload_subs
IMPORT_TUPLES = [
('preproc_annot', None),
('preproc_image', None),
('preproc_occurrence', None),
('preproc_residual', None),
('preproc_rvec', None),
]
"""
Regen Command:
cd /home/joncrall/code/wbia/wbia/algo/preproc
makeinit.py --modname=wbia.algo.preproc --write
"""
|
# -*- coding: utf-8 -*-
import sys
import os
import tkinter as tk
from tkinter import ttk
# =================================
# == 公開関数
# =================================
def resource_path(relative):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative)
# =================================
# == 公開クラス
# =================================
class LabelEntry(ttk.Frame):
""" ラベル付きEntry(横並び) """
def __init__(self, master=None, text=None, **entry_kw):
ttk.Frame.__init__(self, master)
# Label
self.Label = ttk.Label(self, text=text)
self.Label.pack(side=tk.LEFT)
# Entry
self.Entry = ttk.Entry(self)
self.Entry.configure(entry_kw)
self.Entry.pack()
class LabelReadonlyEntry(ttk.Frame):
""" ラベル付き非活性Entry(縦並び) """
def __init__(self, master=None, text=None, **entry_kw):
ttk.Frame.__init__(self, master)
# Label
self.Label = ttk.Label(self, text=text)
self.Label.pack()
# Entry
self.Entry = ttk.Entry(self, justify=tk.RIGHT)
self.Entry.configure(entry_kw)
self.Entry.state(['readonly'])
self.Entry.pack()
|
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.echarts={})}(this,function(t){"use strict";function e(t,e){"createCanvas"===t&&(ah=null),ih[t]=e}function n(t){if(null==t||"object"!=typeof t)return t;var e=t,i=$l.call(t);if("[object Array]"===i){if(!E(t)){e=[];for(var r=0,a=t.length;r<a;r++)e[r]=n(t[r])}}else if(jl[i]){if(!E(t)){var o=t.constructor;if(t.constructor.from)e=o.from(t);else{e=new o(t.length);for(var r=0,a=t.length;r<a;r++)e[r]=n(t[r])}}}else if(!Zl[i]&&!E(t)&&!M(t)){e={};for(var s in t)t.hasOwnProperty(s)&&(e[s]=n(t[s]))}return e}function i(t,e,r){if(!w(e)||!w(t))return r?n(e):t;for(var a in e)if(e.hasOwnProperty(a)){var o=t[a],s=e[a];!w(s)||!w(o)||y(s)||y(o)||M(s)||M(o)||b(s)||b(o)||E(s)||E(o)?!r&&a in t||(t[a]=n(e[a],!0)):i(o,s,r)}return t}function r(t,e){for(var n=t[0],r=1,a=t.length;r<a;r++)n=i(n,t[r],e);return n}function a(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t}function o(t,e,n){for(var i in e)e.hasOwnProperty(i)&&(n?null!=e[i]:null==t[i])&&(t[i]=e[i]);return t}function s(){return ah||(ah=rh().getContext("2d")),ah}function l(t,e){if(t){if(t.indexOf)return t.indexOf(e);for(var n=0,i=t.length;n<i;n++)if(t[n]===e)return n}return-1}function h(t,e){function n(){}var i=t.prototype;n.prototype=e.prototype,t.prototype=new n;for(var r in i)t.prototype[r]=i[r];t.prototype.constructor=t,t.superClass=e}function u(t,e,n){o(t="prototype"in t?t.prototype:t,e="prototype"in e?e.prototype:e,n)}function c(t){if(t)return"string"!=typeof t&&"number"==typeof t.length}function f(t,e,n){if(t&&e)if(t.forEach&&t.forEach===Ql)t.forEach(e,n);else if(t.length===+t.length)for(var i=0,r=t.length;i<r;i++)e.call(n,t[i],i,t);else for(var a in t)t.hasOwnProperty(a)&&e.call(n,t[a],a,t)}function d(t,e,n){if(t&&e){if(t.map&&t.map===eh)return t.map(e,n);for(var i=[],r=0,a=t.length;r<a;r++)i.push(e.call(n,t[r],r,t));return i}}function p(t,e,n,i){if(t&&e){if(t.reduce&&t.reduce===nh)return t.reduce(e,n,i);for(var r=0,a=t.length;r<a;r++)n=e.call(i,n,t[r],r,t);return n}}function g(t,e,n){if(t&&e){if(t.filter&&t.filter===Jl)return t.filter(e,n);for(var i=[],r=0,a=t.length;r<a;r++)e.call(n,t[r],r,t)&&i.push(t[r]);return i}}function m(t,e){var n=th.call(arguments,2);return function(){return t.apply(e,n.concat(th.call(arguments)))}}function v(t){var e=th.call(arguments,1);return function(){return t.apply(this,e.concat(th.call(arguments)))}}function y(t){return"[object Array]"===$l.call(t)}function _(t){return"function"==typeof t}function x(t){return"[object String]"===$l.call(t)}function w(t){var e=typeof t;return"function"===e||!!t&&"object"==e}function b(t){return!!Zl[$l.call(t)]}function S(t){return!!jl[$l.call(t)]}function M(t){return"object"==typeof t&&"number"==typeof t.nodeType&&"object"==typeof t.ownerDocument}function I(t){return t!==t}function T(t){for(var e=0,n=arguments.length;e<n;e++)if(null!=arguments[e])return arguments[e]}function C(t,e){return null!=t?t:e}function D(t,e,n){return null!=t?t:null!=e?e:n}function k(){return Function.call.apply(th,arguments)}function A(t){if("number"==typeof t)return[t,t,t,t];var e=t.length;return 2===e?[t[0],t[1],t[0],t[1]]:3===e?[t[0],t[1],t[2],t[1]]:t}function L(t,e){if(!t)throw new Error(e)}function P(t){return null==t?null:"function"==typeof t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}function O(t){t[oh]=!0}function E(t){return t[oh]}function B(t){function e(t,e){n?i.set(t,e):i.set(e,t)}var n=y(t),i=this;t instanceof B?t.each(e):t&&f(t,e)}function N(t){return new B(t)}function R(){}function z(t,e){var n=new sh(2);return null==t&&(t=0),null==e&&(e=0),n[0]=t,n[1]=e,n}function F(t){var e=new sh(2);return e[0]=t[0],e[1]=t[1],e}function V(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t}function W(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t}function H(t){return Math.sqrt(G(t))}function G(t){return t[0]*t[0]+t[1]*t[1]}function q(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function X(t,e){var n=H(e);return 0===n?(t[0]=0,t[1]=0):(t[0]=e[0]/n,t[1]=e[1]/n),t}function U(t,e){return Math.sqrt((t[0]-e[0])*(t[0]-e[0])+(t[1]-e[1])*(t[1]-e[1]))}function Y(t,e,n){var i=e[0],r=e[1];return t[0]=n[0]*i+n[2]*r+n[4],t[1]=n[1]*i+n[3]*r+n[5],t}function Z(t,e,n){return t[0]=Math.min(e[0],n[0]),t[1]=Math.min(e[1],n[1]),t}function j(t,e,n){return t[0]=Math.max(e[0],n[0]),t[1]=Math.max(e[1],n[1]),t}function $(){this.on("mousedown",this._dragStart,this),this.on("mousemove",this._drag,this),this.on("mouseup",this._dragEnd,this),this.on("globalout",this._dragEnd,this)}function K(t,e){return{target:t,topTarget:e&&e.topTarget}}function Q(t,e,n){return{type:t,event:n,target:e.target,topTarget:e.topTarget,cancelBubble:!1,offsetX:n.zrX,offsetY:n.zrY,gestureEvent:n.gestureEvent,pinchX:n.pinchX,pinchY:n.pinchY,pinchScale:n.pinchScale,wheelDelta:n.zrDelta,zrByTouch:n.zrByTouch,which:n.which}}function J(){}function tt(t,e,n){if(t[t.rectHover?"rectContain":"contain"](e,n)){for(var i,r=t;r;){if(r.clipPath&&!r.clipPath.contain(e,n))return!1;r.silent&&(i=!0),r=r.parent}return!i||fh}return!1}function et(){var t=new gh(6);return nt(t),t}function nt(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function it(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t}function rt(t,e,n){var i=e[0]*n[0]+e[2]*n[1],r=e[1]*n[0]+e[3]*n[1],a=e[0]*n[2]+e[2]*n[3],o=e[1]*n[2]+e[3]*n[3],s=e[0]*n[4]+e[2]*n[5]+e[4],l=e[1]*n[4]+e[3]*n[5]+e[5];return t[0]=i,t[1]=r,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t}function at(t,e,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4]+n[0],t[5]=e[5]+n[1],t}function ot(t,e,n){var i=e[0],r=e[2],a=e[4],o=e[1],s=e[3],l=e[5],h=Math.sin(n),u=Math.cos(n);return t[0]=i*u+o*h,t[1]=-i*h+o*u,t[2]=r*u+s*h,t[3]=-r*h+u*s,t[4]=u*a+h*l,t[5]=u*l-h*a,t}function st(t,e,n){var i=n[0],r=n[1];return t[0]=e[0]*i,t[1]=e[1]*r,t[2]=e[2]*i,t[3]=e[3]*r,t[4]=e[4]*i,t[5]=e[5]*r,t}function lt(t,e){var n=e[0],i=e[2],r=e[4],a=e[1],o=e[3],s=e[5],l=n*o-a*i;return l?(l=1/l,t[0]=o*l,t[1]=-a*l,t[2]=-i*l,t[3]=n*l,t[4]=(i*s-o*r)*l,t[5]=(a*r-n*s)*l,t):null}function ht(t){return t>vh||t<-vh}function ut(t){this._target=t.target,this._life=t.life||1e3,this._delay=t.delay||0,this._initialized=!1,this.loop=null!=t.loop&&t.loop,this.gap=t.gap||0,this.easing=t.easing||"Linear",this.onframe=t.onframe,this.ondestroy=t.ondestroy,this.onrestart=t.onrestart,this._pausedTime=0,this._paused=!1}function ct(t){return(t=Math.round(t))<0?0:t>255?255:t}function ft(t){return t<0?0:t>1?1:t}function dt(t){return ct(t.length&&"%"===t.charAt(t.length-1)?parseFloat(t)/100*255:parseInt(t,10))}function pt(t){return ft(t.length&&"%"===t.charAt(t.length-1)?parseFloat(t)/100:parseFloat(t))}function gt(t,e,n){return n<0?n+=1:n>1&&(n-=1),6*n<1?t+(e-t)*n*6:2*n<1?e:3*n<2?t+(e-t)*(2/3-n)*6:t}function mt(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function vt(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}function yt(t,e){kh&&vt(kh,e),kh=Dh.put(t,kh||e.slice())}function _t(t,e){if(t){e=e||[];var n=Dh.get(t);if(n)return vt(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in Ch)return vt(e,Ch[i]),yt(t,e),e;if("#"!==i.charAt(0)){var r=i.indexOf("("),a=i.indexOf(")");if(-1!==r&&a+1===i.length){var o=i.substr(0,r),s=i.substr(r+1,a-(r+1)).split(","),l=1;switch(o){case"rgba":if(4!==s.length)return void mt(e,0,0,0,1);l=pt(s.pop());case"rgb":return 3!==s.length?void mt(e,0,0,0,1):(mt(e,dt(s[0]),dt(s[1]),dt(s[2]),l),yt(t,e),e);case"hsla":return 4!==s.length?void mt(e,0,0,0,1):(s[3]=pt(s[3]),xt(s,e),yt(t,e),e);case"hsl":return 3!==s.length?void mt(e,0,0,0,1):(xt(s,e),yt(t,e),e);default:return}}mt(e,0,0,0,1)}else{if(4===i.length)return(h=parseInt(i.substr(1),16))>=0&&h<=4095?(mt(e,(3840&h)>>4|(3840&h)>>8,240&h|(240&h)>>4,15&h|(15&h)<<4,1),yt(t,e),e):void mt(e,0,0,0,1);if(7===i.length){var h=parseInt(i.substr(1),16);return h>=0&&h<=16777215?(mt(e,(16711680&h)>>16,(65280&h)>>8,255&h,1),yt(t,e),e):void mt(e,0,0,0,1)}}}}function xt(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=pt(t[1]),r=pt(t[2]),a=r<=.5?r*(i+1):r+i-r*i,o=2*r-a;return e=e||[],mt(e,ct(255*gt(o,a,n+1/3)),ct(255*gt(o,a,n)),ct(255*gt(o,a,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function wt(t,e){var n=_t(t);if(n){for(var i=0;i<3;i++)n[i]=e<0?n[i]*(1-e)|0:(255-n[i])*e+n[i]|0,n[i]>255?n[i]=255:t[i]<0&&(n[i]=0);return bt(n,4===n.length?"rgba":"rgb")}}function bt(t,e){if(t&&t.length){var n=t[0]+","+t[1]+","+t[2];return"rgba"!==e&&"hsva"!==e&&"hsla"!==e||(n+=","+t[3]),e+"("+n+")"}}function St(t,e){return t[e]}function Mt(t,e,n){t[e]=n}function It(t,e,n){return(e-t)*n+t}function Tt(t,e,n){return n>.5?e:t}function Ct(t,e,n,i,r){var a=t.length;if(1==r)for(s=0;s<a;s++)i[s]=It(t[s],e[s],n);else for(var o=a&&t[0].length,s=0;s<a;s++)for(var l=0;l<o;l++)i[s][l]=It(t[s][l],e[s][l],n)}function Dt(t,e,n){var i=t.length,r=e.length;if(i!==r)if(i>r)t.length=r;else for(o=i;o<r;o++)t.push(1===n?e[o]:Ah.call(e[o]));for(var a=t[0]&&t[0].length,o=0;o<t.length;o++)if(1===n)isNaN(t[o])&&(t[o]=e[o]);else for(var s=0;s<a;s++)isNaN(t[o][s])&&(t[o][s]=e[o][s])}function kt(t,e,n){if(t===e)return!0;var i=t.length;if(i!==e.length)return!1;if(1===n){for(a=0;a<i;a++)if(t[a]!==e[a])return!1}else for(var r=t[0].length,a=0;a<i;a++)for(var o=0;o<r;o++)if(t[a][o]!==e[a][o])return!1;return!0}function At(t,e,n,i,r,a,o,s,l){var h=t.length;if(1==l)for(c=0;c<h;c++)s[c]=Lt(t[c],e[c],n[c],i[c],r,a,o);else for(var u=t[0].length,c=0;c<h;c++)for(var f=0;f<u;f++)s[c][f]=Lt(t[c][f],e[c][f],n[c][f],i[c][f],r,a,o)}function Lt(t,e,n,i,r,a,o){var s=.5*(n-t),l=.5*(i-e);return(2*(e-n)+s+l)*o+(-3*(e-n)-2*s-l)*a+s*r+e}function Pt(t){if(c(t)){var e=t.length;if(c(t[0])){for(var n=[],i=0;i<e;i++)n.push(Ah.call(t[i]));return n}return Ah.call(t)}return t}function Ot(t){return t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.floor(t[2]),"rgba("+t.join(",")+")"}function Et(t){var e=t[t.length-1].value;return c(e&&e[0])?2:1}function Bt(t,e,n,i,r,a){var o=t._getter,s=t._setter,l="spline"===e,h=i.length;if(h){var u,f=c(i[0].value),d=!1,p=!1,g=f?Et(i):0;i.sort(function(t,e){return t.time-e.time}),u=i[h-1].time;for(var m=[],v=[],y=i[0].value,_=!0,x=0;x<h;x++){m.push(i[x].time/u);var w=i[x].value;if(f&&kt(w,y,g)||!f&&w===y||(_=!1),y=w,"string"==typeof w){var b=_t(w);b?(w=b,d=!0):p=!0}v.push(w)}if(a||!_){for(var S=v[h-1],x=0;x<h-1;x++)f?Dt(v[x],S,g):!isNaN(v[x])||isNaN(S)||p||d||(v[x]=S);f&&Dt(o(t._target,r),S,g);var M,I,T,C,D,k,A=0,L=0;if(d)var P=[0,0,0,0];var O=new ut({target:t._target,life:u,loop:t._loop,delay:t._delay,onframe:function(t,e){var n;if(e<0)n=0;else if(e<L){for(n=M=Math.min(A+1,h-1);n>=0&&!(m[n]<=e);n--);n=Math.min(n,h-2)}else{for(n=A;n<h&&!(m[n]>e);n++);n=Math.min(n-1,h-2)}A=n,L=e;var i=m[n+1]-m[n];if(0!==i)if(I=(e-m[n])/i,l)if(C=v[n],T=v[0===n?n:n-1],D=v[n>h-2?h-1:n+1],k=v[n>h-3?h-1:n+2],f)At(T,C,D,k,I,I*I,I*I*I,o(t,r),g);else{if(d)a=At(T,C,D,k,I,I*I,I*I*I,P,1),a=Ot(P);else{if(p)return Tt(C,D,I);a=Lt(T,C,D,k,I,I*I,I*I*I)}s(t,r,a)}else if(f)Ct(v[n],v[n+1],I,o(t,r),g);else{var a;if(d)Ct(v[n],v[n+1],I,P,1),a=Ot(P);else{if(p)return Tt(v[n],v[n+1],I);a=It(v[n],v[n+1],I)}s(t,r,a)}},ondestroy:n});return e&&"spline"!==e&&(O.easing=e),O}}}function Nt(t,e,n,i){n<0&&(t+=n,n=-n),i<0&&(e+=i,i=-i),this.x=t,this.y=e,this.width=n,this.height=i}function Rt(t){for(var e=0;t>=Hh;)e|=1&t,t>>=1;return t+e}function zt(t,e,n,i){var r=e+1;if(r===n)return 1;if(i(t[r++],t[e])<0){for(;r<n&&i(t[r],t[r-1])<0;)r++;Ft(t,e,r)}else for(;r<n&&i(t[r],t[r-1])>=0;)r++;return r-e}function Ft(t,e,n){for(n--;e<n;){var i=t[e];t[e++]=t[n],t[n--]=i}}function Vt(t,e,n,i,r){for(i===e&&i++;i<n;i++){for(var a,o=t[i],s=e,l=i;s<l;)r(o,t[a=s+l>>>1])<0?l=a:s=a+1;var h=i-s;switch(h){case 3:t[s+3]=t[s+2];case 2:t[s+2]=t[s+1];case 1:t[s+1]=t[s];break;default:for(;h>0;)t[s+h]=t[s+h-1],h--}t[s]=o}}function Wt(t,e,n,i,r,a){var o=0,s=0,l=1;if(a(t,e[n+r])>0){for(s=i-r;l<s&&a(t,e[n+r+l])>0;)o=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),o+=r,l+=r}else{for(s=r+1;l<s&&a(t,e[n+r-l])<=0;)o=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s);var h=o;o=r-l,l=r-h}for(o++;o<l;){var u=o+(l-o>>>1);a(t,e[n+u])>0?o=u+1:l=u}return l}function Ht(t,e,n,i,r,a){var o=0,s=0,l=1;if(a(t,e[n+r])<0){for(s=r+1;l<s&&a(t,e[n+r-l])<0;)o=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s);var h=o;o=r-l,l=r-h}else{for(s=i-r;l<s&&a(t,e[n+r+l])>=0;)o=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),o+=r,l+=r}for(o++;o<l;){var u=o+(l-o>>>1);a(t,e[n+u])<0?l=u:o=u+1}return l}function Gt(t,e){function n(n){var s=a[n],h=o[n],u=a[n+1],c=o[n+1];o[n]=h+c,n===l-3&&(a[n+1]=a[n+2],o[n+1]=o[n+2]),l--;var f=Ht(t[u],t,s,h,0,e);s+=f,0!==(h-=f)&&0!==(c=Wt(t[s+h-1],t,u,c,c-1,e))&&(h<=c?i(s,h,u,c):r(s,h,u,c))}function i(n,i,r,a){var o=0;for(o=0;o<i;o++)h[o]=t[n+o];var l=0,u=r,c=n;if(t[c++]=t[u++],0!=--a)if(1!==i){for(var f,d,p,g=s;;){f=0,d=0,p=!1;do{if(e(t[u],h[l])<0){if(t[c++]=t[u++],d++,f=0,0==--a){p=!0;break}}else if(t[c++]=h[l++],f++,d=0,1==--i){p=!0;break}}while((f|d)<g);if(p)break;do{if(0!==(f=Ht(t[u],h,l,i,0,e))){for(o=0;o<f;o++)t[c+o]=h[l+o];if(c+=f,l+=f,(i-=f)<=1){p=!0;break}}if(t[c++]=t[u++],0==--a){p=!0;break}if(0!==(d=Wt(h[l],t,u,a,0,e))){for(o=0;o<d;o++)t[c+o]=t[u+o];if(c+=d,u+=d,0===(a-=d)){p=!0;break}}if(t[c++]=h[l++],1==--i){p=!0;break}g--}while(f>=Gh||d>=Gh);if(p)break;g<0&&(g=0),g+=2}if((s=g)<1&&(s=1),1===i){for(o=0;o<a;o++)t[c+o]=t[u+o];t[c+a]=h[l]}else{if(0===i)throw new Error;for(o=0;o<i;o++)t[c+o]=h[l+o]}}else{for(o=0;o<a;o++)t[c+o]=t[u+o];t[c+a]=h[l]}else for(o=0;o<i;o++)t[c+o]=h[l+o]}function r(n,i,r,a){var o=0;for(o=0;o<a;o++)h[o]=t[r+o];var l=n+i-1,u=a-1,c=r+a-1,f=0,d=0;if(t[c--]=t[l--],0!=--i)if(1!==a){for(var p=s;;){var g=0,m=0,v=!1;do{if(e(h[u],t[l])<0){if(t[c--]=t[l--],g++,m=0,0==--i){v=!0;break}}else if(t[c--]=h[u--],m++,g=0,1==--a){v=!0;break}}while((g|m)<p);if(v)break;do{if(0!=(g=i-Ht(h[u],t,n,i,i-1,e))){for(i-=g,d=(c-=g)+1,f=(l-=g)+1,o=g-1;o>=0;o--)t[d+o]=t[f+o];if(0===i){v=!0;break}}if(t[c--]=h[u--],1==--a){v=!0;break}if(0!=(m=a-Wt(t[l],h,0,a,a-1,e))){for(a-=m,d=(c-=m)+1,f=(u-=m)+1,o=0;o<m;o++)t[d+o]=h[f+o];if(a<=1){v=!0;break}}if(t[c--]=t[l--],0==--i){v=!0;break}p--}while(g>=Gh||m>=Gh);if(v)break;p<0&&(p=0),p+=2}if((s=p)<1&&(s=1),1===a){for(d=(c-=i)+1,f=(l-=i)+1,o=i-1;o>=0;o--)t[d+o]=t[f+o];t[c]=h[u]}else{if(0===a)throw new Error;for(f=c-(a-1),o=0;o<a;o++)t[f+o]=h[o]}}else{for(d=(c-=i)+1,f=(l-=i)+1,o=i-1;o>=0;o--)t[d+o]=t[f+o];t[c]=h[u]}else for(f=c-(a-1),o=0;o<a;o++)t[f+o]=h[o]}var a,o,s=Gh,l=0,h=[];a=[],o=[],this.mergeRuns=function(){for(;l>1;){var t=l-2;if(t>=1&&o[t-1]<=o[t]+o[t+1]||t>=2&&o[t-2]<=o[t]+o[t-1])o[t-1]<o[t+1]&&t--;else if(o[t]>o[t+1])break;n(t)}},this.forceMergeRuns=function(){for(;l>1;){var t=l-2;t>0&&o[t-1]<o[t+1]&&t--,n(t)}},this.pushRun=function(t,e){a[l]=t,o[l]=e,l+=1}}function qt(t,e,n,i){n||(n=0),i||(i=t.length);var r=i-n;if(!(r<2)){var a=0;if(r<Hh)return a=zt(t,n,i,e),void Vt(t,n,i,n+a,e);var o=new Gt(t,e),s=Rt(r);do{if((a=zt(t,n,i,e))<s){var l=r;l>s&&(l=s),Vt(t,n,n+l,n+a,e),a=l}o.pushRun(n,a),o.mergeRuns(),r-=a,n+=a}while(0!==r);o.forceMergeRuns()}}function Xt(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}function Ut(t,e,n){var i=null==e.x?0:e.x,r=null==e.x2?1:e.x2,a=null==e.y?0:e.y,o=null==e.y2?0:e.y2;return e.global||(i=i*n.width+n.x,r=r*n.width+n.x,a=a*n.height+n.y,o=o*n.height+n.y),i=isNaN(i)?0:i,r=isNaN(r)?1:r,a=isNaN(a)?0:a,o=isNaN(o)?0:o,t.createLinearGradient(i,a,r,o)}function Yt(t,e,n){var i=n.width,r=n.height,a=Math.min(i,r),o=null==e.x?.5:e.x,s=null==e.y?.5:e.y,l=null==e.r?.5:e.r;return e.global||(o=o*i+n.x,s=s*r+n.y,l*=a),t.createRadialGradient(o,s,0,o,s,l)}function Zt(){return!1}function jt(t,e,n){var i=rh(),r=e.getWidth(),a=e.getHeight(),o=i.style;return o&&(o.position="absolute",o.left=0,o.top=0,o.width=r+"px",o.height=a+"px",i.setAttribute("data-zr-dom-id",t)),i.width=r*n,i.height=a*n,i}function $t(t){if("string"==typeof t){var e=eu.get(t);return e&&e.image}return t}function Kt(t,e,n,i,r){if(t){if("string"==typeof t){if(e&&e.__zrImageSrc===t||!n)return e;var a=eu.get(t),o={hostEl:n,cb:i,cbPayload:r};return a?!Jt(e=a.image)&&a.pending.push(o):(!e&&(e=new Image),e.onload=Qt,eu.put(t,e.__cachedImgObj={image:e,pending:[o]}),e.src=e.__zrImageSrc=t),e}return t}return e}function Qt(){var t=this.__cachedImgObj;this.onload=this.__cachedImgObj=null;for(var e=0;e<t.pending.length;e++){var n=t.pending[e],i=n.cb;i&&i(this,n.cbPayload),n.hostEl.dirty()}t.pending.length=0}function Jt(t){return t&&t.width&&t.height}function te(t,e){var n=t+":"+(e=e||ou);if(nu[n])return nu[n];for(var i=(t+"").split("\n"),r=0,a=0,o=i.length;a<o;a++)r=Math.max(fe(i[a],e).width,r);return iu>ru&&(iu=0,nu={}),iu++,nu[n]=r,r}function ee(t,e,n,i,r,a,o){return a?ie(t,e,n,i,r,a,o):ne(t,e,n,i,r,o)}function ne(t,e,n,i,r,a){var o=de(t,e,r,a),s=te(t,e);r&&(s+=r[1]+r[3]);var l=o.outerHeight,h=new Nt(re(0,s,n),ae(0,l,i),s,l);return h.lineHeight=o.lineHeight,h}function ie(t,e,n,i,r,a,o){var s=pe(t,{rich:a,truncate:o,font:e,textAlign:n,textPadding:r}),l=s.outerWidth,h=s.outerHeight;return new Nt(re(0,l,n),ae(0,h,i),l,h)}function re(t,e,n){return"right"===n?t-=e:"center"===n&&(t-=e/2),t}function ae(t,e,n){return"middle"===n?t-=e/2:"bottom"===n&&(t-=e),t}function oe(t,e,n){var i=e.x,r=e.y,a=e.height,o=e.width,s=a/2,l="left",h="top";switch(t){case"left":i-=n,r+=s,l="right",h="middle";break;case"right":i+=n+o,r+=s,h="middle";break;case"top":i+=o/2,r-=n,l="center",h="bottom";break;case"bottom":i+=o/2,r+=a+n,l="center";break;case"inside":i+=o/2,r+=s,l="center",h="middle";break;case"insideLeft":i+=n,r+=s,h="middle";break;case"insideRight":i+=o-n,r+=s,l="right",h="middle";break;case"insideTop":i+=o/2,r+=n,l="center";break;case"insideBottom":i+=o/2,r+=a-n,l="center",h="bottom";break;case"insideTopLeft":i+=n,r+=n;break;case"insideTopRight":i+=o-n,r+=n,l="right";break;case"insideBottomLeft":i+=n,r+=a-n,h="bottom";break;case"insideBottomRight":i+=o-n,r+=a-n,l="right",h="bottom"}return{x:i,y:r,textAlign:l,textVerticalAlign:h}}function se(t,e,n,i,r){if(!e)return"";var a=(t+"").split("\n");r=le(e,n,i,r);for(var o=0,s=a.length;o<s;o++)a[o]=he(a[o],r);return a.join("\n")}function le(t,e,n,i){(i=a({},i)).font=e;var n=C(n,"...");i.maxIterations=C(i.maxIterations,2);var r=i.minChar=C(i.minChar,0);i.cnCharWidth=te("国",e);var o=i.ascCharWidth=te("a",e);i.placeholder=C(i.placeholder,"");for(var s=t=Math.max(0,t-1),l=0;l<r&&s>=o;l++)s-=o;var h=te(n);return h>s&&(n="",h=0),s=t-h,i.ellipsis=n,i.ellipsisWidth=h,i.contentWidth=s,i.containerWidth=t,i}function he(t,e){var n=e.containerWidth,i=e.font,r=e.contentWidth;if(!n)return"";var a=te(t,i);if(a<=n)return t;for(var o=0;;o++){if(a<=r||o>=e.maxIterations){t+=e.ellipsis;break}var s=0===o?ue(t,r,e.ascCharWidth,e.cnCharWidth):a>0?Math.floor(t.length*r/a):0;a=te(t=t.substr(0,s),i)}return""===t&&(t=e.placeholder),t}function ue(t,e,n,i){for(var r=0,a=0,o=t.length;a<o&&r<e;a++){var s=t.charCodeAt(a);r+=0<=s&&s<=127?n:i}return a}function ce(t){return te("国",t)}function fe(t,e){return su.measureText(t,e)}function de(t,e,n,i){null!=t&&(t+="");var r=ce(e),a=t?t.split("\n"):[],o=a.length*r,s=o;if(n&&(s+=n[0]+n[2]),t&&i){var l=i.outerHeight,h=i.outerWidth;if(null!=l&&s>l)t="",a=[];else if(null!=h)for(var u=le(h-(n?n[1]+n[3]:0),e,i.ellipsis,{minChar:i.minChar,placeholder:i.placeholder}),c=0,f=a.length;c<f;c++)a[c]=he(a[c],u)}return{lines:a,height:o,outerHeight:s,lineHeight:r}}function pe(t,e){var n={lines:[],width:0,height:0};if(null!=t&&(t+=""),!t)return n;for(var i,r=au.lastIndex=0;null!=(i=au.exec(t));){var a=i.index;a>r&&ge(n,t.substring(r,a)),ge(n,i[2],i[1]),r=au.lastIndex}r<t.length&&ge(n,t.substring(r,t.length));var o=n.lines,s=0,l=0,h=[],u=e.textPadding,c=e.truncate,f=c&&c.outerWidth,d=c&&c.outerHeight;u&&(null!=f&&(f-=u[1]+u[3]),null!=d&&(d-=u[0]+u[2]));for(A=0;A<o.length;A++){for(var p=o[A],g=0,m=0,v=0;v<p.tokens.length;v++){var y=(L=p.tokens[v]).styleName&&e.rich[L.styleName]||{},_=L.textPadding=y.textPadding,x=L.font=y.font||e.font,w=L.textHeight=C(y.textHeight,ce(x));if(_&&(w+=_[0]+_[2]),L.height=w,L.lineHeight=D(y.textLineHeight,e.textLineHeight,w),L.textAlign=y&&y.textAlign||e.textAlign,L.textVerticalAlign=y&&y.textVerticalAlign||"middle",null!=d&&s+L.lineHeight>d)return{lines:[],width:0,height:0};L.textWidth=te(L.text,x);var b=y.textWidth,S=null==b||"auto"===b;if("string"==typeof b&&"%"===b.charAt(b.length-1))L.percentWidth=b,h.push(L),b=0;else{if(S){b=L.textWidth;var M=y.textBackgroundColor,I=M&&M.image;I&&Jt(I=$t(I))&&(b=Math.max(b,I.width*w/I.height))}var T=_?_[1]+_[3]:0;b+=T;var k=null!=f?f-m:null;null!=k&&k<b&&(!S||k<T?(L.text="",L.textWidth=b=0):(L.text=se(L.text,k-T,x,c.ellipsis,{minChar:c.minChar}),L.textWidth=te(L.text,x),b=L.textWidth+T))}m+=L.width=b,y&&(g=Math.max(g,L.lineHeight))}p.width=m,p.lineHeight=g,s+=g,l=Math.max(l,m)}n.outerWidth=n.width=C(e.textWidth,l),n.outerHeight=n.height=C(e.textHeight,s),u&&(n.outerWidth+=u[1]+u[3],n.outerHeight+=u[0]+u[2]);for(var A=0;A<h.length;A++){var L=h[A],P=L.percentWidth;L.width=parseInt(P,10)/100*l}return n}function ge(t,e,n){for(var i=""===e,r=e.split("\n"),a=t.lines,o=0;o<r.length;o++){var s=r[o],l={styleName:n,text:s,isLineHolder:!s&&!i};if(o)a.push({tokens:[l]});else{var h=(a[a.length-1]||(a[0]={tokens:[]})).tokens,u=h.length;1===u&&h[0].isLineHolder?h[0]=l:(s||!u||i)&&h.push(l)}}}function me(t){var e=(t.fontSize||t.fontFamily)&&[t.fontStyle,t.fontWeight,(t.fontSize||12)+"px",t.fontFamily||"sans-serif"].join(" ");return e&&P(e)||t.textFont||t.font}function ve(t,e){var n,i,r,a,o=e.x,s=e.y,l=e.width,h=e.height,u=e.r;l<0&&(o+=l,l=-l),h<0&&(s+=h,h=-h),"number"==typeof u?n=i=r=a=u:u instanceof Array?1===u.length?n=i=r=a=u[0]:2===u.length?(n=r=u[0],i=a=u[1]):3===u.length?(n=u[0],i=a=u[1],r=u[2]):(n=u[0],i=u[1],r=u[2],a=u[3]):n=i=r=a=0;var c;n+i>l&&(n*=l/(c=n+i),i*=l/c),r+a>l&&(r*=l/(c=r+a),a*=l/c),i+r>h&&(i*=h/(c=i+r),r*=h/c),n+a>h&&(n*=h/(c=n+a),a*=h/c),t.moveTo(o+n,s),t.lineTo(o+l-i,s),0!==i&&t.arc(o+l-i,s+i,i,-Math.PI/2,0),t.lineTo(o+l,s+h-r),0!==r&&t.arc(o+l-r,s+h-r,r,0,Math.PI/2),t.lineTo(o+a,s+h),0!==a&&t.arc(o+a,s+h-a,a,Math.PI/2,Math.PI),t.lineTo(o,s+n),0!==n&&t.arc(o+n,s+n,n,Math.PI,1.5*Math.PI)}function ye(t){return _e(t),f(t.rich,_e),t}function _e(t){if(t){t.font=me(t);var e=t.textAlign;"middle"===e&&(e="center"),t.textAlign=null==e||lu[e]?e:"left";var n=t.textVerticalAlign||t.textBaseline;"center"===n&&(n="middle"),t.textVerticalAlign=null==n||hu[n]?n:"top",t.textPadding&&(t.textPadding=A(t.textPadding))}}function xe(t,e,n,i,r){i.rich?be(t,e,n,i,r):we(t,e,n,i,r)}function we(t,e,n,i,r){var a=Ae(e,"font",i.font||ou),o=i.textPadding,s=t.__textCotentBlock;s&&!t.__dirty||(s=t.__textCotentBlock=de(n,a,o,i.truncate));var l=s.outerHeight,h=s.lines,u=s.lineHeight,c=ke(l,i,r),f=c.baseX,d=c.baseY,p=c.textAlign,g=c.textVerticalAlign;Me(e,i,r,f,d);var m=ae(d,l,g),v=f,y=m,_=Te(i);if(_||o){var x=te(n,a);o&&(x+=o[1]+o[3]);var w=re(f,x,p);_&&Ce(t,e,i,w,m,x,l),o&&(v=Ee(f,p,o),y+=o[0])}Ae(e,"textAlign",p||"left"),Ae(e,"textBaseline","middle"),Ae(e,"shadowBlur",i.textShadowBlur||0),Ae(e,"shadowColor",i.textShadowColor||"transparent"),Ae(e,"shadowOffsetX",i.textShadowOffsetX||0),Ae(e,"shadowOffsetY",i.textShadowOffsetY||0),y+=u/2;var b=i.textStrokeWidth,S=Le(i.textStroke,b),M=Pe(i.textFill);S&&(Ae(e,"lineWidth",b),Ae(e,"strokeStyle",S)),M&&Ae(e,"fillStyle",M);for(var I=0;I<h.length;I++)S&&e.strokeText(h[I],v,y),M&&e.fillText(h[I],v,y),y+=u}function be(t,e,n,i,r){var a=t.__textCotentBlock;a&&!t.__dirty||(a=t.__textCotentBlock=pe(n,i)),Se(t,e,a,i,r)}function Se(t,e,n,i,r){var a=n.width,o=n.outerWidth,s=n.outerHeight,l=i.textPadding,h=ke(s,i,r),u=h.baseX,c=h.baseY,f=h.textAlign,d=h.textVerticalAlign;Me(e,i,r,u,c);var p=re(u,o,f),g=ae(c,s,d),m=p,v=g;l&&(m+=l[3],v+=l[0]);var y=m+a;Te(i)&&Ce(t,e,i,p,g,o,s);for(var _=0;_<n.lines.length;_++){for(var x,w=n.lines[_],b=w.tokens,S=b.length,M=w.lineHeight,I=w.width,T=0,C=m,D=y,k=S-1;T<S&&(!(x=b[T]).textAlign||"left"===x.textAlign);)Ie(t,e,x,i,M,v,C,"left"),I-=x.width,C+=x.width,T++;for(;k>=0&&"right"===(x=b[k]).textAlign;)Ie(t,e,x,i,M,v,D,"right"),I-=x.width,D-=x.width,k--;for(C+=(a-(C-m)-(y-D)-I)/2;T<=k;)Ie(t,e,x=b[T],i,M,v,C+x.width/2,"center"),C+=x.width,T++;v+=M}}function Me(t,e,n,i,r){if(n&&e.textRotation){var a=e.textOrigin;"center"===a?(i=n.width/2+n.x,r=n.height/2+n.y):a&&(i=a[0]+n.x,r=a[1]+n.y),t.translate(i,r),t.rotate(-e.textRotation),t.translate(-i,-r)}}function Ie(t,e,n,i,r,a,o,s){var l=i.rich[n.styleName]||{},h=n.textVerticalAlign,u=a+r/2;"top"===h?u=a+n.height/2:"bottom"===h&&(u=a+r-n.height/2),!n.isLineHolder&&Te(l)&&Ce(t,e,l,"right"===s?o-n.width:"center"===s?o-n.width/2:o,u-n.height/2,n.width,n.height);var c=n.textPadding;c&&(o=Ee(o,s,c),u-=n.height/2-c[2]-n.textHeight/2),Ae(e,"shadowBlur",D(l.textShadowBlur,i.textShadowBlur,0)),Ae(e,"shadowColor",l.textShadowColor||i.textShadowColor||"transparent"),Ae(e,"shadowOffsetX",D(l.textShadowOffsetX,i.textShadowOffsetX,0)),Ae(e,"shadowOffsetY",D(l.textShadowOffsetY,i.textShadowOffsetY,0)),Ae(e,"textAlign",s),Ae(e,"textBaseline","middle"),Ae(e,"font",n.font||ou);var f=Le(l.textStroke||i.textStroke,p),d=Pe(l.textFill||i.textFill),p=C(l.textStrokeWidth,i.textStrokeWidth);f&&(Ae(e,"lineWidth",p),Ae(e,"strokeStyle",f),e.strokeText(n.text,o,u)),d&&(Ae(e,"fillStyle",d),e.fillText(n.text,o,u))}function Te(t){return t.textBackgroundColor||t.textBorderWidth&&t.textBorderColor}function Ce(t,e,n,i,r,a,o){var s=n.textBackgroundColor,l=n.textBorderWidth,h=n.textBorderColor,u=x(s);if(Ae(e,"shadowBlur",n.textBoxShadowBlur||0),Ae(e,"shadowColor",n.textBoxShadowColor||"transparent"),Ae(e,"shadowOffsetX",n.textBoxShadowOffsetX||0),Ae(e,"shadowOffsetY",n.textBoxShadowOffsetY||0),u||l&&h){e.beginPath();var c=n.textBorderRadius;c?ve(e,{x:i,y:r,width:a,height:o,r:c}):e.rect(i,r,a,o),e.closePath()}if(u)Ae(e,"fillStyle",s),e.fill();else if(w(s)){var f=s.image;(f=Kt(f,null,t,De,s))&&Jt(f)&&e.drawImage(f,i,r,a,o)}l&&h&&(Ae(e,"lineWidth",l),Ae(e,"strokeStyle",h),e.stroke())}function De(t,e){e.image=t}function ke(t,e,n){var i=e.x||0,r=e.y||0,a=e.textAlign,o=e.textVerticalAlign;if(n){var s=e.textPosition;if(s instanceof Array)i=n.x+Oe(s[0],n.width),r=n.y+Oe(s[1],n.height);else{var l=oe(s,n,e.textDistance);i=l.x,r=l.y,a=a||l.textAlign,o=o||l.textVerticalAlign}var h=e.textOffset;h&&(i+=h[0],r+=h[1])}return{baseX:i,baseY:r,textAlign:a,textVerticalAlign:o}}function Ae(t,e,n){return t[e]=Uh(t,e,n),t[e]}function Le(t,e){return null==t||e<=0||"transparent"===t||"none"===t?null:t.image||t.colorStops?"#000":t}function Pe(t){return null==t||"none"===t?null:t.image||t.colorStops?"#000":t}function Oe(t,e){return"string"==typeof t?t.lastIndexOf("%")>=0?parseFloat(t)/100*e:parseFloat(t):t}function Ee(t,e,n){return"right"===e?t-n[1]:"center"===e?t+n[3]/2-n[1]/2:t+n[3]}function Be(t,e){return null!=t&&(t||e.textBackgroundColor||e.textBorderWidth&&e.textBorderColor||e.textPadding)}function Ne(t){t=t||{},Rh.call(this,t);for(var e in t)t.hasOwnProperty(e)&&"style"!==e&&(this[e]=t[e]);this.style=new Zh(t.style,this),this._rect=null,this.__clipPaths=[]}function Re(t){Ne.call(this,t)}function ze(t){return parseInt(t,10)}function Fe(t){return!!t&&(!!t.__builtin__||"function"==typeof t.resize&&"function"==typeof t.refresh)}function Ve(t,e,n){return fu.copy(t.getBoundingRect()),t.transform&&fu.applyTransform(t.transform),du.width=e,du.height=n,!fu.intersect(du)}function We(t,e){if(t==e)return!1;if(!t||!e||t.length!==e.length)return!0;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!0}function He(t,e){for(var n=0;n<t.length;n++){var i=t[n];i.setTransform(e),e.beginPath(),i.buildPath(e,i.shape),e.clip(),i.restoreTransform(e)}}function Ge(t,e){var n=document.createElement("div");return n.style.cssText=["position:relative","overflow:hidden","width:"+t+"px","height:"+e+"px","padding:0","margin:0","border-width:0"].join(";")+";",n}function qe(t){return t.getBoundingClientRect?t.getBoundingClientRect():{left:0,top:0}}function Xe(t,e,n,i){return n=n||{},i||!Yl.canvasSupported?Ue(t,e,n):Yl.browser.firefox&&null!=e.layerX&&e.layerX!==e.offsetX?(n.zrX=e.layerX,n.zrY=e.layerY):null!=e.offsetX?(n.zrX=e.offsetX,n.zrY=e.offsetY):Ue(t,e,n),n}function Ue(t,e,n){var i=qe(t);n.zrX=e.clientX-i.left,n.zrY=e.clientY-i.top}function Ye(t,e,n){if(null!=(e=e||window.event).zrX)return e;var i=e.type;if(i&&i.indexOf("touch")>=0){var r="touchend"!=i?e.targetTouches[0]:e.changedTouches[0];r&&Xe(t,r,e,n)}else Xe(t,e,e,n),e.zrDelta=e.wheelDelta?e.wheelDelta/120:-(e.detail||0)/3;var a=e.button;return null==e.which&&void 0!==a&&mu.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function Ze(t,e,n){gu?t.addEventListener(e,n):t.attachEvent("on"+e,n)}function je(t,e,n){gu?t.removeEventListener(e,n):t.detachEvent("on"+e,n)}function $e(t){var e=t[1][0]-t[0][0],n=t[1][1]-t[0][1];return Math.sqrt(e*e+n*n)}function Ke(t){return[(t[0][0]+t[1][0])/2,(t[0][1]+t[1][1])/2]}function Qe(t){return"mousewheel"===t&&Yl.browser.firefox?"DOMMouseScroll":t}function Je(t,e,n){var i=t._gestureMgr;"start"===n&&i.clear();var r=i.recognize(e,t.handler.findHover(e.zrX,e.zrY,null).target,t.dom);if("end"===n&&i.clear(),r){var a=r.type;e.gestureEvent=a,t.handler.dispatchToElement({target:r.target},a,r.event)}}function tn(t){t._touching=!0,clearTimeout(t._touchTimer),t._touchTimer=setTimeout(function(){t._touching=!1},700)}function en(t){var e=t.pointerType;return"pen"===e||"touch"===e}function nn(t){function e(t,e){return function(){if(!e._touching)return t.apply(e,arguments)}}f(wu,function(e){t._handlers[e]=m(Mu[e],t)}),f(Su,function(e){t._handlers[e]=m(Mu[e],t)}),f(xu,function(n){t._handlers[n]=e(Mu[n],t)})}function rn(t){function e(e,n){f(e,function(e){Ze(t,Qe(e),n._handlers[e])},n)}ch.call(this),this.dom=t,this._touching=!1,this._touchTimer,this._gestureMgr=new yu,this._handlers={},nn(this),Yl.pointerEventsSupported?e(Su,this):(Yl.touchEventsSupported&&e(wu,this),e(xu,this))}function an(t,e){return new Du(Xl(),t,e)}function on(t){return t instanceof Array?t:null==t?[]:[t]}function sn(t,e,n){if(t){t[e]=t[e]||{},t.emphasis=t.emphasis||{},t.emphasis[e]=t.emphasis[e]||{};for(var i=0,r=n.length;i<r;i++){var a=n[i];!t.emphasis[e].hasOwnProperty(a)&&t[e].hasOwnProperty(a)&&(t.emphasis[e][a]=t[e][a])}}}function ln(t){return!Au(t)||Lu(t)||t instanceof Date?t:t.value}function hn(t){return Au(t)&&!(t instanceof Array)}function un(t,e){e=(e||[]).slice();var n=d(t||[],function(t,e){return{exist:t}});return ku(e,function(t,i){if(Au(t)){for(r=0;r<n.length;r++)if(!n[r].option&&null!=t.id&&n[r].exist.id===t.id+"")return n[r].option=t,void(e[i]=null);for(var r=0;r<n.length;r++){var a=n[r].exist;if(!(n[r].option||null!=a.id&&null!=t.id||null==t.name||dn(t)||dn(a)||a.name!==t.name+""))return n[r].option=t,void(e[i]=null)}}}),ku(e,function(t,e){if(Au(t)){for(var i=0;i<n.length;i++){var r=n[i].exist;if(!n[i].option&&!dn(r)&&null==t.id){n[i].option=t;break}}i>=n.length&&n.push({option:t})}}),n}function cn(t){var e=N();ku(t,function(t,n){var i=t.exist;i&&e.set(i.id,t)}),ku(t,function(t,n){var i=t.option;L(!i||null==i.id||!e.get(i.id)||e.get(i.id)===t,"id duplicates: "+(i&&i.id)),i&&null!=i.id&&e.set(i.id,t),!t.keyInfo&&(t.keyInfo={})}),ku(t,function(t,n){var i=t.exist,r=t.option,a=t.keyInfo;if(Au(r)){if(a.name=null!=r.name?r.name+"":i?i.name:Pu+n,i)a.id=i.id;else if(null!=r.id)a.id=r.id+"";else{var o=0;do{a.id="\0"+a.name+"\0"+o++}while(e.get(a.id))}e.set(a.id,t)}})}function fn(t){var e=t.name;return!(!e||!e.indexOf(Pu))}function dn(t){return Au(t)&&t.id&&0===(t.id+"").indexOf("\0_ec_\0")}function pn(t,e){return null!=e.dataIndexInside?e.dataIndexInside:null!=e.dataIndex?y(e.dataIndex)?d(e.dataIndex,function(e){return t.indexOfRawIndex(e)}):t.indexOfRawIndex(e.dataIndex):null!=e.name?y(e.name)?d(e.name,function(e){return t.indexOfName(e)}):t.indexOfName(e.name):void 0}function gn(){var t="__\0ec_inner_"+Eu+++"_"+Math.random().toFixed(5);return function(e){return e[t]||(e[t]={})}}function mn(t,e,n){if(x(e)){var i={};i[e+"Index"]=0,e=i}var r=n&&n.defaultMainType;!r||vn(e,r+"Index")||vn(e,r+"Id")||vn(e,r+"Name")||(e[r+"Index"]=0);var a={};return ku(e,function(i,r){var i=e[r];if("dataIndex"!==r&&"dataIndexInside"!==r){var o=r.match(/^(\w+)(Index|Id|Name)$/)||[],s=o[1],h=(o[2]||"").toLowerCase();if(!(!s||!h||null==i||"index"===h&&"none"===i||n&&n.includeMainTypes&&l(n.includeMainTypes,s)<0)){var u={mainType:s};"index"===h&&"all"===i||(u[h]=i);var c=t.queryComponents(u);a[s+"Models"]=c,a[s+"Model"]=c[0]}}else a[r]=i}),a}function vn(t,e){return t&&t.hasOwnProperty(e)}function yn(t,e,n){t.setAttribute?t.setAttribute(e,n):t[e]=n}function _n(t,e){return t.getAttribute?t.getAttribute(e):t[e]}function xn(t){var e={main:"",sub:""};return t&&(t=t.split(Bu),e.main=t[0]||"",e.sub=t[1]||""),e}function wn(t){L(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(t),'componentType "'+t+'" illegal')}function bn(t,e){t.$constructor=t,t.extend=function(t){var e=this,n=function(){t.$constructor?t.$constructor.apply(this,arguments):e.apply(this,arguments)};return a(n.prototype,t),n.extend=this.extend,n.superCall=Mn,n.superApply=In,h(n,this),n.superClass=e,n}}function Sn(t){var e=["__\0is_clz",Ru++,Math.random().toFixed(3)].join("_");t.prototype[e]=!0,t.isInstance=function(t){return!(!t||!t[e])}}function Mn(t,e){var n=k(arguments,2);return this.superClass.prototype[e].apply(t,n)}function In(t,e,n){return this.superClass.prototype[e].apply(t,n)}function Tn(t,e){function n(t){var e=i[t.main];return e&&e[Nu]||((e=i[t.main]={})[Nu]=!0),e}e=e||{};var i={};if(t.registerClass=function(t,e){return e&&(wn(e),(e=xn(e)).sub?e.sub!==Nu&&(n(e)[e.sub]=t):i[e.main]=t),t},t.getClass=function(t,e,n){var r=i[t];if(r&&r[Nu]&&(r=e?r[e]:null),n&&!r)throw new Error(e?"Component "+t+"."+(e||"")+" not exists. Load it first.":t+".type should be specified.");return r},t.getClassesByMainType=function(t){t=xn(t);var e=[],n=i[t.main];return n&&n[Nu]?f(n,function(t,n){n!==Nu&&e.push(t)}):e.push(n),e},t.hasClass=function(t){return t=xn(t),!!i[t.main]},t.getAllClassMainTypes=function(){var t=[];return f(i,function(e,n){t.push(n)}),t},t.hasSubTypes=function(t){t=xn(t);var e=i[t.main];return e&&e[Nu]},t.parseClassType=xn,e.registerWhenExtend){var r=t.extend;r&&(t.extend=function(e){var n=r.call(this,e);return t.registerClass(n,e.type)})}return t}function Cn(t){return t>-Xu&&t<Xu}function Dn(t){return t>Xu||t<-Xu}function kn(t,e,n,i,r){var a=1-r;return a*a*(a*t+3*r*e)+r*r*(r*i+3*a*n)}function An(t,e,n,i,r){var a=1-r;return 3*(((e-t)*a+2*(n-e)*r)*a+(i-n)*r*r)}function Ln(t,e,n,i,r,a){var o=i+3*(e-n)-t,s=3*(n-2*e+t),l=3*(e-t),h=t-r,u=s*s-3*o*l,c=s*l-9*o*h,f=l*l-3*s*h,d=0;if(Cn(u)&&Cn(c))Cn(s)?a[0]=0:(M=-l/s)>=0&&M<=1&&(a[d++]=M);else{var p=c*c-4*u*f;if(Cn(p)){var g=c/u,m=-g/2;(M=-s/o+g)>=0&&M<=1&&(a[d++]=M),m>=0&&m<=1&&(a[d++]=m)}else if(p>0){var v=qu(p),y=u*s+1.5*o*(-c+v),_=u*s+1.5*o*(-c-v);(M=(-s-((y=y<0?-Gu(-y,Zu):Gu(y,Zu))+(_=_<0?-Gu(-_,Zu):Gu(_,Zu))))/(3*o))>=0&&M<=1&&(a[d++]=M)}else{var x=(2*u*s-3*o*c)/(2*qu(u*u*u)),w=Math.acos(x)/3,b=qu(u),S=Math.cos(w),M=(-s-2*b*S)/(3*o),m=(-s+b*(S+Yu*Math.sin(w)))/(3*o),I=(-s+b*(S-Yu*Math.sin(w)))/(3*o);M>=0&&M<=1&&(a[d++]=M),m>=0&&m<=1&&(a[d++]=m),I>=0&&I<=1&&(a[d++]=I)}}return d}function Pn(t,e,n,i,r){var a=6*n-12*e+6*t,o=9*e+3*i-3*t-9*n,s=3*e-3*t,l=0;if(Cn(o))Dn(a)&&(c=-s/a)>=0&&c<=1&&(r[l++]=c);else{var h=a*a-4*o*s;if(Cn(h))r[0]=-a/(2*o);else if(h>0){var u=qu(h),c=(-a+u)/(2*o),f=(-a-u)/(2*o);c>=0&&c<=1&&(r[l++]=c),f>=0&&f<=1&&(r[l++]=f)}}return l}function On(t,e,n,i,r,a){var o=(e-t)*r+t,s=(n-e)*r+e,l=(i-n)*r+n,h=(s-o)*r+o,u=(l-s)*r+s,c=(u-h)*r+h;a[0]=t,a[1]=o,a[2]=h,a[3]=c,a[4]=c,a[5]=u,a[6]=l,a[7]=i}function En(t,e,n,i,r,a,o,s,l,h,u){var c,f,d,p,g,m=.005,v=1/0;ju[0]=l,ju[1]=h;for(var y=0;y<1;y+=.05)$u[0]=kn(t,n,r,o,y),$u[1]=kn(e,i,a,s,y),(p=hh(ju,$u))<v&&(c=y,v=p);v=1/0;for(var _=0;_<32&&!(m<Uu);_++)f=c-m,d=c+m,$u[0]=kn(t,n,r,o,f),$u[1]=kn(e,i,a,s,f),p=hh($u,ju),f>=0&&p<v?(c=f,v=p):(Ku[0]=kn(t,n,r,o,d),Ku[1]=kn(e,i,a,s,d),g=hh(Ku,ju),d<=1&&g<v?(c=d,v=g):m*=.5);return u&&(u[0]=kn(t,n,r,o,c),u[1]=kn(e,i,a,s,c)),qu(v)}function Bn(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function Nn(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function Rn(t,e,n,i,r){var a=t-2*e+n,o=2*(e-t),s=t-i,l=0;if(Cn(a))Dn(o)&&(c=-s/o)>=0&&c<=1&&(r[l++]=c);else{var h=o*o-4*a*s;if(Cn(h))(c=-o/(2*a))>=0&&c<=1&&(r[l++]=c);else if(h>0){var u=qu(h),c=(-o+u)/(2*a),f=(-o-u)/(2*a);c>=0&&c<=1&&(r[l++]=c),f>=0&&f<=1&&(r[l++]=f)}}return l}function zn(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function Fn(t,e,n,i,r){var a=(e-t)*i+t,o=(n-e)*i+e,s=(o-a)*i+a;r[0]=t,r[1]=a,r[2]=s,r[3]=s,r[4]=o,r[5]=n}function Vn(t,e,n,i,r,a,o,s,l){var h,u=.005,c=1/0;ju[0]=o,ju[1]=s;for(var f=0;f<1;f+=.05)$u[0]=Bn(t,n,r,f),$u[1]=Bn(e,i,a,f),(m=hh(ju,$u))<c&&(h=f,c=m);c=1/0;for(var d=0;d<32&&!(u<Uu);d++){var p=h-u,g=h+u;$u[0]=Bn(t,n,r,p),$u[1]=Bn(e,i,a,p);var m=hh($u,ju);if(p>=0&&m<c)h=p,c=m;else{Ku[0]=Bn(t,n,r,g),Ku[1]=Bn(e,i,a,g);var v=hh(Ku,ju);g<=1&&v<c?(h=g,c=v):u*=.5}}return l&&(l[0]=Bn(t,n,r,h),l[1]=Bn(e,i,a,h)),qu(c)}function Wn(t,e,n,i,r,a){r[0]=Qu(t,n),r[1]=Qu(e,i),a[0]=Ju(t,n),a[1]=Ju(e,i)}function Hn(t,e,n,i,r,a,o,s,l,h){var u,c=Pn,f=kn,d=c(t,n,r,o,oc);for(l[0]=1/0,l[1]=1/0,h[0]=-1/0,h[1]=-1/0,u=0;u<d;u++){var p=f(t,n,r,o,oc[u]);l[0]=Qu(p,l[0]),h[0]=Ju(p,h[0])}for(d=c(e,i,a,s,sc),u=0;u<d;u++){var g=f(e,i,a,s,sc[u]);l[1]=Qu(g,l[1]),h[1]=Ju(g,h[1])}l[0]=Qu(t,l[0]),h[0]=Ju(t,h[0]),l[0]=Qu(o,l[0]),h[0]=Ju(o,h[0]),l[1]=Qu(e,l[1]),h[1]=Ju(e,h[1]),l[1]=Qu(s,l[1]),h[1]=Ju(s,h[1])}function Gn(t,e,n,i,r,a,o,s){var l=zn,h=Bn,u=Ju(Qu(l(t,n,r),1),0),c=Ju(Qu(l(e,i,a),1),0),f=h(t,n,r,u),d=h(e,i,a,c);o[0]=Qu(t,r,f),o[1]=Qu(e,a,d),s[0]=Ju(t,r,f),s[1]=Ju(e,a,d)}function qn(t,e,n,i,r,a,o,s,l){var h=Z,u=j,c=Math.abs(r-a);if(c%nc<1e-4&&c>1e-4)return s[0]=t-n,s[1]=e-i,l[0]=t+n,void(l[1]=e+i);if(ic[0]=ec(r)*n+t,ic[1]=tc(r)*i+e,rc[0]=ec(a)*n+t,rc[1]=tc(a)*i+e,h(s,ic,rc),u(l,ic,rc),(r%=nc)<0&&(r+=nc),(a%=nc)<0&&(a+=nc),r>a&&!o?a+=nc:r<a&&o&&(r+=nc),o){var f=a;a=r,r=f}for(var d=0;d<a;d+=Math.PI/2)d>r&&(ac[0]=ec(d)*n+t,ac[1]=tc(d)*i+e,h(s,ac,s),u(l,ac,l))}function Xn(t,e,n,i,r,a,o){if(0===r)return!1;var s=r,l=0,h=t;if(o>e+s&&o>i+s||o<e-s&&o<i-s||a>t+s&&a>n+s||a<t-s&&a<n-s)return!1;if(t===n)return Math.abs(a-t)<=s/2;var u=(l=(e-i)/(t-n))*a-o+(h=(t*i-n*e)/(t-n));return u*u/(l*l+1)<=s/2*s/2}function Un(t,e,n,i,r,a,o,s,l,h,u){if(0===l)return!1;var c=l;return!(u>e+c&&u>i+c&&u>a+c&&u>s+c||u<e-c&&u<i-c&&u<a-c&&u<s-c||h>t+c&&h>n+c&&h>r+c&&h>o+c||h<t-c&&h<n-c&&h<r-c&&h<o-c)&&En(t,e,n,i,r,a,o,s,h,u,null)<=c/2}function Yn(t,e,n,i,r,a,o,s,l){if(0===o)return!1;var h=o;return!(l>e+h&&l>i+h&&l>a+h||l<e-h&&l<i-h&&l<a-h||s>t+h&&s>n+h&&s>r+h||s<t-h&&s<n-h&&s<r-h)&&Vn(t,e,n,i,r,a,s,l,null)<=h/2}function Zn(t){return(t%=wc)<0&&(t+=wc),t}function jn(t,e,n,i,r,a,o,s,l){if(0===o)return!1;var h=o;s-=t,l-=e;var u=Math.sqrt(s*s+l*l);if(u-h>n||u+h<n)return!1;if(Math.abs(i-r)%bc<1e-4)return!0;if(a){var c=i;i=Zn(r),r=Zn(c)}else i=Zn(i),r=Zn(r);i>r&&(r+=bc);var f=Math.atan2(l,s);return f<0&&(f+=bc),f>=i&&f<=r||f+bc>=i&&f+bc<=r}function $n(t,e,n,i,r,a){if(a>e&&a>i||a<e&&a<i)return 0;if(i===e)return 0;var o=i<e?1:-1,s=(a-e)/(i-e);return 1!==s&&0!==s||(o=i<e?.5:-.5),s*(n-t)+t>r?o:0}function Kn(t,e){return Math.abs(t-e)<Ic}function Qn(){var t=Cc[0];Cc[0]=Cc[1],Cc[1]=t}function Jn(t,e,n,i,r,a,o,s,l,h){if(h>e&&h>i&&h>a&&h>s||h<e&&h<i&&h<a&&h<s)return 0;var u=Ln(e,i,a,s,h,Tc);if(0===u)return 0;for(var c,f,d=0,p=-1,g=0;g<u;g++){var m=Tc[g],v=0===m||1===m?.5:1;kn(t,n,r,o,m)<l||(p<0&&(p=Pn(e,i,a,s,Cc),Cc[1]<Cc[0]&&p>1&&Qn(),c=kn(e,i,a,s,Cc[0]),p>1&&(f=kn(e,i,a,s,Cc[1]))),2==p?m<Cc[0]?d+=c<e?v:-v:m<Cc[1]?d+=f<c?v:-v:d+=s<f?v:-v:m<Cc[0]?d+=c<e?v:-v:d+=s<c?v:-v)}return d}function ti(t,e,n,i,r,a,o,s){if(s>e&&s>i&&s>a||s<e&&s<i&&s<a)return 0;var l=Rn(e,i,a,s,Tc);if(0===l)return 0;var h=zn(e,i,a);if(h>=0&&h<=1){for(var u=0,c=Bn(e,i,a,h),f=0;f<l;f++){d=0===Tc[f]||1===Tc[f]?.5:1;(p=Bn(t,n,r,Tc[f]))<o||(Tc[f]<h?u+=c<e?d:-d:u+=a<c?d:-d)}return u}var d=0===Tc[0]||1===Tc[0]?.5:1,p=Bn(t,n,r,Tc[0]);return p<o?0:a<e?d:-d}function ei(t,e,n,i,r,a,o,s){if((s-=e)>n||s<-n)return 0;h=Math.sqrt(n*n-s*s);Tc[0]=-h,Tc[1]=h;var l=Math.abs(i-r);if(l<1e-4)return 0;if(l%Mc<1e-4){i=0,r=Mc;p=a?1:-1;return o>=Tc[0]+t&&o<=Tc[1]+t?p:0}if(a){var h=i;i=Zn(r),r=Zn(h)}else i=Zn(i),r=Zn(r);i>r&&(r+=Mc);for(var u=0,c=0;c<2;c++){var f=Tc[c];if(f+t>o){var d=Math.atan2(s,f),p=a?1:-1;d<0&&(d=Mc+d),(d>=i&&d<=r||d+Mc>=i&&d+Mc<=r)&&(d>Math.PI/2&&d<1.5*Math.PI&&(p=-p),u+=p)}}return u}function ni(t,e,n,i,r){for(var a=0,o=0,s=0,l=0,h=0,u=0;u<t.length;){var c=t[u++];switch(c===Sc.M&&u>1&&(n||(a+=$n(o,s,l,h,i,r))),1==u&&(l=o=t[u],h=s=t[u+1]),c){case Sc.M:o=l=t[u++],s=h=t[u++];break;case Sc.L:if(n){if(Xn(o,s,t[u],t[u+1],e,i,r))return!0}else a+=$n(o,s,t[u],t[u+1],i,r)||0;o=t[u++],s=t[u++];break;case Sc.C:if(n){if(Un(o,s,t[u++],t[u++],t[u++],t[u++],t[u],t[u+1],e,i,r))return!0}else a+=Jn(o,s,t[u++],t[u++],t[u++],t[u++],t[u],t[u+1],i,r)||0;o=t[u++],s=t[u++];break;case Sc.Q:if(n){if(Yn(o,s,t[u++],t[u++],t[u],t[u+1],e,i,r))return!0}else a+=ti(o,s,t[u++],t[u++],t[u],t[u+1],i,r)||0;o=t[u++],s=t[u++];break;case Sc.A:var f=t[u++],d=t[u++],p=t[u++],g=t[u++],m=t[u++],v=t[u++],y=(t[u++],1-t[u++]),_=Math.cos(m)*p+f,x=Math.sin(m)*g+d;u>1?a+=$n(o,s,_,x,i,r):(l=_,h=x);var w=(i-f)*g/p+f;if(n){if(jn(f,d,g,m,m+v,y,e,w,r))return!0}else a+=ei(f,d,g,m,m+v,y,w,r);o=Math.cos(m+v)*p+f,s=Math.sin(m+v)*g+d;break;case Sc.R:l=o=t[u++],h=s=t[u++];var _=l+t[u++],x=h+t[u++];if(n){if(Xn(l,h,_,h,e,i,r)||Xn(_,h,_,x,e,i,r)||Xn(_,x,l,x,e,i,r)||Xn(l,x,l,h,e,i,r))return!0}else a+=$n(_,h,_,x,i,r),a+=$n(l,x,l,h,i,r);break;case Sc.Z:if(n){if(Xn(o,s,l,h,e,i,r))return!0}else a+=$n(o,s,l,h,i,r);o=l,s=h}}return n||Kn(s,h)||(a+=$n(o,s,l,h,i,r)||0),0!==a}function ii(t,e,n){return ni(t,0,!1,e,n)}function ri(t,e,n,i){return ni(t,e,!0,n,i)}function ai(t){Ne.call(this,t),this.path=null}function oi(t,e,n,i,r,a,o,s,l,h,u){var c=l*(Vc/180),f=Fc(c)*(t-n)/2+zc(c)*(e-i)/2,d=-1*zc(c)*(t-n)/2+Fc(c)*(e-i)/2,p=f*f/(o*o)+d*d/(s*s);p>1&&(o*=Rc(p),s*=Rc(p));var g=(r===a?-1:1)*Rc((o*o*(s*s)-o*o*(d*d)-s*s*(f*f))/(o*o*(d*d)+s*s*(f*f)))||0,m=g*o*d/s,v=g*-s*f/o,y=(t+n)/2+Fc(c)*m-zc(c)*v,_=(e+i)/2+zc(c)*m+Fc(c)*v,x=Gc([1,0],[(f-m)/o,(d-v)/s]),w=[(f-m)/o,(d-v)/s],b=[(-1*f-m)/o,(-1*d-v)/s],S=Gc(w,b);Hc(w,b)<=-1&&(S=Vc),Hc(w,b)>=1&&(S=0),0===a&&S>0&&(S-=2*Vc),1===a&&S<0&&(S+=2*Vc),u.addData(h,y,_,o,s,x,S,c,a)}function si(t){if(!t)return[];var e,n=t.replace(/-/g," -").replace(/ /g," ").replace(/ /g,",").replace(/,,/g,",");for(e=0;e<Nc.length;e++)n=n.replace(new RegExp(Nc[e],"g"),"|"+Nc[e]);var i,r=n.split("|"),a=0,o=0,s=new xc,l=xc.CMD;for(e=1;e<r.length;e++){var h,u=r[e],c=u.charAt(0),f=0,d=u.slice(1).replace(/e,-/g,"e-").split(",");d.length>0&&""===d[0]&&d.shift();for(var p=0;p<d.length;p++)d[p]=parseFloat(d[p]);for(;f<d.length&&!isNaN(d[f])&&!isNaN(d[0]);){var g,m,v,y,_,x,w,b=a,S=o;switch(c){case"l":a+=d[f++],o+=d[f++],h=l.L,s.addData(h,a,o);break;case"L":a=d[f++],o=d[f++],h=l.L,s.addData(h,a,o);break;case"m":a+=d[f++],o+=d[f++],h=l.M,s.addData(h,a,o),c="l";break;case"M":a=d[f++],o=d[f++],h=l.M,s.addData(h,a,o),c="L";break;case"h":a+=d[f++],h=l.L,s.addData(h,a,o);break;case"H":a=d[f++],h=l.L,s.addData(h,a,o);break;case"v":o+=d[f++],h=l.L,s.addData(h,a,o);break;case"V":o=d[f++],h=l.L,s.addData(h,a,o);break;case"C":h=l.C,s.addData(h,d[f++],d[f++],d[f++],d[f++],d[f++],d[f++]),a=d[f-2],o=d[f-1];break;case"c":h=l.C,s.addData(h,d[f++]+a,d[f++]+o,d[f++]+a,d[f++]+o,d[f++]+a,d[f++]+o),a+=d[f-2],o+=d[f-1];break;case"S":g=a,m=o;var M=s.len(),I=s.data;i===l.C&&(g+=a-I[M-4],m+=o-I[M-3]),h=l.C,b=d[f++],S=d[f++],a=d[f++],o=d[f++],s.addData(h,g,m,b,S,a,o);break;case"s":g=a,m=o;var M=s.len(),I=s.data;i===l.C&&(g+=a-I[M-4],m+=o-I[M-3]),h=l.C,b=a+d[f++],S=o+d[f++],a+=d[f++],o+=d[f++],s.addData(h,g,m,b,S,a,o);break;case"Q":b=d[f++],S=d[f++],a=d[f++],o=d[f++],h=l.Q,s.addData(h,b,S,a,o);break;case"q":b=d[f++]+a,S=d[f++]+o,a+=d[f++],o+=d[f++],h=l.Q,s.addData(h,b,S,a,o);break;case"T":g=a,m=o;var M=s.len(),I=s.data;i===l.Q&&(g+=a-I[M-4],m+=o-I[M-3]),a=d[f++],o=d[f++],h=l.Q,s.addData(h,g,m,a,o);break;case"t":g=a,m=o;var M=s.len(),I=s.data;i===l.Q&&(g+=a-I[M-4],m+=o-I[M-3]),a+=d[f++],o+=d[f++],h=l.Q,s.addData(h,g,m,a,o);break;case"A":v=d[f++],y=d[f++],_=d[f++],x=d[f++],w=d[f++],oi(b=a,S=o,a=d[f++],o=d[f++],x,w,v,y,_,h=l.A,s);break;case"a":v=d[f++],y=d[f++],_=d[f++],x=d[f++],w=d[f++],oi(b=a,S=o,a+=d[f++],o+=d[f++],x,w,v,y,_,h=l.A,s)}}"z"!==c&&"Z"!==c||(h=l.Z,s.addData(h)),i=h}return s.toStatic(),s}function li(t,e){var n=si(t);return e=e||{},e.buildPath=function(t){if(t.setData)t.setData(n.data),(e=t.getContext())&&t.rebuildPath(e);else{var e=t;n.rebuildPath(e)}},e.applyTransform=function(t){Bc(n,t),this.dirty(!0)},e}function hi(t,e){return new ai(li(t,e))}function ui(t,e){return ai.extend(li(t,e))}function ci(t,e,n,i,r,a,o){var s=.5*(n-t),l=.5*(i-e);return(2*(e-n)+s+l)*o+(-3*(e-n)-2*s-l)*a+s*r+e}function fi(t,e,n){var i=e.points,r=e.smooth;if(i&&i.length>=2){if(r&&"spline"!==r){var a=Kc(i,r,n,e.smoothConstraint);t.moveTo(i[0][0],i[0][1]);for(var o=i.length,s=0;s<(n?o:o-1);s++){var l=a[2*s],h=a[2*s+1],u=i[(s+1)%o];t.bezierCurveTo(l[0],l[1],h[0],h[1],u[0],u[1])}}else{"spline"===r&&(i=$c(i,n)),t.moveTo(i[0][0],i[0][1]);for(var s=1,c=i.length;s<c;s++)t.lineTo(i[s][0],i[s][1])}n&&t.closePath()}}function di(t,e,n){var i=t.cpx2,r=t.cpy2;return null===i||null===r?[(n?An:kn)(t.x1,t.cpx1,t.cpx2,t.x2,e),(n?An:kn)(t.y1,t.cpy1,t.cpy2,t.y2,e)]:[(n?Nn:Bn)(t.x1,t.cpx1,t.x2,e),(n?Nn:Bn)(t.y1,t.cpy1,t.y2,e)]}function pi(t){Ne.call(this,t),this._displayables=[],this._temporaryDisplayables=[],this._cursor=0,this.notClear=!0}function gi(t){return ai.extend(t)}function mi(t,e,n,i){var r=hi(t,e),a=r.getBoundingRect();return n&&("center"===i&&(n=yi(n,a)),_i(r,n)),r}function vi(t,e,n){var i=new Re({style:{image:t,x:e.x,y:e.y,width:e.width,height:e.height},onload:function(t){if("center"===n){var r={width:t.width,height:t.height};i.setStyle(yi(e,r))}}});return i}function yi(t,e){var n,i=e.width/e.height,r=t.height*i;return n=r<=t.width?t.height:(r=t.width)/i,{x:t.x+t.width/2-r/2,y:t.y+t.height/2-n/2,width:r,height:n}}function _i(t,e){if(t.applyTransform){var n=t.getBoundingRect().calculateTransform(e);t.applyTransform(n)}}function xi(t){var e=t.shape,n=t.style.lineWidth;return cf(2*e.x1)===cf(2*e.x2)&&(e.x1=e.x2=wi(e.x1,n,!0)),cf(2*e.y1)===cf(2*e.y2)&&(e.y1=e.y2=wi(e.y1,n,!0)),t}function wi(t,e,n){var i=cf(2*t);return(i+cf(e))%2==0?i/2:(i+(n?1:-1))/2}function bi(t){return null!=t&&"none"!=t}function Si(t){return"string"==typeof t?wt(t,-.1):t}function Mi(t){if(t.__hoverStlDirty){var e=t.style.stroke,n=t.style.fill,i=t.__hoverStl;i.fill=i.fill||(bi(n)?Si(n):null),i.stroke=i.stroke||(bi(e)?Si(e):null);var r={};for(var a in i)null!=i[a]&&(r[a]=t.style[a]);t.__normalStl=r,t.__hoverStlDirty=!1}}function Ii(t){if(!t.__isHover){if(Mi(t),t.useHoverLayer)t.__zr&&t.__zr.addHover(t,t.__hoverStl);else{var e=t.style,n=e.insideRollbackOpt;n&&Hi(e),e.extendFrom(t.__hoverStl),n&&(Wi(e,e.insideOriginalTextPosition,n),null==e.textFill&&(e.textFill=n.autoColor)),t.dirty(!1),t.z2+=1}t.__isHover=!0}}function Ti(t){if(t.__isHover){var e=t.__normalStl;t.useHoverLayer?t.__zr&&t.__zr.removeHover(t):(e&&t.setStyle(e),t.z2-=1),t.__isHover=!1}}function Ci(t){"group"===t.type?t.traverse(function(t){"group"!==t.type&&Ii(t)}):Ii(t)}function Di(t){"group"===t.type?t.traverse(function(t){"group"!==t.type&&Ti(t)}):Ti(t)}function ki(t,e){t.__hoverStl=t.hoverStyle||e||{},t.__hoverStlDirty=!0,t.__isHover&&Mi(t)}function Ai(t){this.__hoverSilentOnTouch&&t.zrByTouch||!this.__isEmphasis&&Ci(this)}function Li(t){this.__hoverSilentOnTouch&&t.zrByTouch||!this.__isEmphasis&&Di(this)}function Pi(){this.__isEmphasis=!0,Ci(this)}function Oi(){this.__isEmphasis=!1,Di(this)}function Ei(t,e,n){t.__hoverSilentOnTouch=n&&n.hoverSilentOnTouch,"group"===t.type?t.traverse(function(t){"group"!==t.type&&ki(t,e)}):ki(t,e),t.on("mouseover",Ai).on("mouseout",Li),t.on("emphasis",Pi).on("normal",Oi)}function Bi(t,e,n,i,r,a,o){var s,l=(r=r||pf).labelFetcher,h=r.labelDataIndex,u=r.labelDimIndex,c=n.getShallow("show"),f=i.getShallow("show");(c||f)&&(l&&(s=l.getFormattedLabel(h,"normal",null,u)),null==s&&(s=_(r.defaultText)?r.defaultText(h,r):r.defaultText));var d=c?s:null,p=f?C(l?l.getFormattedLabel(h,"emphasis",null,u):null,s):null;null==d&&null==p||(Ni(t,n,a,r),Ni(e,i,o,r,!0)),t.text=d,e.text=p}function Ni(t,e,n,i,r){return Ri(t,e,i,r),n&&a(t,n),t.host&&t.host.dirty&&t.host.dirty(!1),t}function Ri(t,e,n,i){if((n=n||pf).isRectText){var r=e.getShallow("position")||(i?null:"inside");"outside"===r&&(r="top"),t.textPosition=r,t.textOffset=e.getShallow("offset");var a=e.getShallow("rotate");null!=a&&(a*=Math.PI/180),t.textRotation=a,t.textDistance=C(e.getShallow("distance"),i?null:5)}var o,s=e.ecModel,l=s&&s.option.textStyle,h=zi(e);if(h){o={};for(var u in h)if(h.hasOwnProperty(u)){var c=e.getModel(["rich",u]);Fi(o[u]={},c,l,n,i)}}return t.rich=o,Fi(t,e,l,n,i,!0),n.forceRich&&!n.textStyle&&(n.textStyle={}),t}function zi(t){for(var e;t&&t!==t.ecModel;){var n=(t.option||pf).rich;if(n){e=e||{};for(var i in n)n.hasOwnProperty(i)&&(e[i]=1)}t=t.parentModel}return e}function Fi(t,e,n,i,r,a){if(n=!r&&n||pf,t.textFill=Vi(e.getShallow("color"),i)||n.color,t.textStroke=Vi(e.getShallow("textBorderColor"),i)||n.textBorderColor,t.textStrokeWidth=C(e.getShallow("textBorderWidth"),n.textBorderWidth),!r){if(a){var o=t.textPosition;t.insideRollback=Wi(t,o,i),t.insideOriginalTextPosition=o,t.insideRollbackOpt=i}null==t.textFill&&(t.textFill=i.autoColor)}t.fontStyle=e.getShallow("fontStyle")||n.fontStyle,t.fontWeight=e.getShallow("fontWeight")||n.fontWeight,t.fontSize=e.getShallow("fontSize")||n.fontSize,t.fontFamily=e.getShallow("fontFamily")||n.fontFamily,t.textAlign=e.getShallow("align"),t.textVerticalAlign=e.getShallow("verticalAlign")||e.getShallow("baseline"),t.textLineHeight=e.getShallow("lineHeight"),t.textWidth=e.getShallow("width"),t.textHeight=e.getShallow("height"),t.textTag=e.getShallow("tag"),a&&i.disableBox||(t.textBackgroundColor=Vi(e.getShallow("backgroundColor"),i),t.textPadding=e.getShallow("padding"),t.textBorderColor=Vi(e.getShallow("borderColor"),i),t.textBorderWidth=e.getShallow("borderWidth"),t.textBorderRadius=e.getShallow("borderRadius"),t.textBoxShadowColor=e.getShallow("shadowColor"),t.textBoxShadowBlur=e.getShallow("shadowBlur"),t.textBoxShadowOffsetX=e.getShallow("shadowOffsetX"),t.textBoxShadowOffsetY=e.getShallow("shadowOffsetY")),t.textShadowColor=e.getShallow("textShadowColor")||n.textShadowColor,t.textShadowBlur=e.getShallow("textShadowBlur")||n.textShadowBlur,t.textShadowOffsetX=e.getShallow("textShadowOffsetX")||n.textShadowOffsetX,t.textShadowOffsetY=e.getShallow("textShadowOffsetY")||n.textShadowOffsetY}function Vi(t,e){return"auto"!==t?t:e&&e.autoColor?e.autoColor:null}function Wi(t,e,n){var i,r=n.useInsideStyle;return null==t.textFill&&!1!==r&&(!0===r||n.isRectText&&e&&"string"==typeof e&&e.indexOf("inside")>=0)&&(i={textFill:null,textStroke:t.textStroke,textStrokeWidth:t.textStrokeWidth},t.textFill="#fff",null==t.textStroke&&(t.textStroke=n.autoColor,null==t.textStrokeWidth&&(t.textStrokeWidth=2))),i}function Hi(t){var e=t.insideRollback;e&&(t.textFill=e.textFill,t.textStroke=e.textStroke,t.textStrokeWidth=e.textStrokeWidth)}function Gi(t,e){var n=e||e.getModel("textStyle");return P([t.fontStyle||n&&n.getShallow("fontStyle")||"",t.fontWeight||n&&n.getShallow("fontWeight")||"",(t.fontSize||n&&n.getShallow("fontSize")||12)+"px",t.fontFamily||n&&n.getShallow("fontFamily")||"sans-serif"].join(" "))}function qi(t,e,n,i,r,a){if("function"==typeof r&&(a=r,r=null),i&&i.isAnimationEnabled()){var o=t?"Update":"",s=i.getShallow("animationDuration"+o),l=i.getShallow("animationEasing"+o),h=i.getShallow("animationDelay"+o);"function"==typeof h&&(h=h(r,i.getAnimationDelayParams?i.getAnimationDelayParams(e,r):null)),"function"==typeof s&&(s=s(r)),s>0?e.animateTo(n,s,h||0,l,a,!!a):(e.stopAnimation(),e.attr(n),a&&a())}else e.stopAnimation(),e.attr(n),a&&a()}function Xi(t,e,n,i,r){qi(!0,t,e,n,i,r)}function Ui(t,e,n,i,r){qi(!1,t,e,n,i,r)}function Yi(t,e,n){return e&&!c(e)&&(e=yh.getLocalTransform(e)),n&&(e=lt([],e)),Y([],t,e)}function Zi(t,e,n,i){function r(t){var e={position:F(t.position),rotation:t.rotation};return t.shape&&(e.shape=a({},t.shape)),e}if(t&&e){var o=function(t){var e={};return t.traverse(function(t){!t.isGroup&&t.anid&&(e[t.anid]=t)}),e}(t);e.traverse(function(t){if(!t.isGroup&&t.anid){var e=o[t.anid];if(e){var i=r(t);t.attr(r(e)),Xi(t,i,n,t.dataIndex)}}})}}function ji(t,e,n){this.parentModel=e,this.ecModel=n,this.option=t}function $i(t,e,n){for(var i=0;i<e.length&&(!e[i]||null!=(t=t&&"object"==typeof t?t[e[i]]:null));i++);return null==t&&n&&(t=n.get(e)),t}function Ki(t,e){var n=wf(t).getParent;return n?n.call(t,e):t.parentModel}function Qi(t){return[t||"",bf++,Math.random().toFixed(5)].join("_")}function Ji(t){return t.replace(/^\s+/,"").replace(/\s+$/,"")}function tr(t,e,n,i){var r=e[1]-e[0],a=n[1]-n[0];if(0===r)return 0===a?n[0]:(n[0]+n[1])/2;if(i)if(r>0){if(t<=e[0])return n[0];if(t>=e[1])return n[1]}else{if(t>=e[0])return n[0];if(t<=e[1])return n[1]}else{if(t===e[0])return n[0];if(t===e[1])return n[1]}return(t-e[0])/r*a+n[0]}function er(t,e){switch(t){case"center":case"middle":t="50%";break;case"left":case"top":t="0%";break;case"right":case"bottom":t="100%"}return"string"==typeof t?Ji(t).match(/%$/)?parseFloat(t)/100*e:parseFloat(t):null==t?NaN:+t}function nr(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function ir(t){var e=t.toString(),n=e.indexOf("e");if(n>0){var i=+e.slice(n+1);return i<0?-i:0}var r=e.indexOf(".");return r<0?0:e.length-1-r}function rr(t,e){var n=Math.log,i=Math.LN10,r=Math.floor(n(t[1]-t[0])/i),a=Math.round(n(Math.abs(e[1]-e[0]))/i),o=Math.min(Math.max(-r+a,0),20);return isFinite(o)?o:20}function ar(t,e,n){if(!t[e])return 0;var i=p(t,function(t,e){return t+(isNaN(e)?0:e)},0);if(0===i)return 0;for(var r=Math.pow(10,n),a=d(t,function(t){return(isNaN(t)?0:t)/i*r*100}),o=100*r,s=d(a,function(t){return Math.floor(t)}),l=p(s,function(t,e){return t+e},0),h=d(a,function(t,e){return t-s[e]});l<o;){for(var u=Number.NEGATIVE_INFINITY,c=null,f=0,g=h.length;f<g;++f)h[f]>u&&(u=h[f],c=f);++s[c],h[c]=0,++l}return s[e]/r}function or(t){var e=2*Math.PI;return(t%e+e)%e}function sr(t){return t>-Sf&&t<Sf}function lr(t){if(t instanceof Date)return t;if("string"==typeof t){var e=Mf.exec(t);if(!e)return new Date(NaN);if(e[8]){var n=+e[4]||0;return"Z"!==e[8].toUpperCase()&&(n-=e[8].slice(0,3)),new Date(Date.UTC(+e[1],+(e[2]||1)-1,+e[3]||1,n,+(e[5]||0),+e[6]||0,+e[7]||0))}return new Date(+e[1],+(e[2]||1)-1,+e[3]||1,+e[4]||0,+(e[5]||0),+e[6]||0,+e[7]||0)}return null==t?new Date(NaN):new Date(Math.round(t))}function hr(t){return Math.pow(10,ur(t))}function ur(t){return Math.floor(Math.log(t)/Math.LN10)}function cr(t,e){var n,i=ur(t),r=Math.pow(10,i),a=t/r;return n=e?a<1.5?1:a<2.5?2:a<4?3:a<7?5:10:a<1?1:a<2?2:a<3?3:a<5?5:10,t=n*r,i>=-20?+t.toFixed(i<0?-i:0):t}function fr(t){return isNaN(t)?"-":(t=(t+"").split("."))[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(t.length>1?"."+t[1]:"")}function dr(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function pr(t,e,n){y(e)||(e=[e]);var i=e.length;if(!i)return"";for(var r=e[0].$vars||[],a=0;a<r.length;a++){var o=Tf[a];t=t.replace(Cf(o),Cf(o,0))}for(var s=0;s<i;s++)for(var l=0;l<r.length;l++){var h=e[s][r[l]];t=t.replace(Cf(Tf[l],s),n?dr(h):h)}return t}function gr(t,e){var n=(t=x(t)?{color:t,extraCssText:e}:t||{}).color,i=t.type,e=t.extraCssText;return n?"subItem"===i?'<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;border-radius:4px;width:4px;height:4px;background-color:'+dr(n)+";"+(e||"")+'"></span>':'<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:'+dr(n)+";"+(e||"")+'"></span>':""}function mr(t,e){return t+="","0000".substr(0,e-t.length)+t}function vr(t,e,n){"week"!==t&&"month"!==t&&"quarter"!==t&&"half-year"!==t&&"year"!==t||(t="MM-dd\nyyyy");var i=lr(e),r=n?"UTC":"",a=i["get"+r+"FullYear"](),o=i["get"+r+"Month"]()+1,s=i["get"+r+"Date"](),l=i["get"+r+"Hours"](),h=i["get"+r+"Minutes"](),u=i["get"+r+"Seconds"](),c=i["get"+r+"Milliseconds"]();return t=t.replace("MM",mr(o,2)).replace("M",o).replace("yyyy",a).replace("yy",a%100).replace("dd",mr(s,2)).replace("d",s).replace("hh",mr(l,2)).replace("h",l).replace("mm",mr(h,2)).replace("m",h).replace("ss",mr(u,2)).replace("s",u).replace("SSS",mr(c,3))}function yr(t,e,n,i,r){var a=0,o=0;null==i&&(i=1/0),null==r&&(r=1/0);var s=0;e.eachChild(function(l,h){var u,c,f=l.position,d=l.getBoundingRect(),p=e.childAt(h+1),g=p&&p.getBoundingRect();if("horizontal"===t){var m=d.width+(g?-g.x+d.x:0);(u=a+m)>i||l.newline?(a=0,u=m,o+=s+n,s=d.height):s=Math.max(s,d.height)}else{var v=d.height+(g?-g.y+d.y:0);(c=o+v)>r||l.newline?(a+=s+n,o=0,c=v,s=d.width):s=Math.max(s,d.width)}l.newline||(f[0]=a,f[1]=o,"horizontal"===t?a=u+n:o=c+n)})}function _r(t,e,n){n=If(n||0);var i=e.width,r=e.height,a=er(t.left,i),o=er(t.top,r),s=er(t.right,i),l=er(t.bottom,r),h=er(t.width,i),u=er(t.height,r),c=n[2]+n[0],f=n[1]+n[3],d=t.aspect;switch(isNaN(h)&&(h=i-s-f-a),isNaN(u)&&(u=r-l-c-o),null!=d&&(isNaN(h)&&isNaN(u)&&(d>i/r?h=.8*i:u=.8*r),isNaN(h)&&(h=d*u),isNaN(u)&&(u=h/d)),isNaN(a)&&(a=i-s-h-f),isNaN(o)&&(o=r-l-u-c),t.left||t.right){case"center":a=i/2-h/2-n[3];break;case"right":a=i-h-f}switch(t.top||t.bottom){case"middle":case"center":o=r/2-u/2-n[0];break;case"bottom":o=r-u-c}a=a||0,o=o||0,isNaN(h)&&(h=i-f-a-(s||0)),isNaN(u)&&(u=r-c-o-(l||0));var p=new Nt(a+n[3],o+n[0],h,u);return p.margin=n,p}function xr(t,e,n){function i(n,i){var o={},l=0,h={},u=0;if(kf(n,function(e){h[e]=t[e]}),kf(n,function(t){r(e,t)&&(o[t]=h[t]=e[t]),a(o,t)&&l++,a(h,t)&&u++}),s[i])return a(e,n[1])?h[n[2]]=null:a(e,n[2])&&(h[n[1]]=null),h;if(2!==u&&l){if(l>=2)return o;for(var c=0;c<n.length;c++){var f=n[c];if(!r(o,f)&&r(t,f)){o[f]=t[f];break}}return o}return h}function r(t,e){return t.hasOwnProperty(e)}function a(t,e){return null!=t[e]&&"auto"!==t[e]}function o(t,e,n){kf(t,function(t){e[t]=n[t]})}!w(n)&&(n={});var s=n.ignoreSize;!y(s)&&(s=[s,s]);var l=i(Lf[0],0),h=i(Lf[1],1);o(Lf[0],t,l),o(Lf[1],t,h)}function wr(t){return br({},t)}function br(t,e){return e&&t&&kf(Af,function(n){e.hasOwnProperty(n)&&(t[n]=e[n])}),t}function Sr(t,e){for(var n=t.length,i=0;i<n;i++)if(t[i].length>e)return t[i];return t[n-1]}function Mr(t){var e=t.get("coordinateSystem"),n={coordSysName:e,coordSysDims:[],axisMap:N(),categoryAxisMap:N()},i=Ff[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}function Ir(t){return"category"===t.get("type")}function Tr(t){this.fromDataset=t.fromDataset,this.data=t.data||(t.sourceFormat===Gf?{}:[]),this.sourceFormat=t.sourceFormat||qf,this.seriesLayoutBy=t.seriesLayoutBy||Uf,this.dimensionsDefine=t.dimensionsDefine,this.encodeDefine=t.encodeDefine&&N(t.encodeDefine),this.startIndex=t.startIndex||0,this.dimensionsDetectCount=t.dimensionsDetectCount}function Cr(t){var e=t.option.source,n=qf;if(S(e))n=Xf;else if(y(e))for(var i=0,r=e.length;i<r;i++){var a=e[i];if(null!=a){if(y(a)){n=Wf;break}if(w(a)){n=Hf;break}}}else if(w(e)){for(var o in e)if(e.hasOwnProperty(o)&&c(e[o])){n=Gf;break}}else if(null!=e)throw new Error("Invalid data");Zf(t).sourceFormat=n}function Dr(t){return Zf(t).source}function kr(t){Zf(t).datasetMap=N()}function Ar(t){var e=t.option,n=e.data,i=S(n)?Xf:Vf,r=!1,a=e.seriesLayoutBy,o=e.sourceHeader,s=e.dimensions,l=Nr(t);if(l){var h=l.option;n=h.source,i=Zf(l).sourceFormat,r=!0,a=a||h.seriesLayoutBy,null==o&&(o=h.sourceHeader),s=s||h.dimensions}var u=Lr(n,i,a,o,s),c=e.encode;!c&&l&&(c=Br(t,l,n,i,a,u)),Zf(t).source=new Tr({data:n,fromDataset:r,seriesLayoutBy:a,sourceFormat:i,dimensionsDefine:u.dimensionsDefine,startIndex:u.startIndex,dimensionsDetectCount:u.dimensionsDetectCount,encodeDefine:c})}function Lr(t,e,n,i,r){if(!t)return{dimensionsDefine:Pr(r)};var a,o,s;if(e===Wf)"auto"===i||null==i?Or(function(t){null!=t&&"-"!==t&&(x(t)?null==o&&(o=1):o=0)},n,t,10):o=i?1:0,r||1!==o||(r=[],Or(function(t,e){r[e]=null!=t?t:""},n,t)),a=r?r.length:n===Yf?t.length:t[0]?t[0].length:null;else if(e===Hf)r||(r=Er(t),s=!0);else if(e===Gf)r||(r=[],s=!0,f(t,function(t,e){r.push(e)}));else if(e===Vf){var l=ln(t[0]);a=y(l)&&l.length||1}var h;return s&&f(r,function(t,e){"name"===(w(t)?t.name:t)&&(h=e)}),{startIndex:o,dimensionsDefine:Pr(r),dimensionsDetectCount:a,potentialNameDimIndex:h}}function Pr(t){if(t){var e=N();return d(t,function(t,n){if(null==(t=a({},w(t)?t:{name:t})).name)return t;t.name+="",null==t.displayName&&(t.displayName=t.name);var i=e.get(t.name);return i?t.name+="-"+i.count++:e.set(t.name,{count:1}),t})}}function Or(t,e,n,i){if(null==i&&(i=1/0),e===Yf)for(a=0;a<n.length&&a<i;a++)t(n[a]?n[a][0]:null,a);else for(var r=n[0]||[],a=0;a<r.length&&a<i;a++)t(r[a],a)}function Er(t){for(var e,n=0;n<t.length&&!(e=t[n++]););if(e){var i=[];return f(e,function(t,e){i.push(e)}),i}}function Br(t,e,n,i,r,a){var o=Mr(t),s={},l=[],h=[],u=t.subType,c=N(["pie","map","funnel"]),d=N(["line","bar","pictorialBar","scatter","effectScatter","candlestick","boxplot"]);if(o&&null!=d.get(u)){var p=t.ecModel,g=Zf(p).datasetMap,m=e.uid+"_"+r,v=g.get(m)||g.set(m,{categoryWayDim:1,valueWayDim:0});f(o.coordSysDims,function(t){if(null==o.firstCategoryDimIndex){e=v.valueWayDim++;s[t]=e,h.push(e)}else if(o.categoryAxisMap.get(t))s[t]=0,l.push(0);else{var e=v.categoryWayDim++;s[t]=e,h.push(e)}})}else if(null!=c.get(u)){for(var y,_=0;_<5&&null==y;_++)zr(n,i,r,a.dimensionsDefine,a.startIndex,_)||(y=_);if(null!=y){s.value=y;var x=a.potentialNameDimIndex||Math.max(y-1,0);h.push(x),l.push(x)}}return l.length&&(s.itemName=l),h.length&&(s.seriesName=h),s}function Nr(t){var e=t.option;if(!e.data)return t.ecModel.getComponent("dataset",e.datasetIndex||0)}function Rr(t,e){return zr(t.data,t.sourceFormat,t.seriesLayoutBy,t.dimensionsDefine,t.startIndex,e)}function zr(t,e,n,i,r,a){function o(t){return(null==t||!isFinite(t)||""===t)&&(!(!x(t)||"-"===t)||void 0)}var s;if(S(t))return!1;var l;if(i&&(l=w(l=i[a])?l.name:l),e===Wf)if(n===Yf){for(var h=t[a],u=0;u<(h||[]).length&&u<5;u++)if(null!=(s=o(h[r+u])))return s}else for(u=0;u<t.length&&u<5;u++){var c=t[r+u];if(c&&null!=(s=o(c[a])))return s}else if(e===Hf){if(!l)return;for(u=0;u<t.length&&u<5;u++)if((f=t[u])&&null!=(s=o(f[l])))return s}else if(e===Gf){if(!l)return;if(!(h=t[l])||S(h))return!1;for(u=0;u<h.length&&u<5;u++)if(null!=(s=o(h[u])))return s}else if(e===Vf)for(u=0;u<t.length&&u<5;u++){var f=t[u],d=ln(f);if(!y(d))return!1;if(null!=(s=o(d[a])))return s}return!1}function Fr(t,e){if(e){var n=e.seiresIndex,i=e.seriesId,r=e.seriesName;return null!=n&&t.componentIndex!==n||null!=i&&t.id!==i||null!=r&&t.name!==r}}function Vr(t,e){var r=t.color&&!t.colorLayer;f(e,function(e,a){"colorLayer"===a&&r||Ef.hasClass(a)||("object"==typeof e?t[a]=t[a]?i(t[a],e,!1):n(e):null==t[a]&&(t[a]=e))})}function Wr(t){t=t,this.option={},this.option[jf]=1,this._componentsMap=N({series:[]}),this._seriesIndices,this._seriesIndicesMap,Vr(t,this._theme.option),i(t,Nf,!1),this.mergeOption(t)}function Hr(t,e){y(e)||(e=e?[e]:[]);var n={};return f(e,function(e){n[e]=(t.get(e)||[]).slice()}),n}function Gr(t,e,n){return e.type?e.type:n?n.subType:Ef.determineSubType(t,e)}function qr(t,e){t._seriesIndicesMap=N(t._seriesIndices=d(e,function(t){return t.componentIndex})||[])}function Xr(t,e){return e.hasOwnProperty("subType")?g(t,function(t){return t.subType===e.subType}):t}function Ur(t){f(Kf,function(e){this[e]=m(t[e],t)},this)}function Yr(){this._coordinateSystems=[]}function Zr(t){this._api=t,this._timelineOptions=[],this._mediaList=[],this._mediaDefault,this._currentMediaIndices=[],this._optionBackup,this._newBaseOption}function jr(t,e,n){var i,r,a=[],o=[],s=t.timeline;if(t.baseOption&&(r=t.baseOption),(s||t.options)&&(r=r||{},a=(t.options||[]).slice()),t.media){r=r||{};var l=t.media;Jf(l,function(t){t&&t.option&&(t.query?o.push(t):i||(i=t))})}return r||(r=t),r.timeline||(r.timeline=s),Jf([r].concat(a).concat(d(o,function(t){return t.option})),function(t){Jf(e,function(e){e(t,n)})}),{baseOption:r,timelineOptions:a,mediaDefault:i,mediaList:o}}function $r(t,e,n){var i={width:e,height:n,aspectratio:e/n},r=!0;return f(t,function(t,e){var n=e.match(id);if(n&&n[1]&&n[2]){var a=n[1],o=n[2].toLowerCase();Kr(i[o],t,a)||(r=!1)}}),r}function Kr(t,e,n){return"min"===n?t>=e:"max"===n?t<=e:t===e}function Qr(t,e){return t.join(",")===e.join(",")}function Jr(t,e){Jf(e=e||{},function(e,n){if(null!=e){var i=t[n];if(Ef.hasClass(n)){e=on(e);var r=un(i=on(i),e);t[n]=ed(r,function(t){return t.option&&t.exist?nd(t.exist,t.option,!0):t.exist||t.option})}else t[n]=nd(i,e,!0)}})}function ta(t){var e=t&&t.itemStyle;if(e)for(var n=0,r=od.length;n<r;n++){var a=od[n],o=e.normal,s=e.emphasis;o&&o[a]&&(t[a]=t[a]||{},t[a].normal?i(t[a].normal,o[a]):t[a].normal=o[a],o[a]=null),s&&s[a]&&(t[a]=t[a]||{},t[a].emphasis?i(t[a].emphasis,s[a]):t[a].emphasis=s[a],s[a]=null)}}function ea(t,e,n){if(t&&t[e]&&(t[e].normal||t[e].emphasis)){var i=t[e].normal,r=t[e].emphasis;i&&(n?(t[e].normal=t[e].emphasis=null,o(t[e],i)):t[e]=i),r&&(t.emphasis=t.emphasis||{},t.emphasis[e]=r)}}function na(t){ea(t,"itemStyle"),ea(t,"lineStyle"),ea(t,"areaStyle"),ea(t,"label"),ea(t,"labelLine"),ea(t,"upperLabel"),ea(t,"edgeLabel")}function ia(t,e){var n=ad(t)&&t[e],i=ad(n)&&n.textStyle;if(i)for(var r=0,a=Ou.length;r<a;r++){var e=Ou[r];i.hasOwnProperty(e)&&(n[e]=i[e])}}function ra(t){t&&(na(t),ia(t,"label"),t.emphasis&&ia(t.emphasis,"label"))}function aa(t){if(ad(t)){ta(t),na(t),ia(t,"label"),ia(t,"upperLabel"),ia(t,"edgeLabel"),t.emphasis&&(ia(t.emphasis,"label"),ia(t.emphasis,"upperLabel"),ia(t.emphasis,"edgeLabel"));var e=t.markPoint;e&&(ta(e),ra(e));var n=t.markLine;n&&(ta(n),ra(n));var i=t.markArea;i&&ra(i);var r=t.data;if("graph"===t.type){r=r||t.nodes;var a=t.links||t.edges;if(a&&!S(a))for(s=0;s<a.length;s++)ra(a[s]);f(t.categories,function(t){na(t)})}if(r&&!S(r))for(s=0;s<r.length;s++)ra(r[s]);if((e=t.markPoint)&&e.data)for(var o=e.data,s=0;s<o.length;s++)ra(o[s]);if((n=t.markLine)&&n.data)for(var l=n.data,s=0;s<l.length;s++)y(l[s])?(ra(l[s][0]),ra(l[s][1])):ra(l[s]);"gauge"===t.type?(ia(t,"axisLabel"),ia(t,"title"),ia(t,"detail")):"treemap"===t.type&&(ea(t.breadcrumb,"itemStyle"),f(t.levels,function(t){na(t)}))}}function oa(t){return y(t)?t:t?[t]:[]}function sa(t){return(y(t)?t[0]:t)||{}}function la(t,e){e=e.split(",");for(var n=t,i=0;i<e.length&&null!=(n=n&&n[e[i]]);i++);return n}function ha(t,e,n,i){e=e.split(",");for(var r,a=t,o=0;o<e.length-1;o++)null==a[r=e[o]]&&(a[r]={}),a=a[r];(i||null==a[e[o]])&&(a[e[o]]=n)}function ua(t){f(ld,function(e){e[0]in t&&!(e[1]in t)&&(t[e[1]]=t[e[0]])})}function ca(t){f(t,function(e,n){var i=[],r=[NaN,NaN],a=[e.stackResultDimension,e.stackedOverDimension],o=e.data,s=e.isStackedByIndex,l=o.map(a,function(a,l,h){var u=o.get(e.stackedDimension,h);if(isNaN(u))return r;var c,f;s?f=o.getRawIndex(h):c=o.get(e.stackedByDimension,h);for(var d=NaN,p=n-1;p>=0;p--){var g=t[p];if(s||(f=g.data.rawIndexOf(g.stackedByDimension,c)),f>=0){var m=g.data.getByRawIndex(g.stackResultDimension,f);if(u>=0&&m>0||u<=0&&m<0){u+=m,d=m;break}}}return i[0]=u,i[1]=d,i});o.hostModel.setData(l),e.data=l})}function fa(t,e){Tr.isInstance(t)||(t=Tr.seriesDataToSource(t)),this._source=t;var n=this._data=t.data,i=t.sourceFormat;i===Xf&&(this._offset=0,this._dimSize=e,this._data=n),a(this,fd[i===Wf?i+"_"+t.seriesLayoutBy:i])}function da(){return this._data.length}function pa(t){return this._data[t]}function ga(t){for(var e=0;e<t.length;e++)this._data.push(t[e])}function ma(t,e,n,i){return null!=n?t[n]:t}function va(t,e,n,i){return ya(t[i],this._dimensionInfos[e])}function ya(t,e){var n=e&&e.type;if("ordinal"===n){var i=e&&e.ordinalMeta;return i?i.parseAndCollect(t):t}return"time"===n&&"number"!=typeof t&&null!=t&&"-"!==t&&(t=+lr(t)),null==t||""===t?NaN:+t}function _a(t,e,n){if(t){var i=t.getRawDataItem(e);if(null!=i){var r,a,o=t.getProvider().getSource().sourceFormat,s=t.getDimensionInfo(n);return s&&(r=s.name,a=s.index),dd[o](i,e,a,r)}}}function xa(t,e,n){if(t){var i=t.getProvider().getSource().sourceFormat;if(i===Vf||i===Hf){var r=t.getRawDataItem(e);return i!==Vf||w(r)||(r=null),r?r[n]:void 0}}}function wa(t){return new ba(t)}function ba(t){t=t||{},this._reset=t.reset,this._plan=t.plan,this._count=t.count,this._onDirty=t.onDirty,this._dirty=!0,this.context}function Sa(t,e){t._dueIndex=t._outputDueEnd=t._dueEnd=0,t._settedOutputEnd=null;var n,i;!e&&t._reset&&(n=t._reset(t.context))&&n.progress&&(i=n.forceFirstProgress,n=n.progress),t._progress=n;var r=t._downstream;return r&&r.dirty(),i}function Ma(t){var e=t.name;fn(t)||(t.name=Ia(t)||e)}function Ia(t){var e=t.getRawData(),n=[];return f(e.mapDimension("seriesName",!0),function(t){var i=e.getDimensionInfo(t);i.displayName&&n.push(i.displayName)}),n.join(" ")}function Ta(t){return t.model.getRawData().count()}function Ca(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),Da}function Da(t,e){t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function ka(t,e){f(t.CHANGABLE_METHODS,function(n){t.wrapMethod(n,v(Aa,e))})}function Aa(t){var e=La(t);e&&e.setOutputEnd(this.count())}function La(t){var e=(t.ecModel||{}).scheduler,n=e&&e.getPipeline(t.uid);if(n){var i=n.currentTask;if(i){var r=i.agentStubMap;r&&(i=r.get(t.uid))}return i}}function Pa(){this.group=new Wh,this.uid=Qi("viewChart"),this.renderTask=wa({plan:Ba,reset:Na}),this.renderTask.context={view:this}}function Oa(t,e){if(t&&(t.trigger(e),"group"===t.type))for(var n=0;n<t.childCount();n++)Oa(t.childAt(n),e)}function Ea(t,e,n){var i=pn(t,e);null!=i?f(on(i),function(e){Oa(t.getItemGraphicEl(e),n)}):t.eachItemGraphicEl(function(t){Oa(t,n)})}function Ba(t){return Md(t.model)}function Na(t){var e=t.model,n=t.ecModel,i=t.api,r=t.payload,a=e.pipelineContext.canProgressiveRender,o=t.view,s=r&&Sd(r).updateMethod,l=a?"incrementalPrepareRender":s&&o[s]?s:"render";return"render"!==l&&o[l](e,n,i,r),Td[l]}function Ra(t,e,n){function i(){u=(new Date).getTime(),c=null,t.apply(o,s||[])}var r,a,o,s,l,h=0,u=0,c=null;e=e||0;var f=function(){r=(new Date).getTime(),o=this,s=arguments;var t=l||e,f=l||n;l=null,a=r-(f?h:u)-t,clearTimeout(c),f?c=setTimeout(i,t):a>=0?i():c=setTimeout(i,-a),h=r};return f.clear=function(){c&&(clearTimeout(c),c=null)},f.debounceNextCall=function(t){l=t},f}function za(t,e,n,i){this.ecInstance=t,this.api=e,this.unfinished,this._dataProcessorHandlers=n.slice(),this._visualHandlers=i.slice(),this._stageTaskMap=N()}function Fa(t,e,n,i,r){function a(t,e){return t.setDirty&&(!t.dirtyMap||t.dirtyMap.get(e.__pipeline.id))}r=r||{};var o;f(e,function(e,s){if(!r.visualType||r.visualType===e.visualType){var l=t._stageTaskMap.get(e.uid),h=l.seriesTaskMap,u=l.overallTask;if(u){var c,f=u.agentStubMap;f.each(function(t){a(r,t)&&(t.dirty(),c=!0)}),c&&u.dirty(),Pd(u,i);var d=t.getPerformArgs(u,r.block);f.each(function(t){t.perform(d)}),o|=u.perform(d)}else h&&h.each(function(s,l){a(r,s)&&s.dirty();var h=t.getPerformArgs(s,r.block);h.skip=!e.performRawSeries&&n.isSeriesFiltered(s.context.model),Pd(s,i),o|=s.perform(h)})}}),t.unfinished|=o}function Va(t,e,n,i,r){function a(n){var a=n.uid,s=o.get(a)||o.set(a,wa({plan:Ua,reset:Ya,count:ja}));s.context={model:n,ecModel:i,api:r,useClearVisual:e.isVisual&&!e.isLayout,plan:e.plan,reset:e.reset,scheduler:t},$a(t,n,s)}var o=n.seriesTaskMap||(n.seriesTaskMap=N()),s=e.seriesType,l=e.getTargetSeries;e.createOnAllSeries?i.eachRawSeries(a):s?i.eachRawSeriesByType(s,a):l&&l(i,r).each(a);var h=t._pipelineMap;o.each(function(t,e){h.get(e)||(t.dispose(),o.removeKey(e))})}function Wa(t,e,n,i,r){function a(e){var n=e.uid,i=s.get(n)||s.set(n,wa({reset:Ga,onDirty:Xa}));i.context={model:e,overallProgress:u,isOverallFilter:c},i.agent=o,i.__block=u,$a(t,e,i)}var o=n.overallTask=n.overallTask||wa({reset:Ha});o.context={ecModel:i,api:r,overallReset:e.overallReset,scheduler:t};var s=o.agentStubMap=o.agentStubMap||N(),l=e.seriesType,h=e.getTargetSeries,u=!0,c=e.isOverallFilter;l?i.eachRawSeriesByType(l,a):h?h(i,r).each(a):(u=!1,f(i.getSeries(),a));var d=t._pipelineMap;s.each(function(t,e){d.get(e)||(t.dispose(),s.removeKey(e))})}function Ha(t){t.overallReset(t.ecModel,t.api,t.payload)}function Ga(t,e){return t.overallProgress&&qa}function qa(){this.agent.dirty(),this.getDownstream().dirty()}function Xa(){this.agent&&this.agent.dirty()}function Ua(t){return t.plan&&t.plan(t.model,t.ecModel,t.api,t.payload)}function Ya(t){if(t.useClearVisual&&t.data.clearAllVisual(),(t.resetDefines=on(t.reset(t.model,t.ecModel,t.api,t.payload))).length)return Za}function Za(t,e){for(var n=e.data,i=e.resetDefines,r=0;r<i.length;r++){var a=i[r];if(a&&a.dataEach)for(var o=t.start;o<t.end;o++)a.dataEach(n,o);else a&&a.progress&&a.progress(t,n)}}function ja(t){return t.data.count()}function $a(t,e,n){var i=e.uid,r=t._pipelineMap.get(i);!r.head&&(r.head=n),r.tail&&r.tail.pipe(n),r.tail=n,n.__idxInPipeline=r.count++,n.__pipeline=r}function Ka(t){Od=null;try{t(Ed,Bd)}catch(t){}return Od}function Qa(t,e){for(var n in e.prototype)t[n]=R}function Ja(t){return function(e,n,i){e=e&&e.toLowerCase(),ch.prototype[t].call(this,e,n,i)}}function to(){ch.call(this)}function eo(t,e,i){function r(t,e){return t.__prio-e.__prio}i=i||{},"string"==typeof e&&(e=lp[e]),this.id,this.group,this._dom=t;var a=this._zr=an(t,{renderer:i.renderer||"canvas",devicePixelRatio:i.devicePixelRatio,width:i.width,height:i.height});this._throttledZrFlush=Ra(m(a.flush,a),17),(e=n(e))&&ud(e,!0),this._theme=e,this._chartsViews=[],this._chartsMap={},this._componentsViews=[],this._componentsMap={},this._coordSysMgr=new Yr;var o=this._api=xo(this);qt(sp,r),qt(rp,r),this._scheduler=new za(this,o,rp,sp),ch.call(this),this._messageCenter=new to,this._initEvents(),this.resize=m(this.resize,this),this._pendingActions=[],a.animation.on("frame",this._onframe,this),ho(a,this),O(this)}function no(t,e,n){var i,r=this._model,a=this._coordSysMgr.getCoordinateSystems();e=mn(r,e);for(var o=0;o<a.length;o++){var s=a[o];if(s[t]&&null!=(i=s[t](r,e,n)))return i}}function io(t){var e=t._model,n=t._scheduler;n.restorePipelines(e),n.prepareStageTasks(),uo(t,"component",e,n),uo(t,"chart",e,n),n.plan()}function ro(t,e,n,i,r){function a(i){i&&i.__alive&&i[e]&&i[e](i.__model,o,t._api,n)}var o=t._model;if(i){var s={};s[i+"Id"]=n[i+"Id"],s[i+"Index"]=n[i+"Index"],s[i+"Name"]=n[i+"Name"];var l={mainType:i,query:s};r&&(l.subType=r),o&&o.eachComponent(l,function(e,n){a(t["series"===i?"_chartsMap":"_componentsMap"][e.__viewId])},t)}else Wd(t._componentsViews.concat(t._chartsViews),a)}function ao(t,e){var n=t._chartsMap,i=t._scheduler;e.eachSeries(function(t){i.updateStreamModes(t,n[t.__viewId])})}function oo(t,e){var n=t.type,i=t.escapeConnect,r=np[n],s=r.actionInfo,l=(s.update||"update").split(":"),h=l.pop();l=null!=l[0]&&qd(l[0]),this[$d]=!0;var u=[t],c=!1;t.batch&&(c=!0,u=d(t.batch,function(e){return e=o(a({},e),t),e.batch=null,e}));var f,p=[],g="highlight"===n||"downplay"===n;Wd(u,function(t){f=r.action(t,this._model,this._api),(f=f||a({},t)).type=s.event||f.type,p.push(f),g?ro(this,h,t,"series"):l&&ro(this,h,t,l.main,l.sub)},this),"none"===h||g||l||(this[Kd]?(io(this),tp.update.call(this,t),this[Kd]=!1):tp[h].call(this,t)),f=c?{type:s.event||n,escapeConnect:i,batch:p}:p[0],this[$d]=!1,!e&&this._messageCenter.trigger(f.type,f)}function so(t){for(var e=this._pendingActions;e.length;){var n=e.shift();oo.call(this,n,t)}}function lo(t){!t&&this.trigger("updated")}function ho(t,e){t.on("rendered",function(){e.trigger("rendered"),!t.animation.isFinished()||e[Kd]||e._scheduler.unfinished||e._pendingActions.length||e.trigger("finished")})}function uo(t,e,n,i){function r(t){var e="_ec_"+t.id+"_"+t.type,r=s[e];if(!r){var u=qd(t.type);(r=new(a?xd.getClass(u.main,u.sub):Pa.getClass(u.sub))).init(n,h),s[e]=r,o.push(r),l.add(r.group)}t.__viewId=r.__id=e,r.__alive=!0,r.__model=t,r.group.__ecComponentInfo={mainType:t.mainType,index:t.componentIndex},!a&&i.prepareView(r,t,n,h)}for(var a="component"===e,o=a?t._componentsViews:t._chartsViews,s=a?t._componentsMap:t._chartsMap,l=t._zr,h=t._api,u=0;u<o.length;u++)o[u].__alive=!1;a?n.eachComponent(function(t,e){"series"!==t&&r(e)}):n.eachSeries(r);for(u=0;u<o.length;){var c=o[u];c.__alive?u++:(!a&&c.renderTask.dispose(),l.remove(c.group),c.dispose(n,h),o.splice(u,1),delete s[c.__id],c.__id=c.group.__ecComponentInfo=null)}}function co(t){t.clearColorPalette(),t.eachSeries(function(t){t.clearColorPalette()})}function fo(t,e,n,i){po(t,e,n,i),Wd(t._chartsViews,function(t){t.__alive=!1}),go(t,e,n,i),Wd(t._chartsViews,function(t){t.__alive||t.remove(e,n)})}function po(t,e,n,i,r){Wd(r||t._componentsViews,function(t){var r=t.__model;t.render(r,e,n,i),_o(r,t)})}function go(t,e,n,i,r){var a,o=t._scheduler;e.eachSeries(function(e){var n=t._chartsMap[e.__viewId];n.__alive=!0;var s=n.renderTask;o.updatePayload(s,i),r&&r.get(e.uid)&&s.dirty(),a|=s.perform(o.getPerformArgs(s)),n.group.silent=!!e.get("silent"),_o(e,n),yo(e,n)}),o.unfinished|=a,vo(t._zr,e),kd(t._zr.dom,e)}function mo(t,e){Wd(op,function(n){n(t,e)})}function vo(t,e){var n=t.storage,i=0;n.traverse(function(t){t.isGroup||i++}),i>e.get("hoverLayerThreshold")&&!Yl.node&&n.traverse(function(t){t.isGroup||(t.useHoverLayer=!0)})}function yo(t,e){var n=t.get("blendMode")||null;e.group.traverse(function(t){t.isGroup||t.style.blend!==n&&t.setStyle("blend",n),t.eachPendingDisplayable&&t.eachPendingDisplayable(function(t){t.setStyle("blend",n)})})}function _o(t,e){var n=t.get("z"),i=t.get("zlevel");e.group.traverse(function(t){"group"!==t.type&&(null!=n&&(t.z=n),null!=i&&(t.zlevel=i))})}function xo(t){var e=t._coordSysMgr;return a(new Ur(t),{getCoordinateSystems:m(e.getCoordinateSystems,e),getComponentByElement:function(e){for(;e;){var n=e.__ecComponentInfo;if(null!=n)return t._model.getComponent(n.mainType,n.index);e=e.parent}}})}function wo(t){function e(t,e){for(var i=0;i<t.length;i++)t[i][n]=e}var n="__connectUpdateStatus";Wd(ip,function(i,r){t._messageCenter.on(r,function(i){if(cp[t.group]&&0!==t[n]){if(i&&i.escapeConnect)return;var r=t.makeActionFromEvent(i),a=[];Wd(up,function(e){e!==t&&e.group===t.group&&a.push(e)}),e(a,0),Wd(a,function(t){1!==t[n]&&t.dispatchAction(r)}),e(a,2)}})})}function bo(t){cp[t]=!1}function So(t){return up[_n(t,pp)]}function Mo(t,e){lp[t]=e}function Io(t){ap.push(t)}function To(t,e){Ao(rp,t,e,Ud)}function Co(t,e,n){"function"==typeof e&&(n=e,e="");var i=Gd(t)?t.type:[t,t={event:e}][0];t.event=(t.event||i).toLowerCase(),e=t.event,Vd(Qd.test(i)&&Qd.test(e)),np[i]||(np[i]={action:n,actionInfo:t}),ip[e]=i}function Do(t,e){Ao(sp,t,e,Yd,"layout")}function ko(t,e){Ao(sp,t,e,Zd,"visual")}function Ao(t,e,n,i,r){(Hd(e)||Gd(e))&&(n=e,e=i);var a=za.wrapStageHandler(n,r);return a.__prio=e,a.__raw=n,t.push(a),a}function Lo(t,e){hp[t]=e}function Po(t){return Ef.extend(t)}function Oo(t){return xd.extend(t)}function Eo(t){return _d.extend(t)}function Bo(t){return Pa.extend(t)}function No(t){return t}function Ro(t,e,n,i,r){this._old=t,this._new=e,this._oldKeyGetter=n||No,this._newKeyGetter=i||No,this.context=r}function zo(t,e,n,i,r){for(var a=0;a<t.length;a++){var o="_ec_"+r[i](t[a],a),s=e[o];null==s?(n.push(o),e[o]=a):(s.length||(e[o]=s=[s]),s.push(a))}}function Fo(t){var e={},n=e.encode={},i=N(),r=[];f(t.dimensions,function(e){var a=t.getDimensionInfo(e),o=a.coordDim;if(o){var s=n[o];n.hasOwnProperty(o)||(s=n[o]=[]),s[a.coordDimIndex]=e,a.isExtraCoord||(i.set(o,1),Wo(a.type)&&(r[0]=e))}yp.each(function(t,e){var i=n[e];n.hasOwnProperty(e)||(i=n[e]=[]);var r=a.otherDims[e];null!=r&&!1!==r&&(i[r]=a.name)})});var a=[],o={};i.each(function(t,e){var i=n[e];o[e]=i[0],a=a.concat(i)}),e.dataDimsOnCoord=a,e.encodeFirstDimNotExtra=o;var s=n.label;s&&s.length&&(r=s.slice());var l=r.slice(),h=n.tooltip;return h&&h.length&&(l=h.slice()),n.defaultedLabel=r,n.defaultedTooltip=l,e}function Vo(t){return"category"===t?"ordinal":"time"===t?"time":"float"}function Wo(t){return!("ordinal"===t||"time"===t)}function Ho(t){return t._rawCount>65535?Sp:Mp}function Go(t){var e=t.constructor;return e===Array?t.slice():new e(t)}function qo(t,e){f(Ip.concat(e.__wrappedMethods||[]),function(n){e.hasOwnProperty(n)&&(t[n]=e[n])}),t.__wrappedMethods=e.__wrappedMethods}function Xo(t){var e=t._invertedIndicesMap;f(e,function(n,i){var r=t._dimensionInfos[i].ordinalMeta;if(r){n=e[i]=new Sp(r.categories.length);for(a=0;a<n.length;a++)n[a]=NaN;for(var a=0;a<t._count;a++)n[t.get(i,a)]=a}})}function Uo(t){return t}function Yo(t){return t<this._count&&t>=0?this._indices[t]:-1}function Zo(t,e){var n=t._idList[e];return null==n&&(n=t._getIdFromStore(e)),null==n&&(n=wp+e),n}function jo(t){return y(t)||(t=[t]),t}function $o(t,e){var n=t.dimensions,i=new Tp(d(n,t.getDimensionInfo,t),t.hostModel);qo(i,t);for(var r=i._storage={},o=t._storage,s=a({},t._rawExtent),h=0;h<n.length;h++){var u=n[h];o[u]&&(l(e,u)>=0?(r[u]=Ko(o[u]),s[u]=Qo()):r[u]=o[u])}return i}function Ko(t){for(var e=new Array(t.length),n=0;n<t.length;n++)e[n]=Go(t[n]);return e}function Qo(){return[1/0,-1/0]}function Jo(t,e,i){function r(t,e,n){null!=yp.get(e)?t.otherDims[e]=n:(t.coordDim=e,t.coordDimIndex=n,u.set(e,!0))}Tr.isInstance(e)||(e=Tr.seriesDataToSource(e)),i=i||{},t=(t||[]).slice();for(var s=(i.dimsDef||[]).slice(),l=N(i.encodeDef),h=N(),u=N(),c=[],d=ts(e,t,s,i.dimCount),p=0;p<d;p++){var g=s[p]=a({},w(s[p])?s[p]:{name:s[p]}),m=g.name,v=c[p]={otherDims:{}};null!=m&&null==h.get(m)&&(v.name=v.displayName=m,h.set(m,p)),null!=g.type&&(v.type=g.type),null!=g.displayName&&(v.displayName=g.displayName)}l.each(function(t,e){t=on(t).slice();var n=l.set(e,[]);f(t,function(t,i){x(t)&&(t=h.get(t)),null!=t&&t<d&&(n[i]=t,r(c[t],e,i))})});var y=0;f(t,function(t,e){var i,t,a,s;if(x(t))i=t,t={};else{i=t.name;var h=t.ordinalMeta;t.ordinalMeta=null,(t=n(t)).ordinalMeta=h,a=t.dimsDef,s=t.otherDims,t.name=t.coordDim=t.coordDimIndex=t.dimsDef=t.otherDims=null}var u=on(l.get(i));if(!u.length)for(var d=0;d<(a&&a.length||1);d++){for(;y<c.length&&null!=c[y].coordDim;)y++;y<c.length&&u.push(y++)}f(u,function(e,n){var l=c[e];r(o(l,t),i,n),null==l.name&&a&&(l.name=l.displayName=a[n]),s&&o(l.otherDims,s)})});var _=i.generateCoord,b=i.generateCoordCount,S=null!=b;b=_?b||1:0;for(var M=_||"value",I=0;I<d;I++)null==(v=c[I]=c[I]||{}).coordDim&&(v.coordDim=es(M,u,S),v.coordDimIndex=0,(!_||b<=0)&&(v.isExtraCoord=!0),b--),null==v.name&&(v.name=es(v.coordDim,h)),null==v.type&&Rr(e,I,v.name)&&(v.type="ordinal");return c}function ts(t,e,n,i){var r=Math.max(t.dimensionsDetectCount||1,e.length,n.length,i||0);return f(e,function(t){var e=t.dimsDef;e&&(r=Math.max(r,e.length))}),r}function es(t,e,n){if(n||null!=e.get(t)){for(var i=0;null!=e.get(t+i);)i++;t+=i}return e.set(t,!0),t}function ns(t,e,n){var i,r,a,o,s=(n=n||{}).byIndex,l=n.stackedCoordDimension,h=!(!t||!t.get("stack"));if(f(e,function(t,n){x(t)&&(e[n]=t={name:t}),h&&!t.isExtraCoord&&(s||i||!t.ordinalMeta||(i=t),r||"ordinal"===t.type||"time"===t.type||l&&l!==t.coordDim||(r=t))}),r&&(s||i)){a="__\0ecstackresult",o="__\0ecstackedover",i&&(i.createInvertedIndices=!0);var u=r.coordDim,c=r.type,d=0;f(e,function(t){t.coordDim===u&&d++}),e.push({name:a,coordDim:u,coordDimIndex:d,type:c,isExtraCoord:!0,isCalculationCoord:!0}),d++,e.push({name:o,coordDim:o,coordDimIndex:d,type:c,isExtraCoord:!0,isCalculationCoord:!0})}return{stackedDimension:r&&r.name,stackedByDimension:i&&i.name,isStackedByIndex:s,stackedOverDimension:o,stackResultDimension:a}}function is(t,e,n){return e&&e===t.getCalculationInfo("stackedDimension")&&(null!=n?n===t.getCalculationInfo("stackedByDimension"):t.getCalculationInfo("isStackedByIndex"))}function rs(t,e,n){n=n||{},Tr.isInstance(t)||(t=Tr.seriesDataToSource(t));var i,r=e.get("coordinateSystem"),a=Yr.get(r),o=Mr(e);o&&(i=d(o.coordSysDims,function(t){var e={name:t},n=o.axisMap.get(t);if(n){var i=n.get("type");e.type=Vo(i)}return e})),i||(i=a&&(a.getDimensionsInfo?a.getDimensionsInfo():a.dimensions.slice())||["x","y"]);var s,l,h=kp(t,{coordDimensions:i,generateCoord:n.generateCoord});o&&f(h,function(t,e){var n=t.coordDim,i=o.categoryAxisMap.get(n);i&&(null==s&&(s=e),t.ordinalMeta=i.getOrdinalMeta()),null!=t.otherDims.itemName&&(l=!0)}),l||null==s||(h[s].otherDims.itemName=0);var u=ns(e,h),c=new Tp(h,e);c.setCalculationInfo(u);var p=null!=s&&as(t)?function(t,e,n,i){return i===s?n:this.defaultDimValueGetter(t,e,n,i)}:null;return c.hasItemOption=!1,c.initData(t,null,p),c}function as(t){if(t.sourceFormat===Vf){var e=os(t.data||[]);return null!=e&&!y(ln(e))}}function os(t){for(var e=0;e<t.length&&null==t[e];)e++;return t[e]}function ss(t,e){if("image"!==this.type){var n=this.style,i=this.shape;i&&"line"===i.symbolType?n.stroke=t:this.__isEmptyBrush?(n.stroke=t,n.fill=e||"#fff"):(n.fill&&(n.fill=t),n.stroke&&(n.stroke=t)),this.dirty(!1)}}function ls(t,e,n,i,r,a,o){var s=0===t.indexOf("empty");s&&(t=t.substr(5,1).toLowerCase()+t.substr(6));var l;return l=0===t.indexOf("image://")?vi(t.slice(8),new Nt(e,n,i,r),o?"center":"cover"):0===t.indexOf("path://")?mi(t.slice(7),{},new Nt(e,n,i,r),o?"center":"cover"):new Np({shape:{symbolType:t,x:e,y:n,width:i,height:r}}),l.__isEmptyBrush=s,l.setColor=ss,l.setColor(a),l}function hs(t,e){var n=t.mapDimension("defaultedLabel",!0),i=n.length;if(1===i)return _a(t,e,n[0]);if(i){for(var r=[],a=0;a<n.length;a++){var o=_a(t,e,n[a]);r.push(o)}return r.join(" ")}}function us(t,e){var n=t.getItemVisual(e,"symbolSize");return n instanceof Array?n.slice():[+n,+n]}function cs(t){return[t[0]/2,t[1]/2]}function fs(t,e,n){Wh.call(this),this.updateData(t,e,n)}function ds(t,e){this.parent.drift(t,e)}function ps(t){this.group=new Wh,this._symbolCtor=t||fs}function gs(t,e,n,i){return e&&!isNaN(e[0])&&!isNaN(e[1])&&!(i.isIgnore&&i.isIgnore(n))&&!(i.clipShape&&!i.clipShape.contain(e[0],e[1]))&&"none"!==t.getItemVisual(n,"symbol")}function ms(t){return null==t||w(t)||(t={isIgnore:t}),t||{}}function vs(t){var e=t.hostModel;return{itemStyle:e.getModel("itemStyle").getItemStyle(["color"]),hoverItemStyle:e.getModel("emphasis.itemStyle").getItemStyle(),symbolRotate:e.get("symbolRotate"),symbolOffset:e.get("symbolOffset"),hoverAnimation:e.get("hoverAnimation"),labelModel:e.getModel("label"),hoverLabelModel:e.getModel("emphasis.label"),cursorStyle:e.get("cursor")}}function ys(t,e,n){var i=t.getBaseAxis(),r=t.getOtherAxis(i),a=_s(r,n),o=i.dim,s=r.dim,l=e.mapDimension(s),h=e.mapDimension(o),u="x"===s||"radius"===s?1:0,c=is(e,l,h);return{dataDimsForPoint:d(t.dimensions,function(t){return e.mapDimension(t)}),valueStart:a,valueAxisDim:s,baseAxisDim:o,stacked:c,valueDim:l,baseDim:h,baseDataOffset:u,stackedOverDimension:e.getCalculationInfo("stackedOverDimension")}}function _s(t,e){var n=0,i=t.scale.getExtent();return"start"===e?n=i[0]:"end"===e?n=i[1]:i[0]>0?n=i[0]:i[1]<0&&(n=i[1]),n}function xs(t,e,n,i){var r=NaN;t.stacked&&(r=n.get(n.getCalculationInfo("stackedOverDimension"),i)),isNaN(r)&&(r=t.valueStart);var a=t.baseDataOffset,o=[];return o[a]=n.get(t.baseDim,i),o[1-a]=r,e.dataToPoint(o)}function ws(t,e){var n=[];return e.diff(t).add(function(t){n.push({cmd:"+",idx:t})}).update(function(t,e){n.push({cmd:"=",idx:e,idx1:t})}).remove(function(t){n.push({cmd:"-",idx:t})}).execute(),n}function bs(t){return isNaN(t[0])||isNaN(t[1])}function Ss(t,e,n,i,r,a,o,s,l,h,u){return null==h?Ms(e,"x")?Is(t,e,n,i,r,a,o,s,l,"x",u):Ms(e,"y")?Is(t,e,n,i,r,a,o,s,l,"y",u):Ts.apply(this,arguments):"none"!==h&&Ms(e,h)?Is.apply(this,arguments):Ts.apply(this,arguments)}function Ms(t,e){if(t.length<=1)return!0;for(var n="x"===e?0:1,i=t[0][n],r=0,a=1;a<t.length;++a){var o=t[a][n]-i;if(!isNaN(o)&&!isNaN(r)&&0!==o&&0!==r&&o>=0!=r>=0)return!1;isNaN(o)||0===o||(r=o,i=t[a][n])}return!0}function Is(t,e,n,i,r,a,o,s,l,h,u){for(var c=0,f=n,d=0;d<i;d++){var p=e[f];if(f>=r||f<0)break;if(bs(p)){if(u){f+=a;continue}break}if(f===n)t[a>0?"moveTo":"lineTo"](p[0],p[1]);else if(l>0){var g=e[c],m="y"===h?1:0,v=(p[m]-g[m])*l;Yp(jp,g),jp[m]=g[m]+v,Yp($p,p),$p[m]=p[m]-v,t.bezierCurveTo(jp[0],jp[1],$p[0],$p[1],p[0],p[1])}else t.lineTo(p[0],p[1]);c=f,f+=a}return d}function Ts(t,e,n,i,r,a,o,s,l,h,u){for(var c=0,f=n,d=0;d<i;d++){var p=e[f];if(f>=r||f<0)break;if(bs(p)){if(u){f+=a;continue}break}if(f===n)t[a>0?"moveTo":"lineTo"](p[0],p[1]),Yp(jp,p);else if(l>0){var g=f+a,m=e[g];if(u)for(;m&&bs(e[g]);)m=e[g+=a];var v=.5,y=e[c];if(!(m=e[g])||bs(m))Yp($p,p);else{bs(m)&&!u&&(m=p),W(Zp,m,y);var _,x;if("x"===h||"y"===h){var w="x"===h?0:1;_=Math.abs(p[w]-y[w]),x=Math.abs(p[w]-m[w])}else _=lh(p,y),x=lh(p,m);Up($p,p,Zp,-l*(1-(v=x/(x+_))))}qp(jp,jp,s),Xp(jp,jp,o),qp($p,$p,s),Xp($p,$p,o),t.bezierCurveTo(jp[0],jp[1],$p[0],$p[1],p[0],p[1]),Up(jp,p,Zp,l*v)}else t.lineTo(p[0],p[1]);c=f,f+=a}return d}function Cs(t,e){var n=[1/0,1/0],i=[-1/0,-1/0];if(e)for(var r=0;r<t.length;r++){var a=t[r];a[0]<n[0]&&(n[0]=a[0]),a[1]<n[1]&&(n[1]=a[1]),a[0]>i[0]&&(i[0]=a[0]),a[1]>i[1]&&(i[1]=a[1])}return{min:e?n:i,max:e?i:n}}function Ds(t,e){if(t.length===e.length){for(var n=0;n<t.length;n++){var i=t[n],r=e[n];if(i[0]!==r[0]||i[1]!==r[1])return}return!0}}function ks(t){return"number"==typeof t?t:t?.5:0}function As(t){var e=t.getGlobalExtent();if(t.onBand){var n=t.getBandWidth()/2-1,i=e[1]>e[0]?1:-1;e[0]+=i*n,e[1]-=i*n}return e}function Ls(t,e,n){if(!n.valueDim)return[];for(var i=[],r=0,a=e.count();r<a;r++)i.push(xs(n,t,e,r));return i}function Ps(t,e,n){var i=As(t.getAxis("x")),r=As(t.getAxis("y")),a=t.getBaseAxis().isHorizontal(),o=Math.min(i[0],i[1]),s=Math.min(r[0],r[1]),l=Math.max(i[0],i[1])-o,h=Math.max(r[0],r[1])-s,u=n.get("lineStyle.width")||2,c=n.get("clipOverflow")?u/2:Math.max(l,h);a?(s-=c,h+=2*c):(o-=c,l+=2*c);var f=new tf({shape:{x:o,y:s,width:l,height:h}});return e&&(f.shape[a?"width":"height"]=0,Ui(f,{shape:{width:l,height:h}},n)),f}function Os(t,e,n){var i=t.getAngleAxis(),r=t.getRadiusAxis().getExtent(),a=i.getExtent(),o=Math.PI/180,s=new Zc({shape:{cx:t.cx,cy:t.cy,r0:r[0],r:r[1],startAngle:-a[0]*o,endAngle:-a[1]*o,clockwise:i.inverse}});return e&&(s.shape.endAngle=-a[0]*o,Ui(s,{shape:{endAngle:-a[1]*o}},n)),s}function Es(t,e,n){return"polar"===t.type?Os(t,e,n):Ps(t,e,n)}function Bs(t,e,n){for(var i=e.getBaseAxis(),r="x"===i.dim||"radius"===i.dim?0:1,a=[],o=0;o<t.length-1;o++){var s=t[o+1],l=t[o];a.push(l);var h=[];switch(n){case"end":h[r]=s[r],h[1-r]=l[1-r],a.push(h);break;case"middle":var u=(l[r]+s[r])/2,c=[];h[r]=c[r]=u,h[1-r]=l[1-r],c[1-r]=s[1-r],a.push(h),a.push(c);break;default:h[r]=l[r],h[1-r]=s[1-r],a.push(h)}}return t[o]&&a.push(t[o]),a}function Ns(t,e){var n=t.getVisual("visualMeta");if(n&&n.length&&t.count()&&"cartesian2d"===e.type){for(var i,r,a=n.length-1;a>=0;a--){var o=n[a].dimension,s=t.dimensions[o],l=t.getDimensionInfo(s);if("x"===(i=l&&l.coordDim)||"y"===i){r=n[a];break}}if(r){var h=e.getAxis(i),u=d(r.stops,function(t){return{coord:h.toGlobalCoord(h.dataToCoord(t.value)),color:t.color}}),c=u.length,p=r.outerColors.slice();c&&u[0].coord>u[c-1].coord&&(u.reverse(),p.reverse());var g=u[0].coord-10,m=u[c-1].coord+10,v=m-g;if(v<.001)return"transparent";f(u,function(t){t.offset=(t.coord-g)/v}),u.push({offset:c?u[c-1].offset:.5,color:p[1]||"transparent"}),u.unshift({offset:c?u[0].offset:.5,color:p[0]||"transparent"});var y=new lf(0,0,0,0,u,!0);return y[i]=g,y[i+"2"]=m,y}}}function Rs(t){this._setting=t||{},this._extent=[1/0,-1/0],this._interval=0,this.init&&this.init.apply(this,arguments)}function zs(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this._map}function Fs(t){return t._map||(t._map=N(t.categories))}function Vs(t){return w(t)&&null!=t.value?t.value:t+""}function Ws(t,e,n,i){var r={},a=t[1]-t[0],o=r.interval=cr(a/e,!0);null!=n&&o<n&&(o=r.interval=n),null!=i&&o>i&&(o=r.interval=i);var s=r.intervalPrecision=Hs(o);return qs(r.niceTickExtent=[rg(Math.ceil(t[0]/o)*o,s),rg(Math.floor(t[1]/o)*o,s)],t),r}function Hs(t){return ir(t)+2}function Gs(t,e,n){t[e]=Math.max(Math.min(t[e],n[1]),n[0])}function qs(t,e){!isFinite(t[0])&&(t[0]=e[0]),!isFinite(t[1])&&(t[1]=e[1]),Gs(t,0,e),Gs(t,1,e),t[0]>t[1]&&(t[0]=t[1])}function Xs(t,e,n,i){var r=[];if(!t)return r;e[0]<n[0]&&r.push(e[0]);for(var a=n[0];a<=n[1]&&(r.push(a),(a=rg(a+t,i))!==r[r.length-1]);)if(r.length>1e4)return[];return e[1]>(r.length?r[r.length-1]:n[1])&&r.push(e[1]),r}function Us(t){return t.get("stack")||sg+t.seriesIndex}function Ys(t){return t.dim+t.index}function Zs(t,e){return js(d(t,function(t){var e=t.getData(),n=t.coordinateSystem.getBaseAxis(),i=n.getExtent(),r="category"===n.type?n.getBandWidth():Math.abs(i[1]-i[0])/e.count();return{bandWidth:r,barWidth:er(t.get("barWidth"),r),barMaxWidth:er(t.get("barMaxWidth"),r),barGap:t.get("barGap"),barCategoryGap:t.get("barCategoryGap"),axisKey:Ys(n),stackId:Us(t)}}),e)}function js(t,e){var n={};f(t,function(t,e){var i=t.axisKey,r=t.bandWidth,a=n[i]||{bandWidth:r,remainedWidth:r,autoWidthCount:0,categoryGap:"20%",gap:"30%",stacks:{}},o=a.stacks;n[i]=a;var s=t.stackId;o[s]||a.autoWidthCount++,o[s]=o[s]||{width:0,maxWidth:0};var l=t.barWidth;l&&!o[s].width&&(o[s].width=l,l=Math.min(a.remainedWidth,l),a.remainedWidth-=l);var h=t.barMaxWidth;h&&(o[s].maxWidth=h);var u=t.barGap;null!=u&&(a.gap=u);var c=t.barCategoryGap;null!=c&&(a.categoryGap=c)});var i={};return f(n,function(t,e){i[e]={};var n=t.stacks,r=t.bandWidth,a=er(t.categoryGap,r),o=er(t.gap,1),s=t.remainedWidth,l=t.autoWidthCount,h=(s-a)/(l+(l-1)*o);h=Math.max(h,0),f(n,function(t,e){var n=t.maxWidth;n&&n<h&&(n=Math.min(n,s),t.width&&(n=Math.min(n,t.width)),s-=n,t.width=n,l--)}),h=(s-a)/(l+(l-1)*o),h=Math.max(h,0);var u,c=0;f(n,function(t,e){t.width||(t.width=h),u=t,c+=t.width*(1+o)}),u&&(c-=u.width*o);var d=-c/2;f(n,function(t,n){i[e][n]=i[e][n]||{offset:d,width:t.width},d+=t.width*(1+o)})}),i}function $s(t,e){return vg(t,mg(e))}function Ks(t,e){var n,i,r,a=t.type,o=e.getMin(),s=e.getMax(),l=null!=o,h=null!=s,u=t.getExtent();"ordinal"===a?n=e.getCategories().length:(y(i=e.get("boundaryGap"))||(i=[i||0,i||0]),"boolean"==typeof i[0]&&(i=[0,0]),i[0]=er(i[0],1),i[1]=er(i[1],1),r=u[1]-u[0]||Math.abs(u[0])),null==o&&(o="ordinal"===a?n?0:NaN:u[0]-i[0]*r),null==s&&(s="ordinal"===a?n?n-1:NaN:u[1]+i[1]*r),"dataMin"===o?o=u[0]:"function"==typeof o&&(o=o({min:u[0],max:u[1]})),"dataMax"===s?s=u[1]:"function"==typeof s&&(s=s({min:u[0],max:u[1]})),(null==o||!isFinite(o))&&(o=NaN),(null==s||!isFinite(s))&&(s=NaN),t.setBlank(I(o)||I(s)),e.getNeedCrossZero()&&(o>0&&s>0&&!l&&(o=0),o<0&&s<0&&!h&&(s=0));var c=e.ecModel;if(c&&"time"===a){var f,d=[];if(c.eachSeriesByType("bar",function(t){t.coordinateSystem&&"cartesian2d"===t.coordinateSystem.type&&(d.push(t),f|=t.getBaseAxis()===e.axis)}),f){var p=Qs(o,s,e,d);o=p.min,s=p.max}}return[o,s]}function Qs(t,e,n,i){var r=n.axis.getExtent(),a=r[1]-r[0],o=Zs(i)[n.axis.dim+n.axis.index];if(void 0===o)return{min:t,max:e};var s=1/0;f(o,function(t){s=Math.min(t.offset,s)});var l=-1/0;f(o,function(t){l=Math.max(t.offset+t.width,l)}),s=Math.abs(s),l=Math.abs(l);var h=s+l,u=e-t,c=u/(1-(s+l)/a)-u;return e+=c*(l/h),t-=c*(s/h),{min:t,max:e}}function Js(t,e){if(e=e||t.get("type"))switch(e){case"category":return new ig(t.getOrdinalMeta?t.getOrdinalMeta():t.getCategories(),[1/0,-1/0]);case"value":return new og;default:return(Rs.getClass(e)||og).create(t)}}function tl(t,e,n,i,r){var a,o=0,s=0,l=(i-r)/180*Math.PI,h=1;e.length>40&&(h=Math.floor(e.length/40));for(var u=0;u<t.length;u+=h){var c=t[u],f=ee(e[u],n,"center","top");f.x+=c*Math.cos(l),f.y+=c*Math.sin(l),f.width*=1.3,f.height*=1.3,a?a.intersect(f)?(s++,o=Math.max(o,s)):(a.union(f),s=0):a=f.clone()}return 0===o&&h>1?h:(o+1)*h-1}function el(t,e){var n=t.scale,i=n.getTicksLabels(),r=n.getTicks();return"string"==typeof e?(e=function(t){return function(e){return t.replace("{value}",null!=e?e:"")}}(e),d(i,e)):"function"==typeof e?d(r,function(n,i){return e(nl(t,n),i)},this):i}function nl(t,e){return"category"===t.type?t.scale.getLabel(e):e}function il(t){return this._axes[t]}function rl(t){Sg.call(this,t)}function al(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}function ol(t,e){return e.type||(e.data?"category":"value")}function sl(t,e,n){return t.getCoordSysModel()===e}function ll(t,e){var n=e*Math.PI/180,i=t.plain(),r=i.width,a=i.height,o=r*Math.cos(n)+a*Math.sin(n),s=r*Math.sin(n)+a*Math.cos(n);return new Nt(i.x,i.y,o,s)}function hl(t){var e,n=t.model,i=n.get("axisLabel.show")?n.getFormattedLabels():[],r=n.getModel("axisLabel"),a=1,o=i.length;o>40&&(a=Math.ceil(o/40));for(var s=0;s<o;s+=a)if(!t.isLabelIgnored(s)){var l=ll(r.getTextRect(i[s]),r.get("rotate")||0);e?e.union(l):e=l}return e}function ul(t,e,n){this._coordsMap={},this._coordsList=[],this._axesMap={},this._axesList=[],this._initCartesian(t,e,n),this.model=t}function cl(t,e,n){var i=t[e];if(n.onZero){var r=n.onZeroAxisIndex;if(null==r){for(var a in i)if(i.hasOwnProperty(a)){var o=i[a];if(o&&!fl(o)){r=+a;break}}null==r&&(n.onZero=!1),n.onZeroAxisIndex=r}else(o=i[r])&&fl(o)&&(n.onZero=!1)}}function fl(t){return"category"===t.type||"time"===t.type||!Ng(t)}function dl(t,e){var n=t.getExtent(),i=n[0]+n[1];t.toGlobalCoord="x"===t.dim?function(t){return t+e}:function(t){return i-t+e},t.toLocalCoord="x"===t.dim?function(t){return t-e}:function(t){return i-t+e}}function pl(t,e){return d(Fg,function(e){return t.getReferringComponents(e)[0]})}function gl(t){return"cartesian2d"===t.get("coordinateSystem")}function ml(t){var e={componentType:t.mainType};return e[t.mainType+"Index"]=t.componentIndex,e}function vl(t,e,n,i){var r,a,o=or(n-t.rotation),s=i[0]>i[1],l="start"===e&&!s||"start"!==e&&s;return sr(o-Vg/2)?(a=l?"bottom":"top",r="center"):sr(o-1.5*Vg)?(a=l?"top":"bottom",r="center"):(a="middle",r=o<1.5*Vg&&o>Vg/2?l?"left":"right":l?"right":"left"),{rotation:o,textAlign:r,textVerticalAlign:a}}function yl(t){var e=t.get("tooltip");return t.get("silent")||!(t.get("triggerEvent")||e&&e.show)}function _l(t,e,n){var i=t.get("axisLabel.showMinLabel"),r=t.get("axisLabel.showMaxLabel");e=e||[],n=n||[];var a=e[0],o=e[1],s=e[e.length-1],l=e[e.length-2],h=n[0],u=n[1],c=n[n.length-1],f=n[n.length-2];!1===i?(xl(a),xl(h)):wl(a,o)&&(i?(xl(o),xl(u)):(xl(a),xl(h))),!1===r?(xl(s),xl(c)):wl(l,s)&&(r?(xl(l),xl(f)):(xl(s),xl(c)))}function xl(t){t&&(t.ignore=!0)}function wl(t,e,n){var i=t&&t.getBoundingRect().clone(),r=e&&e.getBoundingRect().clone();if(i&&r){var a=nt([]);return ot(a,a,-t.rotation),i.applyTransform(rt([],a,t.getLocalTransform())),r.applyTransform(rt([],a,e.getLocalTransform())),i.intersect(r)}}function bl(t){return"middle"===t||"center"===t}function Sl(t,e,n){var i=e.axis;if(e.get("axisTick.show")&&!i.scale.isBlank()){for(var r=e.getModel("axisTick"),a=r.getModel("lineStyle"),s=r.get("length"),l=Xg(r,n.labelInterval),h=i.getTicksCoords(r.get("alignWithLabel")),u=i.scale.getTicks(),c=e.get("axisLabel.showMinLabel"),f=e.get("axisLabel.showMaxLabel"),d=[],p=[],g=t._transform,m=[],v=h.length,y=0;y<v;y++)if(!qg(i,y,l,v,c,f)){var _=h[y];d[0]=_,d[1]=0,p[0]=_,p[1]=n.tickDirection*s,g&&(Y(d,d,g),Y(p,p,g));var x=new ef(xi({anid:"tick_"+u[y],shape:{x1:d[0],y1:d[1],x2:p[0],y2:p[1]},style:o(a.getLineStyle(),{stroke:e.get("axisLine.lineStyle.color")}),z2:2,silent:!0}));t.group.add(x),m.push(x)}return m}}function Ml(t,e,n){var i=e.axis;if(T(n.axisLabelShow,e.get("axisLabel.show"))&&!i.scale.isBlank()){var r=e.getModel("axisLabel"),a=r.get("margin"),o=i.scale.getTicks(),s=e.getFormattedLabels(),l=(T(n.labelRotate,r.get("rotate"))||0)*Vg/180,h=Gg(n.rotation,l,n.labelDirection),u=e.getCategories(),c=[],d=yl(e),p=e.get("triggerEvent"),g=e.get("axisLabel.showMinLabel"),m=e.get("axisLabel.showMaxLabel");return f(o,function(l,f){if(!qg(i,f,n.labelInterval,o.length,g,m)){var v=r;u&&u[l]&&u[l].textStyle&&(v=new ji(u[l].textStyle,r,e.ecModel));var y=v.getTextColor()||e.get("axisLine.lineStyle.color"),_=[i.dataToCoord(l),n.labelOffset+n.labelDirection*a],x=i.scale.getLabel(l),w=new qc({anid:"label_"+l,position:_,rotation:h.rotation,silent:d,z2:10});Ni(w.style,v,{text:s[f],textAlign:v.getShallow("align",!0)||h.textAlign,textVerticalAlign:v.getShallow("verticalAlign",!0)||v.getShallow("baseline",!0)||h.textVerticalAlign,textFill:"function"==typeof y?y("category"===i.type?x:"value"===i.type?l+"":l,f):y}),p&&(w.eventData=ml(e),w.eventData.targetType="axisLabel",w.eventData.value=x),t._dumbGroup.add(w),w.updateTransform(),c.push(w),t.group.add(w),w.decomposeTransform()}}),c}}function Il(t){var e=Tl(t);if(e){var n=e.axisPointerModel,i=e.axis.scale,r=n.option,a=n.get("status"),o=n.get("value");null!=o&&(o=i.parse(o));var s=Dl(n);null==a&&(r.status=s?"show":"hide");var l=i.getExtent().slice();l[0]>l[1]&&l.reverse(),(null==o||o>l[1])&&(o=l[1]),o<l[0]&&(o=l[0]),r.value=o,s&&(r.status=e.axis.scale.isBlank()?"hide":"show")}}function Tl(t){var e=(t.ecModel.getComponent("axisPointer")||{}).coordSysAxesInfo;return e&&e.axesInfo[kl(t)]}function Cl(t){var e=Tl(t);return e&&e.axisPointerModel}function Dl(t){return!!t.get("handle.show")}function kl(t){return t.type+"||"+t.id}function Al(t,e,n,i,r,a){var o=Ug.getAxisPointerClass(t.axisPointerClass);if(o){var s=Cl(e);s?(t._axisPointer||(t._axisPointer=new o)).render(e,s,i,a):Ll(t,i)}}function Ll(t,e,n){var i=t._axisPointer;i&&i.dispose(e,n),t._axisPointer=null}function Pl(t,e,n){n=n||{};var i=t.coordinateSystem,r=e.axis,a={},o=r.position,s=r.onZero?"onZero":o,l=r.dim,h=i.getRect(),u=[h.x,h.x+h.width,h.y,h.y+h.height],c={left:0,right:1,top:0,bottom:1,onZero:2},f=e.get("offset")||0,d="x"===l?[u[2]-f,u[3]+f]:[u[0]-f,u[1]+f];if(r.onZero){var p=i.getAxis("x"===l?"y":"x",r.onZeroAxisIndex),g=p.toGlobalCoord(p.dataToCoord(0));d[c.onZero]=Math.max(Math.min(g,d[1]),d[0])}a.position=["y"===l?d[c[s]]:u[0],"x"===l?d[c[s]]:u[3]],a.rotation=Math.PI/2*("x"===l?0:1);var m={top:-1,bottom:1,left:-1,right:1};a.labelDirection=a.tickDirection=a.nameDirection=m[o],a.labelOffset=r.onZero?d[c[o]]-d[c.onZero]:0,e.get("axisTick.inside")&&(a.tickDirection=-a.tickDirection),T(n.labelInside,e.get("axisLabel.inside"))&&(a.labelDirection=-a.labelDirection);var v=e.get("axisLabel.rotate");return a.labelRotate="top"===s?-v:v,a.labelInterval=r.getLabelInterval(),a.z2=1,a}function Ol(t,e,n,i,r,a,o){Bi(t,e,n.getModel("label"),n.getModel("emphasis.label"),{labelFetcher:r,labelDataIndex:a,defaultText:hs(r.getData(),a),isRectText:!0,autoColor:i}),El(t),El(e)}function El(t,e){"outside"===t.textPosition&&(t.textPosition=e)}function Bl(t,e,n){n.style.text=null,Xi(n,{shape:{width:0}},e,t,function(){n.parent&&n.parent.remove(n)})}function Nl(t,e,n){n.style.text=null,Xi(n,{shape:{r:n.shape.r0}},e,t,function(){n.parent&&n.parent.remove(n)})}function Rl(t,e,n,i,r,a,s,l){var h=e.getItemVisual(n,"color"),u=e.getItemVisual(n,"opacity"),c=i.getModel("itemStyle"),f=i.getModel("emphasis.itemStyle").getBarItemStyle();l||t.setShape("r",c.get("barBorderRadius")||0),t.useStyle(o({fill:h,opacity:u},c.getBarItemStyle()));var d=i.getShallow("cursor");d&&t.attr("cursor",d);var p=s?r.height>0?"bottom":"top":r.width>0?"left":"right";l||Ol(t.style,f,i,h,a,n,p),Ei(t,f)}function zl(t,e){var n=t.get(em)||0;return Math.min(n,Math.abs(e.width),Math.abs(e.height))}function Fl(t,e,n,i){var r=e.getData(),a=this.dataIndex,o=r.getName(a),s=e.get("selectedOffset");i.dispatchAction({type:"pieToggleSelect",from:t,name:o,seriesId:e.id}),r.each(function(t){Vl(r.getItemGraphicEl(t),r.getItemLayout(t),e.isSelected(r.getName(t)),s,n)})}function Vl(t,e,n,i,r){var a=(e.startAngle+e.endAngle)/2,o=Math.cos(a),s=Math.sin(a),l=n?i:0,h=[o*l,s*l];r?t.animate().when(200,{position:h}).start("bounceOut"):t.attr("position",h)}function Wl(t,e){function n(){a.ignore=a.hoverIgnore,o.ignore=o.hoverIgnore}function i(){a.ignore=a.normalIgnore,o.ignore=o.normalIgnore}Wh.call(this);var r=new Zc({z2:2}),a=new Jc,o=new qc;this.add(r),this.add(a),this.add(o),this.updateData(t,e,!0),this.on("emphasis",n).on("normal",i).on("mouseover",n).on("mouseout",i)}function Hl(t,e,n,i,r,a,o){function s(e,n){for(var i=e;i>=0&&(t[i].y-=n,!(i>0&&t[i].y>t[i-1].y+t[i-1].height));i--);}function l(t,e,n,i,r,a){for(var o=e?Number.MAX_VALUE:0,s=0,l=t.length;s<l;s++)if("center"!==t[s].position){var h=Math.abs(t[s].y-i),u=t[s].len,c=t[s].len2,f=h<r+u?Math.sqrt((r+u+c)*(r+u+c)-h*h):Math.abs(t[s].x-n);e&&f>=o&&(f=o-10),!e&&f<=o&&(f=o+10),t[s].x=n+f*a,o=f}}t.sort(function(t,e){return t.y-e.y});for(var h,u=0,c=t.length,f=[],d=[],p=0;p<c;p++)(h=t[p].y-u)<0&&function(e,n,i,r){for(var a=e;a<n;a++)if(t[a].y+=i,a>e&&a+1<n&&t[a+1].y>t[a].y+t[a].height)return void s(a,i/2);s(n-1,i/2)}(p,c,-h),u=t[p].y+t[p].height;o-u<0&&s(c-1,u-o);for(p=0;p<c;p++)t[p].y>=n?d.push(t[p]):f.push(t[p]);l(f,!1,e,n,i,r),l(d,!0,e,n,i,r)}function Gl(t,e,n,i,r,a){for(var o=[],s=[],l=0;l<t.length;l++)t[l].x<e?o.push(t[l]):s.push(t[l]);Hl(s,e,n,i,1,r,a),Hl(o,e,n,i,-1,r,a);for(l=0;l<t.length;l++){var h=t[l].linePoints;if(h){var u=h[1][0]-h[2][0];t[l].x<e?h[2][0]=t[l].x+3:h[2][0]=t[l].x-3,h[1][1]=h[2][1]=t[l].y,h[1][0]=h[2][0]+u}}}var ql=2311,Xl=function(){return ql++},Ul={},Yl=Ul="undefined"!=typeof wx?{browser:{},os:{},node:!1,wxa:!0,canvasSupported:!0,svgSupported:!1,touchEventsSupported:!0}:"undefined"==typeof document&&"undefined"!=typeof self?{browser:{},os:{},node:!1,worker:!0,canvasSupported:!0}:"undefined"==typeof navigator?{browser:{},os:{},node:!0,worker:!1,canvasSupported:!0,svgSupported:!0}:function(t){var e={},n={},i=t.match(/Firefox\/([\d.]+)/),r=t.match(/MSIE\s([\d.]+)/)||t.match(/Trident\/.+?rv:(([\d.]+))/),a=t.match(/Edge\/([\d.]+)/),o=/micromessenger/i.test(t);return i&&(n.firefox=!0,n.version=i[1]),r&&(n.ie=!0,n.version=r[1]),a&&(n.edge=!0,n.version=a[1]),o&&(n.weChat=!0),{browser:n,os:e,node:!1,canvasSupported:!!document.createElement("canvas").getContext,svgSupported:"undefined"!=typeof SVGRect,touchEventsSupported:"ontouchstart"in window&&!n.ie&&!n.edge,pointerEventsSupported:"onpointerdown"in window&&(n.edge||n.ie&&n.version>=11)}}(navigator.userAgent),Zl={"[object Function]":1,"[object RegExp]":1,"[object Date]":1,"[object Error]":1,"[object CanvasGradient]":1,"[object CanvasPattern]":1,"[object Image]":1,"[object Canvas]":1},jl={"[object Int8Array]":1,"[object Uint8Array]":1,"[object Uint8ClampedArray]":1,"[object Int16Array]":1,"[object Uint16Array]":1,"[object Int32Array]":1,"[object Uint32Array]":1,"[object Float32Array]":1,"[object Float64Array]":1},$l=Object.prototype.toString,Kl=Array.prototype,Ql=Kl.forEach,Jl=Kl.filter,th=Kl.slice,eh=Kl.map,nh=Kl.reduce,ih={},rh=function(){return ih.createCanvas()};ih.createCanvas=function(){return document.createElement("canvas")};var ah,oh="__ec_primitive__";B.prototype={constructor:B,get:function(t){return this.hasOwnProperty(t)?this[t]:null},set:function(t,e){return this[t]=e},each:function(t,e){void 0!==e&&(t=m(t,e));for(var n in this)this.hasOwnProperty(n)&&t(this[n],n)},removeKey:function(t){delete this[t]}};var sh="undefined"==typeof Float32Array?Array:Float32Array,lh=U,hh=function(t,e){return(t[0]-e[0])*(t[0]-e[0])+(t[1]-e[1])*(t[1]-e[1])};$.prototype={constructor:$,_dragStart:function(t){var e=t.target;e&&e.draggable&&(this._draggingTarget=e,e.dragging=!0,this._x=t.offsetX,this._y=t.offsetY,this.dispatchToElement(K(e,t),"dragstart",t.event))},_drag:function(t){var e=this._draggingTarget;if(e){var n=t.offsetX,i=t.offsetY,r=n-this._x,a=i-this._y;this._x=n,this._y=i,e.drift(r,a,t),this.dispatchToElement(K(e,t),"drag",t.event);var o=this.findHover(n,i,e).target,s=this._dropTarget;this._dropTarget=o,e!==o&&(s&&o!==s&&this.dispatchToElement(K(s,t),"dragleave",t.event),o&&o!==s&&this.dispatchToElement(K(o,t),"dragenter",t.event))}},_dragEnd:function(t){var e=this._draggingTarget;e&&(e.dragging=!1),this.dispatchToElement(K(e,t),"dragend",t.event),this._dropTarget&&this.dispatchToElement(K(this._dropTarget,t),"drop",t.event),this._draggingTarget=null,this._dropTarget=null}};var uh=Array.prototype.slice,ch=function(){this._$handlers={}};ch.prototype={constructor:ch,one:function(t,e,n){var i=this._$handlers;if(!e||!t)return this;i[t]||(i[t]=[]);for(var r=0;r<i[t].length;r++)if(i[t][r].h===e)return this;return i[t].push({h:e,one:!0,ctx:n||this}),this},on:function(t,e,n){var i=this._$handlers;if(!e||!t)return this;i[t]||(i[t]=[]);for(var r=0;r<i[t].length;r++)if(i[t][r].h===e)return this;return i[t].push({h:e,one:!1,ctx:n||this}),this},isSilent:function(t){var e=this._$handlers;return e[t]&&e[t].length},off:function(t,e){var n=this._$handlers;if(!t)return this._$handlers={},this;if(e){if(n[t]){for(var i=[],r=0,a=n[t].length;r<a;r++)n[t][r].h!=e&&i.push(n[t][r]);n[t]=i}n[t]&&0===n[t].length&&delete n[t]}else delete n[t];return this},trigger:function(t){if(this._$handlers[t]){var e=arguments,n=e.length;n>3&&(e=uh.call(e,1));for(var i=this._$handlers[t],r=i.length,a=0;a<r;){switch(n){case 1:i[a].h.call(i[a].ctx);break;case 2:i[a].h.call(i[a].ctx,e[1]);break;case 3:i[a].h.call(i[a].ctx,e[1],e[2]);break;default:i[a].h.apply(i[a].ctx,e)}i[a].one?(i.splice(a,1),r--):a++}}return this},triggerWithContext:function(t){if(this._$handlers[t]){var e=arguments,n=e.length;n>4&&(e=uh.call(e,1,e.length-1));for(var i=e[e.length-1],r=this._$handlers[t],a=r.length,o=0;o<a;){switch(n){case 1:r[o].h.call(i);break;case 2:r[o].h.call(i,e[1]);break;case 3:r[o].h.call(i,e[1],e[2]);break;default:r[o].h.apply(i,e)}r[o].one?(r.splice(o,1),a--):o++}}return this}};var fh="silent";J.prototype.dispose=function(){};var dh=["click","dblclick","mousewheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],ph=function(t,e,n,i){ch.call(this),this.storage=t,this.painter=e,this.painterRoot=i,n=n||new J,this.proxy=null,this._hovered={},this._lastTouchMoment,this._lastX,this._lastY,$.call(this),this.setHandlerProxy(n)};ph.prototype={constructor:ph,setHandlerProxy:function(t){this.proxy&&this.proxy.dispose(),t&&(f(dh,function(e){t.on&&t.on(e,this[e],this)},this),t.handler=this),this.proxy=t},mousemove:function(t){var e=t.zrX,n=t.zrY,i=this._hovered,r=i.target;r&&!r.__zr&&(r=(i=this.findHover(i.x,i.y)).target);var a=this._hovered=this.findHover(e,n),o=a.target,s=this.proxy;s.setCursor&&s.setCursor(o?o.cursor:"default"),r&&o!==r&&this.dispatchToElement(i,"mouseout",t),this.dispatchToElement(a,"mousemove",t),o&&o!==r&&this.dispatchToElement(a,"mouseover",t)},mouseout:function(t){this.dispatchToElement(this._hovered,"mouseout",t);var e,n=t.toElement||t.relatedTarget;do{n=n&&n.parentNode}while(n&&9!=n.nodeType&&!(e=n===this.painterRoot));!e&&this.trigger("globalout",{event:t})},resize:function(t){this._hovered={}},dispatch:function(t,e){var n=this[t];n&&n.call(this,e)},dispose:function(){this.proxy.dispose(),this.storage=this.proxy=this.painter=null},setCursorStyle:function(t){var e=this.proxy;e.setCursor&&e.setCursor(t)},dispatchToElement:function(t,e,n){var i=(t=t||{}).target;if(!i||!i.silent){for(var r="on"+e,a=Q(e,t,n);i&&(i[r]&&(a.cancelBubble=i[r].call(i,a)),i.trigger(e,a),i=i.parent,!a.cancelBubble););a.cancelBubble||(this.trigger(e,a),this.painter&&this.painter.eachOtherLayer(function(t){"function"==typeof t[r]&&t[r].call(t,a),t.trigger&&t.trigger(e,a)}))}},findHover:function(t,e,n){for(var i=this.storage.getDisplayList(),r={x:t,y:e},a=i.length-1;a>=0;a--){var o;if(i[a]!==n&&!i[a].ignore&&(o=tt(i[a],t,e))&&(!r.topTarget&&(r.topTarget=i[a]),o!==fh)){r.target=i[a];break}}return r}},f(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){ph.prototype[t]=function(e){var n=this.findHover(e.zrX,e.zrY),i=n.target;if("mousedown"===t)this._downEl=i,this._downPoint=[e.zrX,e.zrY],this._upEl=i;else if("mouseup"===t)this._upEl=i;else if("click"===t){if(this._downEl!==this._upEl||!this._downPoint||lh(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}}),u(ph,ch),u(ph,$);var gh="undefined"==typeof Float32Array?Array:Float32Array,mh=nt,vh=5e-5,yh=function(t){(t=t||{}).position||(this.position=[0,0]),null==t.rotation&&(this.rotation=0),t.scale||(this.scale=[1,1]),this.origin=this.origin||null},_h=yh.prototype;_h.transform=null,_h.needLocalTransform=function(){return ht(this.rotation)||ht(this.position[0])||ht(this.position[1])||ht(this.scale[0]-1)||ht(this.scale[1]-1)},_h.updateTransform=function(){var t=this.parent,e=t&&t.transform,n=this.needLocalTransform(),i=this.transform;n||e?(i=i||et(),n?this.getLocalTransform(i):mh(i),e&&(n?rt(i,t.transform,i):it(i,t.transform)),this.transform=i,this.invTransform=this.invTransform||et(),lt(this.invTransform,i)):i&&mh(i)},_h.getLocalTransform=function(t){return yh.getLocalTransform(this,t)},_h.setTransform=function(t){var e=this.transform,n=t.dpr||1;e?t.setTransform(n*e[0],n*e[1],n*e[2],n*e[3],n*e[4],n*e[5]):t.setTransform(n,0,0,n,0,0)},_h.restoreTransform=function(t){var e=t.dpr||1;t.setTransform(e,0,0,e,0,0)};var xh=[];_h.decomposeTransform=function(){if(this.transform){var t=this.parent,e=this.transform;t&&t.transform&&(rt(xh,t.invTransform,e),e=xh);var n=e[0]*e[0]+e[1]*e[1],i=e[2]*e[2]+e[3]*e[3],r=this.position,a=this.scale;ht(n-1)&&(n=Math.sqrt(n)),ht(i-1)&&(i=Math.sqrt(i)),e[0]<0&&(n=-n),e[3]<0&&(i=-i),r[0]=e[4],r[1]=e[5],a[0]=n,a[1]=i,this.rotation=Math.atan2(-e[1]/i,e[0]/n)}},_h.getGlobalScale=function(){var t=this.transform;if(!t)return[1,1];var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]),n=Math.sqrt(t[2]*t[2]+t[3]*t[3]);return t[0]<0&&(e=-e),t[3]<0&&(n=-n),[e,n]},_h.transformCoordToLocal=function(t,e){var n=[t,e],i=this.invTransform;return i&&Y(n,n,i),n},_h.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&Y(n,n,i),n},yh.getLocalTransform=function(t,e){mh(e=e||[]);var n=t.origin,i=t.scale||[1,1],r=t.rotation||0,a=t.position||[0,0];return n&&(e[4]-=n[0],e[5]-=n[1]),st(e,e,i),r&&ot(e,e,r),n&&(e[4]+=n[0],e[5]+=n[1]),e[4]+=a[0],e[5]+=a[1],e};var wh={linear:function(t){return t},quadraticIn:function(t){return t*t},quadraticOut:function(t){return t*(2-t)},quadraticInOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)},cubicIn:function(t){return t*t*t},cubicOut:function(t){return--t*t*t+1},cubicInOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},quarticIn:function(t){return t*t*t*t},quarticOut:function(t){return 1- --t*t*t*t},quarticInOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)},quinticIn:function(t){return t*t*t*t*t},quinticOut:function(t){return--t*t*t*t*t+1},quinticInOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},sinusoidalIn:function(t){return 1-Math.cos(t*Math.PI/2)},sinusoidalOut:function(t){return Math.sin(t*Math.PI/2)},sinusoidalInOut:function(t){return.5*(1-Math.cos(Math.PI*t))},exponentialIn:function(t){return 0===t?0:Math.pow(1024,t-1)},exponentialOut:function(t){return 1===t?1:1-Math.pow(2,-10*t)},exponentialInOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))},circularIn:function(t){return 1-Math.sqrt(1-t*t)},circularOut:function(t){return Math.sqrt(1- --t*t)},circularInOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},elasticIn:function(t){var e,n=.1;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=.4*Math.asin(1/n)/(2*Math.PI),-n*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},elasticOut:function(t){var e,n=.1;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=.4*Math.asin(1/n)/(2*Math.PI),n*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},elasticInOut:function(t){var e,n=.1;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=.4*Math.asin(1/n)/(2*Math.PI),(t*=2)<1?n*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:n*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)},backIn:function(t){var e=1.70158;return t*t*((e+1)*t-e)},backOut:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},backInOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)},bounceIn:function(t){return 1-wh.bounceOut(1-t)},bounceOut:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},bounceInOut:function(t){return t<.5?.5*wh.bounceIn(2*t):.5*wh.bounceOut(2*t-1)+.5}};ut.prototype={constructor:ut,step:function(t,e){if(this._initialized||(this._startTime=t+this._delay,this._initialized=!0),this._paused)this._pausedTime+=e;else{var n=(t-this._startTime-this._pausedTime)/this._life;if(!(n<0)){n=Math.min(n,1);var i=this.easing,r="string"==typeof i?wh[i]:i,a="function"==typeof r?r(n):n;return this.fire("frame",a),1==n?this.loop?(this.restart(t),"restart"):(this._needsRemove=!0,"destroy"):null}}},restart:function(t){var e=(t-this._startTime-this._pausedTime)%this._life;this._startTime=t-e+this.gap,this._pausedTime=0,this._needsRemove=!1},fire:function(t,e){this[t="on"+t]&&this[t](this._target,e)},pause:function(){this._paused=!0},resume:function(){this._paused=!1}};var bh=function(){this.head=null,this.tail=null,this._len=0},Sh=bh.prototype;Sh.insert=function(t){var e=new Mh(t);return this.insertEntry(e),e},Sh.insertEntry=function(t){this.head?(this.tail.next=t,t.prev=this.tail,t.next=null,this.tail=t):this.head=this.tail=t,this._len++},Sh.remove=function(t){var e=t.prev,n=t.next;e?e.next=n:this.head=n,n?n.prev=e:this.tail=e,t.next=t.prev=null,this._len--},Sh.len=function(){return this._len},Sh.clear=function(){this.head=this.tail=null,this._len=0};var Mh=function(t){this.value=t,this.next,this.prev},Ih=function(t){this._list=new bh,this._map={},this._maxSize=t||10,this._lastRemovedEntry=null},Th=Ih.prototype;Th.put=function(t,e){var n=this._list,i=this._map,r=null;if(null==i[t]){var a=n.len(),o=this._lastRemovedEntry;if(a>=this._maxSize&&a>0){var s=n.head;n.remove(s),delete i[s.key],r=s.value,this._lastRemovedEntry=s}o?o.value=e:o=new Mh(e),o.key=t,n.insertEntry(o),i[t]=o}return r},Th.get=function(t){var e=this._map[t],n=this._list;if(null!=e)return e!==n.tail&&(n.remove(e),n.insertEntry(e)),e.value},Th.clear=function(){this._list.clear(),this._map={}};var Ch={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]},Dh=new Ih(20),kh=null,Ah=Array.prototype.slice,Lh=function(t,e,n,i){this._tracks={},this._target=t,this._loop=e||!1,this._getter=n||St,this._setter=i||Mt,this._clipCount=0,this._delay=0,this._doneList=[],this._onframeList=[],this._clipList=[]};Lh.prototype={when:function(t,e){var n=this._tracks;for(var i in e)if(e.hasOwnProperty(i)){if(!n[i]){n[i]=[];var r=this._getter(this._target,i);if(null==r)continue;0!==t&&n[i].push({time:0,value:Pt(r)})}n[i].push({time:t,value:e[i]})}return this},during:function(t){return this._onframeList.push(t),this},pause:function(){for(var t=0;t<this._clipList.length;t++)this._clipList[t].pause();this._paused=!0},resume:function(){for(var t=0;t<this._clipList.length;t++)this._clipList[t].resume();this._paused=!1},isPaused:function(){return!!this._paused},_doneCallback:function(){this._tracks={},this._clipList.length=0;for(var t=this._doneList,e=t.length,n=0;n<e;n++)t[n].call(this)},start:function(t,e){var n,i=this,r=0;for(var a in this._tracks)if(this._tracks.hasOwnProperty(a)){var o=Bt(this,t,function(){--r||i._doneCallback()},this._tracks[a],a,e);o&&(this._clipList.push(o),r++,this.animation&&this.animation.addClip(o),n=o)}if(n){var s=n.onframe;n.onframe=function(t,e){s(t,e);for(var n=0;n<i._onframeList.length;n++)i._onframeList[n](t,e)}}return r||this._doneCallback(),this},stop:function(t){for(var e=this._clipList,n=this.animation,i=0;i<e.length;i++){var r=e[i];t&&r.onframe(this._target,1),n&&n.removeClip(r)}e.length=0},delay:function(t){return this._delay=t,this},done:function(t){return t&&this._doneList.push(t),this},getClips:function(){return this._clipList}};var Ph=1;"undefined"!=typeof window&&(Ph=Math.max(window.devicePixelRatio||1,1));var Oh=Ph,Eh=function(){},Bh=Eh,Nh=function(){this.animators=[]};Nh.prototype={constructor:Nh,animate:function(t,e){var n,i=!1,r=this,a=this.__zr;if(t){var o=t.split("."),s=r;i="shape"===o[0];for(var h=0,u=o.length;h<u;h++)s&&(s=s[o[h]]);s&&(n=s)}else n=r;if(n){var c=r.animators,f=new Lh(n,e);return f.during(function(t){r.dirty(i)}).done(function(){c.splice(l(c,f),1)}),c.push(f),a&&a.animation.addAnimator(f),f}Bh('Property "'+t+'" is not existed in element '+r.id)},stopAnimation:function(t){for(var e=this.animators,n=e.length,i=0;i<n;i++)e[i].stop(t);return e.length=0,this},animateTo:function(t,e,n,i,r,a){x(n)?(r=i,i=n,n=0):_(i)?(r=i,i="linear",n=0):_(n)?(r=n,n=0):_(e)?(r=e,e=500):e||(e=500),this.stopAnimation(),this._animateToShallow("",this,t,e,n);var o=this.animators.slice(),s=o.length;s||r&&r();for(var l=0;l<o.length;l++)o[l].done(function(){--s||r&&r()}).start(i,a)},_animateToShallow:function(t,e,n,i,r){var a={},o=0;for(var s in n)if(n.hasOwnProperty(s))if(null!=e[s])w(n[s])&&!c(n[s])?this._animateToShallow(t?t+"."+s:s,e[s],n[s],i,r):(a[s]=n[s],o++);else if(null!=n[s])if(t){var l={};l[t]={},l[t][s]=n[s],this.attr(l)}else this.attr(s,n[s]);return o>0&&this.animate(t,!1).when(null==i?500:i,a).delay(r||0),this}};var Rh=function(t){yh.call(this,t),ch.call(this,t),Nh.call(this,t),this.id=t.id||Xl()};Rh.prototype={type:"element",name:"",__zr:null,ignore:!1,clipPath:null,isGroup:!1,drift:function(t,e){switch(this.draggable){case"horizontal":e=0;break;case"vertical":t=0}var n=this.transform;n||(n=this.transform=[1,0,0,1,0,0]),n[4]+=t,n[5]+=e,this.decomposeTransform(),this.dirty(!1)},beforeUpdate:function(){},afterUpdate:function(){},update:function(){this.updateTransform()},traverse:function(t,e){},attrKV:function(t,e){if("position"===t||"scale"===t||"origin"===t){if(e){var n=this[t];n||(n=this[t]=[]),n[0]=e[0],n[1]=e[1]}}else this[t]=e},hide:function(){this.ignore=!0,this.__zr&&this.__zr.refresh()},show:function(){this.ignore=!1,this.__zr&&this.__zr.refresh()},attr:function(t,e){if("string"==typeof t)this.attrKV(t,e);else if(w(t))for(var n in t)t.hasOwnProperty(n)&&this.attrKV(n,t[n]);return this.dirty(!1),this},setClipPath:function(t){var e=this.__zr;e&&t.addSelfToZr(e),this.clipPath&&this.clipPath!==t&&this.removeClipPath(),this.clipPath=t,t.__zr=e,t.__clipTarget=this,this.dirty(!1)},removeClipPath:function(){var t=this.clipPath;t&&(t.__zr&&t.removeSelfFromZr(t.__zr),t.__zr=null,t.__clipTarget=null,this.clipPath=null,this.dirty(!1))},addSelfToZr:function(t){this.__zr=t;var e=this.animators;if(e)for(var n=0;n<e.length;n++)t.animation.addAnimator(e[n]);this.clipPath&&this.clipPath.addSelfToZr(t)},removeSelfFromZr:function(t){this.__zr=null;var e=this.animators;if(e)for(var n=0;n<e.length;n++)t.animation.removeAnimator(e[n]);this.clipPath&&this.clipPath.removeSelfFromZr(t)}},u(Rh,Nh),u(Rh,yh),u(Rh,ch);var zh=Y,Fh=Math.min,Vh=Math.max;Nt.prototype={constructor:Nt,union:function(t){var e=Fh(t.x,this.x),n=Fh(t.y,this.y);this.width=Vh(t.x+t.width,this.x+this.width)-e,this.height=Vh(t.y+t.height,this.y+this.height)-n,this.x=e,this.y=n},applyTransform:function(){var t=[],e=[],n=[],i=[];return function(r){if(r){t[0]=n[0]=this.x,t[1]=i[1]=this.y,e[0]=i[0]=this.x+this.width,e[1]=n[1]=this.y+this.height,zh(t,t,r),zh(e,e,r),zh(n,n,r),zh(i,i,r),this.x=Fh(t[0],e[0],n[0],i[0]),this.y=Fh(t[1],e[1],n[1],i[1]);var a=Vh(t[0],e[0],n[0],i[0]),o=Vh(t[1],e[1],n[1],i[1]);this.width=a-this.x,this.height=o-this.y}}}(),calculateTransform:function(t){var e=this,n=t.width/e.width,i=t.height/e.height,r=et();return at(r,r,[-e.x,-e.y]),st(r,r,[n,i]),at(r,r,[t.x,t.y]),r},intersect:function(t){if(!t)return!1;t instanceof Nt||(t=Nt.create(t));var e=this,n=e.x,i=e.x+e.width,r=e.y,a=e.y+e.height,o=t.x,s=t.x+t.width,l=t.y,h=t.y+t.height;return!(i<o||s<n||a<l||h<r)},contain:function(t,e){var n=this;return t>=n.x&&t<=n.x+n.width&&e>=n.y&&e<=n.y+n.height},clone:function(){return new Nt(this.x,this.y,this.width,this.height)},copy:function(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height},plain:function(){return{x:this.x,y:this.y,width:this.width,height:this.height}}},Nt.create=function(t){return new Nt(t.x,t.y,t.width,t.height)};var Wh=function(t){t=t||{},Rh.call(this,t);for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e]);this._children=[],this.__storage=null,this.__dirty=!0};Wh.prototype={constructor:Wh,isGroup:!0,type:"group",silent:!1,children:function(){return this._children.slice()},childAt:function(t){return this._children[t]},childOfName:function(t){for(var e=this._children,n=0;n<e.length;n++)if(e[n].name===t)return e[n]},childCount:function(){return this._children.length},add:function(t){return t&&t!==this&&t.parent!==this&&(this._children.push(t),this._doAdd(t)),this},addBefore:function(t,e){if(t&&t!==this&&t.parent!==this&&e&&e.parent===this){var n=this._children,i=n.indexOf(e);i>=0&&(n.splice(i,0,t),this._doAdd(t))}return this},_doAdd:function(t){t.parent&&t.parent.remove(t),t.parent=this;var e=this.__storage,n=this.__zr;e&&e!==t.__storage&&(e.addToStorage(t),t instanceof Wh&&t.addChildrenToStorage(e)),n&&n.refresh()},remove:function(t){var e=this.__zr,n=this.__storage,i=this._children,r=l(i,t);return r<0?this:(i.splice(r,1),t.parent=null,n&&(n.delFromStorage(t),t instanceof Wh&&t.delChildrenFromStorage(n)),e&&e.refresh(),this)},removeAll:function(){var t,e,n=this._children,i=this.__storage;for(e=0;e<n.length;e++)t=n[e],i&&(i.delFromStorage(t),t instanceof Wh&&t.delChildrenFromStorage(i)),t.parent=null;return n.length=0,this},eachChild:function(t,e){for(var n=this._children,i=0;i<n.length;i++){var r=n[i];t.call(e,r,i)}return this},traverse:function(t,e){for(var n=0;n<this._children.length;n++){var i=this._children[n];t.call(e,i),"group"===i.type&&i.traverse(t,e)}return this},addChildrenToStorage:function(t){for(var e=0;e<this._children.length;e++){var n=this._children[e];t.addToStorage(n),n instanceof Wh&&n.addChildrenToStorage(t)}},delChildrenFromStorage:function(t){for(var e=0;e<this._children.length;e++){var n=this._children[e];t.delFromStorage(n),n instanceof Wh&&n.delChildrenFromStorage(t)}},dirty:function(){return this.__dirty=!0,this.__zr&&this.__zr.refresh(),this},getBoundingRect:function(t){for(var e=null,n=new Nt(0,0,0,0),i=t||this._children,r=[],a=0;a<i.length;a++){var o=i[a];if(!o.ignore&&!o.invisible){var s=o.getBoundingRect(),l=o.getLocalTransform(r);l?(n.copy(s),n.applyTransform(l),(e=e||n.clone()).union(n)):(e=e||s.clone()).union(s)}}return e||n}},h(Wh,Rh);var Hh=32,Gh=7,qh=function(){this._roots=[],this._displayList=[],this._displayListLen=0};qh.prototype={constructor:qh,traverse:function(t,e){for(var n=0;n<this._roots.length;n++)this._roots[n].traverse(t,e)},getDisplayList:function(t,e){return e=e||!1,t&&this.updateDisplayList(e),this._displayList},updateDisplayList:function(t){this._displayListLen=0;for(var e=this._roots,n=this._displayList,i=0,r=e.length;i<r;i++)this._updateAndAddDisplayable(e[i],null,t);n.length=this._displayListLen,Yl.canvasSupported&&qt(n,Xt)},_updateAndAddDisplayable:function(t,e,n){if(!t.ignore||n){t.beforeUpdate(),t.__dirty&&t.update(),t.afterUpdate();var i=t.clipPath;if(i){e=e?e.slice():[];for(var r=i,a=t;r;)r.parent=a,r.updateTransform(),e.push(r),a=r,r=r.clipPath}if(t.isGroup){for(var o=t._children,s=0;s<o.length;s++){var l=o[s];t.__dirty&&(l.__dirty=!0),this._updateAndAddDisplayable(l,e,n)}t.__dirty=!1}else t.__clipPaths=e,this._displayList[this._displayListLen++]=t}},addRoot:function(t){t.__storage!==this&&(t instanceof Wh&&t.addChildrenToStorage(this),this.addToStorage(t),this._roots.push(t))},delRoot:function(t){if(null==t){for(n=0;n<this._roots.length;n++){var e=this._roots[n];e instanceof Wh&&e.delChildrenFromStorage(this)}return this._roots=[],this._displayList=[],void(this._displayListLen=0)}if(t instanceof Array)for(var n=0,i=t.length;n<i;n++)this.delRoot(t[n]);else{var r=l(this._roots,t);r>=0&&(this.delFromStorage(t),this._roots.splice(r,1),t instanceof Wh&&t.delChildrenFromStorage(this))}},addToStorage:function(t){return t&&(t.__storage=this,t.dirty(!1)),this},delFromStorage:function(t){return t&&(t.__storage=null),this},dispose:function(){this._renderList=this._roots=null},displayableSortFunc:Xt};var Xh={shadowBlur:1,shadowOffsetX:1,shadowOffsetY:1,textShadowBlur:1,textShadowOffsetX:1,textShadowOffsetY:1,textBoxShadowBlur:1,textBoxShadowOffsetX:1,textBoxShadowOffsetY:1},Uh=function(t,e,n){return Xh.hasOwnProperty(e)?n*=t.dpr:n},Yh=[["shadowBlur",0],["shadowOffsetX",0],["shadowOffsetY",0],["shadowColor","#000"],["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]],Zh=function(t,e){this.extendFrom(t,!1),this.host=e};Zh.prototype={constructor:Zh,host:null,fill:"#000",stroke:null,opacity:1,lineDash:null,lineDashOffset:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,lineWidth:1,strokeNoScale:!1,text:null,font:null,textFont:null,fontStyle:null,fontWeight:null,fontSize:null,fontFamily:null,textTag:null,textFill:"#000",textStroke:null,textWidth:null,textHeight:null,textStrokeWidth:0,textLineHeight:null,textPosition:"inside",textRect:null,textOffset:null,textAlign:null,textVerticalAlign:null,textDistance:5,textShadowColor:"transparent",textShadowBlur:0,textShadowOffsetX:0,textShadowOffsetY:0,textBoxShadowColor:"transparent",textBoxShadowBlur:0,textBoxShadowOffsetX:0,textBoxShadowOffsetY:0,transformText:!1,textRotation:0,textOrigin:null,textBackgroundColor:null,textBorderColor:null,textBorderWidth:0,textBorderRadius:0,textPadding:null,rich:null,truncate:null,blend:null,bind:function(t,e,n){for(var i=this,r=n&&n.style,a=!r,o=0;o<Yh.length;o++){var s=Yh[o],l=s[0];(a||i[l]!==r[l])&&(t[l]=Uh(t,l,i[l]||s[1]))}if((a||i.fill!==r.fill)&&(t.fillStyle=i.fill),(a||i.stroke!==r.stroke)&&(t.strokeStyle=i.stroke),(a||i.opacity!==r.opacity)&&(t.globalAlpha=null==i.opacity?1:i.opacity),(a||i.blend!==r.blend)&&(t.globalCompositeOperation=i.blend||"source-over"),this.hasStroke()){var h=i.lineWidth;t.lineWidth=h/(this.strokeNoScale&&e&&e.getLineScale?e.getLineScale():1)}},hasFill:function(){var t=this.fill;return null!=t&&"none"!==t},hasStroke:function(){var t=this.stroke;return null!=t&&"none"!==t&&this.lineWidth>0},extendFrom:function(t,e){if(t)for(var n in t)!t.hasOwnProperty(n)||!0!==e&&(!1===e?this.hasOwnProperty(n):null==t[n])||(this[n]=t[n])},set:function(t,e){"string"==typeof t?this[t]=e:this.extendFrom(t,!0)},clone:function(){var t=new this.constructor;return t.extendFrom(this,!0),t},getGradient:function(t,e,n){for(var i=("radial"===e.type?Yt:Ut)(t,e,n),r=e.colorStops,a=0;a<r.length;a++)i.addColorStop(r[a].offset,r[a].color);return i}};for(var jh=Zh.prototype,$h=0;$h<Yh.length;$h++){var Kh=Yh[$h];Kh[0]in jh||(jh[Kh[0]]=Kh[1])}Zh.getGradient=jh.getGradient;var Qh=function(t,e){this.image=t,this.repeat=e,this.type="pattern"};Qh.prototype.getCanvasPattern=function(t){return t.createPattern(this.image,this.repeat||"repeat")};var Jh=function(t,e,n){var i;n=n||Oh,"string"==typeof t?i=jt(t,e,n):w(t)&&(t=(i=t).id),this.id=t,this.dom=i;var r=i.style;r&&(i.onselectstart=Zt,r["-webkit-user-select"]="none",r["user-select"]="none",r["-webkit-touch-callout"]="none",r["-webkit-tap-highlight-color"]="rgba(0,0,0,0)",r.padding=0,r.margin=0,r["border-width"]=0),this.domBack=null,this.ctxBack=null,this.painter=e,this.config=null,this.clearColor=0,this.motionBlur=!1,this.lastFrameAlpha=.7,this.dpr=n};Jh.prototype={constructor:Jh,__dirty:!0,__used:!1,__drawIndex:0,__startIndex:0,__endIndex:0,incremental:!1,getElementCount:function(){return this.__endIndex-this.__startIndex},initContext:function(){this.ctx=this.dom.getContext("2d"),this.ctx.dpr=this.dpr},createBackBuffer:function(){var t=this.dpr;this.domBack=jt("back-"+this.id,this.painter,t),this.ctxBack=this.domBack.getContext("2d"),1!=t&&this.ctxBack.scale(t,t)},resize:function(t,e){var n=this.dpr,i=this.dom,r=i.style,a=this.domBack;r&&(r.width=t+"px",r.height=e+"px"),i.width=t*n,i.height=e*n,a&&(a.width=t*n,a.height=e*n,1!=n&&this.ctxBack.scale(n,n))},clear:function(t,e){var n=this.dom,i=this.ctx,r=n.width,a=n.height,e=e||this.clearColor,o=this.motionBlur&&!t,s=this.lastFrameAlpha,l=this.dpr;if(o&&(this.domBack||this.createBackBuffer(),this.ctxBack.globalCompositeOperation="copy",this.ctxBack.drawImage(n,0,0,r/l,a/l)),i.clearRect(0,0,r,a),e&&"transparent"!==e){var h;e.colorStops?(h=e.__canvasGradient||Zh.getGradient(i,e,{x:0,y:0,width:r,height:a}),e.__canvasGradient=h):e.image&&(h=Qh.prototype.getCanvasPattern.call(e,i)),i.save(),i.fillStyle=h||e,i.fillRect(0,0,r,a),i.restore()}if(o){var u=this.domBack;i.save(),i.globalAlpha=s,i.drawImage(u,0,0,r,a),i.restore()}}};var tu="undefined"!=typeof window&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){setTimeout(t,16)},eu=new Ih(50),nu={},iu=0,ru=5e3,au=/\{([a-zA-Z0-9_]+)\|([^}]*)\}/g,ou="12px sans-serif",su={};su.measureText=function(t,e){var n=s();return n.font=e||ou,n.measureText(t)};var lu={left:1,right:1,center:1},hu={top:1,bottom:1,middle:1},uu=new Nt,cu=function(){};cu.prototype={constructor:cu,drawRectText:function(t,e){var n=this.style;e=n.textRect||e,this.__dirty&&ye(n);var i=n.text;if(null!=i&&(i+=""),Be(i,n)){t.save();var r=this.transform;n.transformText?this.setTransform(t):r&&(uu.copy(e),uu.applyTransform(r),e=uu),xe(this,t,i,n,e),t.restore()}}},Ne.prototype={constructor:Ne,type:"displayable",__dirty:!0,invisible:!1,z:0,z2:0,zlevel:0,draggable:!1,dragging:!1,silent:!1,culling:!1,cursor:"pointer",rectHover:!1,progressive:!1,incremental:!1,inplace:!1,beforeBrush:function(t){},afterBrush:function(t){},brush:function(t,e){},getBoundingRect:function(){},contain:function(t,e){return this.rectContain(t,e)},traverse:function(t,e){t.call(e,this)},rectContain:function(t,e){var n=this.transformCoordToLocal(t,e);return this.getBoundingRect().contain(n[0],n[1])},dirty:function(){this.__dirty=!0,this._rect=null,this.__zr&&this.__zr.refresh()},animateStyle:function(t){return this.animate("style",t)},attrKV:function(t,e){"style"!==t?Rh.prototype.attrKV.call(this,t,e):this.style.set(e)},setStyle:function(t,e){return this.style.set(t,e),this.dirty(!1),this},useStyle:function(t){return this.style=new Zh(t,this),this.dirty(!1),this}},h(Ne,Rh),u(Ne,cu),Re.prototype={constructor:Re,type:"image",brush:function(t,e){var n=this.style,i=n.image;n.bind(t,this,e);var r=this._image=Kt(i,this._image,this,this.onload);if(r&&Jt(r)){var a=n.x||0,o=n.y||0,s=n.width,l=n.height,h=r.width/r.height;if(null==s&&null!=l?s=l*h:null==l&&null!=s?l=s/h:null==s&&null==l&&(s=r.width,l=r.height),this.setTransform(t),n.sWidth&&n.sHeight){var u=n.sx||0,c=n.sy||0;t.drawImage(r,u,c,n.sWidth,n.sHeight,a,o,s,l)}else if(n.sx&&n.sy){var f=s-(u=n.sx),d=l-(c=n.sy);t.drawImage(r,u,c,f,d,a,o,s,l)}else t.drawImage(r,a,o,s,l);null!=n.text&&(this.restoreTransform(t),this.drawRectText(t,this.getBoundingRect()))}},getBoundingRect:function(){var t=this.style;return this._rect||(this._rect=new Nt(t.x||0,t.y||0,t.width||0,t.height||0)),this._rect}},h(Re,Ne);var fu=new Nt(0,0,0,0),du=new Nt(0,0,0,0),pu=function(t,e,n){this.type="canvas";var i=!t.nodeName||"CANVAS"===t.nodeName.toUpperCase();this._opts=n=a({},n||{}),this.dpr=n.devicePixelRatio||Oh,this._singleCanvas=i,this.root=t;var r=t.style;r&&(r["-webkit-tap-highlight-color"]="transparent",r["-webkit-user-select"]=r["user-select"]=r["-webkit-touch-callout"]="none",t.innerHTML=""),this.storage=e;var o=this._zlevelList=[],s=this._layers={};if(this._layerConfig={},this._needsManuallyCompositing=!1,i){var l=t.width,h=t.height;null!=n.width&&(l=n.width),null!=n.height&&(h=n.height),this.dpr=n.devicePixelRatio||1,t.width=l*this.dpr,t.height=h*this.dpr,this._width=l,this._height=h;var u=new Jh(t,this,this.dpr);u.__builtin__=!0,u.initContext(),s[314159]=u,o.push(314159),this._domRoot=t}else{this._width=this._getSize(0),this._height=this._getSize(1);var c=this._domRoot=Ge(this._width,this._height);t.appendChild(c)}this._hoverlayer=null,this._hoverElements=[]};pu.prototype={constructor:pu,getType:function(){return"canvas"},isSingleCanvas:function(){return this._singleCanvas},getViewportRoot:function(){return this._domRoot},getViewportRootOffset:function(){var t=this.getViewportRoot();if(t)return{offsetLeft:t.offsetLeft||0,offsetTop:t.offsetTop||0}},refresh:function(t){var e=this.storage.getDisplayList(!0),n=this._zlevelList;this._redrawId=Math.random(),this._paintList(e,t,this._redrawId);for(var i=0;i<n.length;i++){var r=n[i],a=this._layers[r];if(!a.__builtin__&&a.refresh){var o=0===i?this._backgroundColor:null;a.refresh(o)}}return this.refreshHover(),this},addHover:function(t,e){if(!t.__hoverMir){var n=new t.constructor({style:t.style,shape:t.shape});n.__from=t,t.__hoverMir=n,n.setStyle(e),this._hoverElements.push(n)}},removeHover:function(t){var e=t.__hoverMir,n=this._hoverElements,i=l(n,e);i>=0&&n.splice(i,1),t.__hoverMir=null},clearHover:function(t){for(var e=this._hoverElements,n=0;n<e.length;n++){var i=e[n].__from;i&&(i.__hoverMir=null)}e.length=0},refreshHover:function(){var t=this._hoverElements,e=t.length,n=this._hoverlayer;if(n&&n.clear(),e){qt(t,this.storage.displayableSortFunc),n||(n=this._hoverlayer=this.getLayer(1e5));var i={};n.ctx.save();for(var r=0;r<e;){var a=t[r],o=a.__from;o&&o.__zr?(r++,o.invisible||(a.transform=o.transform,a.invTransform=o.invTransform,a.__clipPaths=o.__clipPaths,this._doPaintEl(a,n,!0,i))):(t.splice(r,1),o.__hoverMir=null,e--)}n.ctx.restore()}},getHoverLayer:function(){return this.getLayer(1e5)},_paintList:function(t,e,n){if(this._redrawId===n){e=e||!1,this._updateLayerStatus(t);var i=this._doPaintList(t,e);if(this._needsManuallyCompositing&&this._compositeManually(),!i){var r=this;tu(function(){r._paintList(t,e,n)})}}},_compositeManually:function(){var t=this.getLayer(314159).ctx,e=this._domRoot.width,n=this._domRoot.height;t.clearRect(0,0,e,n),this.eachBuiltinLayer(function(i){i.virtual&&t.drawImage(i.dom,0,0,e,n)})},_doPaintList:function(t,e){for(var n=[],i=0;i<this._zlevelList.length;i++){var r=this._zlevelList[i];(s=this._layers[r]).__builtin__&&s!==this._hoverlayer&&(s.__dirty||e)&&n.push(s)}for(var a=!0,o=0;o<n.length;o++){var s=n[o],l=s.ctx,h={};l.save();var u=e?s.__startIndex:s.__drawIndex,c=!e&&s.incremental&&Date.now,d=c&&Date.now(),p=s.zlevel===this._zlevelList[0]?this._backgroundColor:null;if(s.__startIndex===s.__endIndex)s.clear(!1,p);else if(u===s.__startIndex){var g=t[u];g.incremental&&g.notClear&&!e||s.clear(!1,p)}-1===u&&(console.error("For some unknown reason. drawIndex is -1"),u=s.__startIndex);for(var m=u;m<s.__endIndex;m++){var v=t[m];if(this._doPaintEl(v,s,e,h),v.__dirty=!1,c&&Date.now()-d>15)break}s.__drawIndex=m,s.__drawIndex<s.__endIndex&&(a=!1),h.prevElClipPaths&&l.restore(),l.restore()}return Yl.wxa&&f(this._layers,function(t){t&&t.ctx&&t.ctx.draw&&t.ctx.draw()}),a},_doPaintEl:function(t,e,n,i){var r=e.ctx,a=t.transform;if((e.__dirty||n)&&!t.invisible&&0!==t.style.opacity&&(!a||a[0]||a[3])&&(!t.culling||!Ve(t,this._width,this._height))){var o=t.__clipPaths;i.prevElClipPaths&&!We(o,i.prevElClipPaths)||(i.prevElClipPaths&&(e.ctx.restore(),i.prevElClipPaths=null,i.prevEl=null),o&&(r.save(),He(o,r),i.prevElClipPaths=o)),t.beforeBrush&&t.beforeBrush(r),t.brush(r,i.prevEl||null),i.prevEl=t,t.afterBrush&&t.afterBrush(r)}},getLayer:function(t,e){this._singleCanvas&&!this._needsManuallyCompositing&&(t=314159);var n=this._layers[t];return n||((n=new Jh("zr_"+t,this,this.dpr)).zlevel=t,n.__builtin__=!0,this._layerConfig[t]&&i(n,this._layerConfig[t],!0),e&&(n.virtual=e),this.insertLayer(t,n),n.initContext()),n},insertLayer:function(t,e){var n=this._layers,i=this._zlevelList,r=i.length,a=null,o=-1,s=this._domRoot;if(n[t])Bh("ZLevel "+t+" has been used already");else if(Fe(e)){if(r>0&&t>i[0]){for(o=0;o<r-1&&!(i[o]<t&&i[o+1]>t);o++);a=n[i[o]]}if(i.splice(o+1,0,t),n[t]=e,!e.virtual)if(a){var l=a.dom;l.nextSibling?s.insertBefore(e.dom,l.nextSibling):s.appendChild(e.dom)}else s.firstChild?s.insertBefore(e.dom,s.firstChild):s.appendChild(e.dom)}else Bh("Layer of zlevel "+t+" is not valid")},eachLayer:function(t,e){var n,i,r=this._zlevelList;for(i=0;i<r.length;i++)n=r[i],t.call(e,this._layers[n],n)},eachBuiltinLayer:function(t,e){var n,i,r,a=this._zlevelList;for(r=0;r<a.length;r++)i=a[r],(n=this._layers[i]).__builtin__&&t.call(e,n,i)},eachOtherLayer:function(t,e){var n,i,r,a=this._zlevelList;for(r=0;r<a.length;r++)i=a[r],(n=this._layers[i]).__builtin__||t.call(e,n,i)},getLayers:function(){return this._layers},_updateLayerStatus:function(t){function e(t){n&&(n.__endIndex!==t&&(n.__dirty=!0),n.__endIndex=t)}if(this.eachBuiltinLayer(function(t,e){t.__dirty=t.__used=!1}),this._singleCanvas)for(r=1;r<t.length;r++)if((o=t[r]).zlevel!==t[r-1].zlevel||o.incremental){this._needsManuallyCompositing=!0;break}for(var n=null,i=0,r=0;r<t.length;r++){var a,o=t[r],s=o.zlevel;o.incremental?((a=this.getLayer(s+.001,this._needsManuallyCompositing)).incremental=!0,i=1):a=this.getLayer(s+(i>0?.01:0),this._needsManuallyCompositing),a.__builtin__||Bh("ZLevel "+s+" has been used by unkown layer "+a.id),a!==n&&(a.__used=!0,a.__startIndex!==r&&(a.__dirty=!0),a.__startIndex=r,a.incremental?a.__drawIndex=-1:a.__drawIndex=r,e(r),n=a),o.__dirty&&(a.__dirty=!0,a.incremental&&a.__drawIndex<0&&(a.__drawIndex=r))}e(r),this.eachBuiltinLayer(function(t,e){!t.__used&&t.getElementCount()>0&&(t.__dirty=!0,t.__startIndex=t.__endIndex=t.__drawIndex=0),t.__dirty&&t.__drawIndex<0&&(t.__drawIndex=t.__startIndex)})},clear:function(){return this.eachBuiltinLayer(this._clearLayer),this},_clearLayer:function(t){t.clear()},setBackgroundColor:function(t){this._backgroundColor=t},configLayer:function(t,e){if(e){var n=this._layerConfig;n[t]?i(n[t],e,!0):n[t]=e;for(var r=0;r<this._zlevelList.length;r++){var a=this._zlevelList[r];a!==t&&a!==t+.01||i(this._layers[a],n[t],!0)}}},delLayer:function(t){var e=this._layers,n=this._zlevelList,i=e[t];i&&(i.dom.parentNode.removeChild(i.dom),delete e[t],n.splice(l(n,t),1))},resize:function(t,e){if(this._domRoot.style){var n=this._domRoot;n.style.display="none";var i=this._opts;if(null!=t&&(i.width=t),null!=e&&(i.height=e),t=this._getSize(0),e=this._getSize(1),n.style.display="",this._width!=t||e!=this._height){n.style.width=t+"px",n.style.height=e+"px";for(var r in this._layers)this._layers.hasOwnProperty(r)&&this._layers[r].resize(t,e);f(this._progressiveLayers,function(n){n.resize(t,e)}),this.refresh(!0)}this._width=t,this._height=e}else{if(null==t||null==e)return;this._width=t,this._height=e,this.getLayer(314159).resize(t,e)}return this},clearLayer:function(t){var e=this._layers[t];e&&e.clear()},dispose:function(){this.root.innerHTML="",this.root=this.storage=this._domRoot=this._layers=null},getRenderedCanvas:function(t){if(t=t||{},this._singleCanvas&&!this._compositeManually)return this._layers[314159].dom;var e=new Jh("image",this,t.pixelRatio||this.dpr);if(e.initContext(),e.clear(!1,t.backgroundColor||this._backgroundColor),t.pixelRatio<=this.dpr){this.refresh();var n=e.dom.width,i=e.dom.height,r=e.ctx;this.eachLayer(function(t){t.__builtin__?r.drawImage(t.dom,0,0,n,i):t.renderToCanvas&&(e.ctx.save(),t.renderToCanvas(e.ctx),e.ctx.restore())})}else for(var a={},o=this.storage.getDisplayList(!0),s=0;s<o.length;s++){var l=o[s];this._doPaintEl(l,e,!0,a)}return e.dom},getWidth:function(){return this._width},getHeight:function(){return this._height},_getSize:function(t){var e=this._opts,n=["width","height"][t],i=["clientWidth","clientHeight"][t],r=["paddingLeft","paddingTop"][t],a=["paddingRight","paddingBottom"][t];if(null!=e[n]&&"auto"!==e[n])return parseFloat(e[n]);var o=this.root,s=document.defaultView.getComputedStyle(o);return(o[i]||ze(s[n])||ze(o.style[n]))-(ze(s[r])||0)-(ze(s[a])||0)|0},pathToImage:function(t,e){e=e||this.dpr;var n=document.createElement("canvas"),i=n.getContext("2d"),r=t.getBoundingRect(),a=t.style,o=a.shadowBlur*e,s=a.shadowOffsetX*e,l=a.shadowOffsetY*e,h=a.hasStroke()?a.lineWidth:0,u=Math.max(h/2,-s+o),c=Math.max(h/2,s+o),f=Math.max(h/2,-l+o),d=Math.max(h/2,l+o),p=r.width+u+c,g=r.height+f+d;n.width=p*e,n.height=g*e,i.scale(e,e),i.clearRect(0,0,p,g),i.dpr=e;var m={position:t.position,rotation:t.rotation,scale:t.scale};t.position=[u-r.x,f-r.y],t.rotation=0,t.scale=[1,1],t.updateTransform(),t&&t.brush(i);var v=new Re({style:{x:0,y:0,image:n}});return null!=m.position&&(v.position=t.position=m.position),null!=m.rotation&&(v.rotation=t.rotation=m.rotation),null!=m.scale&&(v.scale=t.scale=m.scale),v}};var gu="undefined"!=typeof window&&!!window.addEventListener,mu=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,vu=function(t){t=t||{},this.stage=t.stage||{},this.onframe=t.onframe||function(){},this._clips=[],this._running=!1,this._time,this._pausedTime,this._pauseStart,this._paused=!1,ch.call(this)};vu.prototype={constructor:vu,addClip:function(t){this._clips.push(t)},addAnimator:function(t){t.animation=this;for(var e=t.getClips(),n=0;n<e.length;n++)this.addClip(e[n])},removeClip:function(t){var e=l(this._clips,t);e>=0&&this._clips.splice(e,1)},removeAnimator:function(t){for(var e=t.getClips(),n=0;n<e.length;n++)this.removeClip(e[n]);t.animation=null},_update:function(){for(var t=(new Date).getTime()-this._pausedTime,e=t-this._time,n=this._clips,i=n.length,r=[],a=[],o=0;o<i;o++){var s=n[o],l=s.step(t,e);l&&(r.push(l),a.push(s))}for(o=0;o<i;)n[o]._needsRemove?(n[o]=n[i-1],n.pop(),i--):o++;i=r.length;for(o=0;o<i;o++)a[o].fire(r[o]);this._time=t,this.onframe(e),this.trigger("frame",e),this.stage.update&&this.stage.update()},_startLoop:function(){function t(){e._running&&(tu(t),!e._paused&&e._update())}var e=this;this._running=!0,tu(t)},start:function(){this._time=(new Date).getTime(),this._pausedTime=0,this._startLoop()},stop:function(){this._running=!1},pause:function(){this._paused||(this._pauseStart=(new Date).getTime(),this._paused=!0)},resume:function(){this._paused&&(this._pausedTime+=(new Date).getTime()-this._pauseStart,this._paused=!1)},clear:function(){this._clips=[]},isFinished:function(){return!this._clips.length},animate:function(t,e){var n=new Lh(t,(e=e||{}).loop,e.getter,e.setter);return this.addAnimator(n),n}},u(vu,ch);var yu=function(){this._track=[]};yu.prototype={constructor:yu,recognize:function(t,e,n){return this._doTrack(t,e,n),this._recognize(t)},clear:function(){return this._track.length=0,this},_doTrack:function(t,e,n){var i=t.touches;if(i){for(var r={points:[],touches:[],target:e,event:t},a=0,o=i.length;a<o;a++){var s=i[a],l=Xe(n,s,{});r.points.push([l.zrX,l.zrY]),r.touches.push(s)}this._track.push(r)}},_recognize:function(t){for(var e in _u)if(_u.hasOwnProperty(e)){var n=_u[e](this._track,t);if(n)return n}}};var _u={pinch:function(t,e){var n=t.length;if(n){var i=(t[n-1]||{}).points,r=(t[n-2]||{}).points||i;if(r&&r.length>1&&i&&i.length>1){var a=$e(i)/$e(r);!isFinite(a)&&(a=1),e.pinchScale=a;var o=Ke(i);return e.pinchX=o[0],e.pinchY=o[1],{type:"pinch",target:t[0].target,event:e}}}}},xu=["click","dblclick","mousewheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],wu=["touchstart","touchend","touchmove"],bu={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},Su=d(xu,function(t){var e=t.replace("mouse","pointer");return bu[e]?e:t}),Mu={mousemove:function(t){t=Ye(this.dom,t),this.trigger("mousemove",t)},mouseout:function(t){var e=(t=Ye(this.dom,t)).toElement||t.relatedTarget;if(e!=this.dom)for(;e&&9!=e.nodeType;){if(e===this.dom)return;e=e.parentNode}this.trigger("mouseout",t)},touchstart:function(t){(t=Ye(this.dom,t)).zrByTouch=!0,this._lastTouchMoment=new Date,Je(this,t,"start"),Mu.mousemove.call(this,t),Mu.mousedown.call(this,t),tn(this)},touchmove:function(t){(t=Ye(this.dom,t)).zrByTouch=!0,Je(this,t,"change"),Mu.mousemove.call(this,t),tn(this)},touchend:function(t){(t=Ye(this.dom,t)).zrByTouch=!0,Je(this,t,"end"),Mu.mouseup.call(this,t),+new Date-this._lastTouchMoment<300&&Mu.click.call(this,t),tn(this)},pointerdown:function(t){Mu.mousedown.call(this,t)},pointermove:function(t){en(t)||Mu.mousemove.call(this,t)},pointerup:function(t){Mu.mouseup.call(this,t)},pointerout:function(t){en(t)||Mu.mouseout.call(this,t)}};f(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){Mu[t]=function(e){e=Ye(this.dom,e),this.trigger(t,e)}});var Iu=rn.prototype;Iu.dispose=function(){for(var t=xu.concat(wu),e=0;e<t.length;e++){var n=t[e];je(this.dom,Qe(n),this._handlers[n])}},Iu.setCursor=function(t){this.dom.style&&(this.dom.style.cursor=t||"default")},u(rn,ch);var Tu=!Yl.canvasSupported,Cu={canvas:pu},Du=function(t,e,n){n=n||{},this.dom=e,this.id=t;var i=this,r=new qh,a=n.renderer;if(Tu){if(!Cu.vml)throw new Error("You need to require 'zrender/vml/vml' to support IE8");a="vml"}else a&&Cu[a]||(a="canvas");var o=new Cu[a](e,r,n,t);this.storage=r,this.painter=o;var s=Yl.node||Yl.worker?null:new rn(o.getViewportRoot());this.handler=new ph(r,o,s,o.root),this.animation=new vu({stage:{update:m(this.flush,this)}}),this.animation.start(),this._needsRefresh;var l=r.delFromStorage,h=r.addToStorage;r.delFromStorage=function(t){l.call(r,t),t&&t.removeSelfFromZr(i)},r.addToStorage=function(t){h.call(r,t),t.addSelfToZr(i)}};Du.prototype={constructor:Du,getId:function(){return this.id},add:function(t){this.storage.addRoot(t),this._needsRefresh=!0},remove:function(t){this.storage.delRoot(t),this._needsRefresh=!0},configLayer:function(t,e){this.painter.configLayer&&this.painter.configLayer(t,e),this._needsRefresh=!0},setBackgroundColor:function(t){this.painter.setBackgroundColor&&this.painter.setBackgroundColor(t),this._needsRefresh=!0},refreshImmediately:function(){this._needsRefresh=!1,this.painter.refresh(),this._needsRefresh=!1},refresh:function(){this._needsRefresh=!0},flush:function(){var t;this._needsRefresh&&(t=!0,this.refreshImmediately()),this._needsRefreshHover&&(t=!0,this.refreshHoverImmediately()),t&&this.trigger("rendered")},addHover:function(t,e){this.painter.addHover&&(this.painter.addHover(t,e),this.refreshHover())},removeHover:function(t){this.painter.removeHover&&(this.painter.removeHover(t),this.refreshHover())},clearHover:function(){this.painter.clearHover&&(this.painter.clearHover(),this.refreshHover())},refreshHover:function(){this._needsRefreshHover=!0},refreshHoverImmediately:function(){this._needsRefreshHover=!1,this.painter.refreshHover&&this.painter.refreshHover()},resize:function(t){t=t||{},this.painter.resize(t.width,t.height),this.handler.resize()},clearAnimation:function(){this.animation.clear()},getWidth:function(){return this.painter.getWidth()},getHeight:function(){return this.painter.getHeight()},pathToImage:function(t,e){return this.painter.pathToImage(t,e)},setCursorStyle:function(t){this.handler.setCursorStyle(t)},findHover:function(t,e){return this.handler.findHover(t,e)},on:function(t,e,n){this.handler.on(t,e,n)},off:function(t,e){this.handler.off(t,e)},trigger:function(t,e){this.handler.trigger(t,e)},clear:function(){this.storage.delRoot(),this.painter.clear()},dispose:function(){this.animation.stop(),this.clear(),this.storage.dispose(),this.painter.dispose(),this.handler.dispose(),this.animation=this.storage=this.painter=this.handler=null}};var ku=f,Au=w,Lu=y,Pu="series\0",Ou=["fontStyle","fontWeight","fontSize","fontFamily","rich","tag","color","textBorderColor","textBorderWidth","width","height","lineHeight","align","verticalAlign","baseline","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","textShadowColor","textShadowBlur","textShadowOffsetX","textShadowOffsetY","backgroundColor","borderColor","borderWidth","borderRadius","padding"],Eu=0,Bu=".",Nu="___EC__COMPONENT__CONTAINER___",Ru=0,zu=function(t){for(var e=0;e<t.length;e++)t[e][1]||(t[e][1]=t[e][0]);return function(e,n,i){for(var r={},a=0;a<t.length;a++){var o=t[a][1];if(!(n&&l(n,o)>=0||i&&l(i,o)<0)){var s=e.getShallow(o);null!=s&&(r[t[a][0]]=s)}}return r}},Fu=zu([["lineWidth","width"],["stroke","color"],["opacity"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["shadowColor"]]),Vu={getLineStyle:function(t){var e=Fu(this,t),n=this.getLineDash(e.lineWidth);return n&&(e.lineDash=n),e},getLineDash:function(t){null==t&&(t=1);var e=this.get("type"),n=Math.max(t,2),i=4*t;return"solid"===e||null==e?null:"dashed"===e?[i,i]:[n,n]}},Wu=zu([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),Hu={getAreaStyle:function(t,e){return Wu(this,t,e)}},Gu=Math.pow,qu=Math.sqrt,Xu=1e-8,Uu=1e-4,Yu=qu(3),Zu=1/3,ju=z(),$u=z(),Ku=z(),Qu=Math.min,Ju=Math.max,tc=Math.sin,ec=Math.cos,nc=2*Math.PI,ic=z(),rc=z(),ac=z(),oc=[],sc=[],lc={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},hc=[],uc=[],cc=[],fc=[],dc=Math.min,pc=Math.max,gc=Math.cos,mc=Math.sin,vc=Math.sqrt,yc=Math.abs,_c="undefined"!=typeof Float32Array,xc=function(t){this._saveData=!t,this._saveData&&(this.data=[]),this._ctx=null};xc.prototype={constructor:xc,_xi:0,_yi:0,_x0:0,_y0:0,_ux:0,_uy:0,_len:0,_lineDash:null,_dashOffset:0,_dashIdx:0,_dashSum:0,setScale:function(t,e){this._ux=yc(1/Oh/t)||0,this._uy=yc(1/Oh/e)||0},getContext:function(){return this._ctx},beginPath:function(t){return this._ctx=t,t&&t.beginPath(),t&&(this.dpr=t.dpr),this._saveData&&(this._len=0),this._lineDash&&(this._lineDash=null,this._dashOffset=0),this},moveTo:function(t,e){return this.addData(lc.M,t,e),this._ctx&&this._ctx.moveTo(t,e),this._x0=t,this._y0=e,this._xi=t,this._yi=e,this},lineTo:function(t,e){var n=yc(t-this._xi)>this._ux||yc(e-this._yi)>this._uy||this._len<5;return this.addData(lc.L,t,e),this._ctx&&n&&(this._needsDash()?this._dashedLineTo(t,e):this._ctx.lineTo(t,e)),n&&(this._xi=t,this._yi=e),this},bezierCurveTo:function(t,e,n,i,r,a){return this.addData(lc.C,t,e,n,i,r,a),this._ctx&&(this._needsDash()?this._dashedBezierTo(t,e,n,i,r,a):this._ctx.bezierCurveTo(t,e,n,i,r,a)),this._xi=r,this._yi=a,this},quadraticCurveTo:function(t,e,n,i){return this.addData(lc.Q,t,e,n,i),this._ctx&&(this._needsDash()?this._dashedQuadraticTo(t,e,n,i):this._ctx.quadraticCurveTo(t,e,n,i)),this._xi=n,this._yi=i,this},arc:function(t,e,n,i,r,a){return this.addData(lc.A,t,e,n,n,i,r-i,0,a?0:1),this._ctx&&this._ctx.arc(t,e,n,i,r,a),this._xi=gc(r)*n+t,this._yi=mc(r)*n+t,this},arcTo:function(t,e,n,i,r){return this._ctx&&this._ctx.arcTo(t,e,n,i,r),this},rect:function(t,e,n,i){return this._ctx&&this._ctx.rect(t,e,n,i),this.addData(lc.R,t,e,n,i),this},closePath:function(){this.addData(lc.Z);var t=this._ctx,e=this._x0,n=this._y0;return t&&(this._needsDash()&&this._dashedLineTo(e,n),t.closePath()),this._xi=e,this._yi=n,this},fill:function(t){t&&t.fill(),this.toStatic()},stroke:function(t){t&&t.stroke(),this.toStatic()},setLineDash:function(t){if(t instanceof Array){this._lineDash=t,this._dashIdx=0;for(var e=0,n=0;n<t.length;n++)e+=t[n];this._dashSum=e}return this},setLineDashOffset:function(t){return this._dashOffset=t,this},len:function(){return this._len},setData:function(t){var e=t.length;this.data&&this.data.length==e||!_c||(this.data=new Float32Array(e));for(var n=0;n<e;n++)this.data[n]=t[n];this._len=e},appendPath:function(t){t instanceof Array||(t=[t]);for(var e=t.length,n=0,i=this._len,r=0;r<e;r++)n+=t[r].len();_c&&this.data instanceof Float32Array&&(this.data=new Float32Array(i+n));for(r=0;r<e;r++)for(var a=t[r].data,o=0;o<a.length;o++)this.data[i++]=a[o];this._len=i},addData:function(t){if(this._saveData){var e=this.data;this._len+arguments.length>e.length&&(this._expandData(),e=this.data);for(var n=0;n<arguments.length;n++)e[this._len++]=arguments[n];this._prevCmd=t}},_expandData:function(){if(!(this.data instanceof Array)){for(var t=[],e=0;e<this._len;e++)t[e]=this.data[e];this.data=t}},_needsDash:function(){return this._lineDash},_dashedLineTo:function(t,e){var n,i,r=this._dashSum,a=this._dashOffset,o=this._lineDash,s=this._ctx,l=this._xi,h=this._yi,u=t-l,c=e-h,f=vc(u*u+c*c),d=l,p=h,g=o.length;for(u/=f,c/=f,a<0&&(a=r+a),d-=(a%=r)*u,p-=a*c;u>0&&d<=t||u<0&&d>=t||0==u&&(c>0&&p<=e||c<0&&p>=e);)d+=u*(n=o[i=this._dashIdx]),p+=c*n,this._dashIdx=(i+1)%g,u>0&&d<l||u<0&&d>l||c>0&&p<h||c<0&&p>h||s[i%2?"moveTo":"lineTo"](u>=0?dc(d,t):pc(d,t),c>=0?dc(p,e):pc(p,e));u=d-t,c=p-e,this._dashOffset=-vc(u*u+c*c)},_dashedBezierTo:function(t,e,n,i,r,a){var o,s,l,h,u,c=this._dashSum,f=this._dashOffset,d=this._lineDash,p=this._ctx,g=this._xi,m=this._yi,v=kn,y=0,_=this._dashIdx,x=d.length,w=0;for(f<0&&(f=c+f),f%=c,o=0;o<1;o+=.1)s=v(g,t,n,r,o+.1)-v(g,t,n,r,o),l=v(m,e,i,a,o+.1)-v(m,e,i,a,o),y+=vc(s*s+l*l);for(;_<x&&!((w+=d[_])>f);_++);for(o=(w-f)/y;o<=1;)h=v(g,t,n,r,o),u=v(m,e,i,a,o),_%2?p.moveTo(h,u):p.lineTo(h,u),o+=d[_]/y,_=(_+1)%x;_%2!=0&&p.lineTo(r,a),s=r-h,l=a-u,this._dashOffset=-vc(s*s+l*l)},_dashedQuadraticTo:function(t,e,n,i){var r=n,a=i;n=(n+2*t)/3,i=(i+2*e)/3,t=(this._xi+2*t)/3,e=(this._yi+2*e)/3,this._dashedBezierTo(t,e,n,i,r,a)},toStatic:function(){var t=this.data;t instanceof Array&&(t.length=this._len,_c&&(this.data=new Float32Array(t)))},getBoundingRect:function(){hc[0]=hc[1]=cc[0]=cc[1]=Number.MAX_VALUE,uc[0]=uc[1]=fc[0]=fc[1]=-Number.MAX_VALUE;for(var t=this.data,e=0,n=0,i=0,r=0,a=0;a<t.length;){var o=t[a++];switch(1==a&&(i=e=t[a],r=n=t[a+1]),o){case lc.M:e=i=t[a++],n=r=t[a++],cc[0]=i,cc[1]=r,fc[0]=i,fc[1]=r;break;case lc.L:Wn(e,n,t[a],t[a+1],cc,fc),e=t[a++],n=t[a++];break;case lc.C:Hn(e,n,t[a++],t[a++],t[a++],t[a++],t[a],t[a+1],cc,fc),e=t[a++],n=t[a++];break;case lc.Q:Gn(e,n,t[a++],t[a++],t[a],t[a+1],cc,fc),e=t[a++],n=t[a++];break;case lc.A:var s=t[a++],l=t[a++],h=t[a++],u=t[a++],c=t[a++],f=t[a++]+c,d=(t[a++],1-t[a++]);1==a&&(i=gc(c)*h+s,r=mc(c)*u+l),qn(s,l,h,u,c,f,d,cc,fc),e=gc(f)*h+s,n=mc(f)*u+l;break;case lc.R:Wn(i=e=t[a++],r=n=t[a++],i+t[a++],r+t[a++],cc,fc);break;case lc.Z:e=i,n=r}Z(hc,hc,cc),j(uc,uc,fc)}return 0===a&&(hc[0]=hc[1]=uc[0]=uc[1]=0),new Nt(hc[0],hc[1],uc[0]-hc[0],uc[1]-hc[1])},rebuildPath:function(t){for(var e,n,i,r,a,o,s=this.data,l=this._ux,h=this._uy,u=this._len,c=0;c<u;){var f=s[c++];switch(1==c&&(e=i=s[c],n=r=s[c+1]),f){case lc.M:e=i=s[c++],n=r=s[c++],t.moveTo(i,r);break;case lc.L:a=s[c++],o=s[c++],(yc(a-i)>l||yc(o-r)>h||c===u-1)&&(t.lineTo(a,o),i=a,r=o);break;case lc.C:t.bezierCurveTo(s[c++],s[c++],s[c++],s[c++],s[c++],s[c++]),i=s[c-2],r=s[c-1];break;case lc.Q:t.quadraticCurveTo(s[c++],s[c++],s[c++],s[c++]),i=s[c-2],r=s[c-1];break;case lc.A:var d=s[c++],p=s[c++],g=s[c++],m=s[c++],v=s[c++],y=s[c++],_=s[c++],x=s[c++],w=g>m?g:m,b=g>m?1:g/m,S=g>m?m/g:1,M=v+y;Math.abs(g-m)>.001?(t.translate(d,p),t.rotate(_),t.scale(b,S),t.arc(0,0,w,v,M,1-x),t.scale(1/b,1/S),t.rotate(-_),t.translate(-d,-p)):t.arc(d,p,w,v,M,1-x),1==c&&(e=gc(v)*g+d,n=mc(v)*m+p),i=gc(M)*g+d,r=mc(M)*m+p;break;case lc.R:e=i=s[c],n=r=s[c+1],t.rect(s[c++],s[c++],s[c++],s[c++]);break;case lc.Z:t.closePath(),i=e,r=n}}}},xc.CMD=lc;var wc=2*Math.PI,bc=2*Math.PI,Sc=xc.CMD,Mc=2*Math.PI,Ic=1e-4,Tc=[-1,-1,-1],Cc=[-1,-1],Dc=Qh.prototype.getCanvasPattern,kc=Math.abs,Ac=new xc(!0);ai.prototype={constructor:ai,type:"path",__dirtyPath:!0,strokeContainThreshold:5,brush:function(t,e){var n=this.style,i=this.path||Ac,r=n.hasStroke(),a=n.hasFill(),o=n.fill,s=n.stroke,l=a&&!!o.colorStops,h=r&&!!s.colorStops,u=a&&!!o.image,c=r&&!!s.image;if(n.bind(t,this,e),this.setTransform(t),this.__dirty){var f;l&&(f=f||this.getBoundingRect(),this._fillGradient=n.getGradient(t,o,f)),h&&(f=f||this.getBoundingRect(),this._strokeGradient=n.getGradient(t,s,f))}l?t.fillStyle=this._fillGradient:u&&(t.fillStyle=Dc.call(o,t)),h?t.strokeStyle=this._strokeGradient:c&&(t.strokeStyle=Dc.call(s,t));var d=n.lineDash,p=n.lineDashOffset,g=!!t.setLineDash,m=this.getGlobalScale();i.setScale(m[0],m[1]),this.__dirtyPath||d&&!g&&r?(i.beginPath(t),d&&!g&&(i.setLineDash(d),i.setLineDashOffset(p)),this.buildPath(i,this.shape,!1),this.path&&(this.__dirtyPath=!1)):(t.beginPath(),this.path.rebuildPath(t)),a&&i.fill(t),d&&g&&(t.setLineDash(d),t.lineDashOffset=p),r&&i.stroke(t),d&&g&&t.setLineDash([]),null!=n.text&&(this.restoreTransform(t),this.drawRectText(t,this.getBoundingRect()))},buildPath:function(t,e,n){},createPathProxy:function(){this.path=new xc},getBoundingRect:function(){var t=this._rect,e=this.style,n=!t;if(n){var i=this.path;i||(i=this.path=new xc),this.__dirtyPath&&(i.beginPath(),this.buildPath(i,this.shape,!1)),t=i.getBoundingRect()}if(this._rect=t,e.hasStroke()){var r=this._rectWithStroke||(this._rectWithStroke=t.clone());if(this.__dirty||n){r.copy(t);var a=e.lineWidth,o=e.strokeNoScale?this.getLineScale():1;e.hasFill()||(a=Math.max(a,this.strokeContainThreshold||4)),o>1e-10&&(r.width+=a/o,r.height+=a/o,r.x-=a/o/2,r.y-=a/o/2)}return r}return t},contain:function(t,e){var n=this.transformCoordToLocal(t,e),i=this.getBoundingRect(),r=this.style;if(t=n[0],e=n[1],i.contain(t,e)){var a=this.path.data;if(r.hasStroke()){var o=r.lineWidth,s=r.strokeNoScale?this.getLineScale():1;if(s>1e-10&&(r.hasFill()||(o=Math.max(o,this.strokeContainThreshold)),ri(a,o/s,t,e)))return!0}if(r.hasFill())return ii(a,t,e)}return!1},dirty:function(t){null==t&&(t=!0),t&&(this.__dirtyPath=t,this._rect=null),this.__dirty=!0,this.__zr&&this.__zr.refresh(),this.__clipTarget&&this.__clipTarget.dirty()},animateShape:function(t){return this.animate("shape",t)},attrKV:function(t,e){"shape"===t?(this.setShape(e),this.__dirtyPath=!0,this._rect=null):Ne.prototype.attrKV.call(this,t,e)},setShape:function(t,e){var n=this.shape;if(n){if(w(t))for(var i in t)t.hasOwnProperty(i)&&(n[i]=t[i]);else n[t]=e;this.dirty(!0)}return this},getLineScale:function(){var t=this.transform;return t&&kc(t[0]-1)>1e-10&&kc(t[3]-1)>1e-10?Math.sqrt(kc(t[0]*t[3]-t[2]*t[1])):1}},ai.extend=function(t){var e=function(e){ai.call(this,e),t.style&&this.style.extendFrom(t.style,!1);var n=t.shape;if(n){this.shape=this.shape||{};var i=this.shape;for(var r in n)!i.hasOwnProperty(r)&&n.hasOwnProperty(r)&&(i[r]=n[r])}t.init&&t.init.call(this,e)};h(e,ai);for(var n in t)"style"!==n&&"shape"!==n&&(e.prototype[n]=t[n]);return e},h(ai,Ne);var Lc=xc.CMD,Pc=[[],[],[]],Oc=Math.sqrt,Ec=Math.atan2,Bc=function(t,e){var n,i,r,a,o,s,l=t.data,h=Lc.M,u=Lc.C,c=Lc.L,f=Lc.R,d=Lc.A,p=Lc.Q;for(r=0,a=0;r<l.length;){switch(n=l[r++],a=r,i=0,n){case h:case c:i=1;break;case u:i=3;break;case p:i=2;break;case d:var g=e[4],m=e[5],v=Oc(e[0]*e[0]+e[1]*e[1]),y=Oc(e[2]*e[2]+e[3]*e[3]),_=Ec(-e[1]/y,e[0]/v);l[r]*=v,l[r++]+=g,l[r]*=y,l[r++]+=m,l[r++]*=v,l[r++]*=y,l[r++]+=_,l[r++]+=_,a=r+=2;break;case f:s[0]=l[r++],s[1]=l[r++],Y(s,s,e),l[a++]=s[0],l[a++]=s[1],s[0]+=l[r++],s[1]+=l[r++],Y(s,s,e),l[a++]=s[0],l[a++]=s[1]}for(o=0;o<i;o++)(s=Pc[o])[0]=l[r++],s[1]=l[r++],Y(s,s,e),l[a++]=s[0],l[a++]=s[1]}},Nc=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"],Rc=Math.sqrt,zc=Math.sin,Fc=Math.cos,Vc=Math.PI,Wc=function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},Hc=function(t,e){return(t[0]*e[0]+t[1]*e[1])/(Wc(t)*Wc(e))},Gc=function(t,e){return(t[0]*e[1]<t[1]*e[0]?-1:1)*Math.acos(Hc(t,e))},qc=function(t){Ne.call(this,t)};qc.prototype={constructor:qc,type:"text",brush:function(t,e){var n=this.style;this.__dirty&&ye(n),n.fill=n.stroke=n.shadowBlur=n.shadowColor=n.shadowOffsetX=n.shadowOffsetY=null;var i=n.text;null!=i&&(i+=""),n.bind(t,this,e),Be(i,n)&&(this.setTransform(t),xe(this,t,i,n),this.restoreTransform(t))},getBoundingRect:function(){var t=this.style;if(this.__dirty&&ye(t),!this._rect){var e=t.text;null!=e?e+="":e="";var n=ee(t.text+"",t.font,t.textAlign,t.textVerticalAlign,t.textPadding,t.rich);if(n.x+=t.x||0,n.y+=t.y||0,Le(t.textStroke,t.textStrokeWidth)){var i=t.textStrokeWidth;n.x-=i/2,n.y-=i/2,n.width+=i,n.height+=i}this._rect=n}return this._rect}},h(qc,Ne);var Xc=ai.extend({type:"circle",shape:{cx:0,cy:0,r:0},buildPath:function(t,e,n){n&&t.moveTo(e.cx+e.r,e.cy),t.arc(e.cx,e.cy,e.r,0,2*Math.PI,!0)}}),Uc=[["shadowBlur",0],["shadowColor","#000"],["shadowOffsetX",0],["shadowOffsetY",0]],Yc=function(t){return Yl.browser.ie&&Yl.browser.version>=11?function(){var e,n=this.__clipPaths,i=this.style;if(n)for(var r=0;r<n.length;r++){var a=n[r],o=a&&a.shape,s=a&&a.type;if(o&&("sector"===s&&o.startAngle===o.endAngle||"rect"===s&&(!o.width||!o.height))){for(l=0;l<Uc.length;l++)Uc[l][2]=i[Uc[l][0]],i[Uc[l][0]]=Uc[l][1];e=!0;break}}if(t.apply(this,arguments),e)for(var l=0;l<Uc.length;l++)i[Uc[l][0]]=Uc[l][2]}:t},Zc=ai.extend({type:"sector",shape:{cx:0,cy:0,r0:0,r:0,startAngle:0,endAngle:2*Math.PI,clockwise:!0},brush:Yc(ai.prototype.brush),buildPath:function(t,e){var n=e.cx,i=e.cy,r=Math.max(e.r0||0,0),a=Math.max(e.r,0),o=e.startAngle,s=e.endAngle,l=e.clockwise,h=Math.cos(o),u=Math.sin(o);t.moveTo(h*r+n,u*r+i),t.lineTo(h*a+n,u*a+i),t.arc(n,i,a,o,s,!l),t.lineTo(Math.cos(s)*r+n,Math.sin(s)*r+i),0!==r&&t.arc(n,i,r,s,o,l),t.closePath()}}),jc=ai.extend({type:"ring",shape:{cx:0,cy:0,r:0,r0:0},buildPath:function(t,e){var n=e.cx,i=e.cy,r=2*Math.PI;t.moveTo(n+e.r,i),t.arc(n,i,e.r,0,r,!1),t.moveTo(n+e.r0,i),t.arc(n,i,e.r0,0,r,!0)}}),$c=function(t,e){for(var n=t.length,i=[],r=0,a=1;a<n;a++)r+=U(t[a-1],t[a]);var o=r/2;o=o<n?n:o;for(a=0;a<o;a++){var s,l,h,u=a/(o-1)*(e?n:n-1),c=Math.floor(u),f=u-c,d=t[c%n];e?(s=t[(c-1+n)%n],l=t[(c+1)%n],h=t[(c+2)%n]):(s=t[0===c?c:c-1],l=t[c>n-2?n-1:c+1],h=t[c>n-3?n-1:c+2]);var p=f*f,g=f*p;i.push([ci(s[0],d[0],l[0],h[0],f,p,g),ci(s[1],d[1],l[1],h[1],f,p,g)])}return i},Kc=function(t,e,n,i){var r,a,o,s,l=[],h=[],u=[],c=[];if(i){o=[1/0,1/0],s=[-1/0,-1/0];for(var f=0,d=t.length;f<d;f++)Z(o,o,t[f]),j(s,s,t[f]);Z(o,o,i[0]),j(s,s,i[1])}for(var f=0,d=t.length;f<d;f++){var p=t[f];if(n)r=t[f?f-1:d-1],a=t[(f+1)%d];else{if(0===f||f===d-1){l.push(F(t[f]));continue}r=t[f-1],a=t[f+1]}W(h,a,r),q(h,h,e);var g=U(p,r),m=U(p,a),v=g+m;0!==v&&(g/=v,m/=v),q(u,h,-g),q(c,h,m);var y=V([],p,u),_=V([],p,c);i&&(j(y,y,o),Z(y,y,s),j(_,_,o),Z(_,_,s)),l.push(y),l.push(_)}return n&&l.push(l.shift()),l},Qc=ai.extend({type:"polygon",shape:{points:null,smooth:!1,smoothConstraint:null},buildPath:function(t,e){fi(t,e,!0)}}),Jc=ai.extend({type:"polyline",shape:{points:null,smooth:!1,smoothConstraint:null},style:{stroke:"#000",fill:null},buildPath:function(t,e){fi(t,e,!1)}}),tf=ai.extend({type:"rect",shape:{r:0,x:0,y:0,width:0,height:0},buildPath:function(t,e){var n=e.x,i=e.y,r=e.width,a=e.height;e.r?ve(t,e):t.rect(n,i,r,a),t.closePath()}}),ef=ai.extend({type:"line",shape:{x1:0,y1:0,x2:0,y2:0,percent:1},style:{stroke:"#000",fill:null},buildPath:function(t,e){var n=e.x1,i=e.y1,r=e.x2,a=e.y2,o=e.percent;0!==o&&(t.moveTo(n,i),o<1&&(r=n*(1-o)+r*o,a=i*(1-o)+a*o),t.lineTo(r,a))},pointAt:function(t){var e=this.shape;return[e.x1*(1-t)+e.x2*t,e.y1*(1-t)+e.y2*t]}}),nf=[],rf=ai.extend({type:"bezier-curve",shape:{x1:0,y1:0,x2:0,y2:0,cpx1:0,cpy1:0,percent:1},style:{stroke:"#000",fill:null},buildPath:function(t,e){var n=e.x1,i=e.y1,r=e.x2,a=e.y2,o=e.cpx1,s=e.cpy1,l=e.cpx2,h=e.cpy2,u=e.percent;0!==u&&(t.moveTo(n,i),null==l||null==h?(u<1&&(Fn(n,o,r,u,nf),o=nf[1],r=nf[2],Fn(i,s,a,u,nf),s=nf[1],a=nf[2]),t.quadraticCurveTo(o,s,r,a)):(u<1&&(On(n,o,l,r,u,nf),o=nf[1],l=nf[2],r=nf[3],On(i,s,h,a,u,nf),s=nf[1],h=nf[2],a=nf[3]),t.bezierCurveTo(o,s,l,h,r,a)))},pointAt:function(t){return di(this.shape,t,!1)},tangentAt:function(t){var e=di(this.shape,t,!0);return X(e,e)}}),af=ai.extend({type:"arc",shape:{cx:0,cy:0,r:0,startAngle:0,endAngle:2*Math.PI,clockwise:!0},style:{stroke:"#000",fill:null},buildPath:function(t,e){var n=e.cx,i=e.cy,r=Math.max(e.r,0),a=e.startAngle,o=e.endAngle,s=e.clockwise,l=Math.cos(a),h=Math.sin(a);t.moveTo(l*r+n,h*r+i),t.arc(n,i,r,a,o,!s)}}),of=ai.extend({type:"compound",shape:{paths:null},_updatePathDirty:function(){for(var t=this.__dirtyPath,e=this.shape.paths,n=0;n<e.length;n++)t=t||e[n].__dirtyPath;this.__dirtyPath=t,this.__dirty=this.__dirty||t},beforeBrush:function(){this._updatePathDirty();for(var t=this.shape.paths||[],e=this.getGlobalScale(),n=0;n<t.length;n++)t[n].path||t[n].createPathProxy(),t[n].path.setScale(e[0],e[1])},buildPath:function(t,e){for(var n=e.paths||[],i=0;i<n.length;i++)n[i].buildPath(t,n[i].shape,!0)},afterBrush:function(){for(var t=this.shape.paths||[],e=0;e<t.length;e++)t[e].__dirtyPath=!1},getBoundingRect:function(){return this._updatePathDirty(),ai.prototype.getBoundingRect.call(this)}}),sf=function(t){this.colorStops=t||[]};sf.prototype={constructor:sf,addColorStop:function(t,e){this.colorStops.push({offset:t,color:e})}};var lf=function(t,e,n,i,r,a){this.x=null==t?0:t,this.y=null==e?0:e,this.x2=null==n?1:n,this.y2=null==i?0:i,this.type="linear",this.global=a||!1,sf.call(this,r)};lf.prototype={constructor:lf},h(lf,sf);var hf=function(t,e,n,i,r){this.x=null==t?.5:t,this.y=null==e?.5:e,this.r=null==n?.5:n,this.type="radial",this.global=r||!1,sf.call(this,i)};hf.prototype={constructor:hf},h(hf,sf),pi.prototype.incremental=!0,pi.prototype.clearDisplaybles=function(){this._displayables=[],this._temporaryDisplayables=[],this._cursor=0,this.dirty(),this.notClear=!1},pi.prototype.addDisplayable=function(t,e){e?this._temporaryDisplayables.push(t):this._displayables.push(t),this.dirty()},pi.prototype.addDisplayables=function(t,e){e=e||!1;for(var n=0;n<t.length;n++)this.addDisplayable(t[n],e)},pi.prototype.eachPendingDisplayable=function(t){for(e=this._cursor;e<this._displayables.length;e++)t&&t(this._displayables[e]);for(var e=0;e<this._temporaryDisplayables.length;e++)t&&t(this._temporaryDisplayables[e])},pi.prototype.update=function(){this.updateTransform();for(t=this._cursor;t<this._displayables.length;t++)(e=this._displayables[t]).parent=this,e.update(),e.parent=null;for(var t=0;t<this._temporaryDisplayables.length;t++){var e=this._temporaryDisplayables[t];e.parent=this,e.update(),e.parent=null}},pi.prototype.brush=function(t,e){for(n=this._cursor;n<this._displayables.length;n++)(i=this._temporaryDisplayables[n]).beforeBrush&&i.beforeBrush(t),i.brush(t,n===this._cursor?null:this._displayables[n-1]),i.afterBrush&&i.afterBrush(t);this._cursor=n;for(var n=0;n<this._temporaryDisplayables.length;n++){var i=this._temporaryDisplayables[n];i.beforeBrush&&i.beforeBrush(t),i.brush(t,0===n?null:this._temporaryDisplayables[n-1]),i.afterBrush&&i.afterBrush(t)}this._temporaryDisplayables=[],this.notClear=!0};var uf=[];pi.prototype.getBoundingRect=function(){if(!this._rect){for(var t=new Nt(1/0,1/0,-1/0,-1/0),e=0;e<this._displayables.length;e++){var n=this._displayables[e],i=n.getBoundingRect().clone();n.needLocalTransform()&&i.applyTransform(n.getLocalTransform(uf)),t.union(i)}this._rect=t}return this._rect},pi.prototype.contain=function(t,e){var n=this.transformCoordToLocal(t,e);if(this.getBoundingRect().contain(n[0],n[1]))for(var i=0;i<this._displayables.length;i++)if(this._displayables[i].contain(t,e))return!0;return!1},h(pi,Ne);var cf=Math.round,ff=Math.max,df=Math.min,pf={},gf=(Object.freeze||Object)({extendShape:gi,extendPath:function(t,e){return ui(t,e)},makePath:mi,makeImage:vi,mergePath:function(t,e){for(var n=[],i=t.length,r=0;r<i;r++){var a=t[r];a.path||a.createPathProxy(),a.__dirtyPath&&a.buildPath(a.path,a.shape,!0),n.push(a.path)}var o=new ai(e);return o.createPathProxy(),o.buildPath=function(t){t.appendPath(n);var e=t.getContext();e&&t.rebuildPath(e)},o},resizePath:_i,subPixelOptimizeLine:xi,subPixelOptimizeRect:function(t){var e=t.shape,n=t.style.lineWidth,i=e.x,r=e.y,a=e.width,o=e.height;return e.x=wi(e.x,n,!0),e.y=wi(e.y,n,!0),e.width=Math.max(wi(i+a,n,!1)-e.x,0===a?0:1),e.height=Math.max(wi(r+o,n,!1)-e.y,0===o?0:1),t},subPixelOptimize:wi,setHoverStyle:Ei,setLabelStyle:Bi,setTextStyle:Ni,setText:function(t,e,n){var i,r={isRectText:!0};!1===n?i=!0:r.autoColor=n,Ri(t,e,r,i),t.host&&t.host.dirty&&t.host.dirty(!1)},getFont:Gi,updateProps:Xi,initProps:Ui,getTransform:function(t,e){for(var n=nt([]);t&&t!==e;)rt(n,t.getLocalTransform(),n),t=t.parent;return n},applyTransform:Yi,transformDirection:function(t,e,n){var i=0===e[4]||0===e[5]||0===e[0]?1:Math.abs(2*e[4]/e[0]),r=0===e[4]||0===e[5]||0===e[2]?1:Math.abs(2*e[4]/e[2]),a=["left"===t?-i:"right"===t?i:0,"top"===t?-r:"bottom"===t?r:0];return a=Yi(a,e,n),Math.abs(a[0])>Math.abs(a[1])?a[0]>0?"right":"left":a[1]>0?"bottom":"top"},groupTransition:Zi,clipPointsByRect:function(t,e){return d(t,function(t){var n=t[0];n=ff(n,e.x),n=df(n,e.x+e.width);var i=t[1];return i=ff(i,e.y),i=df(i,e.y+e.height),[n,i]})},clipRectByRect:function(t,e){var n=ff(t.x,e.x),i=df(t.x+t.width,e.x+e.width),r=ff(t.y,e.y),a=df(t.y+t.height,e.y+e.height);if(i>=n&&a>=r)return{x:n,y:r,width:i-n,height:a-r}},createIcon:function(t,e,n){var i=(e=a({rectHover:!0},e)).style={strokeNoScale:!0};if(n=n||{x:-1,y:-1,width:2,height:2},t)return 0===t.indexOf("image://")?(i.image=t.slice(8),o(i,n),new Re(e)):mi(t.replace("path://",""),e,n,"center")},Group:Wh,Image:Re,Text:qc,Circle:Xc,Sector:Zc,Ring:jc,Polygon:Qc,Polyline:Jc,Rect:tf,Line:ef,BezierCurve:rf,Arc:af,IncrementalDisplayable:pi,CompoundPath:of,LinearGradient:lf,RadialGradient:hf,BoundingRect:Nt}),mf=["textStyle","color"],vf={getTextColor:function(t){var e=this.ecModel;return this.getShallow("color")||(!t&&e?e.get(mf):null)},getFont:function(){return Gi({fontStyle:this.getShallow("fontStyle"),fontWeight:this.getShallow("fontWeight"),fontSize:this.getShallow("fontSize"),fontFamily:this.getShallow("fontFamily")},this.ecModel)},getTextRect:function(t){return ee(t,this.getFont(),this.getShallow("align"),this.getShallow("verticalAlign")||this.getShallow("baseline"),this.getShallow("padding"),this.getShallow("rich"),this.getShallow("truncateText"))}},yf=zu([["fill","color"],["stroke","borderColor"],["lineWidth","borderWidth"],["opacity"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["shadowColor"],["textPosition"],["textAlign"]]),_f={getItemStyle:function(t,e){var n=yf(this,t,e),i=this.getBorderLineDash();return i&&(n.lineDash=i),n},getBorderLineDash:function(){var t=this.get("borderType");return"solid"===t||null==t?null:"dashed"===t?[5,5]:[1,1]}},xf=u,wf=gn();ji.prototype={constructor:ji,init:null,mergeOption:function(t){i(this.option,t,!0)},get:function(t,e){return null==t?this.option:$i(this.option,this.parsePath(t),!e&&Ki(this,t))},getShallow:function(t,e){var n=this.option,i=null==n?n:n[t],r=!e&&Ki(this,t);return null==i&&r&&(i=r.getShallow(t)),i},getModel:function(t,e){var n,i=null==t?this.option:$i(this.option,t=this.parsePath(t));return e=e||(n=Ki(this,t))&&n.getModel(t),new ji(i,e,this.ecModel)},isEmpty:function(){return null==this.option},restoreData:function(){},clone:function(){return new(0,this.constructor)(n(this.option))},setReadOnly:function(t){},parsePath:function(t){return"string"==typeof t&&(t=t.split(".")),t},customizeGetParent:function(t){wf(this).getParent=t},isAnimationEnabled:function(){if(!Yl.node){if(null!=this.option.animation)return!!this.option.animation;if(this.parentModel)return this.parentModel.isAnimationEnabled()}}},bn(ji),Sn(ji),xf(ji,Vu),xf(ji,Hu),xf(ji,vf),xf(ji,_f);var bf=0,Sf=1e-4,Mf=/^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d\d)(?::(\d\d)(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/,If=A,Tf=["a","b","c","d","e","f","g"],Cf=function(t,e){return"{"+t+(null==e?"":e)+"}"},Df=se,kf=f,Af=["left","right","top","bottom","width","height"],Lf=[["width","left","right"],["height","top","bottom"]],Pf=(v(yr,"vertical"),v(yr,"horizontal"),{getBoxLayoutParams:function(){return{left:this.get("left"),top:this.get("top"),right:this.get("right"),bottom:this.get("bottom"),width:this.get("width"),height:this.get("height")}}}),Of=gn(),Ef=ji.extend({type:"component",id:"",name:"",mainType:"",subType:"",componentIndex:0,defaultOption:null,ecModel:null,dependentModels:[],uid:null,layoutMode:null,$constructor:function(t,e,n,i){ji.call(this,t,e,n,i),this.uid=Qi("ec_cpt_model")},init:function(t,e,n,i){this.mergeDefaultAndTheme(t,n)},mergeDefaultAndTheme:function(t,e){var n=this.layoutMode,r=n?wr(t):{};i(t,e.getTheme().get(this.mainType)),i(t,this.getDefaultOption()),n&&xr(t,r,n)},mergeOption:function(t,e){i(this.option,t,!0);var n=this.layoutMode;n&&xr(this.option,t,n)},optionUpdated:function(t,e){},getDefaultOption:function(){var t=Of(this);if(!t.defaultOption){for(var e=[],n=this.constructor;n;){var r=n.prototype.defaultOption;r&&e.push(r),n=n.superClass}for(var a={},o=e.length-1;o>=0;o--)a=i(a,e[o],!0);t.defaultOption=a}return t.defaultOption},getReferringComponents:function(t){return this.ecModel.queryComponents({mainType:t,index:this.get(t+"Index",!0),id:this.get(t+"Id",!0)})}});Tn(Ef,{registerWhenExtend:!0}),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){t=xn(t),e[t.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var a=xn(n).main;t.hasSubTypes(n)&&e[a]&&(r=e[a](i))}return r}}(Ef),function(t,e){function n(t){var n={},a=[];return f(t,function(o){var s=i(n,o),h=r(s.originalDeps=e(o),t);s.entryCount=h.length,0===s.entryCount&&a.push(o),f(h,function(t){l(s.predecessor,t)<0&&s.predecessor.push(t);var e=i(n,t);l(e.successor,t)<0&&e.successor.push(o)})}),{graph:n,noEntryList:a}}function i(t,e){return t[e]||(t[e]={predecessor:[],successor:[]}),t[e]}function r(t,e){var n=[];return f(t,function(t){l(e,t)>=0&&n.push(t)}),n}t.topologicalTravel=function(t,e,i,r){function a(t){s[t].entryCount--,0===s[t].entryCount&&l.push(t)}if(t.length){var o=n(e),s=o.graph,l=o.noEntryList,h={};for(f(t,function(t){h[t]=!0});l.length;){var u=l.pop(),c=s[u],d=!!h[u];d&&(i.call(r,u,c.originalDeps.slice()),delete h[u]),f(c.successor,d?function(t){h[t]=!0,a(t)}:a)}f(h,function(){throw new Error("Circle dependency may exists")})}}}(Ef,function(t){var e=[];return f(Ef.getClassesByMainType(t),function(t){e=e.concat(t.prototype.dependencies||[])}),e=d(e,function(t){return xn(t).main}),"dataset"!==t&&l(e,"dataset")<=0&&e.unshift("dataset"),e}),u(Ef,Pf);var Bf="";"undefined"!=typeof navigator&&(Bf=navigator.platform||"");var Nf={color:["#c23531","#2f4554","#61a0a8","#d48265","#91c7ae","#749f83","#ca8622","#bda29a","#6e7074","#546570","#c4ccd3"],gradientColor:["#f6efa6","#d88273","#bf444c"],textStyle:{fontFamily:Bf.match(/^Win/)?"Microsoft YaHei":"sans-serif",fontSize:12,fontStyle:"normal",fontWeight:"normal"},blendMode:null,animation:"auto",animationDuration:1e3,animationDurationUpdate:300,animationEasing:"exponentialOut",animationEasingUpdate:"cubicOut",animationThreshold:2e3,progressiveThreshold:3e3,progressive:400,hoverLayerThreshold:3e3,useUTC:!1},Rf=gn(),zf={clearColorPalette:function(){Rf(this).colorIdx=0,Rf(this).colorNameMap={}},getColorFromPalette:function(t,e,n){var i=Rf(e=e||this),r=i.colorIdx||0,a=i.colorNameMap=i.colorNameMap||{};if(a.hasOwnProperty(t))return a[t];var o=on(this.get("color",!0)),s=this.get("colorLayer",!0),l=null!=n&&s?Sr(s,n):o;if((l=l||o)&&l.length){var h=l[r];return t&&(a[t]=h),i.colorIdx=(r+1)%l.length,h}}},Ff={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis")[0],a=t.getReferringComponents("yAxis")[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",a),Ir(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),Ir(a)&&(i.set("y",a),e.firstCategoryDimIndex=1)},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis")[0];e.coordSysDims=["single"],n.set("single",r),Ir(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar")[0],a=r.findAxisModel("radiusAxis"),o=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",a),n.set("angle",o),Ir(a)&&(i.set("radius",a),e.firstCategoryDimIndex=0),Ir(o)&&(i.set("angle",o),e.firstCategoryDimIndex=1)},geo:function(t,e,n,i){e.coordSysDims=["lng","lat"]},parallel:function(t,e,n,i){var r=t.ecModel,a=r.getComponent("parallel",t.get("parallelIndex")),o=e.coordSysDims=a.dimensions.slice();f(a.parallelAxisIndex,function(t,a){var s=r.getComponent("parallelAxis",t),l=o[a];n.set(l,s),Ir(s)&&null==e.firstCategoryDimIndex&&(i.set(l,s),e.firstCategoryDimIndex=a)})}},Vf="original",Wf="arrayRows",Hf="objectRows",Gf="keyedColumns",qf="unknown",Xf="typedArray",Uf="column",Yf="row";Tr.seriesDataToSource=function(t){return new Tr({data:t,sourceFormat:S(t)?Xf:Vf,fromDataset:!1})},Sn(Tr);var Zf=gn(),jf="\0_ec_inner",$f=ji.extend({constructor:$f,init:function(t,e,n,i){n=n||{},this.option=null,this._theme=new ji(n),this._optionManager=i},setOption:function(t,e){L(!(jf in t),"please use chart.getOption()"),this._optionManager.setOption(t,e),this.resetOption(null)},resetOption:function(t){var e=!1,n=this._optionManager;if(!t||"recreate"===t){var i=n.mountOption("recreate"===t);this.option&&"recreate"!==t?(this.restoreData(),this.mergeOption(i)):Wr.call(this,i),e=!0}if("timeline"!==t&&"media"!==t||this.restoreData(),!t||"recreate"===t||"timeline"===t){var r=n.getTimelineOption(this);r&&(this.mergeOption(r),e=!0)}if(!t||"recreate"===t||"media"===t){var a=n.getMediaOption(this,this._api);a.length&&f(a,function(t){this.mergeOption(t,e=!0)},this)}return e},mergeOption:function(t){var e=this.option,r=this._componentsMap,o=[];kr(this),f(t,function(t,r){null!=t&&(Ef.hasClass(r)?r&&o.push(r):e[r]=null==e[r]?n(t):i(e[r],t,!0))}),Ef.topologicalTravel(o,Ef.getAllClassMainTypes(),function(n,i){var o=on(t[n]),s=un(r.get(n),o);cn(s),f(s,function(t,e){var i=t.option;w(i)&&(t.keyInfo.mainType=n,t.keyInfo.subType=Gr(n,i,t.exist))});var l=Hr(r,i);e[n]=[],r.set(n,[]),f(s,function(t,i){var o=t.exist,s=t.option;if(L(w(s)||o,"Empty component definition"),s){var h=Ef.getClass(n,t.keyInfo.subType,!0);if(o&&o instanceof h)o.name=t.keyInfo.name,o.mergeOption(s,this),o.optionUpdated(s,!1);else{var u=a({dependentModels:l,componentIndex:i},t.keyInfo);a(o=new h(s,this,this,u),u),o.init(s,this,this,u),o.optionUpdated(null,!0)}}else o.mergeOption({},this),o.optionUpdated({},!1);r.get(n)[i]=o,e[n][i]=o.option},this),"series"===n&&qr(this,r.get("series"))},this),this._seriesIndicesMap=N(this._seriesIndices=this._seriesIndices||[])},getOption:function(){var t=n(this.option);return f(t,function(e,n){if(Ef.hasClass(n)){for(var i=(e=on(e)).length-1;i>=0;i--)dn(e[i])&&e.splice(i,1);t[n]=e}}),delete t[jf],t},getTheme:function(){return this._theme},getComponent:function(t,e){var n=this._componentsMap.get(t);if(n)return n[e||0]},queryComponents:function(t){var e=t.mainType;if(!e)return[];var n=t.index,i=t.id,r=t.name,a=this._componentsMap.get(e);if(!a||!a.length)return[];var o;if(null!=n)y(n)||(n=[n]),o=g(d(n,function(t){return a[t]}),function(t){return!!t});else if(null!=i){var s=y(i);o=g(a,function(t){return s&&l(i,t.id)>=0||!s&&t.id===i})}else if(null!=r){var h=y(r);o=g(a,function(t){return h&&l(r,t.name)>=0||!h&&t.name===r})}else o=a.slice();return Xr(o,t)},findComponents:function(t){var e=t.query,n=t.mainType,i=function(t){var e=n+"Index",i=n+"Id",r=n+"Name";return!t||null==t[e]&&null==t[i]&&null==t[r]?null:{mainType:n,index:t[e],id:t[i],name:t[r]}}(e);return function(e){return t.filter?g(e,t.filter):e}(Xr(i?this.queryComponents(i):this._componentsMap.get(n),t))},eachComponent:function(t,e,n){var i=this._componentsMap;"function"==typeof t?(n=e,e=t,i.each(function(t,i){f(t,function(t,r){e.call(n,i,t,r)})})):x(t)?f(i.get(t),e,n):w(t)&&f(this.findComponents(t),e,n)},getSeriesByName:function(t){return g(this._componentsMap.get("series"),function(e){return e.name===t})},getSeriesByIndex:function(t){return this._componentsMap.get("series")[t]},getSeriesByType:function(t){return g(this._componentsMap.get("series"),function(e){return e.subType===t})},getSeries:function(){return this._componentsMap.get("series").slice()},getSeriesCount:function(){return this._componentsMap.get("series").length},eachSeries:function(t,e){f(this._seriesIndices,function(n){var i=this._componentsMap.get("series")[n];t.call(e,i,n)},this)},eachRawSeries:function(t,e){f(this._componentsMap.get("series"),t,e)},eachSeriesByType:function(t,e,n){f(this._seriesIndices,function(i){var r=this._componentsMap.get("series")[i];r.subType===t&&e.call(n,r,i)},this)},eachRawSeriesByType:function(t,e,n){return f(this.getSeriesByType(t),e,n)},isSeriesFiltered:function(t){return null==this._seriesIndicesMap.get(t.componentIndex)},getCurrentSeriesIndices:function(){return(this._seriesIndices||[]).slice()},filterSeries:function(t,e){qr(this,g(this._componentsMap.get("series"),t,e))},restoreData:function(t){var e=this._componentsMap;qr(this,e.get("series"));var n=[];e.each(function(t,e){n.push(e)}),Ef.topologicalTravel(n,Ef.getAllClassMainTypes(),function(n,i){f(e.get(n),function(e){("series"!==n||!Fr(e,t))&&e.restoreData()})})}});u($f,zf);var Kf=["getDom","getZr","getWidth","getHeight","getDevicePixelRatio","dispatchAction","isDisposed","on","off","getDataURL","getConnectedDataURL","getModel","getOption","getViewOfComponentModel","getViewOfSeriesModel"],Qf={};Yr.prototype={constructor:Yr,create:function(t,e){var n=[];f(Qf,function(i,r){var a=i.create(t,e);n=n.concat(a||[])}),this._coordinateSystems=n},update:function(t,e){f(this._coordinateSystems,function(n){n.update&&n.update(t,e)})},getCoordinateSystems:function(){return this._coordinateSystems.slice()}},Yr.register=function(t,e){Qf[t]=e},Yr.get=function(t){return Qf[t]};var Jf=f,td=n,ed=d,nd=i,id=/^(min|max)?(.+)$/;Zr.prototype={constructor:Zr,setOption:function(t,e){t&&f(on(t.series),function(t){t&&t.data&&S(t.data)&&O(t.data)}),t=td(t,!0);var n=this._optionBackup,i=jr.call(this,t,e,!n);this._newBaseOption=i.baseOption,n?(Jr(n.baseOption,i.baseOption),i.timelineOptions.length&&(n.timelineOptions=i.timelineOptions),i.mediaList.length&&(n.mediaList=i.mediaList),i.mediaDefault&&(n.mediaDefault=i.mediaDefault)):this._optionBackup=i},mountOption:function(t){var e=this._optionBackup;return this._timelineOptions=ed(e.timelineOptions,td),this._mediaList=ed(e.mediaList,td),this._mediaDefault=td(e.mediaDefault),this._currentMediaIndices=[],td(t?e.baseOption:this._newBaseOption)},getTimelineOption:function(t){var e,n=this._timelineOptions;if(n.length){var i=t.getComponent("timeline");i&&(e=td(n[i.getCurrentIndex()],!0))}return e},getMediaOption:function(t){var e=this._api.getWidth(),n=this._api.getHeight(),i=this._mediaList,r=this._mediaDefault,a=[],o=[];if(!i.length&&!r)return o;for(var s=0,l=i.length;s<l;s++)$r(i[s].query,e,n)&&a.push(s);return!a.length&&r&&(a=[-1]),a.length&&!Qr(a,this._currentMediaIndices)&&(o=ed(a,function(t){return td(-1===t?r.option:i[t].option)})),this._currentMediaIndices=a,o}};var rd=f,ad=w,od=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"],sd=function(t,e){rd(oa(t.series),function(t){ad(t)&&aa(t)});var n=["xAxis","yAxis","radiusAxis","angleAxis","singleAxis","parallelAxis","radar"];e&&n.push("valueAxis","categoryAxis","logAxis","timeAxis"),rd(n,function(e){rd(oa(t[e]),function(t){t&&(ia(t,"axisLabel"),ia(t.axisPointer,"label"))})}),rd(oa(t.parallel),function(t){var e=t&&t.parallelAxisDefault;ia(e,"axisLabel"),ia(e&&e.axisPointer,"label")}),rd(oa(t.calendar),function(t){ea(t,"itemStyle"),ia(t,"dayLabel"),ia(t,"monthLabel"),ia(t,"yearLabel")}),rd(oa(t.radar),function(t){ia(t,"name")}),rd(oa(t.geo),function(t){ad(t)&&(ra(t),rd(oa(t.regions),function(t){ra(t)}))}),rd(oa(t.timeline),function(t){ra(t),ea(t,"label"),ea(t,"itemStyle"),ea(t,"controlStyle",!0);var e=t.data;y(e)&&f(e,function(t){w(t)&&(ea(t,"label"),ea(t,"itemStyle"))})}),rd(oa(t.toolbox),function(t){ea(t,"iconStyle"),rd(t.feature,function(t){ea(t,"iconStyle")})}),ia(sa(t.axisPointer),"label"),ia(sa(t.tooltip).axisPointer,"label")},ld=[["x","left"],["y","top"],["x2","right"],["y2","bottom"]],hd=["grid","geo","parallel","legend","toolbox","title","visualMap","dataZoom","timeline"],ud=function(t,e){sd(t,e),t.series=on(t.series),f(t.series,function(t){if(w(t)){var e=t.type;if("pie"!==e&&"gauge"!==e||null!=t.clockWise&&(t.clockwise=t.clockWise),"gauge"===e){var n=la(t,"pointer.color");null!=n&&ha(t,"itemStyle.normal.color",n)}ua(t)}}),t.dataRange&&(t.visualMap=t.dataRange),f(hd,function(e){var n=t[e];n&&(y(n)||(n=[n]),f(n,function(t){ua(t)}))})},cd=fa.prototype;cd.pure=!1,cd.persistent=!0,cd.getSource=function(){return this._source};var fd={arrayRows_column:{pure:!0,count:function(){return Math.max(0,this._data.length-this._source.startIndex)},getItem:function(t){return this._data[t+this._source.startIndex]},appendData:ga},arrayRows_row:{pure:!0,count:function(){var t=this._data[0];return t?Math.max(0,t.length-this._source.startIndex):0},getItem:function(t){t+=this._source.startIndex;for(var e=[],n=this._data,i=0;i<n.length;i++){var r=n[i];e.push(r?r[t]:null)}return e},appendData:function(){throw new Error('Do not support appendData when set seriesLayoutBy: "row".')}},objectRows:{pure:!0,count:da,getItem:pa,appendData:ga},keyedColumns:{pure:!0,count:function(){var t=this._source.dimensionsDefine[0].name,e=this._data[t];return e?e.length:0},getItem:function(t){for(var e=[],n=this._source.dimensionsDefine,i=0;i<n.length;i++){var r=this._data[n[i].name];e.push(r?r[t]:null)}return e},appendData:function(t){var e=this._data;f(t,function(t,n){for(var i=e[n]||(e[n]=[]),r=0;r<(t||[]).length;r++)i.push(t[r])})}},original:{count:da,getItem:pa,appendData:ga},typedArray:{persistent:!1,pure:!0,count:function(){return this._data?this._data.length/this._dimSize:0},getItem:function(t){t-=this._offset;for(var e=[],n=this._dimSize*t,i=0;i<this._dimSize;i++)e[i]=this._data[n+i];return e},appendData:function(t){this._data=t},clean:function(){this._offset+=this.count(),this._data=null}}},dd={arrayRows:ma,objectRows:function(t,e,n,i){return null!=n?t[i]:t},keyedColumns:ma,original:function(t,e,n,i){var r=ln(t);return null!=n&&r instanceof Array?r[n]:r},typedArray:ma},pd={arrayRows:va,objectRows:function(t,e,n,i){return ya(t[e],this._dimensionInfos[e])},keyedColumns:va,original:function(t,e,n,i){var r=t&&(null==t.value?t:t.value);return!this._rawData.pure&&hn(t)&&(this.hasItemOption=!0),ya(r instanceof Array?r[i]:r,this._dimensionInfos[e])},typedArray:function(t,e,n,i){return t[i]}},gd=/\{@(.+?)\}/g,md={getDataParams:function(t,e){var n=this.getData(e),i=this.getRawValue(t,e),r=n.getRawIndex(t),a=n.getName(t,!0),o=n.getRawDataItem(t),s=n.getItemVisual(t,"color");return{componentType:this.mainType,componentSubType:this.subType,seriesType:"series"===this.mainType?this.subType:null,seriesIndex:this.seriesIndex,seriesId:this.id,seriesName:this.name,name:a,dataIndex:r,data:o,dataType:e,value:i,color:s,marker:gr(s),$vars:["seriesName","name","value"]}},getFormattedLabel:function(t,e,n,i,r){e=e||"normal";var a=this.getData(n),o=a.getItemModel(t),s=this.getDataParams(t,n);null!=i&&s.value instanceof Array&&(s.value=s.value[i]);var l=o.get("normal"===e?[r||"label","formatter"]:[e,r||"label","formatter"]);return"function"==typeof l?(s.status=e,l(s)):"string"==typeof l?pr(l,s).replace(gd,function(e,n){var i=n.length;return"["===n.charAt(0)&&"]"===n.charAt(i-1)&&(n=+n.slice(1,i-1)),_a(a,t,n)}):void 0},getRawValue:function(t,e){return _a(this.getData(e),t)},formatTooltip:function(){}},vd=ba.prototype;vd.perform=function(t){var e=this._upstream,n=t&&t.skip;if(this._dirty&&e){var i=this.context;i.data=i.outputData=e.context.outputData}this.__pipeline&&(this.__pipeline.currentTask=this);var r;this._plan&&!n&&(r=this._plan(this.context));var a;(this._dirty||"reset"===r)&&(this._dirty=!1,a=Sa(this,n));var o=t&&t.step;if(this._dueEnd=e?e._outputDueEnd:this._count?this._count(this.context):1/0,this._progress){var s=this._dueIndex,l=Math.min(null!=o?this._dueIndex+o:1/0,this._dueEnd);!n&&(a||s<l)&&this._progress({start:s,end:l},this.context),this._dueIndex=l;var h=null!=this._settedOutputEnd?this._settedOutputEnd:l;this._outputDueEnd=h}else this._dueIndex=this._outputDueEnd=null!=this._settedOutputEnd?this._settedOutputEnd:this._dueEnd;return this.unfinished()},vd.dirty=function(){this._dirty=!0,this._onDirty&&this._onDirty(this.context)},vd.unfinished=function(){return this._progress&&this._dueIndex<this._dueEnd},vd.pipe=function(t){(this._downstream!==t||this._dirty)&&(this._downstream=t,t._upstream=this,t.dirty())},vd.dispose=function(){this._disposed||(this._upstream&&(this._upstream._downstream=null),this._downstream&&(this._downstream._upstream=null),this._dirty=!1,this._disposed=!0)},vd.getUpstream=function(){return this._upstream},vd.getDownstream=function(){return this._downstream},vd.setOutputEnd=function(t){this._outputDueEnd=this._settedOutputEnd=t};var yd=gn(),_d=Ef.extend({type:"series.__base__",seriesIndex:0,coordinateSystem:null,defaultOption:null,legendDataProvider:null,visualColorAccessPath:"itemStyle.color",layoutMode:null,init:function(t,e,n,i){this.seriesIndex=this.componentIndex,this.dataTask=wa({count:Ta,reset:Ca}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),Ar(this);var r=this.getInitialData(t,n);ka(r,this),this.dataTask.context.data=r,yd(this).dataBeforeProcessed=r,Ma(this)},mergeDefaultAndTheme:function(t,e){var n=this.layoutMode,r=n?wr(t):{},a=this.subType;Ef.hasClass(a)&&(a+="Series"),i(t,e.getTheme().get(this.subType)),i(t,this.getDefaultOption()),sn(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&xr(t,r,n)},mergeOption:function(t,e){t=i(this.option,t,!0),this.fillDataTextStyle(t.data);var n=this.layoutMode;n&&xr(this.option,t,n),Ar(this);var r=this.getInitialData(t,e);ka(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,yd(this).dataBeforeProcessed=r,Ma(this)},fillDataTextStyle:function(t){if(t)for(var e=["show"],n=0;n<t.length;n++)t[n]&&t[n].label&&sn(t[n],"label",e)},getInitialData:function(){},appendData:function(t){this.getRawData().appendData(t.data)},getData:function(t){var e=La(this);if(e){var n=e.context.data;return null==t?n:n.getLinkedData(t)}return yd(this).data},setData:function(t){var e=La(this);if(e){var n=e.context;n.data!==t&&e.isOverallFilter&&e.setOutputEnd(t.count()),n.outputData=t,e!==this.dataTask&&(n.data=t)}yd(this).data=t},getSource:function(){return Dr(this)},getRawData:function(){return yd(this).dataBeforeProcessed},getBaseAxis:function(){var t=this.coordinateSystem;return t&&t.getBaseAxis&&t.getBaseAxis()},formatTooltip:function(t,e,n){function i(t){return dr(fr(t))}var r=this.getData(),a=r.mapDimension("defaultedTooltip",!0),o=a.length,s=this.getRawValue(t),l=y(s),h=r.getItemVisual(t,"color");w(h)&&h.colorStops&&(h=(h.colorStops[0]||{}).color),h=h||"transparent";var u=o>1||l&&!o?function(n){function i(t,n){var i=r.getDimensionInfo(n);if(i&&!1!==i.otherDims.tooltip){var a=i.type,l=gr({color:h,type:"subItem"}),u=(o?l+dr(i.displayName||"-")+": ":"")+dr("ordinal"===a?t+"":"time"===a?e?"":vr("yyyy/MM/dd hh:mm:ss",t):fr(t));u&&s.push(u)}}var o=p(n,function(t,e,n){var i=r.getDimensionInfo(n);return t|=i&&!1!==i.tooltip&&null!=i.displayName},0),s=[];return a.length?f(a,function(e){i(_a(r,t,e),e)}):f(n,i),(o?"<br/>":"")+s.join(o?"<br/>":", ")}(s):i(o?_a(r,t,a[0]):l?s[0]:s),c=gr(h),d=r.getName(t),g=this.name;return fn(this)||(g=""),g=g?dr(g)+(e?": ":"<br/>"):"",e?c+g+u:g+c+(d?dr(d)+": "+u:u)},isAnimationEnabled:function(){if(Yl.node)return!1;var t=this.getShallow("animation");return t&&this.getData().count()>this.getShallow("animationThreshold")&&(t=!1),t},restoreData:function(){this.dataTask.dirty()},getColorFromPalette:function(t,e,n){var i=this.ecModel,r=zf.getColorFromPalette.call(this,t,e,n);return r||(r=i.getColorFromPalette(t,e,n)),r},coordDimToDataDim:function(t){return this.getRawData().mapDimension(t,!0)},getProgressive:function(){return this.get("progressive")},getProgressiveThreshold:function(){return this.get("progressiveThreshold")},getAxisTooltipData:null,getTooltipPosition:null,pipeTask:null,preventIncremental:null,pipelineContext:null});u(_d,md),u(_d,zf);var xd=function(){this.group=new Wh,this.uid=Qi("viewComponent")};xd.prototype={constructor:xd,init:function(t,e){},render:function(t,e,n,i){},dispose:function(){}};var wd=xd.prototype;wd.updateView=wd.updateLayout=wd.updateVisual=function(t,e,n,i){},bn(xd),Tn(xd,{registerWhenExtend:!0});var bd=function(){var t=gn();return function(e){var n=t(e),i=e.pipelineContext,r=n.large,a=n.canProgressiveRender,o=n.large=i.large,s=n.canProgressiveRender=i.canProgressiveRender;return!!(r^o||a^s)&&"reset"}},Sd=gn(),Md=bd();Pa.prototype={type:"chart",init:function(t,e){},render:function(t,e,n,i){},highlight:function(t,e,n,i){Ea(t.getData(),i,"emphasis")},downplay:function(t,e,n,i){Ea(t.getData(),i,"normal")},remove:function(t,e){this.group.removeAll()},dispose:function(){},incrementalPrepareRender:null,incrementalRender:null,updateTransform:null};var Id=Pa.prototype;Id.updateView=Id.updateLayout=Id.updateVisual=function(t,e,n,i){this.render(t,e,n,i)},bn(Pa),Tn(Pa,{registerWhenExtend:!0}),Pa.markUpdateMethod=function(t,e){Sd(t).updateMethod=e};var Td={incrementalPrepareRender:{progress:function(t,e){e.view.incrementalRender(t,e.model,e.ecModel,e.api,e.payload)}},render:{forceFirstProgress:!0,progress:function(t,e){e.view.render(e.model,e.ecModel,e.api,e.payload)}}},Cd={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData(),i=(t.visualColorAccessPath||"itemStyle.color").split("."),r=t.get(i)||t.getColorFromPalette(t.name,null,e.getSeriesCount());if(n.setVisual("color",r),!e.isSeriesFiltered(t)){"function"!=typeof r||r instanceof sf||n.each(function(e){n.setItemVisual(e,"color",r(t.getDataParams(e)))});return{dataEach:n.hasItemOption?function(t,e){var n=t.getItemModel(e).get(i,!0);null!=n&&t.setItemVisual(e,"color",n)}:null}}}},Dd={toolbox:{brush:{title:{rect:"矩形选择",polygon:"圈选",lineX:"横向选择",lineY:"纵向选择",keep:"保持选择",clear:"清除选择"}},dataView:{title:"数据视图",lang:["数据视图","关闭","刷新"]},dataZoom:{title:{zoom:"区域缩放",back:"区域缩放还原"}},magicType:{title:{line:"切换为折线图",bar:"切换为柱状图",stack:"切换为堆叠",tiled:"切换为平铺"}},restore:{title:"还原"},saveAsImage:{title:"保存为图片",lang:["右键另存为图片"]}},series:{typeNames:{pie:"饼图",bar:"柱状图",line:"折线图",scatter:"散点图",effectScatter:"涟漪散点图",radar:"雷达图",tree:"树图",treemap:"矩形树图",boxplot:"箱型图",candlestick:"K线图",k:"K线图",heatmap:"热力图",map:"地图",parallel:"平行坐标图",lines:"线图",graph:"关系图",sankey:"桑基图",funnel:"漏斗图",gauge:"仪表盘图",pictorialBar:"象形柱图",themeRiver:"主题河流图",sunburst:"旭日图"}},aria:{general:{withTitle:"这是一个关于“{title}”的图表。",withoutTitle:"这是一个图表,"},series:{single:{prefix:"",withName:"图表类型是{seriesType},表示{seriesName}。",withoutName:"图表类型是{seriesType}。"},multiple:{prefix:"它由{seriesCount}个图表系列组成。",withName:"第{seriesId}个系列是一个表示{seriesName}的{seriesType},",withoutName:"第{seriesId}个系列是一个{seriesType},",separator:{middle:";",end:"。"}}},data:{allData:"其数据是——",partialData:"其中,前{displayCnt}项是——",withName:"{name}的数据是{value}",withoutName:"{value}",separator:{middle:",",end:""}}}},kd=function(t,e){function n(t,e){if("string"!=typeof t)return t;var n=t;return f(e,function(t,e){n=n.replace(new RegExp("\\{\\s*"+e+"\\s*\\}","g"),t)}),n}function i(t){var e=a.get(t);if(null==e){for(var n=t.split("."),i=Dd.aria,r=0;r<n.length;++r)i=i[n[r]];return i}return e}function r(t){return Dd.series.typeNames[t]||"自定义图"}var a=e.getModel("aria");if(a.get("show"))if(a.get("description"))t.setAttribute("aria-label",a.get("description"));else{var o=0;e.eachSeries(function(t,e){++o},this);var s,l=a.get("data.maxCount")||10,h=a.get("series.maxCount")||10,u=Math.min(o,h);if(!(o<1)){var c=function(){var t=e.getModel("title").option;return t&&t.length&&(t=t[0]),t&&t.text}();s=c?n(i("general.withTitle"),{title:c}):i("general.withoutTitle");var d=[];s+=n(i(o>1?"series.multiple.prefix":"series.single.prefix"),{seriesCount:o}),e.eachSeries(function(t,e){if(e<u){var a,s=t.get("name"),h="series."+(o>1?"multiple":"single")+".";a=n(a=i(s?h+"withName":h+"withoutName"),{seriesId:t.seriesIndex,seriesName:t.get("name"),seriesType:r(t.subType)});var c=t.getData();window.data=c,c.count()>l?a+=n(i("data.partialData"),{displayCnt:l}):a+=i("data.allData");for(var f=[],p=0;p<c.count();p++)if(p<l){var g=c.getName(p),m=_a(c,p);f.push(n(i(g?"data.withName":"data.withoutName"),{name:g,value:m}))}a+=f.join(i("data.separator.middle"))+i("data.separator.end"),d.push(a)}}),s+=d.join(i("series.multiple.separator.middle"))+i("series.multiple.separator.end"),t.setAttribute("aria-label",s)}}},Ad=Math.PI,Ld=za.prototype;Ld.getPerformArgs=function(t,e){if(t.__pipeline){var n=this._pipelineMap.get(t.__pipeline.id),i=n.context;return{step:!e&&n.progressiveEnabled&&(!i||i.canProgressiveRender)&&t.__idxInPipeline>n.bockIndex?n.step:null}}},Ld.getPipeline=function(t){return this._pipelineMap.get(t)},Ld.updateStreamModes=function(t,e){var n=this._pipelineMap.get(t.uid),i=t.getData().count(),r=n.progressiveEnabled&&e.incrementalPrepareRender&&i>=n.threshold,a=t.get("large")&&i>=t.get("largeThreshold");t.pipelineContext=n.context={canProgressiveRender:r,large:a}},Ld.restorePipelines=function(t){var e=this,n=e._pipelineMap=N();t.eachSeries(function(t){var i=t.getProgressive(),r=t.uid;n.set(r,{id:r,head:null,tail:null,threshold:t.getProgressiveThreshold(),progressiveEnabled:i&&!(t.preventIncremental&&t.preventIncremental()),bockIndex:-1,step:i||700,count:0}),$a(e,t,t.dataTask)})},Ld.prepareStageTasks=function(){var t=this._stageTaskMap,e=this.ecInstance.getModel(),n=this.api;f([this._dataProcessorHandlers,this._visualHandlers],function(i){f(i,function(i){var r=t.get(i.uid)||t.set(i.uid,[]);i.reset&&Va(this,i,r,e,n),i.overallReset&&Wa(this,i,r,e,n)},this)},this)},Ld.prepareView=function(t,e,n,i){var r=t.renderTask,a=r.context;a.model=e,a.ecModel=n,a.api=i,r.__block=!t.incrementalPrepareRender,$a(this,e,r)},Ld.performDataProcessorTasks=function(t,e){Fa(this,this._dataProcessorHandlers,t,e,{block:!0})},Ld.performVisualTasks=function(t,e,n){Fa(this,this._visualHandlers,t,e,n)},Ld.performSeriesTasks=function(t){var e;t.eachSeries(function(t){e|=t.dataTask.perform()}),this.unfinished|=e},Ld.plan=function(){this._pipelineMap.each(function(t){var e=t.tail;do{if(e.__block){t.bockIndex=e.__idxInPipeline;break}e=e.getUpstream()}while(e)})};var Pd=Ld.updatePayload=function(t,e){"remain"!==e&&(t.context.payload=e)};za.wrapStageHandler=function(t,e){return _(t)&&(t={overallReset:t,seriesType:Ka(t)}),t.uid=Qi("stageHandler"),e&&(t.visualType=e),t};var Od,Ed={},Bd={};Qa(Ed,$f),Qa(Bd,Ur),Ed.eachSeriesByType=Ed.eachRawSeriesByType=function(t){Od=t},Ed.eachComponent=function(t){"series"===t.mainType&&t.subType&&(Od=t.subType)};var Nd=["#37A2DA","#32C5E9","#67E0E3","#9FE6B8","#FFDB5C","#ff9f7f","#fb7293","#E062AE","#E690D1","#e7bcf3","#9d96f5","#8378EA","#96BFFF"],Rd={color:Nd,colorLayer:[["#37A2DA","#ffd85c","#fd7b5f"],["#37A2DA","#67E0E3","#FFDB5C","#ff9f7f","#E062AE","#9d96f5"],["#37A2DA","#32C5E9","#9FE6B8","#FFDB5C","#ff9f7f","#fb7293","#e7bcf3","#8378EA","#96BFFF"],Nd]},zd=["#dd6b66","#759aa0","#e69d87","#8dc1a9","#ea7e53","#eedd78","#73a373","#73b9bc","#7289ab","#91ca8c","#f49f42"],Fd={color:zd,backgroundColor:"#333",tooltip:{axisPointer:{lineStyle:{color:"#eee"},crossStyle:{color:"#eee"}}},legend:{textStyle:{color:"#eee"}},textStyle:{color:"#eee"},title:{textStyle:{color:"#eee"}},toolbox:{iconStyle:{normal:{borderColor:"#eee"}}},dataZoom:{textStyle:{color:"#eee"}},visualMap:{textStyle:{color:"#eee"}},timeline:{lineStyle:{color:"#eee"},itemStyle:{normal:{color:zd[1]}},label:{normal:{textStyle:{color:"#eee"}}},controlStyle:{normal:{color:"#eee",borderColor:"#eee"}}},timeAxis:{axisLine:{lineStyle:{color:"#eee"}},axisTick:{lineStyle:{color:"#eee"}},axisLabel:{textStyle:{color:"#eee"}},splitLine:{lineStyle:{type:"dashed",color:"#aaa"}},splitArea:{areaStyle:{color:"#eee"}}},logAxis:{axisLine:{lineStyle:{color:"#eee"}},axisTick:{lineStyle:{color:"#eee"}},axisLabel:{textStyle:{color:"#eee"}},splitLine:{lineStyle:{type:"dashed",color:"#aaa"}},splitArea:{areaStyle:{color:"#eee"}}},valueAxis:{axisLine:{lineStyle:{color:"#eee"}},axisTick:{lineStyle:{color:"#eee"}},axisLabel:{textStyle:{color:"#eee"}},splitLine:{lineStyle:{type:"dashed",color:"#aaa"}},splitArea:{areaStyle:{color:"#eee"}}},categoryAxis:{axisLine:{lineStyle:{color:"#eee"}},axisTick:{lineStyle:{color:"#eee"}},axisLabel:{textStyle:{color:"#eee"}},splitLine:{lineStyle:{type:"dashed",color:"#aaa"}},splitArea:{areaStyle:{color:"#eee"}}},line:{symbol:"circle"},graph:{color:zd},gauge:{title:{textStyle:{color:"#eee"}}},candlestick:{itemStyle:{normal:{color:"#FD1050",color0:"#0CF49B",borderColor:"#FD1050",borderColor0:"#0CF49B"}}}};Fd.categoryAxis.splitLine.show=!1;var Vd=L,Wd=f,Hd=_,Gd=w,qd=Ef.parseClassType,Xd={zrender:"4.0.3"},Ud=1e3,Yd=1e3,Zd=3e3,jd={PROCESSOR:{FILTER:Ud,STATISTIC:5e3},VISUAL:{LAYOUT:Yd,GLOBAL:2e3,CHART:Zd,COMPONENT:4e3,BRUSH:5e3}},$d="__flagInMainProcess",Kd="__optionUpdated",Qd=/^[a-zA-Z0-9_]+$/;to.prototype.on=Ja("on"),to.prototype.off=Ja("off"),to.prototype.one=Ja("one"),u(to,ch);var Jd=eo.prototype;Jd._onframe=function(){if(!this._disposed){var t=this._scheduler;if(this[Kd]){var e=this[Kd].silent;this[$d]=!0,io(this),tp.update.call(this),this[$d]=!1,this[Kd]=!1,so.call(this,e),lo.call(this,e)}else if(t.unfinished){var n=1,i=this._model;this._api;t.unfinished=!1;do{var r=+new Date;t.performSeriesTasks(i),t.performDataProcessorTasks(i),ao(this,i),t.performVisualTasks(i),go(this,this._model,0,"remain"),n-=+new Date-r}while(n>0&&t.unfinished);t.unfinished||this._zr.flush()}}},Jd.getDom=function(){return this._dom},Jd.getZr=function(){return this._zr},Jd.setOption=function(t,e,n){var i;if(Gd(e)&&(n=e.lazyUpdate,i=e.silent,e=e.notMerge),this[$d]=!0,!this._model||e){var r=new Zr(this._api),a=this._theme,o=this._model=new $f(null,null,a,r);o.scheduler=this._scheduler,o.init(null,null,a,r)}this._model.setOption(t,ap),n?(this[Kd]={silent:i},this[$d]=!1):(io(this),tp.update.call(this),this._zr.flush(),this[Kd]=!1,this[$d]=!1,so.call(this,i),lo.call(this,i))},Jd.setTheme=function(){console.log("ECharts#setTheme() is DEPRECATED in ECharts 3.0")},Jd.getModel=function(){return this._model},Jd.getOption=function(){return this._model&&this._model.getOption()},Jd.getWidth=function(){return this._zr.getWidth()},Jd.getHeight=function(){return this._zr.getHeight()},Jd.getDevicePixelRatio=function(){return this._zr.painter.dpr||window.devicePixelRatio||1},Jd.getRenderedCanvas=function(t){if(Yl.canvasSupported)return(t=t||{}).pixelRatio=t.pixelRatio||1,t.backgroundColor=t.backgroundColor||this._model.get("backgroundColor"),this._zr.painter.getRenderedCanvas(t)},Jd.getSvgDataUrl=function(){if(Yl.svgSupported){var t=this._zr;return f(t.storage.getDisplayList(),function(t){t.stopAnimation(!0)}),t.painter.pathToDataUrl()}},Jd.getDataURL=function(t){var e=(t=t||{}).excludeComponents,n=this._model,i=[],r=this;Wd(e,function(t){n.eachComponent({mainType:t},function(t){var e=r._componentsMap[t.__viewId];e.group.ignore||(i.push(e),e.group.ignore=!0)})});var a="svg"===this._zr.painter.getType()?this.getSvgDataUrl():this.getRenderedCanvas(t).toDataURL("image/"+(t&&t.type||"png"));return Wd(i,function(t){t.group.ignore=!1}),a},Jd.getConnectedDataURL=function(t){if(Yl.canvasSupported){var e=this.group,i=Math.min,r=Math.max;if(cp[e]){var a=1/0,o=1/0,s=-1/0,l=-1/0,h=[],u=t&&t.pixelRatio||1;f(up,function(u,c){if(u.group===e){var f=u.getRenderedCanvas(n(t)),d=u.getDom().getBoundingClientRect();a=i(d.left,a),o=i(d.top,o),s=r(d.right,s),l=r(d.bottom,l),h.push({dom:f,left:d.left,top:d.top})}});var c=(s*=u)-(a*=u),d=(l*=u)-(o*=u),p=rh();p.width=c,p.height=d;var g=an(p);return Wd(h,function(t){var e=new Re({style:{x:t.left*u-a,y:t.top*u-o,image:t.dom}});g.add(e)}),g.refreshImmediately(),p.toDataURL("image/"+(t&&t.type||"png"))}return this.getDataURL(t)}},Jd.convertToPixel=v(no,"convertToPixel"),Jd.convertFromPixel=v(no,"convertFromPixel"),Jd.containPixel=function(t,e){var n;return t=mn(this._model,t),f(t,function(t,i){i.indexOf("Models")>=0&&f(t,function(t){var r=t.coordinateSystem;if(r&&r.containPoint)n|=!!r.containPoint(e);else if("seriesModels"===i){var a=this._chartsMap[t.__viewId];a&&a.containPoint&&(n|=a.containPoint(e,t))}},this)},this),!!n},Jd.getVisual=function(t,e){var n=(t=mn(this._model,t,{defaultMainType:"series"})).seriesModel.getData(),i=t.hasOwnProperty("dataIndexInside")?t.dataIndexInside:t.hasOwnProperty("dataIndex")?n.indexOfRawIndex(t.dataIndex):null;return null!=i?n.getItemVisual(i,e):n.getVisual(e)},Jd.getViewOfComponentModel=function(t){return this._componentsMap[t.__viewId]},Jd.getViewOfSeriesModel=function(t){return this._chartsMap[t.__viewId]};var tp={prepareAndUpdate:function(t){io(this),tp.update.call(this,t)},update:function(t){var e=this._model,n=this._api,i=this._zr,r=this._coordSysMgr,a=this._scheduler;if(e){e.restoreData(t),a.performSeriesTasks(e),r.create(e,n),a.performDataProcessorTasks(e,t),ao(this,e),r.update(e,n),co(e),a.performVisualTasks(e,t),fo(this,e,n,t);var o=e.get("backgroundColor")||"transparent";if(Yl.canvasSupported)i.setBackgroundColor(o);else{var s=_t(o);o=bt(s,"rgb"),0===s[3]&&(o="transparent")}mo(e,n)}},updateTransform:function(t){var e=this._model,n=this,i=this._api;if(e){var r=[];e.eachComponent(function(a,o){var s=n.getViewOfComponentModel(o);if(s&&s.__alive)if(s.updateTransform){var l=s.updateTransform(o,e,i,t);l&&l.update&&r.push(s)}else r.push(s)});var a=N();e.eachSeries(function(r){var o=n._chartsMap[r.__viewId];if(o.updateTransform){var s=o.updateTransform(r,e,i,t);s&&s.update&&a.set(r.uid,1)}else a.set(r.uid,1)}),co(e),this._scheduler.performVisualTasks(e,t,{setDirty:!0,dirtyMap:a}),go(n,e,0,t,a),mo(e,this._api)}},updateView:function(t){var e=this._model;e&&(Pa.markUpdateMethod(t,"updateView"),co(e),this._scheduler.performVisualTasks(e,t,{setDirty:!0}),fo(this,this._model,this._api,t),mo(e,this._api))},updateVisual:function(t){tp.update.call(this,t)},updateLayout:function(t){tp.update.call(this,t)}};Jd.resize=function(t){this._zr.resize(t);var e=this._model;if(this._loadingFX&&this._loadingFX.resize(),e){var n=e.resetOption("media"),i=t&&t.silent;this[$d]=!0,n&&io(this),tp.update.call(this),this[$d]=!1,so.call(this,i),lo.call(this,i)}},Jd.showLoading=function(t,e){if(Gd(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),hp[t]){var n=hp[t](this._api,e),i=this._zr;this._loadingFX=n,i.add(n)}},Jd.hideLoading=function(){this._loadingFX&&this._zr.remove(this._loadingFX),this._loadingFX=null},Jd.makeActionFromEvent=function(t){var e=a({},t);return e.type=ip[t.type],e},Jd.dispatchAction=function(t,e){Gd(e)||(e={silent:!!e}),np[t.type]&&this._model&&(this[$d]?this._pendingActions.push(t):(oo.call(this,t,e.silent),e.flush?this._zr.flush(!0):!1!==e.flush&&Yl.browser.weChat&&this._throttledZrFlush(),so.call(this,e.silent),lo.call(this,e.silent)))},Jd.appendData=function(t){var e=t.seriesIndex;this.getModel().getSeriesByIndex(e).appendData(t),this._scheduler.unfinished=!0},Jd.on=Ja("on"),Jd.off=Ja("off"),Jd.one=Ja("one");var ep=["click","dblclick","mouseover","mouseout","mousemove","mousedown","mouseup","globalout","contextmenu"];Jd._initEvents=function(){Wd(ep,function(t){this._zr.on(t,function(e){var n,i=this.getModel(),r=e.target;if("globalout"===t)n={};else if(r&&null!=r.dataIndex){var o=r.dataModel||i.getSeriesByIndex(r.seriesIndex);n=o&&o.getDataParams(r.dataIndex,r.dataType)||{}}else r&&r.eventData&&(n=a({},r.eventData));n&&(n.event=e,n.type=t,this.trigger(t,n))},this)},this),Wd(ip,function(t,e){this._messageCenter.on(e,function(t){this.trigger(e,t)},this)},this)},Jd.isDisposed=function(){return this._disposed},Jd.clear=function(){this.setOption({series:[]},!0)},Jd.dispose=function(){if(!this._disposed){this._disposed=!0,yn(this.getDom(),pp,"");var t=this._api,e=this._model;Wd(this._componentsViews,function(n){n.dispose(e,t)}),Wd(this._chartsViews,function(n){n.dispose(e,t)}),this._zr.dispose(),delete up[this.id]}},u(eo,ch);var np={},ip={},rp=[],ap=[],op=[],sp=[],lp={},hp={},up={},cp={},fp=new Date-0,dp=new Date-0,pp="_echarts_instance_",gp={},mp=bo;ko(2e3,Cd),Io(ud),To(5e3,function(t){var e=N();t.eachSeries(function(t){var n=t.get("stack");if(n){var i=e.get(n)||e.set(n,[]),r=t.getData(),a={stackResultDimension:r.getCalculationInfo("stackResultDimension"),stackedOverDimension:r.getCalculationInfo("stackedOverDimension"),stackedDimension:r.getCalculationInfo("stackedDimension"),stackedByDimension:r.getCalculationInfo("stackedByDimension"),isStackedByIndex:r.getCalculationInfo("isStackedByIndex"),data:r,seriesModel:t};if(!a.stackedDimension||!a.isStackedByIndex&&!a.stackedByDimension)return;i.length&&r.setCalculationInfo("stackedOnSeries",i[i.length-1].seriesModel),i.push(a)}}),e.each(ca)}),Lo("default",function(t,e){o(e=e||{},{text:"loading",color:"#c23531",textColor:"#000",maskColor:"rgba(255, 255, 255, 0.8)",zlevel:0});var n=new tf({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4}),i=new af({shape:{startAngle:-Ad/2,endAngle:-Ad/2+.1,r:10},style:{stroke:e.color,lineCap:"round",lineWidth:5},zlevel:e.zlevel,z:10001}),r=new tf({style:{fill:"none",text:e.text,textPosition:"right",textDistance:10,textFill:e.textColor},zlevel:e.zlevel,z:10001});i.animateShape(!0).when(1e3,{endAngle:3*Ad/2}).start("circularInOut"),i.animateShape(!0).when(1e3,{startAngle:3*Ad/2}).delay(300).start("circularInOut");var a=new Wh;return a.add(i),a.add(r),a.add(n),a.resize=function(){var e=t.getWidth()/2,a=t.getHeight()/2;i.setShape({cx:e,cy:a});var o=i.shape.r;r.setShape({x:e-o,y:a-o,width:2*o,height:2*o}),n.setShape({x:0,y:0,width:t.getWidth(),height:t.getHeight()})},a.resize(),a}),Co({type:"highlight",event:"highlight",update:"highlight"},R),Co({type:"downplay",event:"downplay",update:"downplay"},R),Mo("light",Rd),Mo("dark",Fd);var vp={};Po({type:"dataset",defaultOption:{seriesLayoutBy:Uf,sourceHeader:null,dimensions:null,source:null},optionUpdated:function(){Cr(this)}});Oo({type:"dataset"}),Ro.prototype={constructor:Ro,add:function(t){return this._add=t,this},update:function(t){return this._update=t,this},remove:function(t){return this._remove=t,this},execute:function(){var t=this._old,e=this._new,n={},i=[],r=[];for(zo(t,{},i,"_oldKeyGetter",this),zo(e,n,r,"_newKeyGetter",this),a=0;a<t.length;a++)null!=(s=n[o=i[a]])?((h=s.length)?(1===h&&(n[o]=null),s=s.unshift()):n[o]=null,this._update&&this._update(s,a)):this._remove&&this._remove(a);for(var a=0;a<r.length;a++){var o=r[a];if(n.hasOwnProperty(o)){var s=n[o];if(null==s)continue;if(s.length)for(var l=0,h=s.length;l<h;l++)this._add&&this._add(s[l]);else this._add&&this._add(s)}}}};var yp=N(["tooltip","label","itemName","itemId","seriesName"]),_p=w,xp="undefined"==typeof window?global:window,wp="e\0\0",bp={float:void 0===xp.Float64Array?Array:xp.Float64Array,int:void 0===xp.Int32Array?Array:xp.Int32Array,ordinal:Array,number:Array,time:Array},Sp=void 0===xp.Uint32Array?Array:xp.Uint32Array,Mp=void 0===xp.Uint16Array?Array:xp.Uint16Array,Ip=["hasItemOption","_nameList","_idList","_calculationInfo","_invertedIndicesMap","_rawData","_rawExtent","_chunkSize","_chunkCount","_dimValueGetter","_count","_rawCount","_nameDimIdx","_idDimIdx"],Tp=function(t,e){t=t||["x","y"];for(var n={},i=[],r={},a=0;a<t.length;a++){var o=t[a];x(o)&&(o={name:o});var s=o.name;o.type=o.type||"float",o.coordDim||(o.coordDim=s,o.coordDimIndex=0),o.otherDims=o.otherDims||{},i.push(s),n[s]=o,o.index=a,o.createInvertedIndices&&(r[s]=[])}this.dimensions=i,this._dimensionInfos=n,this.hostModel=e,this.dataType,this._indices=null,this._count=0,this._rawCount=0,this._storage={},this._nameList=[],this._idList=[],this._optionModels=[],this._visual={},this._layout={},this._itemVisuals=[],this.hasItemVisual={},this._itemLayouts=[],this._graphicEls=[],this._chunkSize=1e5,this._chunkCount=0,this._rawData,this._rawExtent={},this._extent={},this._approximateExtent={},this._dimensionsSummary=Fo(this),this._invertedIndicesMap=r,this._calculationInfo={}},Cp=Tp.prototype;Cp.type="list",Cp.hasItemOption=!0,Cp.getDimension=function(t){return isNaN(t)||(t=this.dimensions[t]||t),t},Cp.getDimensionInfo=function(t){return this._dimensionInfos[this.getDimension(t)]},Cp.getDimensionsOnCoord=function(){return this._dimensionsSummary.dataDimsOnCoord.slice()},Cp.mapDimension=function(t,e){var n=this._dimensionsSummary;if(null==e)return n.encodeFirstDimNotExtra[t];var i=n.encode[t];return!0===e?(i||[]).slice():i&&i[e]},Cp.initData=function(t,e,n){(Tr.isInstance(t)||c(t))&&(t=new fa(t,this.dimensions.length)),this._rawData=t,this._storage={},this._indices=null,this._nameList=e||[],this._idList=[],this._nameRepeatCount={},n||(this.hasItemOption=!1),this.defaultDimValueGetter=pd[this._rawData.getSource().sourceFormat],this._dimValueGetter=n=n||this.defaultDimValueGetter,this._rawExtent={},this._initDataFromProvider(0,t.count()),t.pure&&(this.hasItemOption=!1)},Cp.getProvider=function(){return this._rawData},Cp.appendData=function(t){var e=this._rawData,n=this.count();e.appendData(t);var i=e.count();e.persistent||(i+=n),this._initDataFromProvider(n,i)},Cp._initDataFromProvider=function(t,e){if(!(t>=e)){for(var n,i=this._chunkSize,r=this._rawData,a=this._storage,o=this.dimensions,s=this._dimensionInfos,l=this._nameList,h=this._idList,u=this._rawExtent,c=this._nameRepeatCount={},f=this._chunkCount,d=f-1,p=0;p<o.length;p++){u[I=o[p]]||(u[I]=[1/0,-1/0]);var g=s[I];0===g.otherDims.itemName&&(n=this._nameDimIdx=p),0===g.otherDims.itemId&&(this._idDimIdx=p);var m=bp[g.type];a[I]||(a[I]=[]);var v=a[I][d];if(v&&v.length<i){for(var y=new m(Math.min(e-d*i,i)),_=0;_<v.length;_++)y[_]=v[_];a[I][d]=y}for(M=f*i;M<e;M+=i)a[I].push(new m(Math.min(e-M,i)));this._chunkCount=a[I].length}for(var x=t;x<e;x++){for(var w=r.getItem(x),b=Math.floor(x/i),S=x%i,M=0;M<o.length;M++){var I=o[M],T=a[I][b],C=this._dimValueGetter(w,I,x,M);T[S]=C,C<u[I][0]&&(u[I][0]=C),C>u[I][1]&&(u[I][1]=C)}if(!r.pure){var D=l[x];w&&!D&&(null!=n?D=this._getNameFromStore(x):null!=w.name&&(l[x]=D=w.name));var k=null==w?null:w.id;null==k&&null!=D&&(c[D]=c[D]||0,k=D,c[D]>0&&(k+="__ec__"+c[D]),c[D]++),null!=k&&(h[x]=k)}}!r.persistent&&r.clean&&r.clean(),this._rawCount=this._count=e,this._extent={},Xo(this)}},Cp._getNameFromStore=function(t){var e=this._nameDimIdx;if(null!=e){var n=this._chunkSize,i=Math.floor(t/n),r=t%n,a=this.dimensions[e],o=this._dimensionInfos[a].ordinalMeta;if(o)return o.categories[t];var s=this._storage[a][i];return s&&s[r]}},Cp._getIdFromStore=function(t){var e=this._idDimIdx;if(null!=e){var n=this._chunkSize,i=Math.floor(t/n),r=t%n,a=this.dimensions[e],o=this._dimensionInfos[a].ordinalMeta;if(o)return o.categories[t];var s=this._storage[a][i];return s&&s[r]}},Cp.count=function(){return this._count},Cp.getIndices=function(){if(this._indices)return new(t=this._indices.constructor)(this._indices.buffer,0,this._count);for(var t=Ho(this),e=new t(this.count()),n=0;n<e.length;n++)e[n]=n;return e},Cp.get=function(t,e){if(!(e>=0&&e<this._count))return NaN;var n=this._storage;if(!n[t])return NaN;e=this.getRawIndex(e);var i=Math.floor(e/this._chunkSize),r=e%this._chunkSize;return n[t][i][r]},Cp.getByRawIndex=function(t,e){if(!(e>=0&&e<this._rawCount))return NaN;var n=this._storage[t];if(!n)return NaN;var i=Math.floor(e/this._chunkSize),r=e%this._chunkSize;return n[i][r]},Cp._getFast=function(t,e){var n=Math.floor(e/this._chunkSize),i=e%this._chunkSize;return this._storage[t][n][i]},Cp.getValues=function(t,e){var n=[];y(t)||(e=t,t=this.dimensions);for(var i=0,r=t.length;i<r;i++)n.push(this.get(t[i],e));return n},Cp.hasValue=function(t){for(var e=this._dimensionsSummary.dataDimsOnCoord,n=this._dimensionInfos,i=0,r=e.length;i<r;i++)if("ordinal"!==n[e[i]].type&&isNaN(this.get(e[i],t)))return!1;return!0},Cp.getDataExtent=function(t){t=this.getDimension(t);var e=[1/0,-1/0];if(!this._storage[t])return e;var n,i=this.count();if(!this._indices)return this._rawExtent[t].slice();if(n=this._extent[t])return n.slice();for(var r=(n=e)[0],a=n[1],o=0;o<i;o++){var s=this._getFast(t,this.getRawIndex(o));s<r&&(r=s),s>a&&(a=s)}return n=[r,a],this._extent[t]=n,n},Cp.getApproximateExtent=function(t){return t=this.getDimension(t),this._approximateExtent[t]||this.getDataExtent(t)},Cp.setApproximateExtent=function(t,e){e=this.getDimension(e),this._approximateExtent[e]=t.slice()},Cp.getCalculationInfo=function(t){return this._calculationInfo[t]},Cp.setCalculationInfo=function(t,e){_p(t)?a(this._calculationInfo,t):this._calculationInfo[t]=e},Cp.getSum=function(t){var e=0;if(this._storage[t])for(var n=0,i=this.count();n<i;n++){var r=this.get(t,n);isNaN(r)||(e+=r)}return e},Cp.rawIndexOf=function(t,e){var n=(t&&this._invertedIndicesMap[t])[e];return null==n||isNaN(n)?-1:n},Cp.indexOfName=function(t){for(var e=0,n=this.count();e<n;e++)if(this.getName(e)===t)return e;return-1},Cp.indexOfRawIndex=function(t){if(!this._indices)return t;if(t>=this._rawCount||t<0)return-1;var e=this._indices,n=e[t];if(null!=n&&n<this._count&&n===t)return t;for(var i=0,r=this._count-1;i<=r;){var a=(i+r)/2|0;if(e[a]<t)i=a+1;else{if(!(e[a]>t))return a;r=a-1}}return-1},Cp.indicesOfNearest=function(t,e,n){var i=[];if(!this._storage[t])return i;null==n&&(n=1/0);for(var r=Number.MAX_VALUE,a=-1,o=0,s=this.count();o<s;o++){var l=e-this.get(t,o),h=Math.abs(l);l<=n&&h<=r&&((h<r||l>=0&&a<0)&&(r=h,a=l,i.length=0),i.push(o))}return i},Cp.getRawIndex=Uo,Cp.getRawDataItem=function(t){if(this._rawData.persistent)return this._rawData.getItem(this.getRawIndex(t));for(var e=[],n=0;n<this.dimensions.length;n++){var i=this.dimensions[n];e.push(this.get(i,t))}return e},Cp.getName=function(t){var e=this.getRawIndex(t);return this._nameList[e]||this._getNameFromStore(e)||""},Cp.getId=function(t){return Zo(this,this.getRawIndex(t))},Cp.each=function(t,e,n,i){if(this._count){"function"==typeof t&&(i=n,n=e,e=t,t=[]),n=n||i||this;for(var r=(t=d(jo(t),this.getDimension,this)).length,a=0;a<this.count();a++)switch(r){case 0:e.call(n,a);break;case 1:e.call(n,this.get(t[0],a),a);break;case 2:e.call(n,this.get(t[0],a),this.get(t[1],a),a);break;default:for(var o=0,s=[];o<r;o++)s[o]=this.get(t[o],a);s[o]=a,e.apply(n,s)}}},Cp.filterSelf=function(t,e,n,i){if(this._count){"function"==typeof t&&(i=n,n=e,e=t,t=[]),n=n||i||this,t=d(jo(t),this.getDimension,this);for(var r=this.count(),a=new(Ho(this))(r),o=[],s=t.length,l=0,h=t[0],u=0;u<r;u++){var c,f=this.getRawIndex(u);if(0===s)c=e.call(n,u);else if(1===s){var p=this._getFast(h,f);c=e.call(n,p,u)}else{for(var g=0;g<s;g++)o[g]=this._getFast(h,f);o[g]=u,c=e.apply(n,o)}c&&(a[l++]=f)}return l<r&&(this._indices=a),this._count=l,this._extent={},this.getRawIndex=this._indices?Yo:Uo,this}},Cp.selectRange=function(t){if(this._count){var e=[];for(var n in t)t.hasOwnProperty(n)&&e.push(n);var i=e.length;if(i){var r=this.count(),a=new(Ho(this))(r),o=0,s=e[0],l=t[s][0],h=t[s][1],u=!1;if(!this._indices){var c=0;if(1===i){for(var f=this._storage[e[0]],d=0;d<this._chunkCount;d++)for(var p=f[d],g=Math.min(this._count-d*this._chunkSize,this._chunkSize),m=0;m<g;m++)(w=p[m])>=l&&w<=h&&(a[o++]=c),c++;u=!0}else if(2===i){for(var f=this._storage[s],v=this._storage[e[1]],y=t[e[1]][0],_=t[e[1]][1],d=0;d<this._chunkCount;d++)for(var p=f[d],x=v[d],g=Math.min(this._count-d*this._chunkSize,this._chunkSize),m=0;m<g;m++){var w=p[m],b=x[m];w>=l&&w<=h&&b>=y&&b<=_&&(a[o++]=c),c++}u=!0}}if(!u)if(1===i)for(m=0;m<r;m++){M=this.getRawIndex(m);(w=this._getFast(s,M))>=l&&w<=h&&(a[o++]=M)}else for(m=0;m<r;m++){for(var S=!0,M=this.getRawIndex(m),d=0;d<i;d++){var I=e[d];((w=this._getFast(n,M))<t[I][0]||w>t[I][1])&&(S=!1)}S&&(a[o++]=this.getRawIndex(m))}return o<r&&(this._indices=a),this._count=o,this._extent={},this.getRawIndex=this._indices?Yo:Uo,this}}},Cp.mapArray=function(t,e,n,i){"function"==typeof t&&(i=n,n=e,e=t,t=[]),n=n||i||this;var r=[];return this.each(t,function(){r.push(e&&e.apply(this,arguments))},n),r},Cp.map=function(t,e,n,i){n=n||i||this;var r=$o(this,t=d(jo(t),this.getDimension,this));r._indices=this._indices,r.getRawIndex=r._indices?Yo:Uo;for(var a=r._storage,o=[],s=this._chunkSize,l=t.length,h=this.count(),u=[],c=r._rawExtent,f=0;f<h;f++){for(var p=0;p<l;p++)u[p]=this.get(t[p],f);u[l]=f;var g=e&&e.apply(n,u);if(null!=g){"object"!=typeof g&&(o[0]=g,g=o);for(var m=this.getRawIndex(f),v=Math.floor(m/s),y=m%s,_=0;_<g.length;_++){var x=t[_],w=g[_],b=c[x],S=a[x];S&&(S[v][y]=w),w<b[0]&&(b[0]=w),w>b[1]&&(b[1]=w)}}}return r},Cp.downSample=function(t,e,n,i){for(var r=$o(this,[t]),a=r._storage,o=[],s=Math.floor(1/e),l=a[t],h=this.count(),u=this._chunkSize,c=r._rawExtent[t],f=new(Ho(this))(h),d=0,p=0;p<h;p+=s){s>h-p&&(s=h-p,o.length=s);for(var g=0;g<s;g++){var m=this.getRawIndex(p+g),v=Math.floor(m/u),y=m%u;o[g]=l[v][y]}var _=n(o),x=this.getRawIndex(Math.min(p+i(o,_)||0,h-1)),w=x%u;l[Math.floor(x/u)][w]=_,_<c[0]&&(c[0]=_),_>c[1]&&(c[1]=_),f[d++]=x}return r._count=d,r._indices=f,r.getRawIndex=Yo,r},Cp.getItemModel=function(t){var e=this.hostModel;return new ji(this.getRawDataItem(t),e,e&&e.ecModel)},Cp.diff=function(t){var e=this;return new Ro(t?t.getIndices():[],this.getIndices(),function(e){return Zo(t,e)},function(t){return Zo(e,t)})},Cp.getVisual=function(t){var e=this._visual;return e&&e[t]},Cp.setVisual=function(t,e){if(_p(t))for(var n in t)t.hasOwnProperty(n)&&this.setVisual(n,t[n]);else this._visual=this._visual||{},this._visual[t]=e},Cp.setLayout=function(t,e){if(_p(t))for(var n in t)t.hasOwnProperty(n)&&this.setLayout(n,t[n]);else this._layout[t]=e},Cp.getLayout=function(t){return this._layout[t]},Cp.getItemLayout=function(t){return this._itemLayouts[t]},Cp.setItemLayout=function(t,e,n){this._itemLayouts[t]=n?a(this._itemLayouts[t]||{},e):e},Cp.clearItemLayouts=function(){this._itemLayouts.length=0},Cp.getItemVisual=function(t,e,n){var i=this._itemVisuals[t],r=i&&i[e];return null!=r||n?r:this.getVisual(e)},Cp.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{},r=this.hasItemVisual;if(this._itemVisuals[t]=i,_p(e))for(var a in e)e.hasOwnProperty(a)&&(i[a]=e[a],r[a]=!0);else i[e]=n,r[e]=!0},Cp.clearAllVisual=function(){this._visual={},this._itemVisuals=[],this.hasItemVisual={}};var Dp=function(t){t.seriesIndex=this.seriesIndex,t.dataIndex=this.dataIndex,t.dataType=this.dataType};Cp.setItemGraphicEl=function(t,e){var n=this.hostModel;e&&(e.dataIndex=t,e.dataType=this.dataType,e.seriesIndex=n&&n.seriesIndex,"group"===e.type&&e.traverse(Dp,e)),this._graphicEls[t]=e},Cp.getItemGraphicEl=function(t){return this._graphicEls[t]},Cp.eachItemGraphicEl=function(t,e){f(this._graphicEls,function(n,i){n&&t&&t.call(e,n,i)})},Cp.cloneShallow=function(t){if(!t){var e=d(this.dimensions,this.getDimensionInfo,this);t=new Tp(e,this.hostModel)}if(t._storage=this._storage,qo(t,this),this._indices){var i=this._indices.constructor;t._indices=new i(this._indices)}else t._indices=null;return t.getRawIndex=t._indices?Yo:Uo,t._extent=n(this._extent),t._approximateExtent=n(this._approximateExtent),t},Cp.wrapMethod=function(t,e){var n=this[t];"function"==typeof n&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(t),this[t]=function(){var t=n.apply(this,arguments);return e.apply(this,[t].concat(k(arguments)))})},Cp.TRANSFERABLE_METHODS=["cloneShallow","downSample","map"],Cp.CHANGABLE_METHODS=["filterSelf","selectRange"];var kp=function(t,e){return e=e||{},Jo(e.coordDimensions||[],t,{dimsDef:e.dimensionsDefine||t.dimensionsDefine,encodeDef:e.encodeDefine||t.encodeDefine,dimCount:e.dimensionsCount,generateCoord:e.generateCoord,generateCoordCount:e.generateCoordCount})};_d.extend({type:"series.line",dependencies:["grid","polar"],getInitialData:function(t,e){return rs(this.getSource(),this)},defaultOption:{zlevel:0,z:2,coordinateSystem:"cartesian2d",legendHoverLink:!0,hoverAnimation:!0,clipOverflow:!0,label:{position:"top"},lineStyle:{width:2,type:"solid"},step:!1,smooth:!1,smoothMonotone:null,symbol:"emptyCircle",symbolSize:4,symbolRotate:null,showSymbol:!0,showAllSymbol:!1,connectNulls:!1,sampling:"none",animationEasing:"linear",progressive:0,hoverLayerThreshold:1/0}});var Ap=gi({type:"triangle",shape:{cx:0,cy:0,width:0,height:0},buildPath:function(t,e){var n=e.cx,i=e.cy,r=e.width/2,a=e.height/2;t.moveTo(n,i-a),t.lineTo(n+r,i+a),t.lineTo(n-r,i+a),t.closePath()}}),Lp=gi({type:"diamond",shape:{cx:0,cy:0,width:0,height:0},buildPath:function(t,e){var n=e.cx,i=e.cy,r=e.width/2,a=e.height/2;t.moveTo(n,i-a),t.lineTo(n+r,i),t.lineTo(n,i+a),t.lineTo(n-r,i),t.closePath()}}),Pp=gi({type:"pin",shape:{x:0,y:0,width:0,height:0},buildPath:function(t,e){var n=e.x,i=e.y,r=e.width/5*3,a=Math.max(r,e.height),o=r/2,s=o*o/(a-o),l=i-a+o+s,h=Math.asin(s/o),u=Math.cos(h)*o,c=Math.sin(h),f=Math.cos(h),d=.6*o,p=.7*o;t.moveTo(n-u,l+s),t.arc(n,l,o,Math.PI-h,2*Math.PI+h),t.bezierCurveTo(n+u-c*d,l+s+f*d,n,i-p,n,i),t.bezierCurveTo(n,i-p,n-u+c*d,l+s+f*d,n-u,l+s),t.closePath()}}),Op=gi({type:"arrow",shape:{x:0,y:0,width:0,height:0},buildPath:function(t,e){var n=e.height,i=e.width,r=e.x,a=e.y,o=i/3*2;t.moveTo(r,a),t.lineTo(r+o,a+n),t.lineTo(r,a+n/4*3),t.lineTo(r-o,a+n),t.lineTo(r,a),t.closePath()}}),Ep={line:function(t,e,n,i,r){r.x1=t,r.y1=e+i/2,r.x2=t+n,r.y2=e+i/2},rect:function(t,e,n,i,r){r.x=t,r.y=e,r.width=n,r.height=i},roundRect:function(t,e,n,i,r){r.x=t,r.y=e,r.width=n,r.height=i,r.r=Math.min(n,i)/4},square:function(t,e,n,i,r){var a=Math.min(n,i);r.x=t,r.y=e,r.width=a,r.height=a},circle:function(t,e,n,i,r){r.cx=t+n/2,r.cy=e+i/2,r.r=Math.min(n,i)/2},diamond:function(t,e,n,i,r){r.cx=t+n/2,r.cy=e+i/2,r.width=n,r.height=i},pin:function(t,e,n,i,r){r.x=t+n/2,r.y=e+i/2,r.width=n,r.height=i},arrow:function(t,e,n,i,r){r.x=t+n/2,r.y=e+i/2,r.width=n,r.height=i},triangle:function(t,e,n,i,r){r.cx=t+n/2,r.cy=e+i/2,r.width=n,r.height=i}},Bp={};f({line:ef,rect:tf,roundRect:tf,square:tf,circle:Xc,diamond:Lp,pin:Pp,arrow:Op,triangle:Ap},function(t,e){Bp[e]=new t});var Np=gi({type:"symbol",shape:{symbolType:"",x:0,y:0,width:0,height:0},beforeBrush:function(){var t=this.style;"pin"===this.shape.symbolType&&"inside"===t.textPosition&&(t.textPosition=["50%","40%"],t.textAlign="center",t.textVerticalAlign="middle")},buildPath:function(t,e,n){var i=e.symbolType,r=Bp[i];"none"!==e.symbolType&&(r||(r=Bp[i="rect"]),Ep[i](e.x,e.y,e.width,e.height,r.shape),r.buildPath(t,r.shape,n))}}),Rp=fs.prototype;Rp._createSymbol=function(t,e,n,i){this.removeAll();var r=ls(t,-1,-1,2,2,e.getItemVisual(n,"color"));r.attr({z2:100,culling:!0,scale:cs(i)}),r.drift=ds,this._symbolType=t,this.add(r)},Rp.stopSymbolAnimation=function(t){this.childAt(0).stopAnimation(t)},Rp.getSymbolPath=function(){return this.childAt(0)},Rp.getScale=function(){return this.childAt(0).scale},Rp.highlight=function(){this.childAt(0).trigger("emphasis")},Rp.downplay=function(){this.childAt(0).trigger("normal")},Rp.setZ=function(t,e){var n=this.childAt(0);n.zlevel=t,n.z=e},Rp.setDraggable=function(t){var e=this.childAt(0);e.draggable=t,e.cursor=t?"move":"pointer"},Rp.updateData=function(t,e,n){this.silent=!1;var i=t.getItemVisual(e,"symbol")||"circle",r=t.hostModel,a=us(t,e),o=i!==this._symbolType;if(o?this._createSymbol(i,t,e,a):((s=this.childAt(0)).silent=!1,Xi(s,{scale:cs(a)},r,e)),this._updateCommon(t,e,a,n),o){var s=this.childAt(0),l=n&&n.fadeIn,h={scale:s.scale.slice()};l&&(h.style={opacity:s.style.opacity}),s.scale=[0,0],l&&(s.style.opacity=0),Ui(s,h,r,e)}this._seriesModel=r};var zp=["itemStyle"],Fp=["emphasis","itemStyle"],Vp=["label"],Wp=["emphasis","label"];Rp._updateCommon=function(t,e,n,i){var r=this.childAt(0),o=t.hostModel,s=t.getItemVisual(e,"color");"image"!==r.type&&r.useStyle({strokeNoScale:!0});var l=i&&i.itemStyle,h=i&&i.hoverItemStyle,u=i&&i.symbolRotate,c=i&&i.symbolOffset,f=i&&i.labelModel,d=i&&i.hoverLabelModel,p=i&&i.hoverAnimation,g=i&&i.cursorStyle;if(!i||t.hasItemOption){var m=i&&i.itemModel?i.itemModel:t.getItemModel(e);l=m.getModel(zp).getItemStyle(["color"]),h=m.getModel(Fp).getItemStyle(),u=m.getShallow("symbolRotate"),c=m.getShallow("symbolOffset"),f=m.getModel(Vp),d=m.getModel(Wp),p=m.getShallow("hoverAnimation"),g=m.getShallow("cursor")}else h=a({},h);var v=r.style;r.attr("rotation",(u||0)*Math.PI/180||0),c&&r.attr("position",[er(c[0],n[0]),er(c[1],n[1])]),g&&r.attr("cursor",g),r.setColor(s,i&&i.symbolInnerColor),r.setStyle(l);var y=t.getItemVisual(e,"opacity");null!=y&&(v.opacity=y);var _=i&&i.useNameLabel;Bi(v,h,f,d,{labelFetcher:o,labelDataIndex:e,defaultText:function(e,n){return _?t.getName(e):hs(t,e)},isRectText:!0,autoColor:s}),r.off("mouseover").off("mouseout").off("emphasis").off("normal"),r.hoverStyle=h,Ei(r);var x=cs(n);if(p&&o.isAnimationEnabled()){var w=function(){if(!this.incremental){var t=x[1]/x[0];this.animateTo({scale:[Math.max(1.1*x[0],x[0]+3),Math.max(1.1*x[1],x[1]+3*t)]},400,"elasticOut")}},b=function(){this.incremental||this.animateTo({scale:x},400,"elasticOut")};r.on("mouseover",w).on("mouseout",b).on("emphasis",w).on("normal",b)}},Rp.fadeOut=function(t,e){var n=this.childAt(0);this.silent=n.silent=!0,!(e&&e.keepLabel)&&(n.style.text=null),Xi(n,{style:{opacity:0},scale:[0,0]},this._seriesModel,this.dataIndex,t)},h(fs,Wh);var Hp=ps.prototype;Hp.updateData=function(t,e){e=ms(e);var n=this.group,i=t.hostModel,r=this._data,a=this._symbolCtor,o=vs(t);r||n.removeAll(),t.diff(r).add(function(i){var r=t.getItemLayout(i);if(gs(t,r,i,e)){var s=new a(t,i,o);s.attr("position",r),t.setItemGraphicEl(i,s),n.add(s)}}).update(function(s,l){var h=r.getItemGraphicEl(l),u=t.getItemLayout(s);gs(t,u,s,e)?(h?(h.updateData(t,s,o),Xi(h,{position:u},i)):(h=new a(t,s)).attr("position",u),n.add(h),t.setItemGraphicEl(s,h)):n.remove(h)}).remove(function(t){var e=r.getItemGraphicEl(t);e&&e.fadeOut(function(){n.remove(e)})}).execute(),this._data=t},Hp.isPersistent=function(){return!0},Hp.updateLayout=function(){var t=this._data;t&&t.eachItemGraphicEl(function(e,n){var i=t.getItemLayout(n);e.attr("position",i)})},Hp.incrementalPrepareUpdate=function(t){this._seriesScope=vs(t),this._data=null,this.group.removeAll()},Hp.incrementalUpdate=function(t,e,n){n=ms(n);for(var i=t.start;i<t.end;i++){var r=e.getItemLayout(i);if(gs(e,r,i,n)){var a=new this._symbolCtor(e,i,this._seriesScope);a.traverse(function(t){t.isGroup||(t.incremental=t.useHoverLayer=!0)}),a.attr("position",r),this.group.add(a),e.setItemGraphicEl(i,a)}}},Hp.remove=function(t){var e=this.group,n=this._data;n&&t?n.eachItemGraphicEl(function(t){t.fadeOut(function(){e.remove(t)})}):e.removeAll()};var Gp=function(t,e,n,i,r,a,o,s){for(var l=ws(t,e),h=[],u=[],c=[],f=[],d=[],p=[],g=[],m=ys(r,e,o),v=ys(a,t,s),y=0;y<l.length;y++){var _=l[y],x=!0;switch(_.cmd){case"=":var w=t.getItemLayout(_.idx),b=e.getItemLayout(_.idx1);(isNaN(w[0])||isNaN(w[1]))&&(w=b.slice()),h.push(w),u.push(b),c.push(n[_.idx]),f.push(i[_.idx1]),g.push(e.getRawIndex(_.idx1));break;case"+":S=_.idx;h.push(r.dataToPoint([e.get(m.dataDimsForPoint[0],S),e.get(m.dataDimsForPoint[1],S)])),u.push(e.getItemLayout(S).slice()),c.push(xs(m,r,e,S)),f.push(i[S]),g.push(e.getRawIndex(S));break;case"-":var S=_.idx,M=t.getRawIndex(S);M!==S?(h.push(t.getItemLayout(S)),u.push(a.dataToPoint([t.get(v.dataDimsForPoint[0],S),t.get(v.dataDimsForPoint[1],S)])),c.push(n[S]),f.push(xs(v,a,t,S)),g.push(M)):x=!1}x&&(d.push(_),p.push(p.length))}p.sort(function(t,e){return g[t]-g[e]});for(var I=[],T=[],C=[],D=[],k=[],y=0;y<p.length;y++){S=p[y];I[y]=h[S],T[y]=u[S],C[y]=c[S],D[y]=f[S],k[y]=d[S]}return{current:I,next:T,stackedOnCurrent:C,stackedOnNext:D,status:k}},qp=Z,Xp=j,Up=function(t,e,n,i){return t[0]=e[0]+n[0]*i,t[1]=e[1]+n[1]*i,t},Yp=function(t,e){return t[0]=e[0],t[1]=e[1],t},Zp=[],jp=[],$p=[],Kp=ai.extend({type:"ec-polyline",shape:{points:[],smooth:0,smoothConstraint:!0,smoothMonotone:null,connectNulls:!1},style:{fill:null,stroke:"#000"},brush:Yc(ai.prototype.brush),buildPath:function(t,e){var n=e.points,i=0,r=n.length,a=Cs(n,e.smoothConstraint);if(e.connectNulls){for(;r>0&&bs(n[r-1]);r--);for(;i<r&&bs(n[i]);i++);}for(;i<r;)i+=Ss(t,n,i,r,r,1,a.min,a.max,e.smooth,e.smoothMonotone,e.connectNulls)+1}}),Qp=ai.extend({type:"ec-polygon",shape:{points:[],stackedOnPoints:[],smooth:0,stackedOnSmooth:0,smoothConstraint:!0,smoothMonotone:null,connectNulls:!1},brush:Yc(ai.prototype.brush),buildPath:function(t,e){var n=e.points,i=e.stackedOnPoints,r=0,a=n.length,o=e.smoothMonotone,s=Cs(n,e.smoothConstraint),l=Cs(i,e.smoothConstraint);if(e.connectNulls){for(;a>0&&bs(n[a-1]);a--);for(;r<a&&bs(n[r]);r++);}for(;r<a;){var h=Ss(t,n,r,a,a,1,s.min,s.max,e.smooth,o,e.connectNulls);Ss(t,i,r+h-1,h,a,-1,l.min,l.max,e.stackedOnSmooth,o,e.connectNulls),r+=h+1,t.closePath()}}});Pa.extend({type:"line",init:function(){var t=new Wh,e=new ps;this.group.add(e.group),this._symbolDraw=e,this._lineGroup=t},render:function(t,e,n){var i=t.coordinateSystem,r=this.group,a=t.getData(),s=t.getModel("lineStyle"),l=t.getModel("areaStyle"),h=a.mapArray(a.getItemLayout),u="polar"===i.type,c=this._coordSys,f=this._symbolDraw,d=this._polyline,p=this._polygon,g=this._lineGroup,m=t.get("animation"),v=!l.isEmpty(),y=l.get("origin"),_=Ls(i,a,ys(i,a,y)),x=t.get("showSymbol"),w=x&&!u&&!t.get("showAllSymbol")&&this._getSymbolIgnoreFunc(a,i),b=this._data;b&&b.eachItemGraphicEl(function(t,e){t.__temp&&(r.remove(t),b.setItemGraphicEl(e,null))}),x||f.remove(),r.add(g);var S=!u&&t.get("step");if(d&&c.type===i.type&&S===this._step){v&&!p?p=this._newPolygon(h,_,i,m):p&&!v&&(g.remove(p),p=this._polygon=null);var M=Es(i,!1,t);g.setClipPath(M),x&&f.updateData(a,{isIgnore:w,clipShape:M}),a.eachItemGraphicEl(function(t){t.stopAnimation(!0)}),Ds(this._stackedOnPoints,_)&&Ds(this._points,h)||(m?this._updateAnimation(a,_,i,n,S,y):(S&&(h=Bs(h,i,S),_=Bs(_,i,S)),d.setShape({points:h}),p&&p.setShape({points:h,stackedOnPoints:_})))}else x&&f.updateData(a,{isIgnore:w,clipShape:Es(i,!1,t)}),S&&(h=Bs(h,i,S),_=Bs(_,i,S)),d=this._newPolyline(h,i,m),v&&(p=this._newPolygon(h,_,i,m)),g.setClipPath(Es(i,!0,t));var I=Ns(a,i)||a.getVisual("color");d.useStyle(o(s.getLineStyle(),{fill:"none",stroke:I,lineJoin:"bevel"}));var T=t.get("smooth");if(T=ks(t.get("smooth")),d.setShape({smooth:T,smoothMonotone:t.get("smoothMonotone"),connectNulls:t.get("connectNulls")}),p){var C=a.getCalculationInfo("stackedOnSeries"),D=0;p.useStyle(o(l.getAreaStyle(),{fill:I,opacity:.7,lineJoin:"bevel"})),C&&(D=ks(C.get("smooth"))),p.setShape({smooth:T,stackedOnSmooth:D,smoothMonotone:t.get("smoothMonotone"),connectNulls:t.get("connectNulls")})}this._data=a,this._coordSys=i,this._stackedOnPoints=_,this._points=h,this._step=S,this._valueOrigin=y},dispose:function(){},highlight:function(t,e,n,i){var r=t.getData(),a=pn(r,i);if(!(a instanceof Array)&&null!=a&&a>=0){var o=r.getItemGraphicEl(a);if(!o){var s=r.getItemLayout(a);if(!s)return;(o=new fs(r,a)).position=s,o.setZ(t.get("zlevel"),t.get("z")),o.ignore=isNaN(s[0])||isNaN(s[1]),o.__temp=!0,r.setItemGraphicEl(a,o),o.stopSymbolAnimation(!0),this.group.add(o)}o.highlight()}else Pa.prototype.highlight.call(this,t,e,n,i)},downplay:function(t,e,n,i){var r=t.getData(),a=pn(r,i);if(null!=a&&a>=0){var o=r.getItemGraphicEl(a);o&&(o.__temp?(r.setItemGraphicEl(a,null),this.group.remove(o)):o.downplay())}else Pa.prototype.downplay.call(this,t,e,n,i)},_newPolyline:function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new Kp({shape:{points:t},silent:!0,z2:10}),this._lineGroup.add(e),this._polyline=e,e},_newPolygon:function(t,e){var n=this._polygon;return n&&this._lineGroup.remove(n),n=new Qp({shape:{points:t,stackedOnPoints:e},silent:!0}),this._lineGroup.add(n),this._polygon=n,n},_getSymbolIgnoreFunc:function(t,e){var n=e.getAxesByScale("ordinal")[0];if(n&&n.isLabelIgnored)return m(n.isLabelIgnored,n)},_updateAnimation:function(t,e,n,i,r,a){var o=this._polyline,s=this._polygon,l=t.hostModel,h=Gp(this._data,t,this._stackedOnPoints,e,this._coordSys,n,this._valueOrigin,a),u=h.current,c=h.stackedOnCurrent,f=h.next,d=h.stackedOnNext;r&&(u=Bs(h.current,n,r),c=Bs(h.stackedOnCurrent,n,r),f=Bs(h.next,n,r),d=Bs(h.stackedOnNext,n,r)),o.shape.__points=h.current,o.shape.points=u,Xi(o,{shape:{points:f}},l),s&&(s.setShape({points:u,stackedOnPoints:c}),Xi(s,{shape:{points:f,stackedOnPoints:d}},l));for(var p=[],g=h.status,m=0;m<g.length;m++)if("="===g[m].cmd){var v=t.getItemGraphicEl(g[m].idx1);v&&p.push({el:v,ptIdx:m})}o.animators&&o.animators.length&&o.animators[0].during(function(){for(var t=0;t<p.length;t++)p[t].el.attr("position",o.shape.__points[p[t].ptIdx])})},remove:function(t){var e=this.group,n=this._data;this._lineGroup.removeAll(),this._symbolDraw.remove(!0),n&&n.eachItemGraphicEl(function(t,i){t.__temp&&(e.remove(t),n.setItemGraphicEl(i,null))}),this._polyline=this._polygon=this._coordSys=this._points=this._stackedOnPoints=this._data=null}});var Jp={average:function(t){for(var e=0,n=0,i=0;i<t.length;i++)isNaN(t[i])||(e+=t[i],n++);return 0===n?NaN:e/n},sum:function(t){for(var e=0,n=0;n<t.length;n++)e+=t[n]||0;return e},max:function(t){for(var e=-1/0,n=0;n<t.length;n++)t[n]>e&&(e=t[n]);return e},min:function(t){for(var e=1/0,n=0;n<t.length;n++)t[n]<e&&(e=t[n]);return e},nearest:function(t){return t[0]}},tg=function(t,e){return Math.round(t.length/2)};Rs.prototype.parse=function(t){return t},Rs.prototype.getSetting=function(t){return this._setting[t]},Rs.prototype.contain=function(t){var e=this._extent;return t>=e[0]&&t<=e[1]},Rs.prototype.normalize=function(t){var e=this._extent;return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])},Rs.prototype.scale=function(t){var e=this._extent;return t*(e[1]-e[0])+e[0]},Rs.prototype.unionExtent=function(t){var e=this._extent;t[0]<e[0]&&(e[0]=t[0]),t[1]>e[1]&&(e[1]=t[1])},Rs.prototype.unionExtentFromData=function(t,e){this.unionExtent(t.getApproximateExtent(e))},Rs.prototype.getExtent=function(){return this._extent.slice()},Rs.prototype.setExtent=function(t,e){var n=this._extent;isNaN(t)||(n[0]=t),isNaN(e)||(n[1]=e)},Rs.prototype.getTicksLabels=function(){for(var t=[],e=this.getTicks(),n=0;n<e.length;n++)t.push(this.getLabel(e[n]));return t},Rs.prototype.isBlank=function(){return this._isBlank},Rs.prototype.setBlank=function(t){this._isBlank=t},bn(Rs),Tn(Rs,{registerWhenExtend:!0}),zs.createByAxisModel=function(t){var e=t.option,n=e.data,i=n&&d(n,Vs);return new zs({categories:i,needCollect:!i,deduplication:!1!==e.dedplication})};var eg=zs.prototype;eg.getOrdinal=function(t){return Fs(this).get(t)},eg.parseAndCollect=function(t){var e,n=this._needCollect;if("string"!=typeof t&&!n)return t;if(n&&!this._deduplication)return e=this.categories.length,this.categories[e]=t,e;var i=Fs(this);return null==(e=i.get(t))&&(n?(e=this.categories.length,this.categories[e]=t,i.set(t,e)):e=NaN),e};var ng=Rs.prototype,ig=Rs.extend({type:"ordinal",init:function(t,e){t&&!y(t)||(t=new zs({categories:t})),this._ordinalMeta=t,this._extent=e||[0,t.categories.length-1]},parse:function(t){return"string"==typeof t?this._ordinalMeta.getOrdinal(t):Math.round(t)},contain:function(t){return t=this.parse(t),ng.contain.call(this,t)&&null!=this._ordinalMeta.categories[t]},normalize:function(t){return ng.normalize.call(this,this.parse(t))},scale:function(t){return Math.round(ng.scale.call(this,t))},getTicks:function(){for(var t=[],e=this._extent,n=e[0];n<=e[1];)t.push(n),n++;return t},getLabel:function(t){return this._ordinalMeta.categories[t]},count:function(){return this._extent[1]-this._extent[0]+1},unionExtentFromData:function(t,e){this.unionExtent(t.getApproximateExtent(e))},niceTicks:R,niceExtent:R});ig.create=function(){return new ig};var rg=nr,ag=nr,og=Rs.extend({type:"interval",_interval:0,_intervalPrecision:2,setExtent:function(t,e){var n=this._extent;isNaN(t)||(n[0]=parseFloat(t)),isNaN(e)||(n[1]=parseFloat(e))},unionExtent:function(t){var e=this._extent;t[0]<e[0]&&(e[0]=t[0]),t[1]>e[1]&&(e[1]=t[1]),og.prototype.setExtent.call(this,e[0],e[1])},getInterval:function(){return this._interval},setInterval:function(t){this._interval=t,this._niceExtent=this._extent.slice(),this._intervalPrecision=Hs(t)},getTicks:function(){return Xs(this._interval,this._extent,this._niceExtent,this._intervalPrecision)},getTicksLabels:function(){for(var t=[],e=this.getTicks(),n=0;n<e.length;n++)t.push(this.getLabel(e[n]));return t},getLabel:function(t,e){if(null==t)return"";var n=e&&e.precision;return null==n?n=ir(t)||0:"auto"===n&&(n=this._intervalPrecision),t=ag(t,n,!0),fr(t)},niceTicks:function(t,e,n){t=t||5;var i=this._extent,r=i[1]-i[0];if(isFinite(r)){r<0&&(r=-r,i.reverse());var a=Ws(i,t,e,n);this._intervalPrecision=a.intervalPrecision,this._interval=a.interval,this._niceExtent=a.niceTickExtent}},niceExtent:function(t){var e=this._extent;if(e[0]===e[1])if(0!==e[0]){var n=e[0];t.fixMax?e[0]-=n/2:(e[1]+=n/2,e[0]-=n/2)}else e[1]=1;var i=e[1]-e[0];isFinite(i)||(e[0]=0,e[1]=1),this.niceTicks(t.splitNumber,t.minInterval,t.maxInterval);var r=this._interval;t.fixMin||(e[0]=ag(Math.floor(e[0]/r)*r)),t.fixMax||(e[1]=ag(Math.ceil(e[1]/r)*r))}});og.create=function(){return new og};var sg="__ec_stack_",lg=og.prototype,hg=Math.ceil,ug=Math.floor,cg=function(t,e,n,i){for(;n<i;){var r=n+i>>>1;t[r][1]<e?n=r+1:i=r}return n},fg=og.extend({type:"time",getLabel:function(t){var e=this._stepLvl,n=new Date(t);return vr(e[0],n,this.getSetting("useUTC"))},niceExtent:function(t){var e=this._extent;if(e[0]===e[1]&&(e[0]-=864e5,e[1]+=864e5),e[1]===-1/0&&e[0]===1/0){var n=new Date;e[1]=+new Date(n.getFullYear(),n.getMonth(),n.getDate()),e[0]=e[1]-864e5}this.niceTicks(t.splitNumber,t.minInterval,t.maxInterval);var i=this._interval;t.fixMin||(e[0]=nr(ug(e[0]/i)*i)),t.fixMax||(e[1]=nr(hg(e[1]/i)*i))},niceTicks:function(t,e,n){t=t||10;var i=this._extent,r=i[1]-i[0],a=r/t;null!=e&&a<e&&(a=e),null!=n&&a>n&&(a=n);var o=dg.length,s=cg(dg,a,0,o),l=dg[Math.min(s,o-1)],h=l[1];"year"===l[0]&&(h*=cr(r/h/t,!0));var u=this.getSetting("useUTC")?0:60*new Date(+i[0]||+i[1]).getTimezoneOffset()*1e3,c=[Math.round(hg((i[0]-u)/h)*h+u),Math.round(ug((i[1]-u)/h)*h+u)];qs(c,i),this._stepLvl=l,this._interval=h,this._niceExtent=c},parse:function(t){return+lr(t)}});f(["contain","normalize"],function(t){fg.prototype[t]=function(e){return lg[t].call(this,this.parse(e))}});var dg=[["hh:mm:ss",1e3],["hh:mm:ss",5e3],["hh:mm:ss",1e4],["hh:mm:ss",15e3],["hh:mm:ss",3e4],["hh:mm\nMM-dd",6e4],["hh:mm\nMM-dd",3e5],["hh:mm\nMM-dd",6e5],["hh:mm\nMM-dd",9e5],["hh:mm\nMM-dd",18e5],["hh:mm\nMM-dd",36e5],["hh:mm\nMM-dd",72e5],["hh:mm\nMM-dd",216e5],["hh:mm\nMM-dd",432e5],["MM-dd\nyyyy",864e5],["MM-dd\nyyyy",1728e5],["MM-dd\nyyyy",2592e5],["MM-dd\nyyyy",3456e5],["MM-dd\nyyyy",432e6],["MM-dd\nyyyy",5184e5],["week",6048e5],["MM-dd\nyyyy",864e6],["week",12096e5],["week",18144e5],["month",26784e5],["week",36288e5],["month",53568e5],["week",36288e5],["quarter",8208e6],["month",107136e5],["month",13392e6],["half-year",16416e6],["month",214272e5],["month",26784e6],["year",32832e6]];fg.create=function(t){return new fg({useUTC:t.ecModel.get("useUTC")})};var pg=Rs.prototype,gg=og.prototype,mg=ir,vg=nr,yg=Math.floor,_g=Math.ceil,xg=Math.pow,wg=Math.log,bg=Rs.extend({type:"log",base:10,$constructor:function(){Rs.apply(this,arguments),this._originalScale=new og},getTicks:function(){var t=this._originalScale,e=this._extent,n=t.getExtent();return d(gg.getTicks.call(this),function(i){var r=nr(xg(this.base,i));return r=i===e[0]&&t.__fixMin?$s(r,n[0]):r,r=i===e[1]&&t.__fixMax?$s(r,n[1]):r},this)},getLabel:gg.getLabel,scale:function(t){return t=pg.scale.call(this,t),xg(this.base,t)},setExtent:function(t,e){var n=this.base;t=wg(t)/wg(n),e=wg(e)/wg(n),gg.setExtent.call(this,t,e)},getExtent:function(){var t=this.base,e=pg.getExtent.call(this);e[0]=xg(t,e[0]),e[1]=xg(t,e[1]);var n=this._originalScale,i=n.getExtent();return n.__fixMin&&(e[0]=$s(e[0],i[0])),n.__fixMax&&(e[1]=$s(e[1],i[1])),e},unionExtent:function(t){this._originalScale.unionExtent(t);var e=this.base;t[0]=wg(t[0])/wg(e),t[1]=wg(t[1])/wg(e),pg.unionExtent.call(this,t)},unionExtentFromData:function(t,e){this.unionExtent(t.getApproximateExtent(e))},niceTicks:function(t){t=t||10;var e=this._extent,n=e[1]-e[0];if(!(n===1/0||n<=0)){var i=hr(n);for(t/n*i<=.5&&(i*=10);!isNaN(i)&&Math.abs(i)<1&&Math.abs(i)>0;)i*=10;var r=[nr(_g(e[0]/i)*i),nr(yg(e[1]/i)*i)];this._interval=i,this._niceExtent=r}},niceExtent:function(t){gg.niceExtent.call(this,t);var e=this._originalScale;e.__fixMin=t.fixMin,e.__fixMax=t.fixMax}});f(["contain","normalize"],function(t){bg.prototype[t]=function(e){return e=wg(e)/wg(this.base),pg[t].call(this,e)}}),bg.create=function(){return new bg};var Sg=function(t){this._axes={},this._dimList=[],this.name=t||""};Sg.prototype={constructor:Sg,type:"cartesian",getAxis:function(t){return this._axes[t]},getAxes:function(){return d(this._dimList,il,this)},getAxesByScale:function(t){return t=t.toLowerCase(),g(this.getAxes(),function(e){return e.scale.type===t})},addAxis:function(t){var e=t.dim;this._axes[e]=t,this._dimList.push(e)},dataToCoord:function(t){return this._dataCoordConvert(t,"dataToCoord")},coordToData:function(t){return this._dataCoordConvert(t,"coordToData")},_dataCoordConvert:function(t,e){for(var n=this._dimList,i=t instanceof Array?[]:{},r=0;r<n.length;r++){var a=n[r],o=this._axes[a];i[a]=o[e](t[a])}return i}},rl.prototype={constructor:rl,type:"cartesian2d",dimensions:["x","y"],getBaseAxis:function(){return this.getAxesByScale("ordinal")[0]||this.getAxesByScale("time")[0]||this.getAxis("x")},containPoint:function(t){var e=this.getAxis("x"),n=this.getAxis("y");return e.contain(e.toLocalCoord(t[0]))&&n.contain(n.toLocalCoord(t[1]))},containData:function(t){return this.getAxis("x").containData(t[0])&&this.getAxis("y").containData(t[1])},dataToPoint:function(t,e,n){var i=this.getAxis("x"),r=this.getAxis("y");return n=n||[],n[0]=i.toGlobalCoord(i.dataToCoord(t[0])),n[1]=r.toGlobalCoord(r.dataToCoord(t[1])),n},clampData:function(t,e){var n=this.getAxis("x").scale.getExtent(),i=this.getAxis("y").scale.getExtent();return e=e||[],e[0]=Math.min(Math.max(Math.min(n[0],n[1]),t[0]),Math.max(n[0],n[1])),e[1]=Math.min(Math.max(Math.min(i[0],i[1]),t[1]),Math.max(i[0],i[1])),e},pointToData:function(t,e){var n=this.getAxis("x"),i=this.getAxis("y");return e=e||[],e[0]=n.coordToData(n.toLocalCoord(t[0])),e[1]=i.coordToData(i.toLocalCoord(t[1])),e},getOtherAxis:function(t){return this.getAxis("x"===t.dim?"y":"x")}},h(rl,Sg);var Mg=tr,Ig=[0,1],Tg=function(t,e,n){this.dim=t,this.scale=e,this._extent=n||[0,0],this.inverse=!1,this.onBand=!1,this._labelInterval};Tg.prototype={constructor:Tg,contain:function(t){var e=this._extent,n=Math.min(e[0],e[1]),i=Math.max(e[0],e[1]);return t>=n&&t<=i},containData:function(t){return this.contain(this.dataToCoord(t))},getExtent:function(){return this._extent.slice()},getPixelPrecision:function(t){return rr(t||this.scale.getExtent(),this._extent)},setExtent:function(t,e){var n=this._extent;n[0]=t,n[1]=e},dataToCoord:function(t,e){var n=this._extent,i=this.scale;return t=i.normalize(t),this.onBand&&"ordinal"===i.type&&al(n=n.slice(),i.count()),Mg(t,Ig,n,e)},coordToData:function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&al(n=n.slice(),i.count());var r=Mg(t,n,Ig,e);return this.scale.scale(r)},pointToData:function(t,e){},getTicksCoords:function(t){if(this.onBand&&!t){for(var e=this.getBands(),n=[],i=0;i<e.length;i++)n.push(e[i][0]);return e[i-1]&&n.push(e[i-1][1]),n}return d(this.scale.getTicks(),this.dataToCoord,this)},getLabelsCoords:function(){return d(this.scale.getTicks(),this.dataToCoord,this)},getBands:function(){for(var t=this.getExtent(),e=[],n=this.scale.count(),i=t[0],r=t[1]-i,a=0;a<n;a++)e.push([r*a/n+i,r*(a+1)/n+i]);return e},getBandWidth:function(){var t=this._extent,e=this.scale.getExtent(),n=e[1]-e[0]+(this.onBand?1:0);0===n&&(n=1);var i=Math.abs(t[1]-t[0]);return Math.abs(i)/n},isHorizontal:null,getRotate:null,getLabelInterval:function(){var t=this._labelInterval;if(!t){var e=this.model,n=e.getModel("axisLabel");t=n.get("interval"),"category"!==this.type||null!=t&&"auto"!==t||(t=tl(d(this.scale.getTicks(),this.dataToCoord,this),e.getFormattedLabels(),n.getFont(),this.getRotate?this.getRotate():this.isHorizontal&&!this.isHorizontal()?90:0,n.get("rotate"))),this._labelInterval=t}return t}};var Cg=function(t,e,n,i,r){Tg.call(this,t,e,n),this.type=i||"value",this.position=r||"bottom"};Cg.prototype={constructor:Cg,index:0,onZero:!1,model:null,isHorizontal:function(){var t=this.position;return"top"===t||"bottom"===t},getGlobalExtent:function(t){var e=this.getExtent();return e[0]=this.toGlobalCoord(e[0]),e[1]=this.toGlobalCoord(e[1]),t&&e[0]>e[1]&&e.reverse(),e},getOtherAxis:function(){this.grid.getOtherAxis()},isLabelIgnored:function(t){if("category"===this.type){var e=this.getLabelInterval();return"function"==typeof e&&!e(t,this.scale.getLabel(t))||t%(e+1)}},pointToData:function(t,e){return this.coordToData(this.toLocalCoord(t["x"===this.dim?0:1]),e)},toLocalCoord:null,toGlobalCoord:null},h(Cg,Tg);var Dg={show:!0,zlevel:0,z:0,inverse:!1,name:"",nameLocation:"end",nameRotate:null,nameTruncate:{maxWidth:null,ellipsis:"...",placeholder:"."},nameTextStyle:{},nameGap:15,silent:!1,triggerEvent:!1,tooltip:{show:!1},axisPointer:{},axisLine:{show:!0,onZero:!0,onZeroAxisIndex:null,lineStyle:{color:"#333",width:1,type:"solid"},symbol:["none","none"],symbolSize:[10,15]},axisTick:{show:!0,inside:!1,length:5,lineStyle:{width:1}},axisLabel:{show:!0,inside:!1,rotate:0,showMinLabel:null,showMaxLabel:null,margin:8,fontSize:12},splitLine:{show:!0,lineStyle:{color:["#ccc"],width:1,type:"solid"}},splitArea:{show:!1,areaStyle:{color:["rgba(250,250,250,0.3)","rgba(200,200,200,0.3)"]}}},kg={};kg.categoryAxis=i({boundaryGap:!0,deduplication:null,splitLine:{show:!1},axisTick:{alignWithLabel:!1,interval:"auto"},axisLabel:{interval:"auto"}},Dg),kg.valueAxis=i({boundaryGap:[0,0],splitNumber:5},Dg),kg.timeAxis=o({scale:!0,min:"dataMin",max:"dataMax"},kg.valueAxis),kg.logAxis=o({scale:!0,logBase:10},kg.valueAxis);var Ag=["value","category","time","log"],Lg=function(t,e,n,a){f(Ag,function(o){e.extend({type:t+"Axis."+o,mergeDefaultAndTheme:function(e,r){var a=this.layoutMode,s=a?wr(e):{};i(e,r.getTheme().get(o+"Axis")),i(e,this.getDefaultOption()),e.type=n(t,e),a&&xr(e,s,a)},optionUpdated:function(){"category"===this.option.type&&(this.__ordinalMeta=zs.createByAxisModel(this))},getCategories:function(){if("category"===this.option.type)return this.__ordinalMeta.categories},getOrdinalMeta:function(){return this.__ordinalMeta},defaultOption:r([{},kg[o+"Axis"],a],!0)})}),Ef.registerSubTypeDefaulter(t+"Axis",v(n,t))},Pg={getFormattedLabels:function(){return el(this.axis,this.get("axisLabel.formatter"))},getMin:function(t){var e=this.option,n=t||null==e.rangeStart?e.min:e.rangeStart;return this.axis&&null!=n&&"dataMin"!==n&&"function"!=typeof n&&!I(n)&&(n=this.axis.scale.parse(n)),n},getMax:function(t){var e=this.option,n=t||null==e.rangeEnd?e.max:e.rangeEnd;return this.axis&&null!=n&&"dataMax"!==n&&"function"!=typeof n&&!I(n)&&(n=this.axis.scale.parse(n)),n},getNeedCrossZero:function(){var t=this.option;return null==t.rangeStart&&null==t.rangeEnd&&!t.scale},getCoordSysModel:R,setRange:function(t,e){this.option.rangeStart=t,this.option.rangeEnd=e},resetRange:function(){this.option.rangeStart=this.option.rangeEnd=null}},Og=Ef.extend({type:"cartesian2dAxis",axis:null,init:function(){Og.superApply(this,"init",arguments),this.resetRange()},mergeOption:function(){Og.superApply(this,"mergeOption",arguments),this.resetRange()},restoreData:function(){Og.superApply(this,"restoreData",arguments),this.resetRange()},getCoordSysModel:function(){return this.ecModel.queryComponents({mainType:"grid",index:this.option.gridIndex,id:this.option.gridId})[0]}});i(Og.prototype,Pg);var Eg={offset:0};Lg("x",Og,ol,Eg),Lg("y",Og,ol,Eg),Ef.extend({type:"grid",dependencies:["xAxis","yAxis"],layoutMode:"box",coordinateSystem:null,defaultOption:{show:!1,zlevel:0,z:0,left:"10%",top:60,right:"10%",bottom:60,containLabel:!1,backgroundColor:"rgba(0,0,0,0)",borderWidth:1,borderColor:"#ccc"}});var Bg=f,Ng=function(t){var e=t.scale.getExtent(),n=e[0],i=e[1];return!(n>0&&i>0||n<0&&i<0)},Rg=function(t,e){var n=Ks(t,e),i=null!=e.getMin(),r=null!=e.getMax(),a=e.get("splitNumber");"log"===t.type&&(t.base=e.get("logBase"));var o=t.type;t.setExtent(n[0],n[1]),t.niceExtent({splitNumber:a,fixMin:i,fixMax:r,minInterval:"interval"===o||"time"===o?e.get("minInterval"):null,maxInterval:"interval"===o||"time"===o?e.get("maxInterval"):null});var s=e.get("interval");null!=s&&t.setInterval&&t.setInterval(s)},zg=ul.prototype;zg.type="grid",zg.axisPointerEnabled=!0,zg.getRect=function(){return this._rect},zg.update=function(t,e){var n=this._axesMap;this._updateScale(t,this.model),Bg(n.x,function(t){Rg(t.scale,t.model)}),Bg(n.y,function(t){Rg(t.scale,t.model)}),Bg(n.x,function(t){cl(n,"y",t)}),Bg(n.y,function(t){cl(n,"x",t)}),this.resize(this.model,e)},zg.resize=function(t,e,n){function i(){Bg(a,function(t){var e=t.isHorizontal(),n=e?[0,r.width]:[0,r.height],i=t.inverse?1:0;t.setExtent(n[i],n[1-i]),dl(t,e?r.x:r.y)})}var r=_r(t.getBoxLayoutParams(),{width:e.getWidth(),height:e.getHeight()});this._rect=r;var a=this._axesList;i(),!n&&t.get("containLabel")&&(Bg(a,function(t){if(!t.model.get("axisLabel.inside")){var e=hl(t);if(e){var n=t.isHorizontal()?"height":"width",i=t.model.get("axisLabel.margin");r[n]-=e[n]+i,"top"===t.position?r.y+=e.height+i:"left"===t.position&&(r.x+=e.width+i)}}}),i())},zg.getAxis=function(t,e){var n=this._axesMap[t];if(null!=n){if(null==e)for(var i in n)if(n.hasOwnProperty(i))return n[i];return n[e]}},zg.getAxes=function(){return this._axesList.slice()},zg.getCartesian=function(t,e){if(null!=t&&null!=e){var n="x"+t+"y"+e;return this._coordsMap[n]}w(t)&&(e=t.yAxisIndex,t=t.xAxisIndex);for(var i=0,r=this._coordsList;i<r.length;i++)if(r[i].getAxis("x").index===t||r[i].getAxis("y").index===e)return r[i]},zg.getCartesians=function(){return this._coordsList.slice()},zg.convertToPixel=function(t,e,n){var i=this._findConvertTarget(t,e);return i.cartesian?i.cartesian.dataToPoint(n):i.axis?i.axis.toGlobalCoord(i.axis.dataToCoord(n)):null},zg.convertFromPixel=function(t,e,n){var i=this._findConvertTarget(t,e);return i.cartesian?i.cartesian.pointToData(n):i.axis?i.axis.coordToData(i.axis.toLocalCoord(n)):null},zg._findConvertTarget=function(t,e){var n,i,r=e.seriesModel,a=e.xAxisModel||r&&r.getReferringComponents("xAxis")[0],o=e.yAxisModel||r&&r.getReferringComponents("yAxis")[0],s=e.gridModel,h=this._coordsList;return r?l(h,n=r.coordinateSystem)<0&&(n=null):a&&o?n=this.getCartesian(a.componentIndex,o.componentIndex):a?i=this.getAxis("x",a.componentIndex):o?i=this.getAxis("y",o.componentIndex):s&&s.coordinateSystem===this&&(n=this._coordsList[0]),{cartesian:n,axis:i}},zg.containPoint=function(t){var e=this._coordsList[0];if(e)return e.containPoint(t)},zg._initCartesian=function(t,e,n){function i(n){return function(i,s){if(sl(i,t,e)){var l=i.get("position");"x"===n?"top"!==l&&"bottom"!==l&&r[l="bottom"]&&(l="top"===l?"bottom":"top"):"left"!==l&&"right"!==l&&r[l="left"]&&(l="left"===l?"right":"left"),r[l]=!0;var h=new Cg(n,Js(i),[0,0],i.get("type"),l),u="category"===h.type;h.onBand=u&&i.get("boundaryGap"),h.inverse=i.get("inverse"),h.onZero=i.get("axisLine.onZero"),h.onZeroAxisIndex=i.get("axisLine.onZeroAxisIndex"),i.axis=h,h.model=i,h.grid=this,h.index=s,this._axesList.push(h),a[n][s]=h,o[n]++}}}var r={left:!1,right:!1,top:!1,bottom:!1},a={x:{},y:{}},o={x:0,y:0};if(e.eachComponent("xAxis",i("x"),this),e.eachComponent("yAxis",i("y"),this),!o.x||!o.y)return this._axesMap={},void(this._axesList=[]);this._axesMap=a,Bg(a.x,function(e,n){Bg(a.y,function(i,r){var a="x"+n+"y"+r,o=new rl(a);o.grid=this,o.model=t,this._coordsMap[a]=o,this._coordsList.push(o),o.addAxis(e),o.addAxis(i)},this)},this)},zg._updateScale=function(t,e){function n(t,e,n){Bg(t.mapDimension(e.dim,!0),function(n){e.scale.unionExtentFromData(t,n)})}f(this._axesList,function(t){t.scale.setExtent(1/0,-1/0)}),t.eachSeries(function(i){if(gl(i)){var r=pl(i),a=r[0],o=r[1];if(!sl(a,e,t)||!sl(o,e,t))return;var s=this.getCartesian(a.componentIndex,o.componentIndex),l=i.getData(),h=s.getAxis("x"),u=s.getAxis("y");"list"===l.type&&(n(l,h),n(l,u))}},this)},zg.getTooltipAxes=function(t){var e=[],n=[];return Bg(this.getCartesians(),function(i){var r=null!=t&&"auto"!==t?i.getAxis(t):i.getBaseAxis(),a=i.getOtherAxis(r);l(e,r)<0&&e.push(r),l(n,a)<0&&n.push(a)}),{baseAxes:e,otherAxes:n}};var Fg=["xAxis","yAxis"];ul.create=function(t,e){var n=[];return t.eachComponent("grid",function(i,r){var a=new ul(i,t,e);a.name="grid_"+r,a.resize(i,e,!0),i.coordinateSystem=a,n.push(a)}),t.eachSeries(function(t){if(gl(t)){var e=pl(t),n=e[0],i=e[1],r=n.getCoordSysModel().coordinateSystem;t.coordinateSystem=r.getCartesian(n.componentIndex,i.componentIndex)}}),n},ul.dimensions=ul.prototype.dimensions=rl.prototype.dimensions,Yr.register("cartesian2d",ul);var Vg=Math.PI,Wg=function(t,e){this.opt=e,this.axisModel=t,o(e,{labelOffset:0,nameDirection:1,tickDirection:1,labelDirection:1,silent:!0}),this.group=new Wh;var n=new Wh({position:e.position.slice(),rotation:e.rotation});n.updateTransform(),this._transform=n.transform,this._dumbGroup=n};Wg.prototype={constructor:Wg,hasBuilder:function(t){return!!Hg[t]},add:function(t){Hg[t].call(this)},getGroup:function(){return this.group}};var Hg={axisLine:function(){var t=this.opt,e=this.axisModel;if(e.get("axisLine.show")){var n=this.axisModel.axis.getExtent(),i=this._transform,r=[n[0],0],o=[n[1],0];i&&(Y(r,r,i),Y(o,o,i));var s=a({lineCap:"round"},e.getModel("axisLine.lineStyle").getLineStyle());this.group.add(new ef(xi({anid:"line",shape:{x1:r[0],y1:r[1],x2:o[0],y2:o[1]},style:s,strokeContainThreshold:t.strokeContainThreshold||5,silent:!0,z2:1})));var l=e.get("axisLine.symbol"),h=e.get("axisLine.symbolSize"),u=e.get("axisLine.symbolOffset")||0;if("number"==typeof u&&(u=[u,u]),null!=l){"string"==typeof l&&(l=[l,l]),"string"!=typeof h&&"number"!=typeof h||(h=[h,h]);var c=h[0],d=h[1];f([{rotate:t.rotation+Math.PI/2,offset:u[0],r:0},{rotate:t.rotation-Math.PI/2,offset:u[1],r:Math.sqrt((r[0]-o[0])*(r[0]-o[0])+(r[1]-o[1])*(r[1]-o[1]))}],function(e,n){if("none"!==l[n]&&null!=l[n]){var i=ls(l[n],-c/2,-d/2,c,d,s.stroke,!0),a=e.r+e.offset,o=[r[0]+a*Math.cos(t.rotation),r[1]-a*Math.sin(t.rotation)];i.attr({rotation:e.rotate,position:o,silent:!0}),this.group.add(i)}},this)}}},axisTickLabel:function(){var t=this.axisModel,e=this.opt,n=Sl(this,t,e);_l(t,Ml(this,t,e),n)},axisName:function(){var t=this.opt,e=this.axisModel,n=T(t.axisName,e.get("name"));if(n){var i,r=e.get("nameLocation"),o=t.nameDirection,s=e.getModel("nameTextStyle"),l=e.get("nameGap")||0,h=this.axisModel.axis.getExtent(),u=h[0]>h[1]?-1:1,c=["start"===r?h[0]-u*l:"end"===r?h[1]+u*l:(h[0]+h[1])/2,bl(r)?t.labelOffset+o*l:0],f=e.get("nameRotate");null!=f&&(f=f*Vg/180);var d;bl(r)?i=Gg(t.rotation,null!=f?f:t.rotation,o):(i=vl(t,r,f||0,h),null!=(d=t.axisNameAvailableWidth)&&(d=Math.abs(d/Math.sin(i.rotation)),!isFinite(d)&&(d=null)));var p=s.getFont(),g=e.get("nameTruncate",!0)||{},m=g.ellipsis,v=T(t.nameTruncateMaxWidth,g.maxWidth,d),y=null!=m&&null!=v?Df(n,v,p,m,{minChar:2,placeholder:g.placeholder}):n,_=e.get("tooltip",!0),x=e.mainType,w={componentType:x,name:n,$vars:["name"]};w[x+"Index"]=e.componentIndex;var b=new qc({anid:"name",__fullText:n,__truncatedText:y,position:c,rotation:i.rotation,silent:yl(e),z2:1,tooltip:_&&_.show?a({content:n,formatter:function(){return n},formatterParams:w},_):null});Ni(b.style,s,{text:y,textFont:p,textFill:s.getTextColor()||e.get("axisLine.lineStyle.color"),textAlign:i.textAlign,textVerticalAlign:i.textVerticalAlign}),e.get("triggerEvent")&&(b.eventData=ml(e),b.eventData.targetType="axisName",b.eventData.name=n),this._dumbGroup.add(b),b.updateTransform(),this.group.add(b),b.decomposeTransform()}}},Gg=Wg.innerTextLayout=function(t,e,n){var i,r,a=or(e-t);return sr(a)?(r=n>0?"top":"bottom",i="center"):sr(a-Vg)?(r=n>0?"bottom":"top",i="center"):(r="middle",i=a>0&&a<Vg?n>0?"right":"left":n>0?"left":"right"),{rotation:a,textAlign:i,textVerticalAlign:r}},qg=Wg.ifIgnoreOnTick=function(t,e,n,i,r,a){if(0===e&&r||e===i-1&&a)return!1;var o,s=t.scale;return"ordinal"===s.type&&("function"==typeof n?(o=s.getTicks()[e],!n(o,s.getLabel(o))):e%(n+1))},Xg=Wg.getInterval=function(t,e){var n=t.get("interval");return null!=n&&"auto"!=n||(n=e),n},Ug=Oo({type:"axis",_axisPointer:null,axisPointerClass:null,render:function(t,e,n,i){this.axisPointerClass&&Il(t),Ug.superApply(this,"render",arguments),Al(this,t,0,n,0,!0)},updateAxisPointer:function(t,e,n,i,r){Al(this,t,0,n,0,!1)},remove:function(t,e){var n=this._axisPointer;n&&n.remove(e),Ug.superApply(this,"remove",arguments)},dispose:function(t,e){Ll(this,e),Ug.superApply(this,"dispose",arguments)}}),Yg=[];Ug.registerAxisPointerClass=function(t,e){Yg[t]=e},Ug.getAxisPointerClass=function(t){return t&&Yg[t]};var Zg=Wg.ifIgnoreOnTick,jg=Wg.getInterval,$g=["axisLine","axisTickLabel","axisName"],Kg=["splitArea","splitLine"],Qg=Ug.extend({type:"cartesianAxis",axisPointerClass:"CartesianAxisPointer",render:function(t,e,n,i){this.group.removeAll();var r=this._axisGroup;if(this._axisGroup=new Wh,this.group.add(this._axisGroup),t.get("show")){var a=t.getCoordSysModel(),o=Pl(a,t),s=new Wg(t,o);f($g,s.add,s),this._axisGroup.add(s.getGroup()),f(Kg,function(e){t.get(e+".show")&&this["_"+e](t,a,o.labelInterval)},this),Zi(r,this._axisGroup,t),Qg.superCall(this,"render",t,e,n,i)}},_splitLine:function(t,e,n){var i=t.axis;if(!i.scale.isBlank()){var r=t.getModel("splitLine"),a=r.getModel("lineStyle"),s=a.get("color"),l=jg(r,n);s=y(s)?s:[s];for(var h=e.coordinateSystem.getRect(),u=i.isHorizontal(),c=0,f=i.getTicksCoords(),d=i.scale.getTicks(),p=t.get("axisLabel.showMinLabel"),g=t.get("axisLabel.showMaxLabel"),m=[],v=[],_=a.getLineStyle(),x=0;x<f.length;x++)if(!Zg(i,x,l,f.length,p,g)){var w=i.toGlobalCoord(f[x]);u?(m[0]=w,m[1]=h.y,v[0]=w,v[1]=h.y+h.height):(m[0]=h.x,m[1]=w,v[0]=h.x+h.width,v[1]=w);var b=c++%s.length;this._axisGroup.add(new ef(xi({anid:"line_"+d[x],shape:{x1:m[0],y1:m[1],x2:v[0],y2:v[1]},style:o({stroke:s[b]},_),silent:!0})))}}},_splitArea:function(t,e,n){var i=t.axis;if(!i.scale.isBlank()){var r=t.getModel("splitArea"),a=r.getModel("areaStyle"),s=a.get("color"),l=e.coordinateSystem.getRect(),h=i.getTicksCoords(),u=i.scale.getTicks(),c=i.toGlobalCoord(h[0]),f=i.toGlobalCoord(h[0]),d=0,p=jg(r,n),g=a.getAreaStyle();s=y(s)?s:[s];for(var m=t.get("axisLabel.showMinLabel"),v=t.get("axisLabel.showMaxLabel"),_=1;_<h.length;_++)if(!(Zg(i,_,p,h.length,m,v)&&_<h.length-1)){var x,w,b,S,M=i.toGlobalCoord(h[_]);i.isHorizontal()?(x=c,w=l.y,b=M-x,S=l.height):(x=l.x,w=f,b=l.width,S=M-w);var I=d++%s.length;this._axisGroup.add(new tf({anid:"area_"+u[_],shape:{x:x,y:w,width:b,height:S},style:o({fill:s[I]},g),silent:!0})),c=x+b,f=w+S}}}});Qg.extend({type:"xAxis"}),Qg.extend({type:"yAxis"}),Oo({type:"grid",render:function(t,e){this.group.removeAll(),t.get("show")&&this.group.add(new tf({shape:t.coordinateSystem.getRect(),style:o({fill:t.get("backgroundColor")},t.getItemStyle()),silent:!0,z2:-1}))}}),Io(function(t){t.xAxis&&t.yAxis&&!t.grid&&(t.grid={})}),ko(function(t,e,n){return{seriesType:t,performRawSeries:!0,reset:function(t,i,r){var a=t.getData(),o=t.get("symbol")||e,s=t.get("symbolSize");if(a.setVisual({legendSymbol:n||o,symbol:o,symbolSize:s}),!i.isSeriesFiltered(t)){var l="function"==typeof s;return{dataEach:a.hasItemOption||l?function(e,n){if("function"==typeof s){var i=t.getRawValue(n),r=t.getDataParams(n);e.setItemVisual(n,"symbolSize",s(i,r))}if(e.hasItemOption){var a=e.getItemModel(n),o=a.getShallow("symbol",!0),l=a.getShallow("symbolSize",!0);null!=o&&e.setItemVisual(n,"symbol",o),null!=l&&e.setItemVisual(n,"symbolSize",l)}}:null}}}}}("line","circle","line")),Do(function(t){return{seriesType:t,plan:bd(),reset:function(t){var e=t.getData(),n=t.coordinateSystem,i=t.pipelineContext.large;if(n){var r=d(n.dimensions,function(t){return e.mapDimension(t)}).slice(0,2),a=r.length;return is(e,r[0],r[1])&&(r[0]=e.getCalculationInfo("stackResultDimension")),is(e,r[1],r[0])&&(r[1]=e.getCalculationInfo("stackResultDimension")),a&&{progress:function(t,e){for(var o=t.end-t.start,s=i&&new Float32Array(o*a),l=t.start,h=0,u=[],c=[];l<t.end;l++){var f;if(1===a)d=e.get(r[0],l,!0),f=!isNaN(d)&&n.dataToPoint(d,null,c);else{var d=u[0]=e.get(r[0],l,!0),p=u[1]=e.get(r[1],l,!0);f=!isNaN(d)&&!isNaN(p)&&n.dataToPoint(u,null,c)}i?(s[h++]=f?f[0]:NaN,s[h++]=f?f[1]:NaN):e.setItemLayout(l,f&&f.slice()||[NaN,NaN])}i&&e.setLayout("symbolPoints",s)}}}}}}("line")),To(jd.PROCESSOR.STATISTIC,function(t){return{seriesType:t,reset:function(t,e,n){var i=t.getData(),r=t.get("sampling"),a=t.coordinateSystem;if("cartesian2d"===a.type&&r){var o=a.getBaseAxis(),s=a.getOtherAxis(o),l=o.getExtent(),h=l[1]-l[0],u=Math.round(i.count()/h);if(u>1){var c;"string"==typeof r?c=Jp[r]:"function"==typeof r&&(c=r),c&&t.setData(i.downSample(s.dim,1/u,c,tg))}}}}}("line")),_d.extend({type:"series.__base_bar__",getInitialData:function(t,e){return rs(this.getSource(),this)},getMarkerPosition:function(t){var e=this.coordinateSystem;if(e){var n=e.dataToPoint(e.clampData(t)),i=this.getData(),r=i.getLayout("offset"),a=i.getLayout("size");return n[e.getBaseAxis().isHorizontal()?0:1]+=r+a/2,n}return[NaN,NaN]},defaultOption:{zlevel:0,z:2,coordinateSystem:"cartesian2d",legendHoverLink:!0,barMinHeight:0,barMinAngle:0,itemStyle:{},emphasis:{}}}).extend({type:"series.bar",dependencies:["grid","polar"],brushSelector:"rect"});var Jg=zu([["fill","color"],["stroke","borderColor"],["lineWidth","borderWidth"],["stroke","barBorderColor"],["lineWidth","barBorderWidth"],["opacity"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["shadowColor"]]),tm={getBarItemStyle:function(t){var e=Jg(this,t);if(this.getBorderLineDash){var n=this.getBorderLineDash();n&&(e.lineDash=n)}return e}},em=["itemStyle","barBorderWidth"];a(ji.prototype,tm),Bo({type:"bar",render:function(t,e,n){var i=t.get("coordinateSystem");return"cartesian2d"!==i&&"polar"!==i||this._render(t,e,n),this.group},dispose:R,_render:function(t,e,n){var i,r=this.group,a=t.getData(),o=this._data,s=t.coordinateSystem,l=s.getBaseAxis();"cartesian2d"===s.type?i=l.isHorizontal():"polar"===s.type&&(i="angle"===l.dim);var h=t.isAnimationEnabled()?t:null;a.diff(o).add(function(e){if(a.hasValue(e)){var n=a.getItemModel(e),o=im[s.type](a,e,n),l=nm[s.type](a,e,n,o,i,h);a.setItemGraphicEl(e,l),r.add(l),Rl(l,a,e,n,o,t,i,"polar"===s.type)}}).update(function(e,n){var l=o.getItemGraphicEl(n);if(a.hasValue(e)){var u=a.getItemModel(e),c=im[s.type](a,e,u);l?Xi(l,{shape:c},h,e):l=nm[s.type](a,e,u,c,i,h,!0),a.setItemGraphicEl(e,l),r.add(l),Rl(l,a,e,u,c,t,i,"polar"===s.type)}else r.remove(l)}).remove(function(t){var e=o.getItemGraphicEl(t);"cartesian2d"===s.type?e&&Bl(t,h,e):e&&Nl(t,h,e)}).execute(),this._data=a},remove:function(t,e){var n=this.group,i=this._data;t.get("animation")?i&&i.eachItemGraphicEl(function(e){"sector"===e.type?Nl(e.dataIndex,t,e):Bl(e.dataIndex,t,e)}):n.removeAll()}});var nm={cartesian2d:function(t,e,n,i,r,o,s){var l=new tf({shape:a({},i)});if(o){var h=l.shape,u=r?"height":"width",c={};h[u]=0,c[u]=i[u],gf[s?"updateProps":"initProps"](l,{shape:c},o,e)}return l},polar:function(t,e,n,i,r,a,s){var l=i.startAngle<i.endAngle,h=new Zc({shape:o({clockwise:l},i)});if(a){var u=h.shape,c=r?"r":"endAngle",f={};u[c]=r?0:i.startAngle,f[c]=i[c],gf[s?"updateProps":"initProps"](h,{shape:f},a,e)}return h}},im={cartesian2d:function(t,e,n){var i=t.getItemLayout(e),r=zl(n,i),a=i.width>0?1:-1,o=i.height>0?1:-1;return{x:i.x+a*r/2,y:i.y+o*r/2,width:i.width-a*r,height:i.height-o*r}},polar:function(t,e,n){var i=t.getItemLayout(e);return{cx:i.cx,cy:i.cy,r0:i.r0,r:i.r,startAngle:i.startAngle,endAngle:i.endAngle}}};Do(v(function(t,e,n){var i=[];e.eachSeriesByType(t,function(t){t.coordinateSystem&&"cartesian2d"===t.coordinateSystem.type&&i.push(t)});var r=Zs(i),a={};f(i,function(t){var e=t.getData(),n=t.coordinateSystem,i=n.getBaseAxis(),o=Us(t),s=r[Ys(i)][o],l=s.offset,h=s.width,u=n.getOtherAxis(i),c=t.get("barMinHeight")||0;a[o]=a[o]||[],e.setLayout({offset:l,size:h});for(var f=e.mapDimension(u.dim),d=e.mapDimension(i.dim),p=is(e,f,d),g=u.isHorizontal(),m=i.onZero||p?u.toGlobalCoord(u.dataToCoord(0)):u.getGlobalExtent()[0],v=0,y=e.count();v<y;v++){var _=e.get(f,v),x=e.get(d,v);if(!isNaN(_)){var w=_>=0?"p":"n",b=m;p&&(a[o][x]||(a[o][x]={p:m,n:m}),b=a[o][x][w]);var S,M,I,T;if(g)S=b,M=(C=n.dataToPoint([_,x]))[1]+l,I=C[0]-m,T=h,Math.abs(I)<c&&(I=(I<0?-1:1)*c),p&&(a[o][x][w]+=I);else{var C=n.dataToPoint([x,_]);S=C[0]+l,M=b,I=h,T=C[1]-m,Math.abs(T)<c&&(T=(T<=0?-1:1)*c),p&&(a[o][x][w]+=T)}e.setItemLayout(v,{x:S,y:M,width:I,height:T})}}},this)},"bar")),ko(function(t){t.eachSeriesByType("bar",function(t){t.getData().setVisual("legendSymbol","roundRect")})});var rm=function(t,e,n){e=y(e)&&{coordDimensions:e}||a({},e);var i=t.getSource(),r=kp(i,e),o=new Tp(r,t);return o.initData(i,n),o},am={updateSelectedMap:function(t){this._targetList=y(t)?t.slice():[],this._selectTargetMap=p(t||[],function(t,e){return t.set(e.name,e),t},N())},select:function(t,e){var n=null!=e?this._targetList[e]:this._selectTargetMap.get(t);"single"===this.get("selectedMode")&&this._selectTargetMap.each(function(t){t.selected=!1}),n&&(n.selected=!0)},unSelect:function(t,e){var n=null!=e?this._targetList[e]:this._selectTargetMap.get(t);n&&(n.selected=!1)},toggleSelected:function(t,e){var n=null!=e?this._targetList[e]:this._selectTargetMap.get(t);if(null!=n)return this[n.selected?"unSelect":"select"](t,e),n.selected},isSelected:function(t,e){var n=null!=e?this._targetList[e]:this._selectTargetMap.get(t);return n&&n.selected}},om=Eo({type:"series.pie",init:function(t){om.superApply(this,"init",arguments),this.legendDataProvider=function(){return this.getRawData()},this.updateSelectedMap(this._createSelectableList()),this._defaultLabelLine(t)},mergeOption:function(t){om.superCall(this,"mergeOption",t),this.updateSelectedMap(this._createSelectableList())},getInitialData:function(t,e){return rm(this,["value"])},_createSelectableList:function(){for(var t=this.getRawData(),e=t.mapDimension("value"),n=[],i=0,r=t.count();i<r;i++)n.push({name:t.getName(i),value:t.get(e,i),selected:xa(t,i,"selected")});return n},getDataParams:function(t){var e=this.getData(),n=om.superCall(this,"getDataParams",t),i=[];return e.each(e.mapDimension("value"),function(t){i.push(t)}),n.percent=ar(i,t,e.hostModel.get("percentPrecision")),n.$vars.push("percent"),n},_defaultLabelLine:function(t){sn(t,"labelLine",["show"]);var e=t.labelLine,n=t.emphasis.labelLine;e.show=e.show&&t.label.show,n.show=n.show&&t.emphasis.label.show},defaultOption:{zlevel:0,z:2,legendHoverLink:!0,hoverAnimation:!0,center:["50%","50%"],radius:[0,"75%"],clockwise:!0,startAngle:90,minAngle:0,selectedOffset:10,hoverOffset:10,avoidLabelOverlap:!0,percentPrecision:2,stillShowZeroSum:!0,label:{rotate:!1,show:!0,position:"outer"},labelLine:{show:!0,length:15,length2:15,smooth:!1,lineStyle:{width:1,type:"solid"}},itemStyle:{borderWidth:1},animationType:"expansion",animationEasing:"cubicOut"}});u(om,am);var sm=Wl.prototype;sm.updateData=function(t,e,n){function i(){s.stopAnimation(!0),s.animateTo({shape:{r:u.r+l.get("hoverOffset")}},300,"elasticOut")}function r(){s.stopAnimation(!0),s.animateTo({shape:{r:u.r}},300,"elasticOut")}var s=this.childAt(0),l=t.hostModel,h=t.getItemModel(e),u=t.getItemLayout(e),c=a({},u);c.label=null,n?(s.setShape(c),"scale"===l.getShallow("animationType")?(s.shape.r=u.r0,Ui(s,{shape:{r:u.r}},l,e)):(s.shape.endAngle=u.startAngle,Xi(s,{shape:{endAngle:u.endAngle}},l,e))):Xi(s,{shape:c},l,e);var f=t.getItemVisual(e,"color");s.useStyle(o({lineJoin:"bevel",fill:f},h.getModel("itemStyle").getItemStyle())),s.hoverStyle=h.getModel("emphasis.itemStyle").getItemStyle();var d=h.getShallow("cursor");d&&s.attr("cursor",d),Vl(this,t.getItemLayout(e),l.isSelected(null,e),l.get("selectedOffset"),l.get("animation")),s.off("mouseover").off("mouseout").off("emphasis").off("normal"),h.get("hoverAnimation")&&l.isAnimationEnabled()&&s.on("mouseover",i).on("mouseout",r).on("emphasis",i).on("normal",r),this._updateLabel(t,e),Ei(this)},sm._updateLabel=function(t,e){var n=this.childAt(1),i=this.childAt(2),r=t.hostModel,a=t.getItemModel(e),o=t.getItemLayout(e).label,s=t.getItemVisual(e,"color");Xi(n,{shape:{points:o.linePoints||[[o.x,o.y],[o.x,o.y],[o.x,o.y]]}},r,e),Xi(i,{style:{x:o.x,y:o.y}},r,e),i.attr({rotation:o.rotation,origin:[o.x,o.y],z2:10});var l=a.getModel("label"),h=a.getModel("emphasis.label"),u=a.getModel("labelLine"),c=a.getModel("emphasis.labelLine"),s=t.getItemVisual(e,"color");Bi(i.style,i.hoverStyle={},l,h,{labelFetcher:t.hostModel,labelDataIndex:e,defaultText:t.getName(e),autoColor:s,useInsideStyle:!!o.inside},{textAlign:o.textAlign,textVerticalAlign:o.verticalAlign,opacity:t.getItemVisual(e,"opacity")}),i.ignore=i.normalIgnore=!l.get("show"),i.hoverIgnore=!h.get("show"),n.ignore=n.normalIgnore=!u.get("show"),n.hoverIgnore=!c.get("show"),n.setStyle({stroke:s,opacity:t.getItemVisual(e,"opacity")}),n.setStyle(u.getModel("lineStyle").getLineStyle()),n.hoverStyle=c.getModel("lineStyle").getLineStyle();var f=u.get("smooth");f&&!0===f&&(f=.4),n.setShape({smooth:f})},h(Wl,Wh);Pa.extend({type:"pie",init:function(){var t=new Wh;this._sectorGroup=t},render:function(t,e,n,i){if(!i||i.from!==this.uid){var r=t.getData(),a=this._data,o=this.group,s=e.get("animation"),l=!a,h=t.get("animationType"),u=v(Fl,this.uid,t,s,n),c=t.get("selectedMode");if(r.diff(a).add(function(t){var e=new Wl(r,t);l&&"scale"!==h&&e.eachChild(function(t){t.stopAnimation(!0)}),c&&e.on("click",u),r.setItemGraphicEl(t,e),o.add(e)}).update(function(t,e){var n=a.getItemGraphicEl(e);n.updateData(r,t),n.off("click"),c&&n.on("click",u),o.add(n),r.setItemGraphicEl(t,n)}).remove(function(t){var e=a.getItemGraphicEl(t);o.remove(e)}).execute(),s&&l&&r.count()>0&&"scale"!==h){var f=r.getItemLayout(0),d=Math.max(n.getWidth(),n.getHeight())/2,p=m(o.removeClipPath,o);o.setClipPath(this._createClipPath(f.cx,f.cy,d,f.startAngle,f.clockwise,p,t))}this._data=r}},dispose:function(){},_createClipPath:function(t,e,n,i,r,a,o){var s=new Zc({shape:{cx:t,cy:e,r0:0,r:n,startAngle:i,endAngle:i,clockwise:r}});return Ui(s,{shape:{endAngle:i+(r?1:-1)*Math.PI*2}},o,a),s},containPoint:function(t,e){var n=e.getData().getItemLayout(0);if(n){var i=t[0]-n.cx,r=t[1]-n.cy,a=Math.sqrt(i*i+r*r);return a<=n.r&&a>=n.r0}}});var lm=function(t,e,n,i){var r,a,o=t.getData(),s=[],l=!1;o.each(function(n){var i,h,u,c,f=o.getItemLayout(n),d=o.getItemModel(n),p=d.getModel("label"),g=p.get("position")||d.get("emphasis.label.position"),m=d.getModel("labelLine"),v=m.get("length"),y=m.get("length2"),_=(f.startAngle+f.endAngle)/2,x=Math.cos(_),w=Math.sin(_);r=f.cx,a=f.cy;var b="inside"===g||"inner"===g;if("center"===g)i=f.cx,h=f.cy,c="center";else{var S=(b?(f.r+f.r0)/2*x:f.r*x)+r,M=(b?(f.r+f.r0)/2*w:f.r*w)+a;if(i=S+3*x,h=M+3*w,!b){var I=S+x*(v+e-f.r),T=M+w*(v+e-f.r),C=I+(x<0?-1:1)*y,D=T;i=C+(x<0?-5:5),h=D,u=[[S,M],[I,T],[C,D]]}c=b?"center":x>0?"left":"right"}var k=p.getFont(),A=p.get("rotate")?x<0?-_+Math.PI:-_:0,L=ee(t.getFormattedLabel(n,"normal")||o.getName(n),k,c,"top");l=!!A,f.label={x:i,y:h,position:g,height:L.height,len:v,len2:y,linePoints:u,textAlign:c,verticalAlign:"middle",rotation:A,inside:b},b||s.push(f.label)}),!l&&t.get("avoidLabelOverlap")&&Gl(s,r,a,e,n,i)},hm=2*Math.PI,um=Math.PI/180;!function(t,e){f(e,function(e){e.update="updateView",Co(e,function(n,i){var r={};return i.eachComponent({mainType:"series",subType:t,query:n},function(t){t[e.method]&&t[e.method](n.name,n.dataIndex);var i=t.getData();i.each(function(e){var n=i.getName(e);r[n]=t.isSelected(n)||!1})}),{name:n.name,selected:r}})})}("pie",[{type:"pieToggleSelect",event:"pieselectchanged",method:"toggleSelected"},{type:"pieSelect",event:"pieselected",method:"select"},{type:"pieUnSelect",event:"pieunselected",method:"unSelect"}]),ko(function(t){return{getTargetSeries:function(e){var n={},i=N();return e.eachSeriesByType(t,function(t){t.__paletteScope=n,i.set(t.uid,t)}),i},reset:function(t,e){var n=t.getRawData(),i={},r=t.getData();r.each(function(t){var e=r.getRawIndex(t);i[e]=t}),n.each(function(e){var a=i[e],o=null!=a&&r.getItemVisual(a,"color",!0);if(o)n.setItemVisual(e,"color",o);else{var s=n.getItemModel(e).get("itemStyle.color")||t.getColorFromPalette(n.getName(e)||e+"",t.__paletteScope,n.count());n.setItemVisual(e,"color",s),null!=a&&r.setItemVisual(a,"color",s)}})}}}("pie")),Do(v(function(t,e,n,i){e.eachSeriesByType(t,function(t){var e=t.getData(),i=e.mapDimension("value"),r=t.get("center"),a=t.get("radius");y(a)||(a=[0,a]),y(r)||(r=[r,r]);var o=n.getWidth(),s=n.getHeight(),l=Math.min(o,s),h=er(r[0],o),u=er(r[1],s),c=er(a[0],l/2),f=er(a[1],l/2),d=-t.get("startAngle")*um,p=t.get("minAngle")*um,g=0;e.each(i,function(t){!isNaN(t)&&g++});var m=e.getSum(i),v=Math.PI/(m||g)*2,_=t.get("clockwise"),x=t.get("roseType"),w=t.get("stillShowZeroSum"),b=e.getDataExtent(i);b[0]=0;var S=hm,M=0,I=d,T=_?1:-1;if(e.each(i,function(t,n){var i;if(isNaN(t))e.setItemLayout(n,{angle:NaN,startAngle:NaN,endAngle:NaN,clockwise:_,cx:h,cy:u,r0:c,r:x?NaN:f});else{(i="area"!==x?0===m&&w?v:t*v:hm/g)<p?(i=p,S-=p):M+=t;var r=I+T*i;e.setItemLayout(n,{angle:i,startAngle:I,endAngle:r,clockwise:_,cx:h,cy:u,r0:c,r:x?tr(t,b,[c,f]):f}),I=r}}),S<hm&&g)if(S<=.001){var C=hm/g;e.each(i,function(t,n){if(!isNaN(t)){var i=e.getItemLayout(n);i.angle=C,i.startAngle=d+T*n*C,i.endAngle=d+T*(n+1)*C}})}else v=S/M,I=d,e.each(i,function(t,n){if(!isNaN(t)){var i=e.getItemLayout(n),r=i.angle===p?p:t*v;i.startAngle=I,i.endAngle=I+T*r,I+=T*r}});lm(t,f,o,s)})},"pie")),To(function(t){return{seriesType:t,reset:function(t,e){var n=e.findComponents({mainType:"legend"});if(n&&n.length){var i=t.getData();i.filterSelf(function(t){for(var e=i.getName(t),r=0;r<n.length;r++)if(!n[r].isSelected(e))return!1;return!0})}}}}("pie")),t.version="4.0.4",t.dependencies=Xd,t.PRIORITY=jd,t.init=function(t,e,n){var i=So(t);if(i)return i;var r=new eo(t,e,n);return r.id="ec_"+fp++,up[r.id]=r,yn(t,pp,r.id),wo(r),r},t.connect=function(t){if(y(t)){var e=t;t=null,Wd(e,function(e){null!=e.group&&(t=e.group)}),t=t||"g_"+dp++,Wd(e,function(e){e.group=t})}return cp[t]=!0,t},t.disConnect=bo,t.disconnect=mp,t.dispose=function(t){"string"==typeof t?t=up[t]:t instanceof eo||(t=So(t)),t instanceof eo&&!t.isDisposed()&&t.dispose()},t.getInstanceByDom=So,t.getInstanceById=function(t){return up[t]},t.registerTheme=Mo,t.registerPreprocessor=Io,t.registerProcessor=To,t.registerPostUpdate=function(t){op.push(t)},t.registerAction=Co,t.registerCoordinateSystem=function(t,e){Yr.register(t,e)},t.getCoordinateSystemDimensions=function(t){var e=Yr.get(t);if(e)return e.getDimensionsInfo?e.getDimensionsInfo():e.dimensions.slice()},t.registerLayout=Do,t.registerVisual=ko,t.registerLoading=Lo,t.extendComponentModel=Po,t.extendComponentView=Oo,t.extendSeriesModel=Eo,t.extendChartView=Bo,t.setCanvasCreator=function(t){e("createCanvas",t)},t.registerMap=function(t,e,n){e.geoJson&&!e.features&&(n=e.specialAreas,e=e.geoJson),"string"==typeof e&&(e="undefined"!=typeof JSON&&JSON.parse?JSON.parse(e):new Function("return ("+e+");")()),gp[t]={geoJson:e,specialAreas:n}},t.getMap=function(t){return gp[t]},t.dataTool=vp});
|
load("test-common.js");
try {
assert(Number.isFinite.length === 1);
assert(Number.isFinite(0) === true);
assert(Number.isFinite(1.23) === true);
assert(Number.isFinite(42) === true);
assert(Number.isFinite("") === false);
assert(Number.isFinite("0") === false);
assert(Number.isFinite("42") === false);
assert(Number.isFinite(true) === false);
assert(Number.isFinite(false) === false);
assert(Number.isFinite(null) === false);
assert(Number.isFinite([]) === false);
assert(Number.isFinite() === false);
assert(Number.isFinite(NaN) === false);
assert(Number.isFinite(undefined) === false);
assert(Number.isFinite(Infinity) === false);
assert(Number.isFinite(-Infinity) === false);
assert(Number.isFinite("foo") === false);
assert(Number.isFinite({}) === false);
assert(Number.isFinite([1, 2, 3]) === false);
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e.message);
}
|
module.exports = {
queryPlusSingleParam: 'http://api.travelpayouts.com/v2/prices/latest?currency=rub&show_to_affiliates=true&origin=MOW',
noQueryPlusSingleParam: 'http://api.travelpayouts.com/v2/prices/latest?origin=MOW',
queryPlusMultipleParams: 'http://api.travelpayouts.com/v2/prices/month-matrix?currency=rub&show_to_affiliates=true&month=2017-10-01&origin=MOW&destination=LED',
noQueryPlusMultipleParams: 'http://api.travelpayouts.com/v2/prices/month-matrix?origin=MOW&destination=LED',
pathSingleParam: 'http://api.github.com/users/alcovegan/followers',
pathMultipleParams: [
'http://api.github.com/repos/alcovegan/travelpayouts-js/issues',
'http://api.github.com/repos/alcovegan/travelpayouts-js/milestones/5',
'http://fakeapi.com/param1/veryparam1/param2/veryparam2/param3/veryparam3/param4/veryparam4/param5/veryparam5/param6/veryparam6/param7/veryparam7'
],
pathMultipleParamsPlusQuery: [
'http://api.github.com/repos/alcovegan/travelpayouts-js/issues?page=1',
'http://api.github.com/repos/alcovegan/travelpayouts-js/milestones/5?page=1&finished=true'
],
pathParamsAndAssets: [
'http://api.github.com/someprefix/repos/alcovegan/travelpayouts-js/issues/chp/changingChp/else/working?currency=rub&show_to_affiliates=true&page=1&origin=MOW&destination=LED'
],
oneChangingParamAsString: 'http://api.github.com/someprefix/repos/alcovegan?currency=rub&show_to_affiliates=true&page=1',
oneChangingAssetAsString: 'http://api.github.com/someprefix/repos/alcovegan?currency=rub&show_to_affiliates=true&page=1&origin=MOW',
twoChangingAssetsWithOneString: 'http://api.github.com/someprefix/repos/alcovegan?currency=rub&show_to_affiliates=true&page=1&origin=MOW&destination=MOW',
twoChangingParamsWithOneString: 'http://api.travelpayouts.com/someprefix/origin/MOW/destination/MOW?currency=rub&show_to_affiliates=true&page=1'
}
|
const NATIVE_MSG_HOST_FQDN = "com.aldaviva.tagscanner.discogs";
chrome.runtime.onMessage.addListener((messageFromPage, sender, sendResponseToPage) => {
if(messageFromPage.action === "sendReleaseToTagScanner"){
const releaseId = messageFromPage.releaseId;
const messageToNative = {
service: "discogs",
releaseId: releaseId
};
console.info(`Sending Discogs release ${releaseId} to TagScanner`, messageToNative);
chrome.runtime.sendNativeMessage(NATIVE_MSG_HOST_FQDN, messageToNative, response => {
console.info("Received response from native messaging host", response);
const pageResponse = { error: response.error };
console.debug("Sending response to page:", pageResponse);
sendResponseToPage(pageResponse);
});
return true; //allow sendResponseToPage to be called asynchronously instead of synchronously closing the pipe
}
});
|
/**
* @file Column.h
* @ingroup SQLiteCpp
* @brief Encapsulation of a Column in a row of the result pointed by the prepared SQLite::Statement.
*
* Copyright (c) 2012-2020 Sebastien Rombauts (sebastien.rombauts@gmail.com)
* Copyright (c) 2019-2021 Vladimir Novick ( https://www.linkedin.com/in/vladimirnovick/ )
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#pragma once
#include <WinSQLiteLib/Statement.h>
#include <WinSQLiteLib/Exception.h>
#include <string>
#include <climits> // For INT_MAX
namespace SQLite
{
extern const int INTEGER; ///< SQLITE_INTEGER
extern const int FLOAT; ///< SQLITE_FLOAT
extern const int TEXT; ///< SQLITE_TEXT
extern const int BLOB; ///< SQLITE_BLOB
extern const int Null; ///< SQLITE_NULL
/**
* @brief Encapsulation of a Column in a row of the result pointed by the prepared Statement.
*
* A Column is a particular field of SQLite data in the current row of result
* of the Statement : it points to a single cell.
*
* Its value can be expressed as a text, and, when applicable, as a numeric
* (integer or floating point) or a binary blob.
*
* Thread-safety: a Column object shall not be shared by multiple threads, because :
* 1) in the SQLite "Thread Safe" mode, "SQLite can be safely used by multiple threads
* provided that no single database connection is used simultaneously in two or more threads."
* 2) the SQLite "Serialized" mode is not supported by SQLiteC++,
* because of the way it shares the underling SQLite precompiled statement
* in a custom shared pointer (See the inner class "Statement::Ptr").
*/
class Column
{
public:
/**
* @brief Encapsulation of a Column in a Row of the result.
*
* @param[in] aStmtPtr Shared pointer to the prepared SQLite Statement Object.
* @param[in] aIndex Index of the column in the row of result, starting at 0
*/
Column(Statement::Ptr& aStmtPtr, int aIndex) noexcept;
// default destructor: the finalization will be done by the destructor of the last shared pointer
// default copy constructor and assignment operator are perfectly suited :
// they copy the Statement::Ptr which in turn increments the reference counter.
/**
* @brief Return a pointer to the named assigned to this result column (potentially aliased)
*
* @see getOriginName() to get original column name (not aliased)
*/
const char* getName() const noexcept;
#ifdef SQLITE_ENABLE_COLUMN_METADATA
/**
* @brief Return a pointer to the table column name that is the origin of this result column
*
* Require definition of the SQLITE_ENABLE_COLUMN_METADATA preprocessor macro :
* - when building the SQLite library itself (which is the case for the Debian libsqlite3 binary for instance),
* - and also when compiling this wrapper.
*/
const char* getOriginName() const noexcept;
#endif
/// Return the integer value of the column.
int getInt() const noexcept;
/// Return the 32bits unsigned integer value of the column (note that SQLite3 does not support unsigned 64bits).
unsigned getUInt() const noexcept;
/// Return the 64bits integer value of the column (note that SQLite3 does not support unsigned 64bits).
long long getInt64() const noexcept;
/// Return the double (64bits float) value of the column
double getDouble() const noexcept;
/**
* @brief Return a pointer to the text value (NULL terminated string) of the column.
*
* @warning The value pointed at is only valid while the statement is valid (ie. not finalized),
* thus you must copy it before using it beyond its scope (to a std::string for instance).
*/
const char* getText(const char* apDefaultValue = "") const noexcept;
/**
* @brief Return a pointer to the binary blob value of the column.
*
* @warning The value pointed at is only valid while the statement is valid (ie. not finalized),
* thus you must copy it before using it beyond its scope (to a std::string for instance).
*/
const void* getBlob() const noexcept;
/**
* @brief Return a std::string for a TEXT or BLOB column.
*
* Note this correctly handles strings that contain null bytes.
*/
std::string getString() const;
/**
* @brief Return the type of the value of the column
*
* Return either SQLite::INTEGER, SQLite::FLOAT, SQLite::TEXT, SQLite::BLOB, or SQLite::Null.
*
* @warning After a type conversion (by a call to a getXxx on a Column of a Yyy type),
* the value returned by sqlite3_column_type() is undefined.
*/
int getType() const noexcept;
/// Test if the column is an integer type value (meaningful only before any conversion)
bool isInteger() const noexcept
{
return (SQLite::INTEGER == getType());
}
/// Test if the column is a floating point type value (meaningful only before any conversion)
bool isFloat() const noexcept
{
return (SQLite::FLOAT == getType());
}
/// Test if the column is a text type value (meaningful only before any conversion)
bool isText() const noexcept
{
return (SQLite::TEXT == getType());
}
/// Test if the column is a binary blob type value (meaningful only before any conversion)
bool isBlob() const noexcept
{
return (SQLite::BLOB == getType());
}
/// Test if the column is NULL (meaningful only before any conversion)
bool isNull() const noexcept
{
return (SQLite::Null == getType());
}
/**
* @brief Return the number of bytes used by the text (or blob) value of the column
*
* Return either :
* - size in bytes (not in characters) of the string returned by getText() without the '\0' terminator
* - size in bytes of the string representation of the numerical value (integer or double)
* - size in bytes of the binary blob returned by getBlob()
* - 0 for a NULL value
*/
int getBytes() const noexcept;
/// Alias returning the number of bytes used by the text (or blob) value of the column
int size() const noexcept
{
return getBytes ();
}
/// Inline cast operator to char
operator char() const
{
return static_cast<char>(getInt());
}
/// Inline cast operator to unsigned char
operator unsigned char() const
{
return static_cast<unsigned char>(getInt());
}
/// Inline cast operator to short
operator short() const
{
return static_cast<short>(getInt());
}
/// Inline cast operator to unsigned short
operator unsigned short() const
{
return static_cast<unsigned short>(getInt());
}
/// Inline cast operator to int
operator int() const
{
return getInt();
}
/// Inline cast operator to 32bits unsigned integer
operator unsigned int() const
{
return getUInt();
}
#if (LONG_MAX == INT_MAX) // 4 bytes "long" type means the data model is ILP32 or LLP64 (Win64 Visual C++ and MinGW)
/// Inline cast operator to 32bits long
operator long() const
{
return getInt();
}
/// Inline cast operator to 32bits unsigned long
operator unsigned long() const
{
return getUInt();
}
#else // 8 bytes "long" type means the data model is LP64 (Most Unix-like, Windows when using Cygwin; z/OS)
/// Inline cast operator to 64bits long when the data model of the system is LP64 (Linux 64 bits...)
operator long() const
{
return getInt64();
}
#endif
/// Inline cast operator to 64bits integer
operator long long() const
{
return getInt64();
}
/// Inline cast operator to double
operator double() const
{
return getDouble();
}
/**
* @brief Inline cast operator to char*
*
* @see getText
*/
operator const char*() const
{
return getText();
}
/**
* @brief Inline cast operator to void*
*
* @see getBlob
*/
operator const void*() const
{
return getBlob();
}
/**
* @brief Inline cast operator to std::string
*
* Handles BLOB or TEXT, which may contain null bytes within
*
* @see getString
*/
operator std::string() const
{
return getString();
}
private:
Statement::Ptr mStmtPtr; ///< Shared Pointer to the prepared SQLite Statement Object
int mIndex; ///< Index of the column in the row of result, starting at 0
};
/**
* @brief Standard std::ostream text inserter
*
* Insert the text value of the Column object, using getText(), into the provided stream.
*
* @param[in] aStream Stream to use
* @param[in] aColumn Column object to insert into the provided stream
*
* @return Reference to the stream used
*/
std::ostream& operator<<(std::ostream& aStream, const Column& aColumn);
#if __cplusplus >= 201402L || (defined(_MSC_VER) && _MSC_VER >= 1900) // c++14: Visual Studio 2015
// Create an instance of T from the first N columns, see declaration in Statement.h for full details
template<typename T, int N>
T Statement::getColumns()
{
checkRow();
checkIndex(N - 1);
return getColumns<T>(std::make_integer_sequence<int, N>{});
}
// Helper function called by getColums<typename T, int N>
template<typename T, const int... Is>
T Statement::getColumns(const std::integer_sequence<int, Is...>)
{
return T{Column(mStmtPtr, Is)...};
}
#endif
} // namespace SQLite
|
var types_8h =
[
[ "ovs_16aligned_u32", "structovs__16aligned__u32.html", "structovs__16aligned__u32" ],
[ "ovs_16aligned_be32", "structovs__16aligned__be32.html", "structovs__16aligned__be32" ],
[ "ovs_32aligned_u64", "structovs__32aligned__u64.html", "structovs__32aligned__u64" ],
[ "ovs_32aligned_be64", "structovs__32aligned__be64.html", "structovs__32aligned__be64" ],
[ "OVS_BITWISE", "types_8h.html#a28f92742b7dfcf5f1a1110bc6209ae94", null ],
[ "OVS_FORCE", "types_8h.html#a60b13dba69d229c63e64eba431fbcf19", null ],
[ "OFP_PORT_C", "types_8h.html#a93f35e1f8993d988f58b81ba5e7f96ec", null ],
[ "ODP_PORT_C", "types_8h.html#a79586dc579646bbafc2e5206f9536218", null ],
[ "OFP11_PORT_C", "types_8h.html#a52857be1e1c85b593f4d4057b15b2672", null ],
[ "ovs_be16", "types_8h.html#ad44edc91c129a56ffccf6e3b13b7a6e8", null ],
[ "ovs_be32", "types_8h.html#a319297c2a7ffb2b0a82c346886b638b1", null ],
[ "ovs_be64", "types_8h.html#a7d8c8482c012f1336223fa56a29f5359", null ],
[ "ofp_port_t", "types_8h.html#aff832934c497b6039908104989c8c9f2", null ],
[ "odp_port_t", "types_8h.html#a8ec89192f43ad3253862b05639ae356f", null ],
[ "ofp11_port_t", "types_8h.html#a1656afc781ed85c8b3bb218c4865eacb", null ]
];
|
#!/usr/bin/env python2.7
# -*- encoding: utf8 -*-
import requests
import re
import os
import argparse
import sys
from threading import Thread, Event, Lock
from Queue import Queue
from bs4 import BeautifulSoup
class Multiscanner:
ENGINE_BING = 'bing'
ENGINE_ASK = 'ask'
ENGINE_RAMBLER = 'rambler'
ENGINE_GOOGLE = 'google'
def __init__(self, dork_file, output, threads):
self.dork_file = dork_file
self.output = output
self.links = []
self.ptr_limits = {
'bing': 411,
'ask': 20,
'rambler': 20,
'google': 20
}
self.exclude_itens = 'msn|microsoft|php-brasil|facebook|' \
'4shared|bing|imasters|phpbrasil|php.net|yahoo|' \
'scrwordtbrasil|under-linux|google|msdn|ask|' \
'bing|rambler|youtube'
self.engines = {
Multiscanner.ENGINE_BING: {
'progress_string': '[***Bing***] Quering page {}/{} with dork {}\n',
'search_string': 'http://www.bing.com/search?q={}&count=50&first={}',
'page_range': xrange(1, self.ptr_limits['bing'], 10)
},
Multiscanner.ENGINE_ASK: {
'progress_string': '[***Ask***] Quering page {}/{} with dork {}\n',
'search_string': 'http://www.ask.com/web?q={}&page={}',
'page_range': xrange(1, self.ptr_limits['ask'])
},
Multiscanner.ENGINE_RAMBLER: {
'progress_string': '[***Rambler***] Quering page {}/{} with dork {}\n',
'search_string': 'http://nova.rambler.ru/search?query={}&page={}',
'page_range': xrange(1, self.ptr_limits['rambler'])
},
Multiscanner.ENGINE_GOOGLE: {
'progress_string': '[***GOOGLE***] Quering page {}/{} with dork {}\n',
'search_string': 'http://www.google.com/search?q={}&page={}',
'page_range': xrange(1, self.ptr_limits['google'])
},
}
self.threads = threads
self.q = Queue()
self.t_stop = Event()
self.counter = 0
self.list_size = len(open(self.dork_file).readlines())
self.lock = Lock()
self.terminal = sys.stdout
@staticmethod
def get_engines():
"""Get current engines"""
return [
Multiscanner.ENGINE_BING,
Multiscanner.ENGINE_ASK,
Multiscanner.ENGINE_RAMBLER,
Multiscanner.ENGINE_GOOGLE
]
def get_links(self, word, engine):
"""Fetch links from engnies"""
self.links = []
current_engine = self.engines[engine]
for ptr in current_engine['page_range']:
with self.lock:
self.terminal.write(current_engine['progress_string'].format(
ptr, self.ptr_limits[engine], word
))
content = requests.get(
current_engine['search_string'].format(word, str(ptr))
)
if content.ok:
try:
soup = BeautifulSoup(content.text, 'html.parser')
for link in soup.find_all('a'):
link = link.get('href')
if 'http' in link and not re.search(
self.exclude_itens, link
):
if link not in self.links:
self.links.append(link)
with self.lock:
with open(self.output, 'a+') as fd:
fd.write(link + '\n')
except Exception:
pass
def search(self, q):
"""Control flow"""
while not self.t_stop.is_set():
self.t_stop.wait(1)
try:
word = q.get()
for engine in Multiscanner.get_engines():
self.get_links(word, engine)
except Exception:
pass
finally:
self.counter += 1
q.task_done()
def main(self):
""" Prepare threads and launch main search"""
for _ in xrange(self.threads):
t = Thread(target=self.search, args=(self.q,))
t.setDaemon(True)
t.start()
for word in open(self.dork_file):
self.q.put(word.strip())
try:
while not self.t_stop.is_set():
self.t_stop.wait(1)
if self.counter == self.list_size:
self.t_stop.set()
except KeyboardInterrupt:
print '~ Sending signal to kill threads...'
self.t_stop.set()
exit(0)
self.q.join()
print 'Finished!'
if __name__ == "__main__":
banner = '''
__ __ ___ ____ _
__ / |/ /__ __/ / /_(_)______________ _____ ____ ___ _____
__ / /|_/ // / / / / __/ // ___/ ___/ __ `/ __ \/ __ \/ _ \/ ___/
__ / / / // /_/ / / /_/ /(__ ) /__/ /_/ / / / / / / / __/ /
__/_/ /_/ \__,_/_/\__/_//____/\___/\__,_/_/ /_/_/ /_/\___/_/
by @kyxrec0n
'''
parser = argparse.ArgumentParser(description='Multiscanner by@kyxrec0n')
parser.add_argument(
'-f', '--file',
action='store',
dest='dork_file',
help='List with dorks to scan',
required=True
)
parser.add_argument(
'-o', '--output',
action='store',
dest='output',
help='Output to save valid results',
default='output.txt'
)
parser.add_argument(
'-t', '--threads',
action='store',
default=1,
dest='threads',
help='Concurrent workers ',
type=int
)
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
args = parser.parse_args()
if args.dork_file:
if not os.path.isfile(args.dork_file):
exit('File {} not found'.format(args.dork_file))
print banner
multi_searcher = Multiscanner(
args.dork_file,
args.output,
args.threads
)
multi_searcher.main()
|
#
# 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.
#
import copy
import itertools
import json
import logging
import math
import os
import pkgutil
import socket
import traceback
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
from urllib.parse import quote, unquote
import lazy_object_proxy
import markdown
import sqlalchemy as sqla
from flask import (
Markup, Response, escape, flash, jsonify, make_response, redirect, render_template, request,
session as flask_session, url_for,
)
from flask_appbuilder import BaseView, ModelView, expose, has_access, permission_name
from flask_appbuilder.actions import action
from flask_appbuilder.models.sqla.filters import BaseFilter
from flask_babel import lazy_gettext
from jinja2.utils import htmlsafe_json_dumps # type: ignore
from pygments import highlight, lexers
from pygments.formatters import HtmlFormatter
from sqlalchemy import and_, desc, func, or_, union_all
from sqlalchemy.orm import joinedload
from wtforms import SelectField, validators
import airflow
from airflow import models, settings
from airflow._vendor import nvd3
from airflow.api.common.experimental.mark_tasks import (
set_dag_run_state_to_failed, set_dag_run_state_to_success,
)
from airflow.configuration import AIRFLOW_CONFIG, conf
from airflow.exceptions import AirflowException
from airflow.executors.executor_loader import ExecutorLoader
from airflow.jobs.base_job import BaseJob
from airflow.jobs.scheduler_job import SchedulerJob
from airflow.models import Connection, DagModel, DagTag, Log, SlaMiss, TaskFail, XCom, errors
from airflow.models.dagcode import DagCode
from airflow.models.dagrun import DagRun, DagRunType
from airflow.settings import STORE_SERIALIZED_DAGS
from airflow.ti_deps.dep_context import DepContext
from airflow.ti_deps.dependencies import RUNNING_DEPS, SCHEDULER_QUEUED_DEPS
from airflow.utils import timezone
from airflow.utils.dates import infer_time_unit, scale_time_units
from airflow.utils.helpers import alchemy_to_dict, render_log_filename
from airflow.utils.session import create_session, provide_session
from airflow.utils.state import State
from airflow.www import utils as wwwutils
from airflow.www.app import app, appbuilder
from airflow.www.decorators import action_logging, gzipped, has_dag_access
from airflow.www.forms import (
ConnectionForm, DagRunForm, DateTimeForm, DateTimeWithNumRunsForm, DateTimeWithNumRunsWithDagRunsForm,
)
from airflow.www.widgets import AirflowModelListWidget
PAGE_SIZE = conf.getint('webserver', 'page_size')
FILTER_TAGS_COOKIE = 'tags_filter'
if os.environ.get('SKIP_DAGS_PARSING') != 'True':
dagbag = models.DagBag(settings.DAGS_FOLDER, store_serialized_dags=STORE_SERIALIZED_DAGS)
else:
dagbag = models.DagBag(os.devnull, include_examples=False)
def get_date_time_num_runs_dag_runs_form_data(request, session, dag):
dttm = request.args.get('execution_date')
if dttm:
dttm = timezone.parse(dttm)
else:
dttm = dag.latest_execution_date or timezone.utcnow()
base_date = request.args.get('base_date')
if base_date:
base_date = timezone.parse(base_date)
else:
# The DateTimeField widget truncates milliseconds and would loose
# the first dag run. Round to next second.
base_date = (dttm + timedelta(seconds=1)).replace(microsecond=0)
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
DR = models.DagRun
drs = (
session.query(DR)
.filter(
DR.dag_id == dag.dag_id,
DR.execution_date <= base_date)
.order_by(desc(DR.execution_date))
.limit(num_runs)
.all()
)
dr_choices = []
dr_state = None
for dr in drs:
dr_choices.append((dr.execution_date.isoformat(), dr.run_id))
if dttm == dr.execution_date:
dr_state = dr.state
# Happens if base_date was changed and the selected dag run is not in result
if not dr_state and drs:
dr = drs[0]
dttm = dr.execution_date
dr_state = dr.state
return {
'dttm': dttm,
'base_date': base_date,
'num_runs': num_runs,
'execution_date': dttm.isoformat(),
'dr_choices': dr_choices,
'dr_state': dr_state,
}
######################################################################################
# BaseViews
######################################################################################
@app.errorhandler(404)
def circles(error):
return render_template(
'airflow/circles.html', hostname=socket.getfqdn() if conf.getboolean(
'webserver',
'EXPOSE_HOSTNAME',
fallback=True) else 'redact'), 404
@app.errorhandler(500)
def show_traceback(error):
from airflow.utils import asciiart as ascii_
return render_template(
'airflow/traceback.html',
hostname=socket.getfqdn() if conf.getboolean(
'webserver',
'EXPOSE_HOSTNAME',
fallback=True) else 'redact',
nukular=ascii_.nukular,
info=traceback.format_exc() if conf.getboolean(
'webserver',
'EXPOSE_STACKTRACE',
fallback=True) else 'Error! Please contact server admin'), 500
class AirflowBaseView(BaseView):
from airflow import macros
route_base = ''
# Make our macros available to our UI templates too.
extra_args = {
'macros': macros,
}
def render_template(self, *args, **kwargs):
return super().render_template(
*args,
# Cache this at most once per request, not for the lifetime of the view instance
scheduler_job=lazy_object_proxy.Proxy(SchedulerJob.most_recent_job),
**kwargs
)
class Airflow(AirflowBaseView):
@expose('/health')
def health(self):
"""
An endpoint helping check the health status of the Airflow instance,
including metadatabase and scheduler.
"""
payload = {
'metadatabase': {'status': 'unhealthy'}
}
latest_scheduler_heartbeat = None
scheduler_status = 'unhealthy'
payload['metadatabase'] = {'status': 'healthy'}
try:
scheduler_job = SchedulerJob.most_recent_job()
if scheduler_job:
latest_scheduler_heartbeat = scheduler_job.latest_heartbeat.isoformat()
if scheduler_job.is_alive():
scheduler_status = 'healthy'
except Exception:
payload['metadatabase']['status'] = 'unhealthy'
payload['scheduler'] = {'status': scheduler_status,
'latest_scheduler_heartbeat': latest_scheduler_heartbeat}
return wwwutils.json_response(payload)
@expose('/home')
@has_access
def index(self):
hide_paused_dags_by_default = conf.getboolean('webserver',
'hide_paused_dags_by_default')
show_paused_arg = request.args.get('showPaused', 'None')
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
def get_int_arg(value, default=0):
try:
return int(value)
except ValueError:
return default
arg_current_page = request.args.get('page', '0')
arg_search_query = request.args.get('search', None)
arg_tags_filter = request.args.getlist('tags', None)
if request.args.get('reset_tags') is not None:
flask_session[FILTER_TAGS_COOKIE] = None
arg_tags_filter = None
else:
cookie_val = flask_session.get(FILTER_TAGS_COOKIE)
if arg_tags_filter:
flask_session[FILTER_TAGS_COOKIE] = ','.join(arg_tags_filter)
elif cookie_val:
arg_tags_filter = cookie_val.split(',')
dags_per_page = PAGE_SIZE
current_page = get_int_arg(arg_current_page, default=0)
if show_paused_arg.strip().lower() == 'false':
hide_paused = True
elif show_paused_arg.strip().lower() == 'true':
hide_paused = False
else:
hide_paused = hide_paused_dags_by_default
start = current_page * dags_per_page
end = start + dags_per_page
# Get all the dag id the user could access
filter_dag_ids = appbuilder.sm.get_accessible_dag_ids()
with create_session() as session:
# read orm_dags from the db
dags_query = session.query(DagModel).filter(
~DagModel.is_subdag, DagModel.is_active
)
# optionally filter out "paused" dags
if hide_paused:
dags_query = dags_query.filter(~DagModel.is_paused)
if arg_search_query:
dags_query = dags_query.filter(
DagModel.dag_id.ilike('%' + arg_search_query + '%') |
DagModel.owners.ilike('%' + arg_search_query + '%')
)
if arg_tags_filter:
dags_query = dags_query.filter(DagModel.tags.any(DagTag.name.in_(arg_tags_filter)))
if 'all_dags' not in filter_dag_ids:
dags_query = dags_query.filter(DagModel.dag_id.in_(filter_dag_ids))
dags = dags_query.order_by(DagModel.dag_id).options(
joinedload(DagModel.tags)).offset(start).limit(dags_per_page).all()
dagtags = session.query(DagTag.name).distinct(DagTag.name).all()
tags = [
{"name": name, "selected": bool(arg_tags_filter and name in arg_tags_filter)}
for name, in dagtags
]
import_errors = session.query(errors.ImportError).all()
for ie in import_errors:
flash(
"Broken DAG: [{ie.filename}] {ie.stacktrace}".format(ie=ie),
"dag_import_error")
from airflow.plugins_manager import import_errors as plugin_import_errors
for filename, stacktrace in plugin_import_errors.items():
flash(
"Broken plugin: [{filename}] {stacktrace}".format(
stacktrace=stacktrace,
filename=filename),
"error")
num_of_all_dags = dags_query.count()
num_of_pages = int(math.ceil(num_of_all_dags / float(dags_per_page)))
return self.render_template(
'airflow/dags.html',
dags=dags,
hide_paused=hide_paused,
current_page=current_page,
search_query=arg_search_query if arg_search_query else '',
page_size=dags_per_page,
num_of_pages=num_of_pages,
num_dag_from=min(start + 1, num_of_all_dags),
num_dag_to=min(end, num_of_all_dags),
num_of_all_dags=num_of_all_dags,
paging=wwwutils.generate_pages(current_page, num_of_pages,
search=escape(arg_search_query) if arg_search_query else None,
showPaused=not hide_paused),
num_runs=num_runs,
tags=tags)
@expose('/dag_stats', methods=['POST'])
@has_access
@provide_session
def dag_stats(self, session=None):
dr = models.DagRun
allowed_dag_ids = appbuilder.sm.get_accessible_dag_ids()
if 'all_dags' in allowed_dag_ids:
allowed_dag_ids = [dag_id for dag_id, in session.query(models.DagModel.dag_id)]
dag_state_stats = session.query(dr.dag_id, dr.state, sqla.func.count(dr.state))\
.group_by(dr.dag_id, dr.state)
# Filter by post parameters
selected_dag_ids = {
unquote(dag_id) for dag_id in request.form.getlist('dag_ids') if dag_id
}
if selected_dag_ids:
filter_dag_ids = selected_dag_ids.intersection(allowed_dag_ids)
else:
filter_dag_ids = allowed_dag_ids
if not filter_dag_ids:
return wwwutils.json_response({})
payload = {}
dag_state_stats = dag_state_stats.filter(dr.dag_id.in_(filter_dag_ids))
data = {}
for dag_id, state, count in dag_state_stats:
if dag_id not in data:
data[dag_id] = {}
data[dag_id][state] = count
for dag_id in filter_dag_ids:
payload[dag_id] = []
for state in State.dag_states:
count = data.get(dag_id, {}).get(state, 0)
payload[dag_id].append({
'state': state,
'count': count,
'dag_id': dag_id,
'color': State.color(state)
})
return wwwutils.json_response(payload)
@expose('/task_stats', methods=['POST'])
@has_access
@provide_session
def task_stats(self, session=None):
TI = models.TaskInstance
DagRun = models.DagRun
Dag = models.DagModel
allowed_dag_ids = set(appbuilder.sm.get_accessible_dag_ids())
if not allowed_dag_ids:
return wwwutils.json_response({})
if 'all_dags' in allowed_dag_ids:
allowed_dag_ids = {dag_id for dag_id, in session.query(models.DagModel.dag_id)}
# Filter by post parameters
selected_dag_ids = {
unquote(dag_id) for dag_id in request.form.getlist('dag_ids') if dag_id
}
if selected_dag_ids:
filter_dag_ids = selected_dag_ids.intersection(allowed_dag_ids)
else:
filter_dag_ids = allowed_dag_ids
RunningDagRun = (
session.query(DagRun.dag_id, DagRun.execution_date)
.join(Dag, Dag.dag_id == DagRun.dag_id)
.filter(DagRun.state == State.RUNNING, Dag.is_active)
)
if selected_dag_ids:
RunningDagRun = RunningDagRun.filter(DagRun.dag_id.in_(filter_dag_ids))
RunningDagRun = RunningDagRun.subquery('running_dag_run')
# Select all task_instances from active dag_runs.
RunningTI = (
session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
.join(RunningDagRun,
and_(RunningDagRun.c.dag_id == TI.dag_id,
RunningDagRun.c.execution_date == TI.execution_date))
)
if selected_dag_ids:
RunningTI = RunningTI.filter(TI.dag_id.in_(filter_dag_ids))
if conf.getboolean('webserver', 'SHOW_RECENT_STATS_FOR_COMPLETED_RUNS', fallback=True):
LastDagRun = (
session.query(
DagRun.dag_id,
sqla.func.max(DagRun.execution_date).label('execution_date')
)
.join(Dag, Dag.dag_id == DagRun.dag_id)
.filter(DagRun.state != State.RUNNING, Dag.is_active)
.group_by(DagRun.dag_id)
)
if selected_dag_ids:
LastDagRun = LastDagRun.filter(DagRun.dag_id.in_(filter_dag_ids))
LastDagRun = LastDagRun.subquery('last_dag_run')
# Select all task_instances from active dag_runs.
# If no dag_run is active, return task instances from most recent dag_run.
LastTI = (
session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
.join(LastDagRun,
and_(LastDagRun.c.dag_id == TI.dag_id,
LastDagRun.c.execution_date == TI.execution_date))
)
if selected_dag_ids:
LastTI = LastTI.filter(TI.dag_id.in_(filter_dag_ids))
FinalTI = union_all(LastTI, RunningTI).alias('final_ti')
else:
FinalTI = RunningTI.subquery('final_ti')
qry = (
session.query(FinalTI.c.dag_id, FinalTI.c.state, sqla.func.count())
.group_by(FinalTI.c.dag_id, FinalTI.c.state)
)
data = {}
for dag_id, state, count in qry:
if dag_id not in data:
data[dag_id] = {}
data[dag_id][state] = count
payload = {}
for dag_id in filter_dag_ids:
payload[dag_id] = []
for state in State.task_states:
count = data.get(dag_id, {}).get(state, 0)
payload[dag_id].append({
'state': state,
'count': count,
'dag_id': dag_id,
'color': State.color(state)
})
return wwwutils.json_response(payload)
@expose('/last_dagruns', methods=['POST'])
@has_access
@provide_session
def last_dagruns(self, session=None):
DagRun = models.DagRun
allowed_dag_ids = appbuilder.sm.get_accessible_dag_ids()
if 'all_dags' in allowed_dag_ids:
allowed_dag_ids = [dag_id for dag_id, in session.query(models.DagModel.dag_id)]
# Filter by post parameters
selected_dag_ids = {
unquote(dag_id) for dag_id in request.form.getlist('dag_ids') if dag_id
}
if selected_dag_ids:
filter_dag_ids = selected_dag_ids.intersection(allowed_dag_ids)
else:
filter_dag_ids = allowed_dag_ids
if not filter_dag_ids:
return wwwutils.json_response({})
query = session.query(
DagRun.dag_id, sqla.func.max(DagRun.execution_date).label('last_run')
).group_by(DagRun.dag_id)
# Filter to only ask for accessible and selected dags
query = query.filter(DagRun.dag_id.in_(filter_dag_ids))
resp = {
r.dag_id.replace('.', '__dot__'): {
'dag_id': r.dag_id,
'last_run': r.last_run.strftime("%Y-%m-%d %H:%M"),
} for r in query
}
return wwwutils.json_response(resp)
@expose('/code')
@has_dag_access(can_dag_read=True)
@has_access
@provide_session
def code(self, session=None):
all_errors = ""
try:
dag_id = request.args.get('dag_id')
dag_orm = DagModel.get_dagmodel(dag_id, session=session)
code = DagCode.get_code_by_fileloc(dag_orm.fileloc)
html_code = highlight(
code, lexers.PythonLexer(), HtmlFormatter(linenos=True))
except Exception as e:
all_errors += (
"Exception encountered during " +
"dag_id retrieval/dag retrieval fallback/code highlighting:\n\n{}\n".format(e)
)
html_code = '<p>Failed to load file.</p><p>Details: {}</p>'.format(
escape(all_errors))
return self.render_template(
'airflow/dag_code.html', html_code=html_code, dag=dag_orm, title=dag_id,
root=request.args.get('root'),
demo_mode=conf.getboolean('webserver', 'demo_mode'),
wrapped=conf.getboolean('webserver', 'default_wrap'))
@expose('/dag_details')
@has_dag_access(can_dag_read=True)
@has_access
@provide_session
def dag_details(self, session=None):
dag_id = request.args.get('dag_id')
dag_orm = DagModel.get_dagmodel(dag_id, session=session)
# FIXME: items needed for this view should move to the database
dag = dag_orm.get_dag(STORE_SERIALIZED_DAGS)
title = "DAG details"
root = request.args.get('root', '')
TI = models.TaskInstance
states = (
session.query(TI.state, sqla.func.count(TI.dag_id))
.filter(TI.dag_id == dag_id)
.group_by(TI.state)
.all()
)
active_runs = models.DagRun.find(
dag_id=dag_id,
state=State.RUNNING,
external_trigger=False
)
return self.render_template(
'airflow/dag_details.html',
dag=dag, title=title, root=root, states=states, State=State, active_runs=active_runs)
@expose('/rendered')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def rendered(self, session=None):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
execution_date = request.args.get('execution_date')
dttm = timezone.parse(execution_date)
form = DateTimeForm(data={'execution_date': dttm})
root = request.args.get('root', '')
logging.info("Retrieving rendered templates.")
dag = dagbag.get_dag(dag_id)
task = copy.copy(dag.get_task(task_id))
ti = models.TaskInstance(task=task, execution_date=dttm)
try:
ti.get_rendered_template_fields()
except AirflowException as e:
msg = "Error rendering template: " + escape(e)
if e.__cause__:
msg += Markup("<br/><br/>OriginalError: ") + escape(e.__cause__)
flash(msg, "error")
except Exception as e:
flash("Error rendering template: " + str(e), "error")
title = "Rendered Template"
html_dict = {}
for template_field in task.template_fields:
content = getattr(task, template_field)
if template_field in wwwutils.get_attr_renderer():
html_dict[template_field] = \
wwwutils.get_attr_renderer()[template_field](content)
else:
html_dict[template_field] = (
"<pre><code>" + str(content) + "</pre></code>")
return self.render_template(
'airflow/ti_code.html',
html_dict=html_dict,
dag=dag,
task_id=task_id,
execution_date=execution_date,
form=form,
root=root,
title=title)
@expose('/get_logs_with_metadata')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def get_logs_with_metadata(self, session=None):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
execution_date = request.args.get('execution_date')
dttm = timezone.parse(execution_date)
if request.args.get('try_number') is not None:
try_number = int(request.args.get('try_number'))
else:
try_number = None
metadata = request.args.get('metadata')
metadata = json.loads(metadata)
response_format = request.args.get('format', 'json')
# metadata may be null
if not metadata:
metadata = {}
# Convert string datetime into actual datetime
try:
execution_date = timezone.parse(execution_date)
except ValueError:
error_message = (
'Given execution date, {}, could not be identified '
'as a date. Example date format: 2015-11-16T14:34:15+00:00'.format(
execution_date))
response = jsonify({'error': error_message})
response.status_code = 400
return response
logger = logging.getLogger('airflow.task')
task_log_reader = conf.get('logging', 'task_log_reader')
handler = next((handler for handler in logger.handlers
if handler.name == task_log_reader), None)
ti = session.query(models.TaskInstance).filter(
models.TaskInstance.dag_id == dag_id,
models.TaskInstance.task_id == task_id,
models.TaskInstance.execution_date == dttm).first()
def _get_logs_with_metadata(try_number, metadata):
if ti is None:
logs = ["*** Task instance did not exist in the DB\n"]
metadata['end_of_log'] = True
else:
logs, metadatas = handler.read(ti, try_number, metadata=metadata)
metadata = metadatas[0]
return logs, metadata
try:
if ti is not None:
dag = dagbag.get_dag(dag_id)
if dag:
ti.task = dag.get_task(ti.task_id)
if response_format == 'json':
logs, metadata = _get_logs_with_metadata(try_number, metadata)
message = logs[0] if try_number is not None else logs
return jsonify(message=message, metadata=metadata)
filename_template = conf.get('logging', 'LOG_FILENAME_TEMPLATE')
attachment_filename = render_log_filename(
ti=ti,
try_number="all" if try_number is None else try_number,
filename_template=filename_template)
metadata['download_logs'] = True
def _generate_log_stream(try_number, metadata):
if try_number is None and ti is not None:
next_try = ti.next_try_number
try_numbers = list(range(1, next_try))
else:
try_numbers = [try_number]
for try_number in try_numbers:
metadata.pop('end_of_log', None)
metadata.pop('max_offset', None)
metadata.pop('offset', None)
while 'end_of_log' not in metadata or not metadata['end_of_log']:
logs, metadata = _get_logs_with_metadata(try_number, metadata)
yield "\n".join(logs) + "\n"
return Response(_generate_log_stream(try_number, metadata),
mimetype="text/plain",
headers={"Content-Disposition": "attachment; filename={}".format(
attachment_filename)})
except AttributeError as e:
error_message = ["Task log handler {} does not support read logs.\n{}\n"
.format(task_log_reader, str(e))]
metadata['end_of_log'] = True
return jsonify(message=error_message, error=True, metadata=metadata)
@expose('/log')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def log(self, session=None):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
execution_date = request.args.get('execution_date')
dttm = timezone.parse(execution_date)
form = DateTimeForm(data={'execution_date': dttm})
dag_model = DagModel.get_dagmodel(dag_id)
ti = session.query(models.TaskInstance).filter(
models.TaskInstance.dag_id == dag_id,
models.TaskInstance.task_id == task_id,
models.TaskInstance.execution_date == dttm).first()
num_logs = 0
if ti is not None:
num_logs = ti.next_try_number - 1
if ti.state == State.UP_FOR_RESCHEDULE:
# Tasks in reschedule state decremented the try number
num_logs += 1
logs = [''] * num_logs
root = request.args.get('root', '')
return self.render_template(
'airflow/ti_log.html',
logs=logs, dag=dag_model, title="Log by attempts",
dag_id=dag_id, task_id=task_id,
execution_date=execution_date, form=form,
root=root, wrapped=conf.getboolean('webserver', 'default_wrap'))
@expose('/elasticsearch')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def elasticsearch(self, session=None):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
execution_date = request.args.get('execution_date')
try_number = request.args.get('try_number', 1)
elasticsearch_frontend = conf.get('elasticsearch', 'frontend')
log_id_template = conf.get('elasticsearch', 'log_id_template')
log_id = log_id_template.format(
dag_id=dag_id, task_id=task_id,
execution_date=execution_date, try_number=try_number)
url = 'https://' + elasticsearch_frontend.format(log_id=quote(log_id))
return redirect(url)
@expose('/task')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
def task(self):
TI = models.TaskInstance
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
# Carrying execution_date through, even though it's irrelevant for
# this context
execution_date = request.args.get('execution_date')
dttm = timezone.parse(execution_date)
form = DateTimeForm(data={'execution_date': dttm})
root = request.args.get('root', '')
dag = dagbag.get_dag(dag_id)
if not dag or task_id not in dag.task_ids:
flash(
"Task [{}.{}] doesn't seem to exist"
" at the moment".format(dag_id, task_id),
"error")
return redirect(url_for('Airflow.index'))
task = copy.copy(dag.get_task(task_id))
task.resolve_template_files()
ti = TI(task=task, execution_date=dttm)
ti.refresh_from_db()
ti_attrs = []
for attr_name in dir(ti):
if not attr_name.startswith('_'):
attr = getattr(ti, attr_name)
if type(attr) != type(self.task): # noqa
ti_attrs.append((attr_name, str(attr)))
task_attrs = []
for attr_name in dir(task):
if not attr_name.startswith('_'):
attr = getattr(task, attr_name)
if type(attr) != type(self.task) and \
attr_name not in wwwutils.get_attr_renderer(): # noqa
task_attrs.append((attr_name, str(attr)))
# Color coding the special attributes that are code
special_attrs_rendered = {}
for attr_name in wwwutils.get_attr_renderer():
if hasattr(task, attr_name):
source = getattr(task, attr_name)
special_attrs_rendered[attr_name] = \
wwwutils.get_attr_renderer()[attr_name](source)
no_failed_deps_result = [(
"Unknown",
"All dependencies are met but the task instance is not running. In most "
"cases this just means that the task will probably be scheduled soon "
"unless:<br/>\n- The scheduler is down or under heavy load<br/>\n{}\n"
"<br/>\nIf this task instance does not start soon please contact your "
"Airflow administrator for assistance.".format(
"- This task instance already ran and had it's state changed manually "
"(e.g. cleared in the UI)<br/>" if ti.state == State.NONE else ""))]
# Use the scheduler's context to figure out which dependencies are not met
dep_context = DepContext(SCHEDULER_QUEUED_DEPS)
failed_dep_reasons = [(dep.dep_name, dep.reason) for dep in
ti.get_failed_dep_statuses(
dep_context=dep_context)]
title = "Task Instance Details"
return self.render_template(
'airflow/task.html',
task_attrs=task_attrs,
ti_attrs=ti_attrs,
failed_dep_reasons=failed_dep_reasons or no_failed_deps_result,
task_id=task_id,
execution_date=execution_date,
special_attrs_rendered=special_attrs_rendered,
form=form,
root=root,
dag=dag, title=title)
@expose('/xcom')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def xcom(self, session=None):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
# Carrying execution_date through, even though it's irrelevant for
# this context
execution_date = request.args.get('execution_date')
dttm = timezone.parse(execution_date)
form = DateTimeForm(data={'execution_date': dttm})
root = request.args.get('root', '')
dm_db = models.DagModel
ti_db = models.TaskInstance
dag = session.query(dm_db).filter(dm_db.dag_id == dag_id).first()
ti = session.query(ti_db).filter(ti_db.dag_id == dag_id and ti_db.task_id == task_id).first()
if not ti:
flash(
"Task [{}.{}] doesn't seem to exist"
" at the moment".format(dag_id, task_id),
"error")
return redirect(url_for('Airflow.index'))
xcomlist = session.query(XCom).filter(
XCom.dag_id == dag_id, XCom.task_id == task_id,
XCom.execution_date == dttm).all()
attributes = []
for xcom in xcomlist:
if not xcom.key.startswith('_'):
attributes.append((xcom.key, xcom.value))
title = "XCom"
return self.render_template(
'airflow/xcom.html',
attributes=attributes,
task_id=task_id,
execution_date=execution_date,
form=form,
root=root,
dag=dag, title=title)
@expose('/run', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def run(self):
dag_id = request.form.get('dag_id')
task_id = request.form.get('task_id')
origin = request.form.get('origin')
dag = dagbag.get_dag(dag_id)
task = dag.get_task(task_id)
execution_date = request.form.get('execution_date')
execution_date = timezone.parse(execution_date)
ignore_all_deps = request.form.get('ignore_all_deps') == "true"
ignore_task_deps = request.form.get('ignore_task_deps') == "true"
ignore_ti_state = request.form.get('ignore_ti_state') == "true"
executor = ExecutorLoader.get_default_executor()
valid_celery_config = False
valid_kubernetes_config = False
try:
from airflow.executors.celery_executor import CeleryExecutor
valid_celery_config = isinstance(executor, CeleryExecutor)
except ImportError:
pass
try:
from airflow.executors.kubernetes_executor import KubernetesExecutor
valid_kubernetes_config = isinstance(executor, KubernetesExecutor)
except ImportError:
pass
if not valid_celery_config and not valid_kubernetes_config:
flash("Only works with the Celery or Kubernetes executors, sorry", "error")
return redirect(origin)
ti = models.TaskInstance(task=task, execution_date=execution_date)
ti.refresh_from_db()
# Make sure the task instance can be run
dep_context = DepContext(
deps=RUNNING_DEPS,
ignore_all_deps=ignore_all_deps,
ignore_task_deps=ignore_task_deps,
ignore_ti_state=ignore_ti_state)
failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context))
if failed_deps:
failed_deps_str = ", ".join(
["{}: {}".format(dep.dep_name, dep.reason) for dep in failed_deps])
flash("Could not queue task instance for execution, dependencies not met: "
"{}".format(failed_deps_str),
"error")
return redirect(origin)
executor.start()
executor.queue_task_instance(
ti,
ignore_all_deps=ignore_all_deps,
ignore_task_deps=ignore_task_deps,
ignore_ti_state=ignore_ti_state)
executor.heartbeat()
flash(
"Sent {} to the message queue, "
"it should start any moment now.".format(ti))
return redirect(origin)
@expose('/delete', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def delete(self):
from airflow.api.common.experimental import delete_dag
from airflow.exceptions import DagNotFound, DagFileExists
dag_id = request.values.get('dag_id')
origin = request.values.get('origin') or url_for('Airflow.index')
try:
delete_dag.delete_dag(dag_id)
except DagNotFound:
flash("DAG with id {} not found. Cannot delete".format(dag_id), 'error')
return redirect(request.referrer)
except DagFileExists:
flash("Dag id {} is still in DagBag. "
"Remove the DAG file first.".format(dag_id),
'error')
return redirect(request.referrer)
flash("Deleting DAG with id {}. May take a couple minutes to fully"
" disappear.".format(dag_id))
# Upon success return to origin.
return redirect(origin)
@expose('/trigger', methods=['POST', 'GET'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
@provide_session
def trigger(self, session=None):
dag_id = request.values.get('dag_id')
origin = request.values.get('origin') or url_for('Airflow.index')
if request.method == 'GET':
return self.render_template(
'airflow/trigger.html',
dag_id=dag_id,
origin=origin,
conf=''
)
dag = session.query(models.DagModel).filter(models.DagModel.dag_id == dag_id).first()
if not dag:
flash("Cannot find dag {}".format(dag_id))
return redirect(origin)
execution_date = timezone.utcnow()
run_id = f"{DagRunType.MANUAL.value}__{execution_date.isoformat()}"
dr = DagRun.find(dag_id=dag_id, run_id=run_id)
if dr:
flash("This run_id {} already exists".format(run_id))
return redirect(origin)
run_conf = {}
conf = request.values.get('conf')
if conf:
try:
run_conf = json.loads(conf)
except json.decoder.JSONDecodeError:
flash("Invalid JSON configuration", "error")
return self.render_template(
'airflow/trigger.html',
dag_id=dag_id,
origin=origin,
conf=conf
)
dag.create_dagrun(
run_id=run_id,
execution_date=execution_date,
state=State.RUNNING,
conf=run_conf,
external_trigger=True
)
flash(
"Triggered {}, "
"it should start any moment now.".format(dag_id))
return redirect(origin)
def _clear_dag_tis(self, dag, start_date, end_date, origin,
recursive=False, confirmed=False, only_failed=False):
from airflow.exceptions import AirflowException
if confirmed:
count = dag.clear(
start_date=start_date,
end_date=end_date,
include_subdags=recursive,
include_parentdag=recursive,
only_failed=only_failed,
)
flash("{0} task instances have been cleared".format(count))
return redirect(origin)
try:
tis = dag.clear(
start_date=start_date,
end_date=end_date,
include_subdags=recursive,
include_parentdag=recursive,
only_failed=only_failed,
dry_run=True,
)
except AirflowException as ex:
flash(str(ex), 'error')
return redirect(origin)
if not tis:
flash("No task instances to clear", 'error')
response = redirect(origin)
else:
details = "\n".join([str(t) for t in tis])
response = self.render_template(
'airflow/confirm.html',
message=("Here's the list of task instances you are about "
"to clear:"),
details=details)
return response
@expose('/clear', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def clear(self):
dag_id = request.form.get('dag_id')
task_id = request.form.get('task_id')
origin = request.form.get('origin')
dag = dagbag.get_dag(dag_id)
execution_date = request.form.get('execution_date')
execution_date = timezone.parse(execution_date)
confirmed = request.form.get('confirmed') == "true"
upstream = request.form.get('upstream') == "true"
downstream = request.form.get('downstream') == "true"
future = request.form.get('future') == "true"
past = request.form.get('past') == "true"
recursive = request.form.get('recursive') == "true"
only_failed = request.form.get('only_failed') == "true"
dag = dag.sub_dag(
task_regex=r"^{0}$".format(task_id),
include_downstream=downstream,
include_upstream=upstream)
end_date = execution_date if not future else None
start_date = execution_date if not past else None
return self._clear_dag_tis(dag, start_date, end_date, origin,
recursive=recursive, confirmed=confirmed, only_failed=only_failed)
@expose('/dagrun_clear', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def dagrun_clear(self):
dag_id = request.form.get('dag_id')
origin = request.form.get('origin')
execution_date = request.form.get('execution_date')
confirmed = request.form.get('confirmed') == "true"
dag = dagbag.get_dag(dag_id)
execution_date = timezone.parse(execution_date)
start_date = execution_date
end_date = execution_date
return self._clear_dag_tis(dag, start_date, end_date, origin,
recursive=True, confirmed=confirmed)
@expose('/blocked', methods=['POST'])
@has_access
@provide_session
def blocked(self, session=None):
allowed_dag_ids = appbuilder.sm.get_accessible_dag_ids()
if 'all_dags' in allowed_dag_ids:
allowed_dag_ids = [dag_id for dag_id, in session.query(models.DagModel.dag_id)]
# Filter by post parameters
selected_dag_ids = {
unquote(dag_id) for dag_id in request.form.getlist('dag_ids') if dag_id
}
if selected_dag_ids:
filter_dag_ids = selected_dag_ids.intersection(allowed_dag_ids)
else:
filter_dag_ids = allowed_dag_ids
if not filter_dag_ids:
return wwwutils.json_response([])
DR = models.DagRun
dags = (
session.query(DR.dag_id, sqla.func.count(DR.id))
.filter(DR.state == State.RUNNING)
.filter(DR.dag_id.in_(filter_dag_ids))
.group_by(DR.dag_id)
)
payload = []
for dag_id, active_dag_runs in dags:
max_active_runs = 0
dag = dagbag.get_dag(dag_id)
if dag:
# TODO: Make max_active_runs a column so we can query for it directly
max_active_runs = dag.max_active_runs
payload.append({
'dag_id': dag_id,
'active_dag_run': active_dag_runs,
'max_active_runs': max_active_runs,
})
return wwwutils.json_response(payload)
def _mark_dagrun_state_as_failed(self, dag_id, execution_date, confirmed, origin):
if not execution_date:
flash('Invalid execution date', 'error')
return redirect(origin)
execution_date = timezone.parse(execution_date)
dag = dagbag.get_dag(dag_id)
if not dag:
flash('Cannot find DAG: {}'.format(dag_id), 'error')
return redirect(origin)
new_dag_state = set_dag_run_state_to_failed(dag, execution_date, commit=confirmed)
if confirmed:
flash('Marked failed on {} task instances'.format(len(new_dag_state)))
return redirect(origin)
else:
details = '\n'.join([str(t) for t in new_dag_state])
response = self.render_template(
'airflow/confirm.html',
message="Here's the list of task instances you are about to mark as failed",
details=details)
return response
def _mark_dagrun_state_as_success(self, dag_id, execution_date, confirmed, origin):
if not execution_date:
flash('Invalid execution date', 'error')
return redirect(origin)
execution_date = timezone.parse(execution_date)
dag = dagbag.get_dag(dag_id)
if not dag:
flash('Cannot find DAG: {}'.format(dag_id), 'error')
return redirect(origin)
new_dag_state = set_dag_run_state_to_success(dag, execution_date,
commit=confirmed)
if confirmed:
flash('Marked success on {} task instances'.format(len(new_dag_state)))
return redirect(origin)
else:
details = '\n'.join([str(t) for t in new_dag_state])
response = self.render_template(
'airflow/confirm.html',
message="Here's the list of task instances you are about to mark as success",
details=details)
return response
@expose('/dagrun_failed', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def dagrun_failed(self):
dag_id = request.form.get('dag_id')
execution_date = request.form.get('execution_date')
confirmed = request.form.get('confirmed') == 'true'
origin = request.form.get('origin')
return self._mark_dagrun_state_as_failed(dag_id, execution_date,
confirmed, origin)
@expose('/dagrun_success', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def dagrun_success(self):
dag_id = request.form.get('dag_id')
execution_date = request.form.get('execution_date')
confirmed = request.form.get('confirmed') == 'true'
origin = request.form.get('origin')
return self._mark_dagrun_state_as_success(dag_id, execution_date,
confirmed, origin)
def _mark_task_instance_state(self, dag_id, task_id, origin, execution_date,
confirmed, upstream, downstream,
future, past, state):
dag = dagbag.get_dag(dag_id)
task = dag.get_task(task_id)
task.dag = dag
latest_execution_date = dag.latest_execution_date
if not latest_execution_date:
flash(f"Cannot make {state}, seem that dag {dag_id} has never run", "error")
return redirect(origin)
execution_date = timezone.parse(execution_date)
from airflow.api.common.experimental.mark_tasks import set_state
if confirmed:
altered = set_state(tasks=[task], execution_date=execution_date,
upstream=upstream, downstream=downstream,
future=future, past=past, state=state,
commit=True)
flash("Marked {} on {} task instances".format(state, len(altered)))
return redirect(origin)
to_be_altered = set_state(tasks=[task], execution_date=execution_date,
upstream=upstream, downstream=downstream,
future=future, past=past, state=state,
commit=False)
details = "\n".join([str(t) for t in to_be_altered])
response = self.render_template(
"airflow/confirm.html",
message=("Here's the list of task instances you are about to mark as {}:".format(state)),
details=details)
return response
@expose('/failed', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def failed(self):
dag_id = request.form.get('dag_id')
task_id = request.form.get('task_id')
origin = request.form.get('origin')
execution_date = request.form.get('execution_date')
confirmed = request.form.get('confirmed') == "true"
upstream = request.form.get('failed_upstream') == "true"
downstream = request.form.get('failed_downstream') == "true"
future = request.form.get('failed_future') == "true"
past = request.form.get('failed_past') == "true"
return self._mark_task_instance_state(dag_id, task_id, origin, execution_date,
confirmed, upstream, downstream,
future, past, State.FAILED)
@expose('/success', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def success(self):
dag_id = request.form.get('dag_id')
task_id = request.form.get('task_id')
origin = request.form.get('origin')
execution_date = request.form.get('execution_date')
confirmed = request.form.get('confirmed') == "true"
upstream = request.form.get('success_upstream') == "true"
downstream = request.form.get('success_downstream') == "true"
future = request.form.get('success_future') == "true"
past = request.form.get('success_past') == "true"
return self._mark_task_instance_state(dag_id, task_id, origin, execution_date,
confirmed, upstream, downstream,
future, past, State.SUCCESS)
@expose('/tree')
@has_dag_access(can_dag_read=True)
@has_access
@gzipped
@action_logging
def tree(self):
dag_id = request.args.get('dag_id')
blur = conf.getboolean('webserver', 'demo_mode')
dag = dagbag.get_dag(dag_id)
if not dag:
flash('DAG "{0}" seems to be missing from DagBag.'.format(dag_id), "error")
return redirect(url_for('Airflow.index'))
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_downstream=False,
include_upstream=True)
base_date = request.args.get('base_date')
num_runs = request.args.get('num_runs')
if num_runs:
num_runs = int(num_runs)
else:
num_runs = conf.getint('webserver', 'default_dag_run_display_number')
if base_date:
base_date = timezone.parse(base_date)
else:
base_date = dag.latest_execution_date or timezone.utcnow()
with create_session() as session:
dag_runs = (
session.query(DagRun)
.filter(
DagRun.dag_id == dag.dag_id,
DagRun.execution_date <= base_date)
.order_by(DagRun.execution_date.desc())
.limit(num_runs)
.all()
)
dag_runs = {
dr.execution_date: alchemy_to_dict(dr) for dr in dag_runs
}
dates = sorted(list(dag_runs.keys()))
max_date = max(dates) if dates else None
min_date = min(dates) if dates else None
tis = dag.get_task_instances(start_date=min_date, end_date=base_date)
task_instances: Dict[Tuple[str, datetime], models.TaskInstance] = {}
for ti in tis:
task_instances[(ti.task_id, ti.execution_date)] = ti
expanded = set()
# The default recursion traces every path so that tree view has full
# expand/collapse functionality. After 5,000 nodes we stop and fall
# back on a quick DFS search for performance. See PR #320.
node_count = 0
node_limit = 5000 / max(1, len(dag.leaves))
def encode_ti(ti: Optional[models.TaskInstance]) -> Optional[List]:
if not ti:
return None
# NOTE: order of entry is important here because client JS relies on it for
# tree node reconstruction. Remember to change JS code in tree.html
# whenever order is altered.
data = [
ti.state,
ti.try_number,
None, # start_ts
None, # duration
]
if ti.start_date:
# round to seconds to reduce payload size
data[2] = int(ti.start_date.timestamp())
if ti.duration is not None:
data[3] = int(ti.duration)
return data
def recurse_nodes(task, visited):
nonlocal node_count
node_count += 1
visited.add(task)
task_id = task.task_id
node = {
'name': task.task_id,
'instances': [
encode_ti(task_instances.get((task_id, d)))
for d in dates
],
'num_dep': len(task.downstream_list),
'operator': task.task_type,
'retries': task.retries,
'owner': task.owner,
'ui_color': task.ui_color,
}
if task.downstream_list:
children = [
recurse_nodes(t, visited) for t in task.downstream_list
if node_count < node_limit or t not in visited]
# D3 tree uses children vs _children to define what is
# expanded or not. The following block makes it such that
# repeated nodes are collapsed by default.
if task.task_id not in expanded:
children_key = 'children'
expanded.add(task.task_id)
else:
children_key = "_children"
node[children_key] = children
if task.depends_on_past:
node['depends_on_past'] = task.depends_on_past
if task.start_date:
# round to seconds to reduce payload size
node['start_ts'] = int(task.start_date.timestamp())
if task.end_date:
# round to seconds to reduce payload size
node['end_ts'] = int(task.end_date.timestamp())
if task.extra_links:
node['extra_links'] = task.extra_links
return node
data = {
'name': '[DAG]',
'children': [recurse_nodes(t, set()) for t in dag.roots],
'instances': [
dag_runs.get(d) or {'execution_date': d.isoformat()}
for d in dates
],
}
form = DateTimeWithNumRunsForm(data={'base_date': max_date,
'num_runs': num_runs})
external_logs = conf.get('elasticsearch', 'frontend')
return self.render_template(
'airflow/tree.html',
operators=sorted({op.task_type: op for op in dag.tasks}.values(), key=lambda x: x.task_type),
root=root,
form=form,
dag=dag,
# avoid spaces to reduce payload size
data=htmlsafe_json_dumps(data, separators=(',', ':')),
blur=blur, num_runs=num_runs,
show_external_logs=bool(external_logs))
@expose('/graph')
@has_dag_access(can_dag_read=True)
@has_access
@gzipped
@action_logging
@provide_session
def graph(self, session=None):
dag_id = request.args.get('dag_id')
blur = conf.getboolean('webserver', 'demo_mode')
dag = dagbag.get_dag(dag_id)
if not dag:
flash('DAG "{0}" seems to be missing.'.format(dag_id), "error")
return redirect(url_for('Airflow.index'))
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
arrange = request.args.get('arrange', dag.orientation)
nodes = []
edges = []
for task in dag.tasks:
nodes.append({
'id': task.task_id,
'value': {
'label': task.task_id,
'labelStyle': "fill:{0};".format(task.ui_fgcolor),
'style': "fill:{0};".format(task.ui_color),
'rx': 5,
'ry': 5,
}
})
def get_downstream(task):
for t in task.downstream_list:
edge = {
'source_id': task.task_id,
'target_id': t.task_id,
}
if edge not in edges:
edges.append(edge)
get_downstream(t)
for t in dag.roots:
get_downstream(t)
dt_nr_dr_data = get_date_time_num_runs_dag_runs_form_data(request, session, dag)
dt_nr_dr_data['arrange'] = arrange
dttm = dt_nr_dr_data['dttm']
class GraphForm(DateTimeWithNumRunsWithDagRunsForm):
arrange = SelectField("Layout", choices=(
('LR', "Left->Right"),
('RL', "Right->Left"),
('TB', "Top->Bottom"),
('BT', "Bottom->Top"),
))
form = GraphForm(data=dt_nr_dr_data)
form.execution_date.choices = dt_nr_dr_data['dr_choices']
task_instances = {
ti.task_id: alchemy_to_dict(ti)
for ti in dag.get_task_instances(dttm, dttm)}
tasks = {
t.task_id: {
'dag_id': t.dag_id,
'task_type': t.task_type,
'extra_links': t.extra_links,
}
for t in dag.tasks}
if not tasks:
flash("No tasks found", "error")
session.commit()
doc_md = markdown.markdown(dag.doc_md) \
if hasattr(dag, 'doc_md') and dag.doc_md else ''
external_logs = conf.get('elasticsearch', 'frontend')
return self.render_template(
'airflow/graph.html',
dag=dag,
form=form,
width=request.args.get('width', "100%"),
height=request.args.get('height', "800"),
execution_date=dttm.isoformat(),
state_token=wwwutils.state_token(dt_nr_dr_data['dr_state']),
doc_md=doc_md,
arrange=arrange,
operators=sorted({op.task_type: op for op in dag.tasks}.values(), key=lambda x: x.task_type),
blur=blur,
root=root or '',
task_instances=task_instances,
tasks=tasks,
nodes=nodes,
edges=edges,
show_external_logs=bool(external_logs))
@expose('/duration')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def duration(self, session=None):
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
base_date = request.args.get('base_date')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
if dag is None:
flash('DAG "{0}" seems to be missing.'.format(dag_id), "error")
return redirect(url_for('Airflow.index'))
if base_date:
base_date = timezone.parse(base_date)
else:
base_date = dag.latest_execution_date or timezone.utcnow()
dates = dag.date_range(base_date, num=-abs(num_runs))
min_date = dates[0] if dates else timezone.utc_epoch()
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
chart_height = wwwutils.get_chart_height(dag)
chart = nvd3.lineChart(
name="lineChart", x_is_date=True, height=chart_height, width="1200")
cum_chart = nvd3.lineChart(
name="cumLineChart", x_is_date=True, height=chart_height, width="1200")
y = defaultdict(list)
x = defaultdict(list)
cum_y = defaultdict(list)
tis = dag.get_task_instances(start_date=min_date, end_date=base_date)
TF = TaskFail
ti_fails = (
session.query(TF)
.filter(TF.dag_id == dag.dag_id,
TF.execution_date >= min_date,
TF.execution_date <= base_date,
TF.task_id.in_([t.task_id for t in dag.tasks]))
.all() # noqa
)
fails_totals = defaultdict(int)
for tf in ti_fails:
dict_key = (tf.dag_id, tf.task_id, tf.execution_date)
if tf.duration:
fails_totals[dict_key] += tf.duration
for ti in tis:
if ti.duration:
dttm = wwwutils.epoch(ti.execution_date)
x[ti.task_id].append(dttm)
y[ti.task_id].append(float(ti.duration))
fails_dict_key = (ti.dag_id, ti.task_id, ti.execution_date)
fails_total = fails_totals[fails_dict_key]
cum_y[ti.task_id].append(float(ti.duration + fails_total))
# determine the most relevant time unit for the set of task instance
# durations for the DAG
y_unit = infer_time_unit([d for t in y.values() for d in t])
cum_y_unit = infer_time_unit([d for t in cum_y.values() for d in t])
# update the y Axis on both charts to have the correct time units
chart.create_y_axis('yAxis', format='.02f', custom_format=False,
label='Duration ({})'.format(y_unit))
chart.axislist['yAxis']['axisLabelDistance'] = '40'
cum_chart.create_y_axis('yAxis', format='.02f', custom_format=False,
label='Duration ({})'.format(cum_y_unit))
cum_chart.axislist['yAxis']['axisLabelDistance'] = '40'
for task in dag.tasks:
if x[task.task_id]:
chart.add_serie(name=task.task_id, x=x[task.task_id],
y=scale_time_units(y[task.task_id], y_unit))
cum_chart.add_serie(name=task.task_id, x=x[task.task_id],
y=scale_time_units(cum_y[task.task_id],
cum_y_unit))
dates = sorted(list({ti.execution_date for ti in tis}))
max_date = max([ti.execution_date for ti in tis]) if dates else None
session.commit()
form = DateTimeWithNumRunsForm(data={'base_date': max_date,
'num_runs': num_runs})
chart.buildcontent()
cum_chart.buildcontent()
s_index = cum_chart.htmlcontent.rfind('});')
cum_chart.htmlcontent = (cum_chart.htmlcontent[:s_index] +
"$( document ).trigger('chartload')" +
cum_chart.htmlcontent[s_index:])
return self.render_template(
'airflow/duration_chart.html',
dag=dag,
demo_mode=conf.getboolean('webserver', 'demo_mode'),
root=root,
form=form,
chart=chart.htmlcontent,
cum_chart=cum_chart.htmlcontent
)
@expose('/tries')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def tries(self, session=None):
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
base_date = request.args.get('base_date')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
if base_date:
base_date = timezone.parse(base_date)
else:
base_date = dag.latest_execution_date or timezone.utcnow()
dates = dag.date_range(base_date, num=-abs(num_runs))
min_date = dates[0] if dates else timezone.utc_epoch()
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
chart_height = wwwutils.get_chart_height(dag)
chart = nvd3.lineChart(
name="lineChart", x_is_date=True, y_axis_format='d', height=chart_height,
width="1200")
for task in dag.tasks:
y = []
x = []
for ti in task.get_task_instances(start_date=min_date, end_date=base_date):
dttm = wwwutils.epoch(ti.execution_date)
x.append(dttm)
# y value should reflect completed tries to have a 0 baseline.
y.append(ti.prev_attempted_tries)
if x:
chart.add_serie(name=task.task_id, x=x, y=y)
tis = dag.get_task_instances(start_date=min_date, end_date=base_date)
tries = sorted(list({ti.try_number for ti in tis}))
max_date = max([ti.execution_date for ti in tis]) if tries else None
session.commit()
form = DateTimeWithNumRunsForm(data={'base_date': max_date,
'num_runs': num_runs})
chart.buildcontent()
return self.render_template(
'airflow/chart.html',
dag=dag,
demo_mode=conf.getboolean('webserver', 'demo_mode'),
root=root,
form=form,
chart=chart.htmlcontent,
tab_title='Tries',
)
@expose('/landing_times')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def landing_times(self, session=None):
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
base_date = request.args.get('base_date')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
if base_date:
base_date = timezone.parse(base_date)
else:
base_date = dag.latest_execution_date or timezone.utcnow()
dates = dag.date_range(base_date, num=-abs(num_runs))
min_date = dates[0] if dates else timezone.utc_epoch()
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
chart_height = wwwutils.get_chart_height(dag)
chart = nvd3.lineChart(
name="lineChart", x_is_date=True, height=chart_height, width="1200")
y = {}
x = {}
for task in dag.tasks:
task_id = task.task_id
y[task_id] = []
x[task_id] = []
for ti in task.get_task_instances(start_date=min_date, end_date=base_date):
ts = ti.execution_date
if dag.schedule_interval and dag.following_schedule(ts):
ts = dag.following_schedule(ts)
if ti.end_date:
dttm = wwwutils.epoch(ti.execution_date)
secs = (ti.end_date - ts).total_seconds()
x[task_id].append(dttm)
y[task_id].append(secs)
# determine the most relevant time unit for the set of landing times
# for the DAG
y_unit = infer_time_unit([d for t in y.values() for d in t])
# update the y Axis to have the correct time units
chart.create_y_axis('yAxis', format='.02f', custom_format=False,
label='Landing Time ({})'.format(y_unit))
chart.axislist['yAxis']['axisLabelDistance'] = '40'
for task in dag.tasks:
if x[task.task_id]:
chart.add_serie(name=task.task_id, x=x[task.task_id],
y=scale_time_units(y[task.task_id], y_unit))
tis = dag.get_task_instances(start_date=min_date, end_date=base_date)
dates = sorted(list({ti.execution_date for ti in tis}))
max_date = max([ti.execution_date for ti in tis]) if dates else None
session.commit()
form = DateTimeWithNumRunsForm(data={'base_date': max_date,
'num_runs': num_runs})
chart.buildcontent()
return self.render_template(
'airflow/chart.html',
dag=dag,
chart=chart.htmlcontent,
height=str(chart_height + 100) + "px",
demo_mode=conf.getboolean('webserver', 'demo_mode'),
root=root,
form=form,
tab_title='Landing times',
)
@expose('/paused', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def paused(self):
dag_id = request.args.get('dag_id')
is_paused = True if request.args.get('is_paused') == 'false' else False
models.DagModel.get_dagmodel(dag_id).set_is_paused(
is_paused=is_paused)
return "OK"
@expose('/refresh', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
@provide_session
def refresh(self, session=None):
DagModel = models.DagModel
dag_id = request.values.get('dag_id')
orm_dag = session.query(
DagModel).filter(DagModel.dag_id == dag_id).first()
if orm_dag:
orm_dag.last_expired = timezone.utcnow()
session.merge(orm_dag)
session.commit()
dag = dagbag.get_dag(dag_id)
# sync dag permission
appbuilder.sm.sync_perm_for_dag(dag_id, dag.access_control)
flash("DAG [{}] is now fresh as a daisy".format(dag_id))
return redirect(request.referrer)
@expose('/gantt')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def gantt(self, session=None):
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
demo_mode = conf.getboolean('webserver', 'demo_mode')
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
dt_nr_dr_data = get_date_time_num_runs_dag_runs_form_data(request, session, dag)
dttm = dt_nr_dr_data['dttm']
form = DateTimeWithNumRunsWithDagRunsForm(data=dt_nr_dr_data)
form.execution_date.choices = dt_nr_dr_data['dr_choices']
tis = [
ti for ti in dag.get_task_instances(dttm, dttm)
if ti.start_date and ti.state]
tis = sorted(tis, key=lambda ti: ti.start_date)
TF = TaskFail
ti_fails = list(itertools.chain(*[(
session
.query(TF)
.filter(TF.dag_id == ti.dag_id,
TF.task_id == ti.task_id,
TF.execution_date == ti.execution_date)
.all()
) for ti in tis]))
# determine bars to show in the gantt chart
gantt_bar_items = []
for ti in tis:
end_date = ti.end_date or timezone.utcnow()
# prev_attempted_tries will reflect the currently running try_number
# or the try_number of the last complete run
# https://issues.apache.org/jira/browse/AIRFLOW-2143
try_count = ti.prev_attempted_tries
gantt_bar_items.append((ti.task_id, ti.start_date, end_date, ti.state, try_count))
tf_count = 0
try_count = 1
prev_task_id = ""
for tf in ti_fails:
end_date = tf.end_date or timezone.utcnow()
if tf_count != 0 and tf.task_id == prev_task_id:
try_count = try_count + 1
else:
try_count = 1
prev_task_id = tf.task_id
gantt_bar_items.append((tf.task_id, tf.start_date, end_date, State.FAILED, try_count))
tf_count = tf_count + 1
task_types = {}
extra_links = {}
for t in dag.tasks:
task_types[t.task_id] = t.task_type
extra_links[t.task_id] = t.extra_links
tasks = []
for gantt_bar_item in gantt_bar_items:
task_id = gantt_bar_item[0]
start_date = gantt_bar_item[1]
end_date = gantt_bar_item[2]
state = gantt_bar_item[3]
try_count = gantt_bar_item[4]
tasks.append({
'startDate': wwwutils.epoch(start_date),
'endDate': wwwutils.epoch(end_date),
'isoStart': start_date.isoformat()[:-4],
'isoEnd': end_date.isoformat()[:-4],
'taskName': task_id,
'taskType': task_types[ti.task_id],
'duration': (end_date - start_date).total_seconds(),
'status': state,
'executionDate': dttm.isoformat(),
'try_number': try_count,
'extraLinks': extra_links[ti.task_id],
})
states = {task['status']: task['status'] for task in tasks}
data = {
'taskNames': [ti.task_id for ti in tis],
'tasks': tasks,
'taskStatus': states,
'height': len(tis) * 25 + 25,
}
session.commit()
return self.render_template(
'airflow/gantt.html',
dag=dag,
execution_date=dttm.isoformat(),
form=form,
data=data,
base_date='',
demo_mode=demo_mode,
root=root,
)
@expose('/extra_links')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
def extra_links(self):
"""
A restful endpoint that returns external links for a given Operator
It queries the operator that sent the request for the links it wishes
to provide for a given external link name.
API: GET
Args: dag_id: The id of the dag containing the task in question
task_id: The id of the task in question
execution_date: The date of execution of the task
link_name: The name of the link reference to find the actual URL for
Returns:
200: {url: <url of link>, error: None} - returned when there was no problem
finding the URL
404: {url: None, error: <error message>} - returned when the operator does
not return a URL
"""
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
execution_date = request.args.get('execution_date')
link_name = request.args.get('link_name')
dttm = timezone.parse(execution_date)
dag = dagbag.get_dag(dag_id)
if not dag or task_id not in dag.task_ids:
response = jsonify(
{'url': None,
'error': "can't find dag {dag} or task_id {task_id}".format(
dag=dag,
task_id=task_id
)}
)
response.status_code = 404
return response
task = dag.get_task(task_id)
try:
url = task.get_extra_links(dttm, link_name)
except ValueError as err:
response = jsonify({'url': None, 'error': str(err)})
response.status_code = 404
return response
if url:
response = jsonify({'error': None, 'url': url})
response.status_code = 200
return response
else:
response = jsonify(
{'url': None, 'error': 'No URL found for {dest}'.format(dest=link_name)})
response.status_code = 404
return response
@expose('/object/task_instances')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def task_instances(self, session=None):
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
dttm = request.args.get('execution_date')
if dttm:
dttm = timezone.parse(dttm)
else:
return "Error: Invalid execution_date"
task_instances = {
ti.task_id: alchemy_to_dict(ti)
for ti in dag.get_task_instances(dttm, dttm)}
return json.dumps(task_instances)
class VersionView(AirflowBaseView):
default_view = 'version'
@expose('/version')
@has_access
def version(self):
try:
airflow_version = airflow.__version__
except Exception as e:
airflow_version = None
logging.error(e)
# Get the Git repo and git hash
git_version = None
try:
git_version = str(pkgutil.get_data('airflow', 'git_version'), encoding="UTF-8")
except Exception as e:
logging.error(e)
# Render information
title = "Version Info"
return self.render_template(
'airflow/version.html',
title=title,
airflow_version=airflow_version,
git_version=git_version)
class ConfigurationView(AirflowBaseView):
default_view = 'conf'
@expose('/configuration')
@has_access
def conf(self):
raw = request.args.get('raw') == "true"
title = "Airflow Configuration"
subtitle = AIRFLOW_CONFIG
# Don't show config when expose_config variable is False in airflow config
if conf.getboolean("webserver", "expose_config"):
with open(AIRFLOW_CONFIG, 'r') as file:
config = file.read()
table = [(section, key, value, source)
for section, parameters in conf.as_dict(True, True).items()
for key, (value, source) in parameters.items()]
else:
config = (
"# Your Airflow administrator chose not to expose the "
"configuration, most likely for security reasons.")
table = None
if raw:
return Response(
response=config,
status=200,
mimetype="application/text")
else:
code_html = Markup(highlight(
config,
lexers.IniLexer(), # Lexer call
HtmlFormatter(noclasses=True))
)
return self.render_template(
'airflow/config.html',
pre_subtitle=settings.HEADER + " v" + airflow.__version__,
code_html=code_html, title=title, subtitle=subtitle,
table=table)
######################################################################################
# ModelViews
######################################################################################
class DagFilter(BaseFilter):
def apply(self, query, func): # noqa
if appbuilder.sm.has_all_dags_access():
return query
filter_dag_ids = appbuilder.sm.get_accessible_dag_ids()
return query.filter(self.model.dag_id.in_(filter_dag_ids))
class AirflowModelView(ModelView):
list_widget = AirflowModelListWidget
page_size = PAGE_SIZE
CustomSQLAInterface = wwwutils.CustomSQLAInterface
class SlaMissModelView(AirflowModelView):
route_base = '/slamiss'
datamodel = AirflowModelView.CustomSQLAInterface(SlaMiss)
base_permissions = ['can_list']
list_columns = ['dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp']
add_columns = ['dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp']
edit_columns = ['dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp']
search_columns = ['dag_id', 'task_id', 'email_sent', 'timestamp', 'execution_date']
base_order = ('execution_date', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
formatters_columns = {
'task_id': wwwutils.task_instance_link,
'execution_date': wwwutils.datetime_f('execution_date'),
'timestamp': wwwutils.datetime_f('timestamp'),
'dag_id': wwwutils.dag_link,
}
class XComModelView(AirflowModelView):
route_base = '/xcom'
datamodel = AirflowModelView.CustomSQLAInterface(XCom)
base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete']
search_columns = ['key', 'value', 'timestamp', 'execution_date', 'task_id', 'dag_id']
list_columns = ['key', 'value', 'timestamp', 'execution_date', 'task_id', 'dag_id']
add_columns = ['key', 'value', 'execution_date', 'task_id', 'dag_id']
edit_columns = ['key', 'value', 'execution_date', 'task_id', 'dag_id']
base_order = ('execution_date', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
formatters_columns = {
'task_id': wwwutils.task_instance_link,
'execution_date': wwwutils.datetime_f('execution_date'),
'timestamp': wwwutils.datetime_f('timestamp'),
'dag_id': wwwutils.dag_link,
}
@action('muldelete', 'Delete', "Are you sure you want to delete selected records?",
single=False)
def action_muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
def pre_add(self, item):
item.execution_date = timezone.make_aware(item.execution_date)
item.value = XCom.serialize_value(item.value)
def pre_update(self, item):
item.execution_date = timezone.make_aware(item.execution_date)
item.value = XCom.serialize_value(item.value)
class ConnectionModelView(AirflowModelView):
route_base = '/connection'
datamodel = AirflowModelView.CustomSQLAInterface(Connection)
base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete']
extra_fields = ['extra__jdbc__drv_path', 'extra__jdbc__drv_clsname',
'extra__google_cloud_platform__project',
'extra__google_cloud_platform__key_path',
'extra__google_cloud_platform__keyfile_dict',
'extra__google_cloud_platform__scope',
'extra__google_cloud_platform__num_retries',
'extra__grpc__auth_type',
'extra__grpc__credential_pem_file',
'extra__grpc__scopes',
'extra__yandexcloud__service_account_json',
'extra__yandexcloud__service_account_json_path',
'extra__yandexcloud__oauth',
'extra__yandexcloud__public_ssh_key',
'extra__yandexcloud__folder_id',
'extra__kubernetes__in_cluster',
'extra__kubernetes__kube_config',
'extra__kubernetes__namespace']
list_columns = ['conn_id', 'conn_type', 'host', 'port', 'is_encrypted',
'is_extra_encrypted']
add_columns = edit_columns = ['conn_id', 'conn_type', 'host', 'schema',
'login', 'password', 'port', 'extra'] + extra_fields
add_form = edit_form = ConnectionForm
add_template = 'airflow/conn_create.html'
edit_template = 'airflow/conn_edit.html'
base_order = ('conn_id', 'asc')
@action('muldelete', 'Delete', 'Are you sure you want to delete selected records?',
single=False)
@has_dag_access(can_dag_edit=True)
def action_muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
def process_form(self, form, is_created):
formdata = form.data
if formdata['conn_type'] in ['jdbc', 'google_cloud_platform', 'grpc', 'yandexcloud', 'kubernetes']:
extra = {
key: formdata[key]
for key in self.extra_fields if key in formdata}
form.extra.data = json.dumps(extra)
def prefill_form(self, form, pk):
try:
d = json.loads(form.data.get('extra', '{}'))
except Exception:
d = {}
if not hasattr(d, 'get'):
logging.warning('extra field for {} is not iterable'.format(
form.data.get('conn_id', '<unknown>')))
return
for field in self.extra_fields:
value = d.get(field, '')
if value:
field = getattr(form, field)
field.data = value
class PoolModelView(AirflowModelView):
route_base = '/pool'
datamodel = AirflowModelView.CustomSQLAInterface(models.Pool)
base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete']
list_columns = ['pool', 'slots', 'used_slots', 'queued_slots']
add_columns = ['pool', 'slots', 'description']
edit_columns = ['pool', 'slots', 'description']
base_order = ('pool', 'asc')
@action('muldelete', 'Delete', 'Are you sure you want to delete selected records?',
single=False)
def action_muldelete(self, items):
if any(item.pool == models.Pool.DEFAULT_POOL_NAME for item in items):
flash("default_pool cannot be deleted", 'error')
self.update_redirect()
return redirect(self.get_redirect())
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
def pool_link(attr):
pool_id = attr.get('pool')
if pool_id is not None:
url = url_for('TaskInstanceModelView.list', _flt_3_pool=pool_id)
return Markup("<a href='{url}'>{pool_id}</a>").format(url=url, pool_id=pool_id)
else:
return Markup('<span class="label label-danger">Invalid</span>')
def fused_slots(attr):
pool_id = attr.get('pool')
used_slots = attr.get('used_slots')
if pool_id is not None and used_slots is not None:
url = url_for('TaskInstanceModelView.list', _flt_3_pool=pool_id, _flt_3_state='running')
return Markup("<a href='{url}'>{used_slots}</a>").format(url=url, used_slots=used_slots)
else:
return Markup('<span class="label label-danger">Invalid</span>')
def fqueued_slots(attr):
pool_id = attr.get('pool')
queued_slots = attr.get('queued_slots')
if pool_id is not None and queued_slots is not None:
url = url_for('TaskInstanceModelView.list', _flt_3_pool=pool_id, _flt_3_state='queued')
return Markup("<a href='{url}'>{queued_slots}</a>").format(url=url, queued_slots=queued_slots)
else:
return Markup('<span class="label label-danger">Invalid</span>')
formatters_columns = {
'pool': pool_link,
'used_slots': fused_slots,
'queued_slots': fqueued_slots
}
validators_columns = {
'pool': [validators.DataRequired()],
'slots': [validators.NumberRange(min=-1)]
}
class VariableModelView(AirflowModelView):
route_base = '/variable'
list_template = 'airflow/variable_list.html'
edit_template = 'airflow/variable_edit.html'
datamodel = AirflowModelView.CustomSQLAInterface(models.Variable)
base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete', 'can_varimport']
list_columns = ['key', 'val', 'is_encrypted']
add_columns = ['key', 'val']
edit_columns = ['key', 'val']
search_columns = ['key', 'val']
base_order = ('key', 'asc')
def hidden_field_formatter(attr):
key = attr.get('key')
val = attr.get('val')
if wwwutils.should_hide_value_for_key(key):
return Markup('*' * 8)
if val:
return val
else:
return Markup('<span class="label label-danger">Invalid</span>')
formatters_columns = {
'val': hidden_field_formatter,
}
validators_columns = {
'key': [validators.DataRequired()]
}
def prefill_form(self, form, id):
if wwwutils.should_hide_value_for_key(form.key.data):
form.val.data = '*' * 8
@action('muldelete', 'Delete', 'Are you sure you want to delete selected records?',
single=False)
def action_muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
@action('varexport', 'Export', '', single=False)
def action_varexport(self, items):
var_dict = {}
d = json.JSONDecoder()
for var in items:
try:
val = d.decode(var.val)
except Exception:
val = var.val
var_dict[var.key] = val
response = make_response(json.dumps(var_dict, sort_keys=True, indent=4))
response.headers["Content-Disposition"] = "attachment; filename=variables.json"
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response
@expose('/varimport', methods=["POST"])
@has_access
@action_logging
def varimport(self):
try:
out = request.files['file'].read()
if isinstance(out, bytes):
d = json.loads(out.decode('utf-8'))
else:
d = json.loads(out)
except Exception:
self.update_redirect()
flash("Missing file or syntax error.", 'error')
return redirect(self.get_redirect())
else:
suc_count = fail_count = 0
for k, v in d.items():
try:
models.Variable.set(k, v, serialize_json=not isinstance(v, str))
except Exception as e:
logging.info('Variable import failed: {}'.format(repr(e)))
fail_count += 1
else:
suc_count += 1
flash("{} variable(s) successfully updated.".format(suc_count))
if fail_count:
flash("{} variable(s) failed to be updated.".format(fail_count), 'error')
self.update_redirect()
return redirect(self.get_redirect())
class JobModelView(AirflowModelView):
route_base = '/job'
datamodel = AirflowModelView.CustomSQLAInterface(BaseJob)
base_permissions = ['can_list']
list_columns = ['id', 'dag_id', 'state', 'job_type', 'start_date',
'end_date', 'latest_heartbeat',
'executor_class', 'hostname', 'unixname']
search_columns = ['id', 'dag_id', 'state', 'job_type', 'start_date',
'end_date', 'latest_heartbeat', 'executor_class',
'hostname', 'unixname']
base_order = ('start_date', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
formatters_columns = {
'start_date': wwwutils.datetime_f('start_date'),
'end_date': wwwutils.datetime_f('end_date'),
'hostname': wwwutils.nobr_f('hostname'),
'state': wwwutils.state_f,
'latest_heartbeat': wwwutils.datetime_f('latest_heartbeat'),
}
class DagRunModelView(AirflowModelView):
route_base = '/dagrun'
datamodel = AirflowModelView.CustomSQLAInterface(models.DagRun)
base_permissions = ['can_list', 'can_add']
add_columns = ['state', 'dag_id', 'execution_date', 'run_id', 'external_trigger', 'conf']
list_columns = ['state', 'dag_id', 'execution_date', 'run_id', 'external_trigger']
search_columns = ['state', 'dag_id', 'execution_date', 'run_id', 'external_trigger']
base_order = ('execution_date', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
add_form = edit_form = DagRunForm
formatters_columns = {
'execution_date': wwwutils.datetime_f('execution_date'),
'state': wwwutils.state_f,
'start_date': wwwutils.datetime_f('start_date'),
'dag_id': wwwutils.dag_link,
'run_id': wwwutils.dag_run_link,
}
@action('muldelete', "Delete", "Are you sure you want to delete selected records?",
single=False)
@has_dag_access(can_dag_edit=True)
@provide_session
def action_muldelete(self, items, session=None):
self.datamodel.delete_all(items)
self.update_redirect()
dirty_ids = []
for item in items:
dirty_ids.append(item.dag_id)
return redirect(self.get_redirect())
@action('set_running', "Set state to 'running'", '', single=False)
@provide_session
def action_set_running(self, drs, session=None):
try:
DR = models.DagRun
count = 0
dirty_ids = []
for dr in session.query(DR).filter(
DR.id.in_([dagrun.id for dagrun in drs])).all():
dirty_ids.append(dr.dag_id)
count += 1
dr.start_date = timezone.utcnow()
dr.state = State.RUNNING
session.commit()
flash("{count} dag runs were set to running".format(count=count))
except Exception as ex:
flash(str(ex), 'error')
flash('Failed to set state', 'error')
return redirect(self.get_default_url())
@action('set_failed', "Set state to 'failed'",
"All running task instances would also be marked as failed, are you sure?",
single=False)
@provide_session
def action_set_failed(self, drs, session=None):
try:
DR = models.DagRun
count = 0
dirty_ids = []
altered_tis = []
for dr in session.query(DR).filter(
DR.id.in_([dagrun.id for dagrun in drs])).all():
dirty_ids.append(dr.dag_id)
count += 1
altered_tis += \
set_dag_run_state_to_failed(dagbag.get_dag(dr.dag_id),
dr.execution_date,
commit=True,
session=session)
altered_ti_count = len(altered_tis)
flash(
"{count} dag runs and {altered_ti_count} task instances "
"were set to failed".format(count=count, altered_ti_count=altered_ti_count))
except Exception:
flash('Failed to set state', 'error')
return redirect(self.get_default_url())
@action('set_success', "Set state to 'success'",
"All task instances would also be marked as success, are you sure?",
single=False)
@provide_session
def action_set_success(self, drs, session=None):
try:
DR = models.DagRun
count = 0
dirty_ids = []
altered_tis = []
for dr in session.query(DR).filter(
DR.id.in_([dagrun.id for dagrun in drs])).all():
dirty_ids.append(dr.dag_id)
count += 1
altered_tis += \
set_dag_run_state_to_success(dagbag.get_dag(dr.dag_id),
dr.execution_date,
commit=True,
session=session)
altered_ti_count = len(altered_tis)
flash(
"{count} dag runs and {altered_ti_count} task instances "
"were set to success".format(count=count, altered_ti_count=altered_ti_count))
except Exception:
flash('Failed to set state', 'error')
return redirect(self.get_default_url())
class LogModelView(AirflowModelView):
route_base = '/log'
datamodel = AirflowModelView.CustomSQLAInterface(Log)
base_permissions = ['can_list']
list_columns = ['id', 'dttm', 'dag_id', 'task_id', 'event', 'execution_date',
'owner', 'extra']
search_columns = ['dag_id', 'task_id', 'event', 'execution_date', 'owner', 'extra']
base_order = ('dttm', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
formatters_columns = {
'dttm': wwwutils.datetime_f('dttm'),
'execution_date': wwwutils.datetime_f('execution_date'),
'dag_id': wwwutils.dag_link,
}
class TaskInstanceModelView(AirflowModelView):
route_base = '/taskinstance'
datamodel = AirflowModelView.CustomSQLAInterface(models.TaskInstance)
base_permissions = ['can_list']
page_size = PAGE_SIZE
list_columns = ['state', 'dag_id', 'task_id', 'execution_date', 'operator',
'start_date', 'end_date', 'duration', 'job_id', 'hostname',
'unixname', 'priority_weight', 'queue', 'queued_dttm', 'try_number',
'pool', 'log_url']
search_columns = ['state', 'dag_id', 'task_id', 'execution_date', 'hostname',
'queue', 'pool', 'operator', 'start_date', 'end_date']
base_order = ('job_id', 'asc')
base_filters = [['dag_id', DagFilter, lambda: []]]
def log_url_formatter(attr):
log_url = attr.get('log_url')
return Markup(
'<a href="{log_url}">'
' <span class="glyphicon glyphicon-book" aria-hidden="true">'
'</span></a>').format(log_url=log_url)
def duration_f(attr):
end_date = attr.get('end_date')
duration = attr.get('duration')
if end_date and duration:
return timedelta(seconds=duration)
formatters_columns = {
'log_url': log_url_formatter,
'task_id': wwwutils.task_instance_link,
'hostname': wwwutils.nobr_f('hostname'),
'state': wwwutils.state_f,
'execution_date': wwwutils.datetime_f('execution_date'),
'start_date': wwwutils.datetime_f('start_date'),
'end_date': wwwutils.datetime_f('end_date'),
'queued_dttm': wwwutils.datetime_f('queued_dttm'),
'dag_id': wwwutils.dag_link,
'duration': duration_f,
}
@provide_session
@action('clear', lazy_gettext('Clear'),
lazy_gettext('Are you sure you want to clear the state of the selected task'
' instance(s) and set their dagruns to the running state?'),
single=False)
def action_clear(self, tis, session=None):
try:
dag_to_tis = {}
for ti in tis:
dag = dagbag.get_dag(ti.dag_id)
tis = dag_to_tis.setdefault(dag, [])
tis.append(ti)
for dag, tis in dag_to_tis.items():
models.clear_task_instances(tis, session, dag=dag)
session.commit()
flash("{0} task instances have been cleared".format(len(tis)))
self.update_redirect()
return redirect(self.get_redirect())
except Exception:
flash('Failed to clear task instances', 'error')
@provide_session
def set_task_instance_state(self, tis, target_state, session=None):
try:
count = len(tis)
for ti in tis:
ti.set_state(target_state, session)
session.commit()
flash("{count} task instances were set to '{target_state}'".format(
count=count, target_state=target_state))
except Exception:
flash('Failed to set state', 'error')
@action('set_running', "Set state to 'running'", '', single=False)
@has_dag_access(can_dag_edit=True)
def action_set_running(self, tis):
self.set_task_instance_state(tis, State.RUNNING)
self.update_redirect()
return redirect(self.get_redirect())
@action('set_failed', "Set state to 'failed'", '', single=False)
@has_dag_access(can_dag_edit=True)
def action_set_failed(self, tis):
self.set_task_instance_state(tis, State.FAILED)
self.update_redirect()
return redirect(self.get_redirect())
@action('set_success', "Set state to 'success'", '', single=False)
@has_dag_access(can_dag_edit=True)
def action_set_success(self, tis):
self.set_task_instance_state(tis, State.SUCCESS)
self.update_redirect()
return redirect(self.get_redirect())
@action('set_retry', "Set state to 'up_for_retry'", '', single=False)
@has_dag_access(can_dag_edit=True)
def action_set_retry(self, tis):
self.set_task_instance_state(tis, State.UP_FOR_RETRY)
self.update_redirect()
return redirect(self.get_redirect())
class DagModelView(AirflowModelView):
route_base = '/dagmodel'
datamodel = AirflowModelView.CustomSQLAInterface(models.DagModel)
base_permissions = ['can_list', 'can_show']
list_columns = ['dag_id', 'is_paused', 'last_scheduler_run',
'last_expired', 'scheduler_lock', 'fileloc', 'owners']
formatters_columns = {
'dag_id': wwwutils.dag_link
}
base_filters = [['dag_id', DagFilter, lambda: []]]
def get_query(self):
"""
Default filters for model
"""
return (
super().get_query()
.filter(or_(models.DagModel.is_active,
models.DagModel.is_paused))
.filter(~models.DagModel.is_subdag)
)
def get_count_query(self):
"""
Default filters for model
"""
return (
super().get_count_query()
.filter(models.DagModel.is_active)
.filter(~models.DagModel.is_subdag)
)
@has_access
@permission_name("list")
@provide_session
@expose('/autocomplete')
def autocomplete(self, session=None):
query = unquote(request.args.get('query', ''))
if not query:
wwwutils.json_response([])
# Provide suggestions of dag_ids and owners
dag_ids_query = session.query(DagModel.dag_id.label('item')).filter(
~DagModel.is_subdag, DagModel.is_active,
DagModel.dag_id.ilike('%' + query + '%'))
owners_query = session.query(func.distinct(DagModel.owners).label('item')).filter(
~DagModel.is_subdag, DagModel.is_active,
DagModel.owners.ilike('%' + query + '%'))
# Hide paused dags
if request.args.get('showPaused', 'True').lower() == 'false':
dag_ids_query = dag_ids_query.filter(~DagModel.is_paused)
owners_query = owners_query.filter(~DagModel.is_paused)
filter_dag_ids = appbuilder.sm.get_accessible_dag_ids()
if 'all_dags' not in filter_dag_ids:
dag_ids_query = dag_ids_query.filter(DagModel.dag_id.in_(filter_dag_ids))
owners_query = owners_query.filter(DagModel.dag_id.in_(filter_dag_ids))
payload = [row[0] for row in dag_ids_query.union(owners_query).limit(10).all()]
return wwwutils.json_response(payload)
|
import { ORGANISATION } from '../constants/actions';
export function getAllOrganisations() {
return { type: ORGANISATION.GET_ALL_ORGANISATIONS };
}
export function updateOrganisationData(organisations) {
return {
type: ORGANISATION.UPDATE_ORGANISATION_DATA,
payload: { organisations },
};
}
|
exports.id=0,exports.modules={5:function(e,t,a){"use strict";a.r(t);var n=a(0),r=a.n(n),s=a(2),l=a.n(s),i=a(3),o=a(1);function c(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}process.env.ELECTRON_DISABLE_SECURITY_WARNINGS="true";class d extends r.a.Component{constructor(e){super(e),c(this,"componentDidMount",()=>{this.setState({loading:!1});new(a(4).verbose().Database)("eotdb.sqlite")}),c(this,"_handleClick",()=>{var e=i.ipcRenderer.sendSync("get-result",{name:"react"});alert(e)}),this.showAlert=this.showAlert.bind(this),this.state={text:""}}showAlert(){alert("Hello world!")}render(){return r.a.createElement("div",{className:"App"},r.a.createElement(o.View,{style:{padding:10}},r.a.createElement(o.TextInput,{style:{height:40,width:"10vh"},placeholder:"Type here to translate!",onChangeText:e=>this.setState({text:e}),value:this.state.text}),r.a.createElement(o.Text,{style:{padding:10,fontSize:42}},this.state.text.split(" ").map(e=>e&&"🍕").join(" "))),r.a.createElement("header",{className:"App-header"},r.a.createElement("button",{onClick:this.showAlert},"Click me!")))}}var h=d;process.env.ELECTRON_DISABLE_SECURITY_WARNINGS="true",l.a.render(r.a.createElement("div",null,r.a.createElement(h,null)),document.getElementById("app")),e.hot.accept()}};
//# sourceMappingURL=0.3ae5c331cbb15becde3a.hot-update.js.map
|
import json
from django.urls import reverse
from farms.factories import AddressFactory
from farms.views import AddressDetailView
import postalcodes_mexico
import pytest
class TestAddressViews:
def test_detail_view(self, client, mocker):
"""Unit test for address detail view."""
# GIVEN an address
address = AddressFactory.build()
mocker.patch.object(AddressDetailView, 'get_object', return_value=address)
# WHEN requesting the DetailView
url = reverse('farms:address_detail', kwargs={'pk': 1234})
response = client.get(url)
# THEN there is all the info we want
content = response.content.decode()
assert response.status_code == 200
assert address.street in content
assert address.postal_code in content
assert address.city in content
def test_create_view_GET_request(self, client):
# GIVEN any state
# WHEN requesting the create view for an address
url = reverse('farms:address_create')
response = client.get(url)
# THEN there is a form and stuff
assert response.status_code == 200
@pytest.mark.django_db
def test_create_view_POST_request(self, client, mocker):
# GIVEN any state
# WHEN requesting the create view for an address
url = reverse('farms:address_create')
data = {
'street': 'Bajío 296',
'postal_code': '06760',
'place': 'Roma Sur',
'municipality': 'Alvaro Obregon',
'city': 'Mérida',
'state': 'Jalisco',
}
response = client.post(url, data=data)
# THEN there is a form and stuff
assert response.status_code == 302
def test_get_places_view(client):
# GIVEN a Mexican postal code with one correcponding place
postal_code = '01030'
places = postalcodes_mexico.places(postal_code)
place = places[0]
# WHEN requesting the get_places view
url = reverse('farms:address_get_places')
response = client.get(url, {'postal_code': postal_code})
data_json = response.content.decode()
my_place = json.loads(data_json)
# THEN the response contains a dictionary with all the places info
assert type(my_place) == dict
assert my_place.get('number_of_places') > 0
assert my_place.get('city') == place.city
assert my_place.get('municipality') == place.municipality
assert my_place.get('state') == place.state
|
import React from 'react';
import { render } from 'react-dom';
import { Components } from 'DocComponents';
import { Pages } from 'DocPages';
import { Row, Col, Button, Loading, H1 } from 'Components';
const Containers = []; //precisa ser feito ainda
let Routes = {
Pages,
Components,
Containers
}
class Index extends React.Component {
constructor(props) {
super(props);
//componente que o usuario clicou no menu vai ser chamado
//de acordo com o objeto pego do Components
let InitialComponent = Routes.Pages.Texts;
this.state = {
currentComponent: <InitialComponent handleButtonMenu={() => this.handleButtonMenu}/>
}
}
_setCurrentComponent = (Component) => {
if (!Component) {
this._setPanelRightAsLoading(false);
return;
}
this.setState({
currentComponent: <Component handleButtonMenu={() => this.handleButtonMenu}/>,
panelRightIsLoading: false
});
}
_setPanelRightAsLoading = (loading) => {
return new Promise((resolve, reject) => {
this.setState({
panelRightIsLoading: loading
}, () => {
if (this.state.panelRightIsLoading === loading)
resolve(true)
else
resolve(false)
});
});
}
handleButtonMenu = (event) => {
this._setPanelRightAsLoading(true);
let clickedEl = event.currentTarget;
// if (!clickedEl) return;
let raw = clickedEl.getAttribute('data-component');
let arr = raw.split('/');
let type = arr[0];
let component = arr[1];
this._setCurrentComponent(Routes[type][component]);
}
renderPanelRight = () => {
let loading = this.state.panelRightIsLoading;
if (loading)
return <Loading/>
else
return this.state.currentComponent
}
render() {
return(
<Row defaultAlign="left" style={{height: '100%'}}>
<Col s={3} m={3} l={3} className={'panel-left'}>
<H1>General Components</H1>
<button className={'btn'} onClick={this.handleButtonMenu} data-component={"Pages/Grids"}>Grids</button>
<button className={'btn'} onClick={this.handleButtonMenu} data-component={"Pages/Forms"}>Forms</button>
<button className={'btn'} onClick={this.handleButtonMenu} data-component={"Pages/Texts"}>Texts</button>
<H1>Containers</H1>
</Col>
<Col s={9} m={9} l={9} className={"panel-right"}>
{ this.renderPanelRight() }
</Col>
</Row>
);
}
}
render(<Index/>, document.querySelector('.root'));
|
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]';
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var Symbol = root.Symbol,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array ? array.length : 0;
return length ? baseFlatten(array, 1) : [];
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `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;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = flatten;
|
import sys
import os
import nltk
import spacy
import gensim
import sklearn
import keras
import pandas as pd
import numpy as np
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer, SnowballStemmer
from nltk.stem.porter import *
nltk.download('wordnet')
nltk.download('stopwords')
from gensim.parsing.preprocessing import STOPWORDS
from gensim.utils import simple_preprocess
from gensim import corpora, models
from keras.preprocessing.text import text_to_word_sequence
from sklearn.feature_extraction import stop_words
# define stopwords
def add_words(filename):
with open(filename) as f:
additional_words = f.readlines()
additional_words = [x.strip() for x in additional_words]
return additional_words
def remove_words(filename):
with open(filename) as f:
unstop = f.readlines()
unstop = [x.strip() for x in unstop]
return unstop
def define_stopwords():
"""
default: combine SKLEARN, NLTK, and SPACY stopwords -> 'sns_set'
alternative: set custom 'additional_words' and 'unstop' words (to ignore)
function returns a list: 'stopwords'
"""
# corpus-specific stop words [OPTIONAL]
# add 'stop.txt' to local directory, pass as argument 2
additional_words = ['nan']
# don't remove these words which may be important in our context [OPTIONAL]
# add 'unstop.txt' to local directory, pass as argument 3
unstop = []
gen_stop = gensim.parsing.preprocessing.STOPWORDS
nlp = spacy.load('en')
spacy_stop = nlp.Defaults.stop_words # .add("my_new_stopword")
sk_stop = stop_words.ENGLISH_STOP_WORDS
nltk_stop = stopwords.words('english')
custom_stop = additional_words
sns_stop = []
all_stop = []
# combine sklearn, nltk, and spacy stop word lists: sns_stop
# also add these to all_stop
for i in gen_stop:
if i not in unstop:
sns_stop.append(i)
all_stop.append(i)
for i in spacy_stop:
if i not in unstop:
sns_stop.append(i)
all_stop.append(i)
for i in sk_stop:
if i not in unstop:
sns_stop.append(i)
all_stop.append(i)
for i in nltk_stop:
if i not in unstop:
sns_stop.append(i)
all_stop.append(i)
# add corpus specific stop words to all_stop
for i in custom_stop:
if i not in unstop:
if i not in all_stop:
all_stop.append(i)
sns_set = list(set(sns_stop))
all_set = list(set(all_stop))
if len(custom_stop) == 0 and len(unstop) == 0:
# print(f'sns_set stopwords = {len(sns_set)} words: \nExamples: \n{[x for x in sns_set[0:10]]}\n{[x for x in sns_set[10:20]]}')
my_stopwords = sns_set
else:
# print(f'all_set (custom) stopwords = {len(all_set)} words: \nExamples: \n{[x for x in all_set[0:10]]}\n{[x for x in all_set[10:20]]}')
my_stopwords = all_set
return my_stopwords
# preprocessing functions
stemmer = PorterStemmer()
def lemmatize_stemming(text):
return stemmer.stem(WordNetLemmatizer().lemmatize(text, pos='v'))
def preprocess(text):
result = []
for token in gensim.utils.simple_preprocess(text):
if token not in my_stopwords and len(token) > 2:
result.append(lemmatize_stemming(token))
return result
def word_split(doc):
words = []
for word in doc.split(' '):
words.append(word)
return words
# Infer Topic Probability Distribution of New Document
def infer_topic(new_doc):
print("(1) Performing preprocessing...")
pre_new = preprocess(new_doc) # remove stop-words, lemmatize, and stem
print(f'{pre_new[0:5]} ...')
print("(2) Building term-frequency dictionary...")
dict_new = dictionary.doc2bow(pre_new) # build term-frequency dictionary
first_five = [f'{dict_new[i][0]}: \"{dictionary[dict_new[i][0]]}\"*{dict_new[i][1]}' for i in range(len(dict_new[0:5]))]
print(f'{[x for x in first_five]}')
print("(3) Inferring topic distribution...")
vector = model[dict_new] # get topic probability distribution for new_doc
print("\nTopic Probability Distribution:")
print(vector)
if __name__ == '__main__':
filepath = str(sys.argv[1]) # path to saved tf-lda* files, stop.txt, unstop.txt
new_doc = str(sys.argv[2])
filename_model = filepath + '/' + 'tf-lda.model'
filename_dict = filepath + '/' + 'tf-lda.dict'
filename_stop = filepath + '/' + 'stop.txt'
filename_unstop = filepath + '/' + 'unstop.txt'
print(f'\nLoading model files and stopwords...')
my_stopwords = define_stopwords()
new_words = add_words(filename_stop)
new_unstop = remove_words(filename_unstop)
for i in new_words:
my_stopwords.append(i)
my_stopwords = [w for w in my_stopwords if w not in new_unstop]
my_stopwords = list(set(my_stopwords))
print(f'Loaded {len(my_stopwords)} stopwords.\n')
model = gensim.models.LdaModel.load(filename_model)
dictionary = corpora.Dictionary.load(filename_dict)
# print all topics
for i in range(0, model.num_topics):
print(f'Topic #{i}: {model.print_topic(i)}')
print(f'\nPerforming inference on new document...')
infer_topic(new_doc)
|
"""MIT License
Copyright (c) 2019-2021 PythonistaGuild
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import contextlib
import datetime
import logging
from typing import Any, Dict, Union, Optional
import disnake as discord
from disnake.channel import VoiceChannel
from . import abc
from .pool import Node, NodePool
from .queue import WaitQueue
from .tracks import PartialTrack
from .utils import MISSING
__all__ = ("Player",)
logger: logging.Logger = logging.getLogger(__name__)
VoiceChannel = Union[
discord.VoiceChannel, discord.StageChannel
] # todo: VocalGuildChannel?
class Player(discord.VoiceProtocol):
"""WaveLink Player object.
This class subclasses :class:`discord.VoiceProtocol` and such should be treated as one with additions.
Examples
--------
.. code::
@commands.command()
async def connect(self, channel: discord.VoiceChannel):
voice_client = await channel.connect(cls=wavelink.Player)
.. warning::
This class should not be created manually but can be subclassed to add additional functionality.
You should instead use :meth:`discord.VoiceChannel.connect()` and pass the player object to the cls kwarg.
"""
def __call__(self, client: discord.Client, channel: VoiceChannel):
self.client: discord.Client = client
self.channel: VoiceChannel = channel
return self
def __init__(
self,
client: discord.Client = MISSING,
channel: VoiceChannel = MISSING,
*,
node: Node = MISSING,
):
self.client: discord.Client = client
self.channel: VoiceChannel = channel
if node is MISSING:
node = NodePool.get_node()
self.node: Node = node
self.node._players.append(self)
self._voice_state: Dict[str, Any] = {}
self.last_update: datetime.datetime = MISSING
self.last_position: float = MISSING
self.volume: float = 100
self._paused: bool = False
self._source: Optional[abc.Playable] = None
# self._equalizer = Equalizer.flat()
self.queue = WaitQueue()
@property
def guild(self) -> discord.Guild:
"""The :class:`discord.Guild` this :class:`Player` is in."""
return self.channel.guild
@property
def user(self) -> discord.ClientUser:
"""The :class:`discord.ClientUser` of the :class:`discord.Client`"""
return self.client.user # type: ignore
@property
def source(self) -> Optional[abc.Playable]:
"""The currently playing audio source."""
return self._source
track = source
@property
def position(self) -> float:
"""The current seek position of the playing source in seconds. If nothing is playing this defaults to ``0``."""
if not self.is_playing():
return 0
if self.is_paused():
return min(self.last_position, self.source.duration) # type: ignore
delta = (
datetime.datetime.now(datetime.timezone.utc) - self.last_update
).total_seconds()
position = round(self.last_position + delta, 1)
return min(position, self.source.duration) # type: ignore
async def update_state(self, state: Dict[str, Any]) -> None:
state = state["state"]
self.last_update = datetime.datetime.fromtimestamp(
state.get("time", 0) / 1000, datetime.timezone.utc
)
self.last_position = round(state.get("position", 0) / 1000, 1)
async def on_voice_server_update(self, data: Dict[str, Any]) -> None:
self._voice_state.update({"event": data})
await self._dispatch_voice_update(self._voice_state)
async def on_voice_state_update(self, data: Dict[str, Any]) -> None:
self._voice_state.update({"sessionId": data["session_id"]})
channel_id = data["channel_id"]
if not channel_id: # We're disconnecting
self._voice_state.clear()
return
self.channel = self.guild.get_channel(int(channel_id)) # type: ignore
await self._dispatch_voice_update({**self._voice_state, "event": data})
async def _dispatch_voice_update(self, voice_state: Dict[str, Any]) -> None:
logger.debug(f"Dispatching voice update:: {self.channel.id}")
if {"sessionId", "event"} == self._voice_state.keys():
await self.node._websocket.send(
op="voiceUpdate", guildId=str(self.guild.id), **voice_state
)
async def connect(self, *, timeout: float, reconnect: bool) -> None:
await self.guild.change_voice_state(channel=self.channel)
self._connected = True
logger.info(f"Connected to voice channel:: {self.channel.id}")
async def disconnect(self, *, force: bool = False) -> None:
try:
logger.info(f"Disconnected from voice channel:: {self.channel.id}")
await self.guild.change_voice_state(channel=None)
self._connected = False
finally:
with contextlib.suppress(ValueError):
self.node._players.remove(self)
self.cleanup()
async def move_to(self, channel: discord.VoiceChannel) -> None:
"""|coro|
Moves the player to a different voice channel.
Parameters
-----------
channel: :class:`discord.VoiceChannel`
The channel to move to. Must be a voice channel.
"""
await self.guild.change_voice_state(channel=channel)
logger.info(f"Moving to voice channel:: {channel.id}")
async def play(
self, source: abc.Playable, replace: bool = True, start: int = 0, end: int = 0
):
"""|coro|
Play a WaveLink Track.
Parameters
----------
source: :class:`abc.Playable`
The :class:`abc.Playable` to initiate playing.
replace: bool
Whether or not the current track, if there is one, should be replaced or not. Defaults to ``True``.
start: int
The position to start the player from in milliseconds. Defaults to ``0``.
end: int
The position to end the track on in milliseconds.
By default this always allows the current song to finish playing.
Returns
-------
:class:`wavelink.abc.Playable`
The track that is now playing.
"""
if replace or not self.is_playing():
await self.update_state({"state": {}})
self._paused = False
else:
return
if isinstance(source, PartialTrack):
source = await source._search()
self._source = source
payload = {
"op": "play",
"guildId": str(self.guild.id),
"track": source.id,
"noReplace": not replace,
"startTime": str(start),
}
if end > 0:
payload["endTime"] = str(end)
await self.node._websocket.send(**payload)
logger.debug(f"Started playing track:: {str(source)} ({self.channel.id})")
return source
def is_connected(self) -> bool:
"""Indicates whether the player is connected to voice."""
return self._connected
def is_playing(self) -> bool:
"""Indicates wether a track is currently being played."""
return self.is_connected() and self._source is not None
def is_paused(self) -> bool:
"""Indicates wether the currently playing track is paused."""
return self._paused
async def stop(self) -> None:
"""|coro|
Stop the Player's currently playing song.
"""
await self.node._websocket.send(op="stop", guildId=str(self.guild.id))
logger.debug(f"Current track stopped:: {str(self.source)} ({self.channel.id})")
self._source = None
async def set_pause(self, pause: bool) -> None:
"""|coro|
Set the players paused state.
Parameters
----------
pause: bool
A bool indicating if the player's paused state should be set to True or False.
"""
await self.node._websocket.send(
op="pause", guildId=str(self.guild.id), pause=pause
)
self._paused = pause
logger.info(f"Set pause:: {self._paused} ({self.channel.id})")
async def pause(self) -> None:
"""|coro|
Pauses the player if it was playing.
"""
await self.set_pause(True)
async def resume(self) -> None:
"""|coro|
Resumes the player if it was paused.
"""
await self.set_pause(False)
async def set_volume(self, volume: int) -> None:
"""|coro|
Set the player's volume, between 0 and 1000.
Parameters
----------
volume: int
The volume to set the player to.
"""
self.volume = max(min(volume, 1000), 0)
await self.node._websocket.send(
op="volume", guildId=str(self.guild.id), volume=self.volume
)
logger.debug(f"Set volume:: {self.volume} ({self.channel.id})")
async def seek(self, position: int = 0) -> None:
"""|coro|
Seek to the given position in the song.
Parameters
----------
position: int
The position as an int in milliseconds to seek to. Could be None to seek to beginning.
"""
await self.node._websocket.send(
op="seek", guildId=str(self.guild.id), position=position
)
|
"""
Basic config loader that provides easy to use functionality to load from simple
configuration files that have take the following form on every line:
* Option=Yes
* Number=20
* String=Whatever
This software is licensed under the MIT license. Please refer to LICENSE.txt for more information.
"""
import string
class Config:
""" The config loader class provides simple functionality to load from simple configuration files. """
_settings_entries = None
_yes = ["1", "true", "y", "yes", "enable", "toggle", "enabled"]
def __init__(self, target_file = None):
""" Initializes an instance of the Config loader. """
self._settings_entries = { }
if (target_file is not None):
self.load(target_file)
def load(self, target_file):
""" Loads a configuration file from the hard disk. """
file_handle = open(target_file, "r")
for line_data in file_handle:
preference_data = string.split(line_data, "=")
line_data = line_data.lstrip()
if (len(preference_data) == 2):
data = preference_data[1]
entry_data = data[:len(data)].replace("\n","")
entry_data = entry_data.replace("\r", "")
self._settings_entries[preference_data[0]] = entry_data
# TODO: Make this actually do some work to make post-fix comments work ...
elif(line_data.find("#") and line_data != ""):
continue
file_handle.close()
def get_indices(self):
""" Returns all known indices. This is a list of the indices you would use in :func:`get_index`. """
return self._settings_entries.keys()
def set_index(self, index, value):
self._settings_entries[index] = value
def export(self, output_file):
with open(output_file, "w") as handle:
for key in self._settings_entries.keys():
handle.write("%s=%s\n" % (key, self._settings_entries[key]))
def get_index(self, index=None, datatype=None):
""" Returns a loaded configuration setting from the Settings loader.
Keyword arguments:
* index -- The name of the setting that is to be loaded from the file.
* datatype -- The datatype that is supposed to be used to represent this setting in the return value.
"""
if(index in self._settings_entries):
entries = self._settings_entries
if (datatype is bool):
if (string.lower(self._settings_entries[index]) in self._yes):
return True
else:
return False
else:
return datatype(entries[index])
else:
return None
|
/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app and you should
* disable HTTP caching for this file too.
* See https://goo.gl/nhQhGp
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
* See https://goo.gl/2aRDsh
*/
importScripts("https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js");
importScripts(
"/jw-google-map/build/precache-manifest.9d862388f6b2fa221a13e2376ae94196.js"
);
workbox.clientsClaim();
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
workbox.routing.registerNavigationRoute("/jw-google-map/build/index.html", {
blacklist: [/^\/_/,/\/[^\/]+\.[^\/]+$/],
});
|
///
/// \file TencentOAuth.h
/// \brief QQ互联开放平台授权登录及相关开放接口实现类
///
/// Created by Tencent on 12-12-21.
/// Copyright (c) 2012年 Tencent. All rights reserved.
///
#import <UIKit/UIKit.h>
#import "sdkdef.h"
#import "QQApiInterface.h"
#import "TencentOAuthObject.h"
@protocol TencentSessionDelegate;
@protocol TencentLoginDelegate;
@protocol TencentApiInterfaceDelegate;
@protocol TencentWebViewDelegate;
@class TencentApiReq;
@class TencentApiResp;
typedef enum
{
kTencentNotAuthorizeState,
kTencentSSOAuthorizeState,
kTencentWebviewAuthorzieState,
} TencentAuthorizeState;
typedef enum
{
kAuthModeClientSideToken,
kAuthModeServerSideCode,
} TencentAuthMode;
#pragma mark - TencentOAuth(授权登录及相关开放接口调用)
/**
* \brief TencentOpenAPI授权登录及相关开放接口调用
*
* TencentOAuth实现授权登录逻辑以及相关开放接口的请求调用
*/
@interface TencentOAuth : NSObject
{
NSMutableDictionary* _apiRequests;
NSString* _accessToken;
NSDate* _expirationDate;
id<TencentSessionDelegate> _sessionDelegate;
NSString* _localAppId;
NSString* _openId;
NSString* _redirectURI;
NSArray* _permissions;
}
/** Access Token凭证,用于后续访问各开放接口 */
@property(nonatomic, copy) NSString* accessToken;
/** Access Token的失效期 */
@property(nonatomic, copy) NSDate* expirationDate;
/** 已实现的开放接口的回调委托对象 */
@property(nonatomic, assign) id<TencentSessionDelegate> sessionDelegate;
/** 第三方应用在开发过程中设置的URLSchema,用于浏览器登录后后跳到第三方应用 */
@property(nonatomic, copy) NSString* localAppId;
/** 用户授权登录后对该用户的唯一标识 */
@property(nonatomic, copy) NSString* openId;
/** 用户登录成功过后的跳转页面地址 */
@property(nonatomic, copy) NSString* redirectURI;
/** 第三方应用在互联开放平台申请的appID */
@property(nonatomic, retain) NSString* appId;
/** 主要是互娱的游戏设置uin */
@property(nonatomic, retain) NSString* uin;
/** 主要是互娱的游戏设置鉴定票据 */
@property(nonatomic, retain) NSString* skey;
/** 登陆透传的数据 */
@property(nonatomic, copy) NSDictionary* passData;
/** 授权方式(Client Side Token或者Server Side Code) */
@property(nonatomic, assign) TencentAuthMode authMode;
/**
* 用来获得当前sdk的版本号
* \return 返回sdk版本号
**/
+ (NSString*)sdkVersion;
/**
* 用来获得当前sdk的小版本号
* \return 返回sdk小版本号
**/
+ (NSString*)sdkSubVersion;
/**
* 用来获得当前sdk的是否精简版
* \return 返回YES表示精简版
**/
+ (BOOL)isLiteSDK;
/**
* 主要是用来帮助判断是否有登陆被发起,但是还没有过返回结果
* \return
* kTencentNotAuthorizeState:无授权
* kTencentSSOAuthorizeState:有人发起了sso授权但无返回
* kTencentWebviewAuthorzieState:有人发起了webview授权还未返回
**/
+ (TencentAuthorizeState *)authorizeState;
/**
* 用来获得当前手机qq的版本号
* \return 返回手机qq版本号
**/
+ (QQVersion)iphoneQQVersion;
/**
* 初始化TencentOAuth对象
* \param appId 第三方应用在互联开放平台申请的唯一标识
* \param delegate 第三方应用用于接收请求返回结果的委托对象
* \return 初始化后的授权登录对象
*/
- (id)initWithAppId:(NSString *)appId
andDelegate:(id<TencentSessionDelegate>)delegate;
/**
* 判断用户手机上是否安装手机QQ
* \return YES:安装 NO:没安装
*/
+ (BOOL)iphoneQQInstalled;
/**
* 判断用户手机上的手机QQ是否支持SSO登录
* \return YES:支持 NO:不支持
*/
+ (BOOL)iphoneQQSupportSSOLogin;
/**
* 判断用户手机上是否安装手机QZone
* \return YES:安装 NO:没安装
*/
+ (BOOL)iphoneQZoneInstalled;
/**
* 判断用户手机上的手机QZone是否支持SSO登录
* \return YES:支持 NO:不支持
*/
+ (BOOL)iphoneQZoneSupportSSOLogin;
/**
* 登录授权
*
* \param permissions 授权信息列
*/
- (BOOL)authorize:(NSArray *)permissions;
/**
* 登录授权
* \param permissions 授权信息列表
* \param bInSafari 是否使用safari进行登录.<b>IOS SDK 1.3版本开始此参数废除</b>
*/
- (BOOL)authorize:(NSArray *)permissions
inSafari:(BOOL)bInSafari;
/**
* 登录授权
* \param permissions 授权信息列表
* \param localAppId 应用APPID
* \param bInSafari 是否使用safari进行登录.<b>IOS SDK 1.3版本开始此参数废除</b>
*/
- (BOOL)authorize:(NSArray *)permissions
localAppId:(NSString *)localAppId
inSafari:(BOOL)bInSafari;
/**
* 增量授权,因用户没有授予相应接口调用的权限,需要用户确认是否授权
* \param permissions 需增量授权的信息列表
* \return 增量授权调用是否成功
*/
- (BOOL)incrAuthWithPermissions:(NSArray *)permissions;
/**
* 重新授权,因token废除或失效导致接口调用失败,需用户重新授权
* \param permissions 授权信息列表,同登录授权
* \return 授权调用是否成功
*/
- (BOOL)reauthorizeWithPermissions:(NSArray *)permissions;
/**
* (静态方法)处理应用拉起协议
* \param url 处理被其他应用呼起时的逻辑
* \return 处理结果,YES表示成功,NO表示失败
*/
+ (BOOL)HandleOpenURL:(NSURL *)url;
/**
* (静态方法)sdk是否可以处理应用拉起协议
* \param url 处理被其他应用呼起时的逻辑
* \return 处理结果,YES表示可以 NO表示不行
*/
+ (BOOL)CanHandleOpenURL:(NSURL *)url;
/**
* (静态方法)获取TencentOAuth调用的上一次错误信息
*/
+ (NSString *)getLastErrorMsg;
/**
* 以Server Side Code模式授权登录时,通过此接口获取返回的code值;
* 以Client Side Token模式授权登录时,忽略此接口。
*/
- (NSString *)getServerSideCode;
/**
* 退出登录(退出登录后,TecentOAuth失效,需要重新初始化)
* \param delegate 第三方应用用于接收请求返回结果的委托对象
*/
- (void)logout:(id<TencentSessionDelegate>)delegate;
/**
* 判断登录态是否有效
* \return 处理结果,YES表示有效,NO表示无效,请用户重新登录授权
*/
- (BOOL)isSessionValid;
/**
* 获取用户个人信息
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)getUserInfo;
/**
* SDK内置webview实现定向分享时,第三方应用可以根据应用是否在白名单里来开启该配置开关,默认为关闭;
* 在白名单里的应用调用该接口后,即打开sdk内置webview的二级白名单开关(相对与sdk后台的白名单),
* 那么在sdk后台白名单校验请求失败的情况下,会继续先尝试采用内置webview进行分享。
*/
- (void)openSDKWebViewQQShareEnable;
/**
* 获取用户QZone相册列表
* \attention 需\ref apply_perm
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)getListAlbum;
/**
* 获取用户QZone相片列表
* \attention 需\ref apply_perm
* \param params 参数字典,字典的关键字参见TencentOAuthObject.h中的\ref TCListPhotoDic
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)getListPhotoWithParams:(NSMutableDictionary *)params;
/**
* 分享到QZone
* \param params 参数字典,字典的关键字参见TencentOAuthObject.h中的\ref TCAddShareDic
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)addShareWithParams:(NSMutableDictionary *)params;
/**
* 上传照片到QZone指定相册
* \attention 需\ref apply_perm
* \param params 参数字典,字典的关键字参见TencentOAuthObject.h中的\ref TCUploadPicDic
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)uploadPicWithParams:(NSMutableDictionary *)params;
/**
* 在QZone相册中创建一个新的相册
* \attention 需\ref apply_perm
* \param params 参数字典,字典的关键字参见TencentOAuthObject.h中的\ref TCAddAlbumDic
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)addAlbumWithParams:(NSMutableDictionary *)params;
/**
* 检查是否是QZone某个用户的粉丝
* \param params 参数字典,字典的关键字参见TencentOAuthObject.h中的\ref TCCheckPageFansDic
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)checkPageFansWithParams:(NSMutableDictionary *)params;
/**
* 在QZone中发表一篇日志
* \attention 需\ref apply_perm
* \param params 参数字典,字典的关键字参见TencentOAuthObject.h中的\ref TCAddOneBlogDic
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)addOneBlogWithParams:(NSMutableDictionary *)params;
/**
* 在QZone中发表一条说说
* \attention 需\ref apply_perm
* \param params 参数字典,字典的关键字参见TencentOAuthObject.h中的\ref TCAddTopicDic
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)addTopicWithParams:(NSMutableDictionary *)params;
/**
* 设置QQ头像 使用默认的效果处理设置头像的界面
* \attention 需\ref apply_perm
* \param params 参数字典,字典的关键字参见TencentOAuthObject.h中的\ref TCSetUserHeadpic
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)setUserHeadpic:(NSMutableDictionary *)params;
/**
* 设置QQ头像 会返回设置头像由第三方自己处理界面的弹出方式
* \attention 需\ref apply_perm
* \param params 参数字典,字典的关键字参见TencentOAuthObject.h中的\ref TCSetUserHeadpic
* \param viewController 设置头像的界面
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)setUserHeadpic:(NSMutableDictionary *)params andViewController:(UIViewController **)viewController;
/**
* 获取QQ会员信息(仅包括是否为QQ会员,是否为年费QQ会员)
* \attention 需\ref apply_perm
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)getVipInfo;
/**
* 获取QQ会员详细信息
* \attention 需\ref apply_perm
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)getVipRichInfo;
/**
* QZone定向分享,可以@到具体好友,完成后将触发responseDidReceived:forMessage:回调,message:“SendStory”
* \param params 参数字典
* \param fopenIdArray 第三方应用预传人好友列表,好友以openid标识
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)sendStory:(NSMutableDictionary *)params friendList:(NSArray *)fopenIdArray;
/**
* 发送应用邀请,完成后将触发responseDidReceived:forMessage:回调,message:“AppInvitation”
* \param desc 应用的描述文字,不超过35字符,如果为nil或@“”则显示默认描述
* \param imageUrl 应用的图标,如果为nil或者@“”则显示默认图标
* \param source 透传参数,由开发者自定义该参数内容
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)sendAppInvitationWithDescription:(NSString *)desc imageURL:(NSString *)imageUrl source:(NSString *)source;
/**
* 发起PK或者发送炫耀,完成后将触发responseDidReceived:forMessage:回调,message:“AppChallenge”
* \param receiver 必须指定一位进行PK或者炫耀的好友,填写其OpenID,填写多个OpenID将截取第一个
* \param type 类型,"pk"或者“brag”
* \param imageUrl 炫耀/挑战场景图的URL
* \param message 炫耀/挑战中的内容描述,不超过50个字符,超过限制则自动截断
* \param source 透传参数,由开发者自定义该参数内容
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)sendChallenge:(NSString *)receiver type:(NSString *)type imageURL:(NSString *)imageUrl message:(NSString *)message source:(NSString *)source;
/**
* 赠送或者请求礼物,完成后将触发responseDidReceived:forMessage:回调,message:“AppGiftRequest”
* \param receiver 赠送或者请求礼物的好友的OpenID,支持填写多个,OpenID之用","分隔,为nil时将由用户通过好友选择器选择好友
* \param exclude 用户通过好友选择器选择好友场景下,希望排除的好友(不显示在好友选择器)
* \param specified 用户通过好友选择器选择好友场景下,希望出现的指定好友
* \param only 是否只显示specified指定的好友
* \param type 类型,"request"或者“freegift”
* \param title 免费礼物或请求名称,不超过6个字符
* \param message 礼物或请求的默认赠言,控制在35个汉字以内,超过限制自动截断
* \param imageUrl 请求或礼物配图的URL,如果不传,则默认在弹框中显示应用的icon
* \param source 透传参数,由开发者自定义该参数内容
* \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
*/
- (BOOL)sendGiftRequest:(NSString *)receiver exclude:(NSString *)exclude specified:(NSString *)specified only:(BOOL)only type:(NSString *)type title:(NSString *)title message:(NSString *)message imageURL:(NSString *)imageUrl source:(NSString *)source;
/**
* 退出指定API调用
* \param userData 用户调用某条API的时候传入的保留参数
* \return 处理结果,YES表示成功 NO表示失败
*/
- (BOOL)cancel:(id)userData;
/**
* CGI类任务创建接口
* \param apiURL CGI请求的URL地址
* \param method CGI请求方式:"GET","POST"
* \param params CGI请求参数字典
* \param callback CGI请求结果的回调接口对象
* \return CGI请求任务实例,用于取消任务,返回nil代表任务创建失败
*/
- (TCAPIRequest *)cgiRequestWithURL:(NSURL *)apiURL method:(NSString *)method params:(NSDictionary *)params callback:(id<TCAPIRequestDelegate>)callback;
/**
* TencentOpenApi发送任务统一接口
* \param request 请求发送的任务
* \param callback 任务发送后的回调地址
*/
- (BOOL)sendAPIRequest:(TCAPIRequest *)request callback:(id<TCAPIRequestDelegate>)callback;
- (NSString *)getUserOpenID;
@end
#pragma mark - TencentLoginDelegate(授权登录回调协议)
/**
* \brief TencentLoginDelegate iOS Open SDK 1.3 API回调协议
*
* 第三方应用实现登录的回调协议
*/
@protocol TencentLoginDelegate <NSObject>
@required
/**
* 登录成功后的回调
*/
- (void)tencentDidLogin;
/**
* 登录失败后的回调
* \param cancelled 代表用户是否主动退出登录
*/
- (void)tencentDidNotLogin:(BOOL)cancelled;
/**
* 登录时网络有问题的回调
*/
- (void)tencentDidNotNetWork;
@optional
/**
* 登录时权限信息的获得
*/
- (NSArray *)getAuthorizedPermissions:(NSArray *)permissions withExtraParams:(NSDictionary *)extraParams;
@end
#pragma mark - TencentSessionDelegate(开放接口回调协议)
/**
* \brief TencentSessionDelegate iOS Open SDK 1.3 API回调协议
*
* 第三方应用需要实现每条需要调用的API的回调协议
*/
@protocol TencentSessionDelegate<NSObject, TencentLoginDelegate,
TencentApiInterfaceDelegate,
TencentWebViewDelegate>
@optional
/**
* 退出登录的回调
*/
- (void)tencentDidLogout;
/**
* 因用户未授予相应权限而需要执行增量授权。在用户调用某个api接口时,如果服务器返回操作未被授权,则触发该回调协议接口,由第三方决定是否跳转到增量授权页面,让用户重新授权。
* \param tencentOAuth 登录授权对象。
* \param permissions 需增量授权的权限列表。
* \return 是否仍然回调返回原始的api请求结果。
* \note 不实现该协议接口则默认为不开启增量授权流程。若需要增量授权请调用\ref TencentOAuth#incrAuthWithPermissions: \n注意:增量授权时用户可能会修改登录的帐号
*/
- (BOOL)tencentNeedPerformIncrAuth:(TencentOAuth *)tencentOAuth withPermissions:(NSArray *)permissions;
/**
* [该逻辑未实现]因token失效而需要执行重新登录授权。在用户调用某个api接口时,如果服务器返回token失效,则触发该回调协议接口,由第三方决定是否跳转到登录授权页面,让用户重新授权。
* \param tencentOAuth 登录授权对象。
* \return 是否仍然回调返回原始的api请求结果。
* \note 不实现该协议接口则默认为不开启重新登录授权流程。若需要重新登录授权请调用\ref TencentOAuth#reauthorizeWithPermissions: \n注意:重新登录授权时用户可能会修改登录的帐号
*/
- (BOOL)tencentNeedPerformReAuth:(TencentOAuth *)tencentOAuth;
/**
* 用户通过增量授权流程重新授权登录,token及有效期限等信息已被更新。
* \param tencentOAuth token及有效期限等信息更新后的授权实例对象
* \note 第三方应用需更新已保存的token及有效期限等信息。
*/
- (void)tencentDidUpdate:(TencentOAuth *)tencentOAuth;
/**
* 用户增量授权过程中因取消或网络问题导致授权失败
* \param reason 授权失败原因,具体失败原因参见sdkdef.h文件中\ref UpdateFailType
*/
- (void)tencentFailedUpdate:(UpdateFailType)reason;
/**
* 获取用户个人信息回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/getUserInfoResponse.exp success
* 错误返回示例: \snippet example/getUserInfoResponse.exp fail
*/
- (void)getUserInfoResponse:(APIResponse*) response;
/**
* 获取用户QZone相册列表回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/getListAlbumResponse.exp success
* 错误返回示例: \snippet example/getListAlbumResponse.exp fail
*/
- (void)getListAlbumResponse:(APIResponse*) response;
/**
* 获取用户QZone相片列表
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/getListPhotoResponse.exp success
* 错误返回示例: \snippet example/getListPhotoResponse.exp fail
*/
- (void)getListPhotoResponse:(APIResponse*) response;
/**
* 检查是否是QZone某个用户的粉丝回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/checkPageFansResponse.exp success
* 错误返回示例: \snippet example/checkPageFansResponse.exp fail
*/
- (void)checkPageFansResponse:(APIResponse*) response;
/**
* 分享到QZone回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/addShareResponse.exp success
* 错误返回示例: \snippet example/addShareResponse.exp fail
*/
- (void)addShareResponse:(APIResponse*) response;
/**
* 在QZone相册中创建一个新的相册回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/addAlbumResponse.exp success
* 错误返回示例: \snippet example/addAlbumResponse.exp fail
*/
- (void)addAlbumResponse:(APIResponse*) response;
/**
* 上传照片到QZone指定相册回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/uploadPicResponse.exp success
* 错误返回示例: \snippet example/uploadPicResponse.exp fail
*/
- (void)uploadPicResponse:(APIResponse*) response;
/**
* 在QZone中发表一篇日志回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/addOneBlogResponse.exp success
* 错误返回示例: \snippet example/addOneBlogResponse.exp fail
*/
- (void)addOneBlogResponse:(APIResponse*) response;
/**
* 在QZone中发表一条说说回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/addTopicResponse.exp success
* 错误返回示例: \snippet example/addTopicResponse.exp fail
*/
- (void)addTopicResponse:(APIResponse*) response;
/**
* 设置QQ头像回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/setUserHeadpicResponse.exp success
* 错误返回示例: \snippet example/setUserHeadpicResponse.exp fail
*/
- (void)setUserHeadpicResponse:(APIResponse*) response;
/**
* 获取QQ会员信息回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \remarks 正确返回示例: \snippet example/getVipInfoResponse.exp success
* 错误返回示例: \snippet example/getVipInfoResponse.exp fail
*/
- (void)getVipInfoResponse:(APIResponse*) response;
/**
* 获取QQ会员详细信息回调
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
*/
- (void)getVipRichInfoResponse:(APIResponse*) response;
/**
* sendStory分享的回调(已废弃,使用responseDidReceived:forMessage:)
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
*/
- (void)sendStoryResponse:(APIResponse*) response;
/**
* 社交API统一回调接口
* \param response API返回结果,具体定义参见sdkdef.h文件中\ref APIResponse
* \param message 响应的消息,目前支持‘SendStory’,‘AppInvitation’,‘AppChallenge’,‘AppGiftRequest’
*/
- (void)responseDidReceived:(APIResponse*)response forMessage:(NSString *)message;
/**
* post请求的上传进度
* \param tencentOAuth 返回回调的tencentOAuth对象
* \param bytesWritten 本次回调上传的数据字节数
* \param totalBytesWritten 总共已经上传的字节数
* \param totalBytesExpectedToWrite 总共需要上传的字节数
* \param userData 用户自定义数据
*/
- (void)tencentOAuth:(TencentOAuth *)tencentOAuth didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite userData:(id)userData;
/**
* 通知第三方界面需要被关闭
* \param tencentOAuth 返回回调的tencentOAuth对象
* \param viewController 需要关闭的viewController
*/
- (void)tencentOAuth:(TencentOAuth *)tencentOAuth doCloseViewController:(UIViewController *)viewController;
@end
#pragma mark - TencentWebViewDelegate(H5登录webview旋转方向回调)
/**
* \brief TencentWebViewDelegate: H5登录webview旋转方向回调协议
*
* 第三方应用可以根据自己APP的旋转方向限制,通过此协议设置
*/
@protocol TencentWebViewDelegate <NSObject>
@optional
- (BOOL) tencentWebViewShouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation;
- (NSUInteger) tencentWebViewSupportedInterfaceOrientationsWithWebkit;
- (BOOL) tencentWebViewShouldAutorotateWithWebkit;
@end
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from uuid import uuid4
from sentry.api.serializers import serialize
from sentry.models import Commit, CommitAuthor, Release, ReleaseCommit, Repository
from sentry.testutils import TestCase
class CommitSerializerTest(TestCase):
def test_simple(self):
user = self.create_user()
project = self.create_project()
release = Release.objects.create(
organization_id=project.organization_id, version=uuid4().hex
)
release.add_project(project)
repository = Repository.objects.create(
organization_id=project.organization_id, name="test/test"
)
commit_author = CommitAuthor.objects.create(
name="stebe", email="stebe@sentry.io", organization_id=project.organization_id
)
commit = Commit.objects.create(
organization_id=project.organization_id,
repository_id=repository.id,
key="abc",
author=commit_author,
message="waddap",
)
ReleaseCommit.objects.create(
organization_id=project.organization_id,
project_id=project.id,
release=release,
commit=commit,
order=1,
)
result = serialize(commit, user)
assert result["message"] == "waddap"
assert result["repository"]["name"] == "test/test"
assert result["author"] == {"name": "stebe", "email": "stebe@sentry.io"}
def test_no_author(self):
user = self.create_user()
project = self.create_project()
release = Release.objects.create(
organization_id=project.organization_id, version=uuid4().hex
)
release.add_project(project)
repository = Repository.objects.create(
organization_id=project.organization_id, name="test/test"
)
commit = Commit.objects.create(
organization_id=project.organization_id,
repository_id=repository.id,
key="abc",
message="waddap",
)
ReleaseCommit.objects.create(
organization_id=project.organization_id,
project_id=project.id,
release=release,
commit=commit,
order=1,
)
result = serialize(commit, user)
assert result["author"] == {}
|
// Copyright (c) 2014 International Aid Transparency Initiative (IATI)
// Licensed under the MIT license whose full text can be found at http://opensource.org/licenses/MIT
var view_publisher_countries_top = exports;
exports.name = "view_publisher_countries_top";
var ctrack = require("./ctrack.js");
var plate = require("./plate.js");
var iati = require("./iati.js");
var fetch = require("./fetch.js");
var refry = require("../../dstore/js/refry.js");
var iati_codes = require("../../dstore/json/iati_codes.json");
var un_agencies_codes = require("../../dstore/json/un_agencies_data.json");
var crs_year = require("../../dstore/json/crs_2013.json");
var commafy = function (s) {
return ("" + s).replace(/(^|[^\w.])(\d{4,})/g, function ($0, $1, $2) {
return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
})
};
// the chunk names this view will fill with new data
view_publisher_countries_top.chunks = [
"data_chart_publisher_countries",
"countries_count",
];
//
// Perform fake ajax call to get data
//
view_publisher_countries_top.ajax = function (args) {
args = args || {};
var limit = args.limit || 5;
var list = [];
var year = args.year || parseInt(ctrack.hash.year) || ctrack.year;
ctrack.year_chunks(year);
var dat = {
"from": "act,trans,country",
"limit": -1,
"select": "country_code," + ctrack.convert_str("sum_of_percent_of_trans"),
"groupby": "country_code",
"trans_code": "D|E"
};
if(year !== 'all years'){
dat.trans_day_gteq = year + "-" + ctrack.args.newyear;
dat.trans_day_lt = (parseInt(year) + 1) + "-" + ctrack.args.newyear;
}
fetch.ajax_dat_fix(dat, args);
if (!dat.reporting_ref) {
dat.flags = 0;
}
fetch.ajax(dat, function (data) {
var gTotal = 0;
for (var i = 0; i < data.rows.length; i++) {
var v = data.rows[i];
var d = {};
if (v.country_code in un_agencies_codes['countries']) {
d.country_code = v.country_code || "N/A";
d.country_name = iati_codes.country[v.country_code] || v.country_code || "N/A";
d.usd = Math.floor(ctrack.convert_num("sum_of_percent_of_trans", v));
list.push(d);
} else {
gTotal = gTotal + Math.floor(ctrack.convert_num("sum_of_percent_of_trans", v));
}
}
if (gTotal > 0) {
var gR = {};
gR.country_code = 'global-regional';
gR.country_name = 'Regional and Global';
gR.usd = gTotal;
list.push(gR);
}
list.sort(function (a, b) {
return ( (b.usd || 0) - (a.usd || 0) );
});
var total = 0;
list.forEach(function (it) {
total += it.usd;
});
var shown = 0;
var top = list[0] && list[0].usd || 0;
var dd = [];
list.forEach(function (v) {
var d = {};
d.num = v.usd;
var initialPct = 100 * d.num / total;
if (initialPct < 1) {
d.pct = "<1";
}
else {
d.pct = Math.round(initialPct);
}
if (d.num < 0) {
d.num = -d.num;
}
d.str_lab = v.country_name;
dd.push(d);
});
ctrack.chunk("data_chart_publisher_countries", dd);
ctrack.chunk("countries_count", list.length);
ctrack.display();
});
};
|
"""
This module lets you practice the ITERATE-THROUGH-A-SEQUENCE pattern
in its most classic form:
-- Iterate all the way through the sequence, from beginning to end.
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues,
and Triston Hine.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
import rosegraphics as rg
def main():
""" Calls the TEST functions in this module. """
run_test_count_negatives()
run_test_count_short_ones()
run_test_draw_circles()
def run_test_count_negatives():
""" Tests the count_negatives function. """
# -------------------------------------------------------------------------
# DONE: 2. Implement this TEST function.
# It TESTS the count_negatives function defined below.
# Include at least ** 2 ** ADDITIONAL tests beyond those we wrote.
#
# Use the same 4-step process as for previous TEST functions:
#
# Step 1: Read the doc-string (below) that provides the
# specification of the function you are to test.
# Understand what that function SHOULD return.
#
# Step 2: Pick a test case: numbers that you could send as
# actual arguments to the function.
#
# Step 3: Figure out (by hand, or by trusting a test case that
# your instructor provided) the CORRECT (EXPECTED) answer
# for your test case.
#
# Step 4: Write code that prints both the EXPECTED answer
# and the ACTUAL answer returned when you call the function.
# Follow the same form as in the test case we provided below.
# -------------------------------------------------------------------------
print()
print('--------------------------------------------------')
print('Testing the count_negatives function:')
print('--------------------------------------------------')
# Test 1:
expected = 1
actual = count_negatives([8, 13, 7, -5])
print()
print('Test 1 expected:', expected)
print(' actual: ', actual)
# Test 2:
expected = 0
actual = count_negatives([])
print()
print('Test 2 expected:', expected)
print(' actual: ', actual)
# Test 3:
expected = 0
actual = count_negatives([3, 2.5, 3])
print()
print('Test 3 expected:', expected)
print(' actual: ', actual)
# Test 4:
expected = 4
actual = count_negatives([-500, -500, -500, -0.0000001])
print()
print('Test 4 expected:', expected)
print(' actual: ', actual)
# Test 5:
expected = 1
actual = count_negatives((8, 13, 7, -5))
print()
print('Test 5 expected:', expected)
print(' actual: ', actual)
# -------------------------------------------------------------------------
# TODO 2 (continued): Add your 2 ADDITIONAL tests here:
# -------------------------------------------------------------------------
# Test 6:
expected = 2
actual = count_negatives((-6, 9, 18, -2))
print()
print('Test 6 expected:', expected)
print(' actual: ', actual)
# Test 7:
expected = 4
actual = count_negatives((-6, -22, -1, -13))
print()
print('Test 7 expected:', expected)
print(' actual: ', actual)
def count_negatives(seq):
"""
What comes in: An sequence of numbers.
What goes out: Returns the number of items in the given sequence
that are negative.
Side effects: None.
Examples:
count_negatives([8, 13, 7, -5]) returns 1
count_negatives([]) returns 0
count_negatives([3, 2.5, 3]) returns 0
count_negatives([-500, -500, -500, -0.0000001]) returns 4
count_negatives((8, 13, 7, -5)) returns 1
Type hints:
:type seq: (list | tuple) of (int | float)
"""
# -------------------------------------------------------------------------
# DONE: 3. Implement and test this function.
# Note that you should write its TEST function first (above).
# -------------------------------------------------------------------------
total = 0
for k in range(len(seq)):
if seq[k] < 0:
total = total + 1
return total
def run_test_count_short_ones():
""" Tests the count_short_ones function. """
# -------------------------------------------------------------------------
# DONE: 4. Implement this TEST function.
# It TESTS the count_short_ones function defined below.
# Include at least ** 2 ** ADDITIONAL tests beyond those we wrote.
#
# Use the same 4-step process as for previous TEST functions.
# -------------------------------------------------------------------------
print()
print('--------------------------------------------------')
print('Testing the count_short_ones function:')
print('--------------------------------------------------')
# Test 1:
expected = 5
seq = [[3, 5],
[3, 9, 0, 4],
[5],
[5],
[],
[9, 8, 7],
[5, 6]]
actual = count_short_ones(seq)
print()
print('Test 1 expected:', expected)
print(' actual: ', actual)
# Test 2:
expected = 3
seq = ['all', 'we', 'need', 'is', 'peace', '', 'short', '123']
actual = count_short_ones(seq)
print()
print('Test 2 expected:', expected)
print(' actual: ', actual)
# Test 3:
expected = 6
seq = ['abc', 'a', '', 'foo', 'de', 'dd', 'x', 'foo', 'argh', 'a']
actual = count_short_ones(seq)
print()
print('Test 3 expected:', expected)
print(' actual: ', actual)
# Test 4:
expected = 0
seq = []
actual = count_short_ones(seq)
print()
print('Test 4 expected:', expected)
print(' actual: ', actual)
# Test 5:
expected = 1
seq = [[]]
actual = count_short_ones(seq)
print()
print('Test 5 expected:', expected)
print(' actual: ', actual)
# Test 6:
expected = 4
seq = [[], [], [], []]
actual = count_short_ones(seq)
print()
print('Test 6 expected:', expected)
print(' actual: ', actual)
# Test 7:
expected = 0
seq = [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
actual = count_short_ones(seq)
print()
print('Test 7 expected:', expected)
print(' actual: ', actual)
# -------------------------------------------------------------------------
# DONE 4 (continued): Add your 2 ADDITIONAL test(s) here:
# -------------------------------------------------------------------------
expected = 3
seq = [[1, 5], [38, 5, 7, 16], [3, 12], [100]]
actual = count_short_ones(seq)
print()
print('Test 8 expected:', expected)
print(' actual: ', actual)
expected = 0
seq = [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
actual = count_short_ones(seq)
print()
print('Test 9 expected:', expected)
print(' actual: ', actual)
def count_short_ones(seq_of_lists):
"""
What comes in: An sequence of sequences.
What goes out: Returns the number of sub-sequences in the given
sequence whose length is less than 3.
Side effects: None.
Examples:
If the argument is:
[ [3, 5], [3, 9, 0, 4], [5], [5], [], [9, 8, 7], [5, 6] ]
then this function returns 5, since 5 of the 7 lists in the
above sequence have length less than 3.
If the argument is:
['all', 'we', 'need', 'is', 'peace', '', 'short', '123'],
then this function returns 3,
since 'we' and 'is' and '' all have length less than 3.
Type hints:
:type seq_of_lists: (list | tuple) of (list | tuple | str)
"""
# ------------------------------------------------------------------
# DONE: 5. Implement and test this function.
# Note that you should write its TEST function first (above).
# ------------------------------------------------------------------
total = 0
for k in range(len(seq_of_lists)):
if len(seq_of_lists[k]) < 3:
total = total + 1
return total
def run_test_draw_circles():
""" Tests the draw_circles function. """
# -------------------------------------------------------------------------
# We have supplied two tests for you, on a single window.
# NO ADDITIONAL TESTS ARE REQUIRED, although you are welcome to
# supply more tests if you choose.
# -------------------------------------------------------------------------
print()
print('--------------------------------------------------')
print('Testing the draw_circles function:')
print('See the window that pops up.')
print('--------------------------------------------------')
window = rg.RoseWindow(450, 350, 'Points to Circles')
points1 = [rg.Point(200, 100),
rg.Point(100, 130),
rg.Point(150, 200)]
points2 = [rg.Point(50, 50),
rg.Point(250, 250)]
points3 = []
for k in range(40):
points3.append(rg.Point((10 * k) + 10, 10))
draw_circles(window, points1, 15, 'red') # Test 1: 3 red circles
message = 'You should see 3 SMALL RED circles.\n'
message += 'Click to continue'
window.continue_on_mouse_click(message)
draw_circles(window, points2, 40, 'blue') # Test 2: 2 blue circles
message = 'Now you should see 3 small red circles\n'
message += '** AND ** 2 BIG BLUE ones. Click to continue.'
window.continue_on_mouse_click(message)
draw_circles(window, points3, 4, 'purple') # Test 3: 99 purple dots
message = 'Now you should see 3 small red and 2 big blue\n'
message += '** AND ** 40 TEENY PURPLE circles. Click to exit.'
window.continue_on_mouse_click(message, close_it=True)
# Test 4 on another window:
window = rg.RoseWindow(250, 150, 'More Points to Circles')
points4 = [rg.Point(30, 50),
rg.Point(80, 75),
rg.Point(130, 25)]
draw_circles(window, points4, 25, 'yellow')
window.close_on_mouse_click()
def draw_circles(window, points, radius, color):
"""
What comes in:
-- An rg.RoseWindow
-- A sequence of rg.Point objects
-- A positive number
-- A string that can be used as a RoseGraphics color
What goes out: Nothing (i.e., None).
Side effects:
See draw_circles_picture.pdf in this project for pictures
that may help you better understand the following specification:
For each point in the given sequence of rg.Points,
constructs and draws an rg.Circle centered at that point,
with the given radius and fill color, on the given rg.RoseWindow.
Renders but does NOT close the given rg.RoseWindow.
Type hints:
:type window: rg.RoseWindow
:type points: [rg.Point]
:type radius: int | float
:type color: str
"""
# -------------------------------------------------------------------------
# TODO: 6. Implement and test this function.
# Tests have been written for you (above).
# -------------------------------------------------------------------------
for k in range(len(points)):
circle = rg.Circle(rg.Point(points[k].x, points[k].y), radius)
circle.fill_color = color
circle.attach_to(window)
window.render()
# -----------------------------------------------------------------------------
# Calls main to start the ball rolling.
# -----------------------------------------------------------------------------
main()
|
import pandas as pd
from django.core.management import BaseCommand, CommandError
from DataRepo.utils import CompoundsLoader
class Command(BaseCommand):
# Show this when the user types help
help = "Loads data from a compound list into the database"
def add_arguments(self, parser):
parser.add_argument(
"--compounds",
type=str,
help=(
"Path to tab-delimited file containing headers of "
"'Compound','Formula', 'HMDB ID', and 'Synonyms'; required."
),
required=True,
)
parser.add_argument(
"--synonym-separator",
type=str,
help="Character separating multiple synonyms in 'Synonyms' column (default '%(default)s')",
default=";",
required=False,
)
# optional "do work" argument; otherwise, only reports of possible work
parser.add_argument(
"--validate-only",
action="store_true",
default=False,
help=(
"Validation mode. If specified, command will not change the database, "
"but simply report back potential work or issues."
),
)
def handle(self, *args, **options):
action = "Loading"
if options["validate_only"]:
action = "Validating"
self.stdout.write(self.style.MIGRATE_HEADING(f"{action} compound data"))
self.extract_compounds_from_tsv(options)
# Initialize loader class
loader = CompoundsLoader(
compounds_df=self.compounds_df,
synonym_separator=options["synonym_separator"],
)
# Run validation
loader.validate_data()
if options["verbosity"] >= 2:
for msg in loader.validation_debug_messages:
self.stdout.write(self.style.NOTICE(msg))
if options["verbosity"] >= 1:
for msg in loader.validation_warning_messages:
self.stdout.write(self.style.WARNING(msg))
# If validation failed, raise an exception
if len(loader.validation_error_messages) >= 1:
# report on what errors were discovered by the loader
for err_msg in loader.validation_error_messages:
self.stdout.write(self.style.ERROR(err_msg))
raise CommandError(
"Validation errors when loading compounds, no compounds were loaded"
)
# report on what what work would be done by the loader
self.stdout.write(
self.style.MIGRATE_HEADING(
f"Work to be done: {len(loader.validated_new_compounds_for_insertion)} "
"new compounds will be inserted and all names/synonyms from the file "
"will either be found or inserted."
)
)
if len(loader.validated_new_compounds_for_insertion) >= 1:
self.stdout.write(
self.style.MIGRATE_HEADING("New compounds to be inserted:")
)
for compound in loader.validated_new_compounds_for_insertion:
self.stdout.write(self.style.MIGRATE_LABEL(str(compound)))
# Load compounds
if not options["validate_only"]:
loader.load_validated_compounds()
loader.load_synonyms()
for msg in loader.summary_messages:
self.stdout.write(self.style.MIGRATE_HEADING(msg))
self.stdout.write(self.style.SUCCESS(f"{action} compound data completed"))
def extract_compounds_from_tsv(self, options):
self.compounds_df = pd.read_csv(
options["compounds"], sep="\t", keep_default_na=False
)
|
var express = require("express");
var router = express.Router();
var mysql = require("mysql");
var config = require("../config/database");
var db = mysql.createConnection(config.mysql);
router.get("/getUser",(req,res)=>{
console.log(req.body.id);
db.query('SELECT * FROM user where user_Id=?',[req.body.id], (err,rows)=>{
if(err) console.log(err);
else {
//console.log(res);
console.log(rows);
res.json(rows);}
});
});
router.post("/insert",(req,res)=>{
//insert
var usr_id = null;
var usr_Pwd = req.body.usr_pwd;
var usr_Name = req.body.usr_Name;
var usr_Nickname = req.body.usr_Nickname;
var usr_Email = req.body.usr_Email;
var usr_Birth = req.body.usr_Birth;
var usr_Address = req.body.usr_Address;
var usr_Day = req.body.usr_Day;
var usr_Rdate = req.body.usr_Rdate;
var user_Id = req.body.user_Id; // req.params.id
var sql = 'INSERT INTO user VALUES(null, ?,?,?,?,?,?,?,?,?)'
db.query(sql,[usr_Pwd,usr_Name,usr_Nickname,usr_Email,usr_Birth,usr_Address,usr_Day,usr_Rdate,user_Id], (err,rows)=>{
if(err) console.log(err);
else {
console.log(rows);
res.redirect('/test/getUser');}
});
});
router.get("/delete",(req,res)=>{
const sql = "DELETE FROM user WHERE user_Id = '"+req.query.id+"'";
db.query(sql,[req.params.id],(err,rows) =>{
if(err) console.log(err);
else{
res.redirect('/test/getUser');
}
})
});
module.exports = router;
|
#!/usr/bin/env python
# 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.
from datetime import datetime
from build_pack_utils import Builder
from compile_helpers import setup_webdir_if_it_doesnt_exist
from compile_helpers import setup_log_dir
if __name__ == '__main__':
(Builder()
.configure()
.default_config() # noqa
.stack_config()
.user_config()
.validate()
.done()
.execute()
.method(setup_webdir_if_it_doesnt_exist)
.execute()
.method(setup_log_dir)
.register()
.extension()
.from_build_pack('lib/{WEB_SERVER}')
.extension()
.from_build_pack('lib/php')
.extension()
.from_build_pack('lib/env')
.extensions()
.from_build_pack('extensions')
.extensions()
.from_application('.extensions')
.extension()
.from_build_pack('lib/additional_commands')
.done()
.install()
.build_pack_utils()
.extensions()
.done()
.copy()
.under('{BP_DIR}/bin')
.into('{BUILD_DIR}/.bp/bin')
.where_name_is('rewrite')
.where_name_is('start')
.any_true()
.done()
.save()
.runtime_environment()
.process_list()
.done()
.create_start_script()
.using_process_manager()
.write())
print 'Finished: [%s]' % datetime.now()
|
# from math import *
# from visual import *
# from visual.graph import *
from vpython import *
# import vpython
scene.fullscreen = True
G = 0.5
spheres = [
sphere(pos=vector(0,0,0),radius =0.6,color=color.yellow,mass=sqrt(200),velocity=vector(0,0,0),a = vector(0,0,0),trail=curve(color=color.yellow)),
sphere(pos=vector(0,10,0),radius=0.2,color=color.blue,mass=-sqrt(10),velocity=vector(1,0,0),a=vector(0,0,0),trail=curve(color=color.blue)),
#sphere(pos=vector(0,12,0),radius=.08,color=color.green,mass=sqrt(4),velocity=vector(1.2,0,0.6),a=vector(0,0,0),trail=curve(color=color.green)),
sphere(pos=vector(0,5,0),radius=0.2,color=color.red,mass=-sqrt(8),velocity=vector(1.5,0,0.4),a=vector(0,0,0),trail=curve(color=color.red)),
#sphere(pos=vector(0,28,0),radius=.4,color=color.orange,mass=sqrt(80),velocity=vector(0.7,0,0.4),a=vector(0,0,0),trail=curve(color=color.orange)),
#sphere(pos=vector(0,32,0),radius=0.2,color=color.white,mass=-sqrt(10),velocity=vector(1.5,0,0.4),a=vector(0,0,0),trail=curve(color=color.white))
]
#print(spheres[0].a)
#print(len(spheres))
def acceleration1on2(sphere2,sphere1):
r = sphere2.pos - sphere1.pos
r_mag = mag(r)
normal_r = norm(r)
g = ((G*sphere1.mass*sphere2.mass)/pow(r_mag,2))*normal_r
#print(g)
return g
t = 0
dt = .01
while 1:
rate(100)
for i in spheres:
i.a = vector(0,0,0)
soi = vector(0,0,0)
for j in spheres:
if i!=j:
i.a = i.a + acceleration1on2(i,j)
for i in spheres:
#print(i.velocity)
i.velocity = i.velocity + i.a *dt
i.pos = i.pos+i.velocity*dt
#print(i.a)
i.trail.append(pos=i.pos)
scene.center=vector(spheres[0].pos.x,spheres[0].pos.y,spheres[0].pos.z)
# print(i.a)
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.resizeImage = exports.getImageSize = exports.getMimeType = exports.generateRandomImage = exports.deleteFile = exports.renameFile = exports.editFile = exports.createFile = exports.writeFile = exports.diskUsage = exports.processFiles = exports.renderPostFileInfos = exports.getFiles = undefined;
var downloadFile = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(url, formFieldName, fields) {
var path, proxy, options, result, response, data, file, mimeType;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
path = __dirname + '/../../tmp/upload_' + _uuid2.default.v4();
proxy = _config2.default.proxy();
options = { timeout: (0, _config2.default)('system.httpRequestTimeout') };
if (!/^vk\:\/\//.test(url)) {
_context.next = 10;
break;
}
_context.next = 6;
return (0, _vk2.default)('audio.getById', { audios: url.split('/')[2] });
case 6:
result = _context.sent;
options.url = result.response[0].url;
_context.next = 11;
break;
case 10:
if (proxy) {
options = _merge2.default.recursive(options, {
host: proxy.host,
port: proxy.port,
headers: { 'Proxy-Authorization': proxy.auth },
path: url
});
} else {
optons.url = url;
}
case 11:
_context.next = 13;
return _http2.default.request(options);
case 13:
response = _context.sent;
if (!(200 !== response.status)) {
_context.next = 16;
break;
}
return _context.abrupt('return', Promise.reject(new Error(Tools.translate('Failed to download file'))));
case 16:
_context.next = 18;
return response.body.read();
case 18:
data = _context.sent;
if (!(data.length < 1)) {
_context.next = 21;
break;
}
return _context.abrupt('return', Promise.reject(new Error(Tools.translate('File is empty'))));
case 21:
_context.next = 23;
return writeFile(path, data);
case 23:
file = {
name: url.split('/').pop(),
size: data.length,
path: path
};
setFileRating(file, formFieldName.substr(9), fields);
_context.next = 27;
return getMimeType(path);
case 27:
mimeType = _context.sent;
file.mimeType = mimeType;
return _context.abrupt('return', file);
case 30:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function downloadFile(_x, _x2, _x3) {
return ref.apply(this, arguments);
};
}();
var getFiles = exports.getFiles = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee4(fields, files) {
var downloadedFiles, hashes, fileInfos, existingFiles;
return regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return Tools.series(files.filter(function (file) {
if (file.size < 1) {
_fs2.default.remove(file.path).catch(function (err) {
_logger2.default.error(req, err.stack || err);
});
return false;
}
return true;
}), function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee2(file) {
var mimeType;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
setFileRating(file, file.fieldName.substr(5), fields);
_context2.next = 3;
return getMimeType(file.path);
case 3:
mimeType = _context2.sent;
file.mimeType = mimeType;
return _context2.abrupt('return', file);
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function (_x6) {
return ref.apply(this, arguments);
};
}(), true);
case 2:
files = _context4.sent;
_context4.next = 5;
return Tools.series((0, _underscore2.default)(fields).pick(function (_1, key) {
return (/^file_url_\S+$/.test(key)
);
}), function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee3(url, formFieldName) {
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return downloadFile(url, formFieldName, fields);
case 2:
return _context3.abrupt('return', _context3.sent);
case 3:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
return function (_x7, _x8) {
return ref.apply(this, arguments);
};
}(), true);
case 5:
downloadedFiles = _context4.sent;
files = files.concat(downloadedFiles);
hashes = typeof fields.fileHashes === 'string' ? fields.fileHashes.split(',').filter(function (hash) {
return !!hash;
}) : [];
_context4.next = 10;
return FilesModel.getFileInfosByHashes(hashes);
case 10:
fileInfos = _context4.sent;
existingFiles = fileInfos.map(function (fileInfo, index) {
var fi = {
name: fileInfo.name,
thumbName: fileInfo.thumb.name,
size: fileInfo.size,
boardName: fileInfo.boardName,
mimeType: fileInfo.mimeType,
rating: fileInfo.rating,
copy: true
};
setFileRating(fi, hashes[index], fields);
return fi;
});
return _context4.abrupt('return', files.concat(existingFiles));
case 13:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
return function getFiles(_x4, _x5) {
return ref.apply(this, arguments);
};
}();
var waitForFile = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee6(filePath, options) {
var f = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee5() {
var exists;
return regeneratorRuntime.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return _fs2.default.exists(filePath);
case 2:
exists = _context5.sent;
if (exists) {
_context5.next = 11;
break;
}
if (retry) {
_context5.next = 6;
break;
}
return _context5.abrupt('return', Promise.reject(new Error(Tools.translate('Failed to copy file'))));
case 6:
--retry;
_context5.next = 9;
return new Promise(function (resolve, reject) {
setTimeout(resolve, delay);
});
case 9:
_context5.next = 11;
return f();
case 11:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
return function f() {
return ref.apply(this, arguments);
};
}();
var delay, retry;
return regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
//TODO: That is not okay
delay = 50;
retry = 4;
_context6.next = 4;
return f();
case 4:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
return function waitForFile(_x9, _x10) {
return ref.apply(this, arguments);
};
}();
var generateFileName = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee7(file, plugin) {
var baseName, suffix, canonicalSuffix, thumbSuffix;
return regeneratorRuntime.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
_context7.next = 2;
return IPC.send('fileName');
case 2:
baseName = _context7.sent;
suffix = _path2.default.extname(file.name);
if (typeof suffix === 'string') {
suffix = suffix.substr(1);
}
canonicalSuffix = suffix ? suffix.toLowerCase() : '';
if (!suffix || !plugin.suffixMatchesMimeType(canonicalSuffix, file.mimeType)) {
suffix = plugin.defaultSuffixForMimeType(file.mimeType);
}
thumbSuffix = suffix;
if (typeof plugin.thumbnailSuffixForMimeType === 'function') {
thumbSuffix = plugin.thumbnailSuffixForMimeType(file.mimeType) || canonicalSuffix;
}
return _context7.abrupt('return', {
name: baseName + '.' + suffix,
thumbName: baseName + 's.' + thumbSuffix
});
case 10:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
return function generateFileName(_x11, _x12) {
return ref.apply(this, arguments);
};
}();
var createFileThumb = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee8(file, plugin) {
var thumbPath, result;
return regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
thumbPath = _path2.default.dirname(file.path) + '/' + _uuid2.default.v4();
file.thumbPath = thumbPath;
_context8.next = 4;
return plugin.createThumbnail(file, thumbPath, file.path);
case 4:
_context8.t0 = _context8.sent;
if (_context8.t0) {
_context8.next = 7;
break;
}
_context8.t0 = {};
case 7:
result = _context8.t0;
file.dimensions = result.dimensions || null;
file.extraData = result.extraData || null;
file.thumbDimensions = result.thumbDimensions;
if (result.ihash) {
file.ihash = result.ihash;
}
case 12:
case 'end':
return _context8.stop();
}
}
}, _callee8, this);
}));
return function createFileThumb(_x13, _x14) {
return ref.apply(this, arguments);
};
}();
var renderPostFileInfos = exports.renderPostFileInfos = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee10(post) {
return regeneratorRuntime.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
if (post) {
_context10.next = 2;
break;
}
return _context10.abrupt('return');
case 2:
_context10.next = 4;
return Tools.series(post.fileInfos || [], function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee9(fileInfo) {
var plugin, err;
return regeneratorRuntime.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
if (fileInfo) {
_context9.next = 2;
break;
}
return _context9.abrupt('return');
case 2:
fileInfo.sizeKB = fileInfo.size / 1024;
fileInfo.sizeText = fileInfo.sizeKB.toFixed(2) + ' ' + Tools.translate('KB');
plugin = selectThumbnailingPlugin(fileInfo.mimeType);
if (plugin) {
_context9.next = 9;
break;
}
err = new Error(Tools.translate('Unsupported file type: $[1]', '', fileInfo.mimeType));
_logger2.default.error(err.stack || err);
return _context9.abrupt('return');
case 9:
if (!(typeof plugin.renderPostFileInfo !== 'function')) {
_context9.next = 11;
break;
}
return _context9.abrupt('return');
case 11:
_context9.next = 13;
return plugin.renderPostFileInfo(fileInfo);
case 13:
case 'end':
return _context9.stop();
}
}
}, _callee9, this);
}));
return function (_x16) {
return ref.apply(this, arguments);
};
}());
case 4:
case 'end':
return _context10.stop();
}
}
}, _callee10, this);
}));
return function renderPostFileInfos(_x15) {
return ref.apply(this, arguments);
};
}();
var processFile = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee11(boardName, file, transaction) {
var plugin, fn, targetFilePath, targetThumbPath, sourceFilePath, sourceThumbPath, fileInfo, _sourceFilePath, data;
return regeneratorRuntime.wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
plugin = selectThumbnailingPlugin(file.mimeType);
if (plugin) {
_context11.next = 3;
break;
}
return _context11.abrupt('return', Promise.reject(new Error(Tools.translate('Unsupported file type: $[1]', '', file.mimeType))));
case 3:
_context11.next = 5;
return generateFileName(file, plugin);
case 5:
fn = _context11.sent;
targetFilePath = __dirname + '/../../public/' + boardName + '/src/' + fn.name;
targetThumbPath = __dirname + '/../../public/' + boardName + '/thumb/' + fn.thumbName;
transaction.addFile(targetFilePath);
transaction.addFile(targetThumbPath);
if (!file.copy) {
_context11.next = 25;
break;
}
sourceFilePath = __dirname + '/../../public/' + file.boardName + '/src/' + file.name;
sourceThumbPath = __dirname + '/../../public/' + file.boardName + '/thumb/' + file.thumbName;
_context11.next = 15;
return _fs2.default.copy(sourceFilePath, targetFilePath);
case 15:
_context11.next = 17;
return _fs2.default.copy(sourceThumbPath, targetThumbPath);
case 17:
_context11.next = 19;
return waitForFile(targetThumbPath);
case 19:
_context11.next = 21;
return FilesModel.getFileInfoByName(file.name);
case 21:
fileInfo = _context11.sent;
return _context11.abrupt('return', {
dimensions: fileInfo.dimensions,
extraData: fileInfo.extraData,
hash: fileInfo.hash,
ihash: fileInfo.ihash || null,
mimeType: fileInfo.mimeType,
name: fn.name,
rating: file.rating,
size: fileInfo.size,
thumb: {
dimensions: fileInfo.thumb.dimensions,
name: fn.thumbName
}
});
case 25:
_sourceFilePath = file.path;
if (file.hash) {
_context11.next = 31;
break;
}
_context11.next = 29;
return _fs2.default.read(file.path, 'b');
case 29:
data = _context11.sent;
file.hash = Tools.sha1(data);
case 31:
_context11.next = 33;
return createFileThumb(file, plugin);
case 33:
_context11.next = 35;
return _fs2.default.move(_sourceFilePath, targetFilePath);
case 35:
transaction.addFile(file.thumbPath);
_context11.next = 38;
return _fs2.default.move(file.thumbPath, targetThumbPath);
case 38:
_context11.next = 40;
return waitForFile(targetThumbPath);
case 40:
return _context11.abrupt('return', {
dimensions: file.dimensions,
extraData: file.extraData,
hash: file.hash,
ihash: file.ihash || null,
mimeType: file.mimeType,
name: fn.name,
rating: file.rating,
size: file.size,
thumb: {
dimensions: file.thumbDimensions,
name: fn.thumbName
}
});
case 41:
case 'end':
return _context11.stop();
}
}
}, _callee11, this);
}));
return function processFile(_x18, _x19, _x20) {
return ref.apply(this, arguments);
};
}();
var processFiles = exports.processFiles = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee13(boardName, files, transaction) {
var path;
return regeneratorRuntime.wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
if (!(files.length < 1)) {
_context13.next = 2;
break;
}
return _context13.abrupt('return', []);
case 2:
path = __dirname + '/../../public/' + boardName;
_context13.next = 5;
return mkpath(path + '/src');
case 5:
_context13.next = 7;
return mkpath(path + '/thumb');
case 7:
_context13.next = 9;
return Tools.series(files, function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee12(file) {
return regeneratorRuntime.wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
_context12.next = 2;
return processFile(boardName, file, transaction);
case 2:
return _context12.abrupt('return', _context12.sent);
case 3:
case 'end':
return _context12.stop();
}
}
}, _callee12, this);
}));
return function (_x24) {
return ref.apply(this, arguments);
};
}(), true);
case 9:
return _context13.abrupt('return', _context13.sent);
case 10:
case 'end':
return _context13.stop();
}
}
}, _callee13, this);
}));
return function processFiles(_x21, _x22, _x23) {
return ref.apply(this, arguments);
};
}();
var diskUsage = exports.diskUsage = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee14(path) {
return regeneratorRuntime.wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
_context14.next = 2;
return new Promise(function (resolve, reject) {
(0, _du2.default)(path, function (err, size) {
if (err) {
return reject(err);
}
resolve(size);
});
});
case 2:
return _context14.abrupt('return', _context14.sent);
case 3:
case 'end':
return _context14.stop();
}
}
}, _callee14, this);
}));
return function diskUsage(_x25) {
return ref.apply(this, arguments);
};
}();
var writeFile = exports.writeFile = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee15(filePath, data) {
var tmpFilePath, path, exists;
return regeneratorRuntime.wrap(function _callee15$(_context15) {
while (1) {
switch (_context15.prev = _context15.next) {
case 0:
tmpFilePath = filePath + '.tmp';
path = filePath.split('/').slice(0, -1).join('/');
_context15.next = 4;
return _fs2.default.exists(path);
case 4:
exists = _context15.sent;
if (exists) {
_context15.next = 8;
break;
}
_context15.next = 8;
return _fs2.default.makeTree(path);
case 8:
_context15.next = 10;
return _fs2.default.write(tmpFilePath, data);
case 10:
_context15.next = 12;
return _fs2.default.rename(tmpFilePath, filePath);
case 12:
case 'end':
return _context15.stop();
}
}
}, _callee15, this);
}));
return function writeFile(_x26, _x27) {
return ref.apply(this, arguments);
};
}();
var createFile = exports.createFile = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee16(dir, fileName) {
var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var file = _ref.file;
var isDir = _ref.isDir;
var path;
return regeneratorRuntime.wrap(function _callee16$(_context16) {
while (1) {
switch (_context16.prev = _context16.next) {
case 0:
if (dir.slice(-1)[0] !== '/') {
dir += '/';
}
path = __dirname + '/../../' + dir + fileName;
if (!isDir) {
_context16.next = 5;
break;
}
_context16.next = 5;
return _fs2.default.makeDirectory(path);
case 5:
if (!file) {
_context16.next = 10;
break;
}
_context16.next = 8;
return _fs2.default.move(file.path, path);
case 8:
_context16.next = 12;
break;
case 10:
_context16.next = 12;
return writeFile(path, '');
case 12:
case 'end':
return _context16.stop();
}
}
}, _callee16, this);
}));
return function createFile(_x28, _x29, _x30) {
return ref.apply(this, arguments);
};
}();
var editFile = exports.editFile = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee17(fileName, content) {
return regeneratorRuntime.wrap(function _callee17$(_context17) {
while (1) {
switch (_context17.prev = _context17.next) {
case 0:
_context17.next = 2;
return writeFile(__dirname + '/../../' + fileName, content);
case 2:
case 'end':
return _context17.stop();
}
}
}, _callee17, this);
}));
return function editFile(_x32, _x33) {
return ref.apply(this, arguments);
};
}();
var renameFile = exports.renameFile = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee18(oldFileName, fileName) {
var oldPath;
return regeneratorRuntime.wrap(function _callee18$(_context18) {
while (1) {
switch (_context18.prev = _context18.next) {
case 0:
oldPath = __dirname + '/../../' + oldFileName;
_context18.next = 3;
return _fs2.default.rename(oldPath, oldPath.split('/').slice(0, -1).join('/') + '/' + fileName);
case 3:
case 'end':
return _context18.stop();
}
}
}, _callee18, this);
}));
return function renameFile(_x34, _x35) {
return ref.apply(this, arguments);
};
}();
var deleteFile = exports.deleteFile = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee19(fileName) {
return regeneratorRuntime.wrap(function _callee19$(_context19) {
while (1) {
switch (_context19.prev = _context19.next) {
case 0:
_context19.next = 2;
return _fs2.default.removeTree(__dirname + '/../../' + fileName);
case 2:
case 'end':
return _context19.stop();
}
}
}, _callee19, this);
}));
return function deleteFile(_x36) {
return ref.apply(this, arguments);
};
}();
var generateRandomImage = exports.generateRandomImage = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee20(hash, mimeType, thumbPath) {
var canvas, ctx, data, img;
return regeneratorRuntime.wrap(function _callee20$(_context20) {
while (1) {
switch (_context20.prev = _context20.next) {
case 0:
canvas = new _canvas2.default(200, 200);
ctx = canvas.getContext('2d');
_jdenticon2.default.drawIcon(ctx, hash, 200);
_context20.next = 5;
return _fs2.default.read(__dirname + '/../../misc/thumbs/' + mimeType + '.png', 'b');
case 5:
data = _context20.sent;
img = new _canvas2.default.Image();
img.src = data;
ctx.drawImage(img, 0, 0, 200, 200);
_context20.next = 11;
return new Promise(function (resolve, reject) {
canvas.pngStream().pipe(_fs4.default.createWriteStream(thumbPath).on('error', reject).on('finish', resolve));
});
case 11:
return _context20.abrupt('return', _context20.sent);
case 12:
case 'end':
return _context20.stop();
}
}
}, _callee20, this);
}));
return function generateRandomImage(_x37, _x38, _x39) {
return ref.apply(this, arguments);
};
}();
var getMimeType = exports.getMimeType = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee21(fileName) {
return regeneratorRuntime.wrap(function _callee21$(_context21) {
while (1) {
switch (_context21.prev = _context21.next) {
case 0:
if (!(!fileName || typeof fileName !== 'string')) {
_context21.next = 2;
break;
}
return _context21.abrupt('return', null);
case 2:
_context21.prev = 2;
_context21.next = 5;
return new Promise(function (resolve, reject) {
_child_process2.default.exec('file --brief --mime-type ' + fileName, {
timeout: (0, _config2.default)('system.mimeTypeRetrievingTimeout'),
encoding: 'utf8',
stdio: [0, 'pipe', null]
}, function (err, out) {
if (err) {
return reject(err);
}
resolve(out ? out.replace(/\r*\n+/g, '') : null);
});
});
case 5:
return _context21.abrupt('return', _context21.sent);
case 8:
_context21.prev = 8;
_context21.t0 = _context21['catch'](2);
_logger2.default.error(_context21.t0.stack || _context21.t0);
return _context21.abrupt('return', null);
case 12:
case 'end':
return _context21.stop();
}
}
}, _callee21, this, [[2, 8]]);
}));
return function getMimeType(_x40) {
return ref.apply(this, arguments);
};
}();
var getImageSize = exports.getImageSize = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee22(fileName) {
return regeneratorRuntime.wrap(function _callee22$(_context22) {
while (1) {
switch (_context22.prev = _context22.next) {
case 0:
return _context22.abrupt('return', new Promise(function (resolve, reject) {
(0, _gm2.default)(fileName).size(function (err, value) {
if (err) {
return reject(err);
}
resolve(value);
});
}));
case 1:
case 'end':
return _context22.stop();
}
}
}, _callee22, this);
}));
return function getImageSize(_x41) {
return ref.apply(this, arguments);
};
}();
var resizeImage = exports.resizeImage = function () {
var ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee23(fileName, width, height, options) {
return regeneratorRuntime.wrap(function _callee23$(_context23) {
while (1) {
switch (_context23.prev = _context23.next) {
case 0:
return _context23.abrupt('return', new Promise(function (resolve, reject) {
(0, _gm2.default)(fileName).resize(width, height, options).quality(100).write(fileName, function (err) {
if (err) {
return reject(err);
}
resolve();
});
}));
case 1:
case 'end':
return _context23.stop();
}
}
}, _callee23, this);
}));
return function resizeImage(_x42, _x43, _x44, _x45) {
return ref.apply(this, arguments);
};
}();
exports.selectThumbnailingPlugin = selectThumbnailingPlugin;
exports.parseForm = parseForm;
exports.isAudioType = isAudioType;
exports.isVideoType = isVideoType;
exports.isPdfType = isPdfType;
exports.isImageType = isImageType;
var _underscore = require('underscore');
var _underscore2 = _interopRequireDefault(_underscore);
var _canvas = require('canvas');
var _canvas2 = _interopRequireDefault(_canvas);
var _child_process = require('child_process');
var _child_process2 = _interopRequireDefault(_child_process);
var _du = require('du');
var _du2 = _interopRequireDefault(_du);
var _fs = require('q-io/fs');
var _fs2 = _interopRequireDefault(_fs);
var _fs3 = require('fs');
var _fs4 = _interopRequireDefault(_fs3);
var _gm = require('gm');
var _gm2 = _interopRequireDefault(_gm);
var _http = require('q-io/http');
var _http2 = _interopRequireDefault(_http);
var _jdenticon = require('jdenticon');
var _jdenticon2 = _interopRequireDefault(_jdenticon);
var _merge = require('merge');
var _merge2 = _interopRequireDefault(_merge);
var _mkpath = require('mkpath');
var _mkpath2 = _interopRequireDefault(_mkpath);
var _multiparty = require('multiparty');
var _multiparty2 = _interopRequireDefault(_multiparty);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _promisifyNode = require('promisify-node');
var _promisifyNode2 = _interopRequireDefault(_promisifyNode);
var _uuid = require('uuid');
var _uuid2 = _interopRequireDefault(_uuid);
var _board = require('../boards/board');
var _board2 = _interopRequireDefault(_board);
var _files = require('../models/files');
var FilesModel = _interopRequireWildcard(_files);
var _config = require('../helpers/config');
var _config2 = _interopRequireDefault(_config);
var _ipc = require('../helpers/ipc');
var IPC = _interopRequireWildcard(_ipc);
var _logger = require('../helpers/logger');
var _logger2 = _interopRequireDefault(_logger);
var _tools = require('../helpers/tools');
var Tools = _interopRequireWildcard(_tools);
var _vk = require('../helpers/vk');
var _vk2 = _interopRequireDefault(_vk);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { return step("next", value); }, function (err) { return step("throw", err); }); } } return step("next"); }); }; }
var mkpath = (0, _promisifyNode2.default)('mkpath');
var FILE_RATINGS = new Set(['SFW', 'R-15', 'R-18', 'R-18G']);
_mkpath2.default.sync((0, _config2.default)('system.tmpPath') + '/form');
var fileTypePlugins = Tools.loadPlugins([__dirname + '/../file-types', __dirname + '/../file-types/custom']);
function setFileRating(file, id, fields) {
var rating = fields['file_' + id + '_rating'];
if (FILE_RATINGS.has(rating)) {
file.rating = rating;
} else {
file.rating = 'SFW';
}
}
function selectThumbnailingPlugin(mimeType) {
//TODO: Cache
return (0, _underscore2.default)(fileTypePlugins).find(function (plugin) {
return plugin.match(mimeType);
});
}
function parseForm() {
var req = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var formFields = req.formFields;
var formFiles = req.formFiles;
if (formFields) {
return {
fields: formFields,
files: formFiles || []
};
}
var form = new _multiparty2.default.Form();
form.uploadDir = (0, _config2.default)('system.tmpPath') + '/form';
form.autoFields = true;
form.autoFiles = true;
form.maxFieldsSize = (0, _config2.default)('system.maxFormFieldsSize');
return new Promise(function (resolve, reject) {
form.parse(req, function (err, fields, files) {
if (err) {
return reject(err);
}
resolve({
fields: (0, _underscore2.default)(fields).mapObject(function (value, key) {
return 1 === value.length ? value[0] : value;
}),
files: (0, _underscore2.default)((0, _underscore2.default)(files).toArray()).flatten().map(function (file) {
file.name = file.originalFilename;
return file;
})
});
});
});
}
function isAudioType(mimeType) {
return 'application/ogg' === mimeType || /^audio\//.test(mimeType);
}
function isVideoType(mimeType) {
return (/^video\//.test(mimeType)
);
}
function isPdfType(mimeType) {
return 'application/pdf' === mimeType;
}
function isImageType(mimeType) {
return (/^image\//.test(mimeType)
);
}
//# sourceMappingURL=files.js.map
|
import React from 'react'
import { Row, Col, Card, Input, message } from 'antd'
import D3LogarithmicSpiralLine from '../components/math/D3LogarithmicSpiralLine'
class LogarithmicSpiralLine extends React.Component {
constructor(props) {
super(props)
this.state = {
logarithmicSpiralLine: {
a: Math.E
}
}
this.onLogarithmicSpiralLineAChange = this.onLogarithmicSpiralLineAChange.bind(
this
)
}
onLogarithmicSpiralLineAChange = e => {
const { logarithmicSpiralLine } = this.state
const value = 1 * e.target.value
if (value <= 0 || value === 1) {
message.error('a > 0 且 a ≠ 1')
} else {
this.setState({
logarithmicSpiralLine: Object.assign({}, logarithmicSpiralLine, {
a: 1 * value
})
})
}
}
render() {
const { logarithmicSpiralLine } = this.state
return (
<div className="gutter-example logarithmic-spiral-demo">
<Row gutter={10}>
<Col className="gutter-row" md={24}>
<div className="gutter-box">
<Card
title={
<span>
{' '}
对数函数图像 - 极坐标, Y = logaX( a > 0, 且a≠ 1) 设: a ={' '}
<Input
placeholder="请输入a的值"
style={{
width: '20%'
}}
type="number"
onChange={this.onLogarithmicSpiralLineAChange}
value={logarithmicSpiralLine.a}
/>{' '}
</span>
}
bordered={false}
>
{' '}
<D3LogarithmicSpiralLine a={logarithmicSpiralLine.a} />{' '}
</Card>{' '}
</div>{' '}
</Col>{' '}
</Row>{' '}
</div>
)
}
}
export default LogarithmicSpiralLine
|
/*
Leaflet 1.0.1+ffcfcc1, a JS library for interactive maps. http://leafletjs.com
(c) 2010-2016 Vladimir Agafonkin, (c) 2010-2011 CloudMade
*/
!function (t, e, i) {
function n() {
var e = t.L;
o.noConflict = function () {
return t.L = e, this
}, t.L = o
}
var o = {version: "1.0.1+ffcfcc1"};
"object" == typeof module && "object" == typeof module.exports ? module.exports = o : "function" == typeof define && define.amd && define(o), "undefined" != typeof t && n(), o.Util = {
extend: function (t) {
var e, i, n, o;
for (i = 1, n = arguments.length; i < n; i++) {
o = arguments[i];
for (e in o) t[e] = o[e]
}
return t
}, create: Object.create || function () {
function t() {
}
return function (e) {
return t.prototype = e, new t
}
}(), bind: function (t, e) {
var i = Array.prototype.slice;
if (t.bind) return t.bind.apply(t, i.call(arguments, 1));
var n = i.call(arguments, 2);
return function () {
return t.apply(e, n.length ? n.concat(i.call(arguments)) : arguments)
}
}, stamp: function (t) {
return t._leaflet_id = t._leaflet_id || ++o.Util.lastId, t._leaflet_id
}, lastId: 0, throttle: function (t, e, i) {
var n, o, s, r;
return r = function () {
n = !1, o && (s.apply(i, o), o = !1)
}, s = function () {
n ? o = arguments : (t.apply(i, arguments), setTimeout(r, e), n = !0)
}
}, wrapNum: function (t, e, i) {
var n = e[1], o = e[0], s = n - o;
return t === n && i ? t : ((t - o) % s + s) % s + o
}, falseFn: function () {
return !1
}, formatNum: function (t, e) {
var i = Math.pow(10, e || 5);
return Math.round(t * i) / i
}, trim: function (t) {
return t.trim ? t.trim() : t.replace(/^\s+|\s+$/g, "")
}, splitWords: function (t) {
return o.Util.trim(t).split(/\s+/)
}, setOptions: function (t, e) {
t.hasOwnProperty("options") || (t.options = t.options ? o.Util.create(t.options) : {});
for (var i in e) t.options[i] = e[i];
return t.options
}, getParamString: function (t, e, i) {
var n = [];
for (var o in t) n.push(encodeURIComponent(i ? o.toUpperCase() : o) + "=" + encodeURIComponent(t[o]));
return (e && e.indexOf("?") !== -1 ? "&" : "?") + n.join("&")
}, template: function (t, e) {
return t.replace(o.Util.templateRe, function (t, n) {
var o = e[n];
if (o === i) throw new Error("No value provided for variable " + t);
return "function" == typeof o && (o = o(e)), o
})
}, templateRe: /\{ *([\w_\-]+) *\}/g, isArray: Array.isArray || function (t) {
return "[object Array]" === Object.prototype.toString.call(t)
}, indexOf: function (t, e) {
for (var i = 0; i < t.length; i++) if (t[i] === e) return i;
return -1
}, emptyImageUrl: "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
}, function () {
function e(e) {
return t["webkit" + e] || t["moz" + e] || t["ms" + e]
}
function i(e) {
var i = +new Date, o = Math.max(0, 16 - (i - n));
return n = i + o, t.setTimeout(e, o)
}
var n = 0, s = t.requestAnimationFrame || e("RequestAnimationFrame") || i,
r = t.cancelAnimationFrame || e("CancelAnimationFrame") || e("CancelRequestAnimationFrame") || function (e) {
t.clearTimeout(e)
};
o.Util.requestAnimFrame = function (e, n, r) {
return r && s === i ? void e.call(n) : s.call(t, o.bind(e, n))
}, o.Util.cancelAnimFrame = function (e) {
e && r.call(t, e)
}
}(), o.extend = o.Util.extend, o.bind = o.Util.bind, o.stamp = o.Util.stamp, o.setOptions = o.Util.setOptions, o.Class = function () {
}, o.Class.extend = function (t) {
var e = function () {
this.initialize && this.initialize.apply(this, arguments), this.callInitHooks()
}, i = e.__super__ = this.prototype, n = o.Util.create(i);
n.constructor = e, e.prototype = n;
for (var s in this) this.hasOwnProperty(s) && "prototype" !== s && (e[s] = this[s]);
return t.statics && (o.extend(e, t.statics), delete t.statics), t.includes && (o.Util.extend.apply(null, [n].concat(t.includes)), delete t.includes), n.options && (t.options = o.Util.extend(o.Util.create(n.options), t.options)), o.extend(n, t), n._initHooks = [], n.callInitHooks = function () {
if (!this._initHooksCalled) {
i.callInitHooks && i.callInitHooks.call(this), this._initHooksCalled = !0;
for (var t = 0, e = n._initHooks.length; t < e; t++) n._initHooks[t].call(this)
}
}, e
}, o.Class.include = function (t) {
return o.extend(this.prototype, t), this
}, o.Class.mergeOptions = function (t) {
return o.extend(this.prototype.options, t), this
}, o.Class.addInitHook = function (t) {
var e = Array.prototype.slice.call(arguments, 1), i = "function" == typeof t ? t : function () {
this[t].apply(this, e)
};
return this.prototype._initHooks = this.prototype._initHooks || [], this.prototype._initHooks.push(i), this
}, o.Evented = o.Class.extend({
on: function (t, e, i) {
if ("object" == typeof t) for (var n in t) this._on(n, t[n], e); else {
t = o.Util.splitWords(t);
for (var s = 0, r = t.length; s < r; s++) this._on(t[s], e, i)
}
return this
}, off: function (t, e, i) {
if (t) if ("object" == typeof t) for (var n in t) this._off(n, t[n], e); else {
t = o.Util.splitWords(t);
for (var s = 0, r = t.length; s < r; s++) this._off(t[s], e, i)
} else delete this._events;
return this
}, _on: function (t, e, n) {
this._events = this._events || {};
var o = this._events[t];
o || (o = [], this._events[t] = o), n === this && (n = i);
for (var s = {
fn: e,
ctx: n
}, r = o, a = 0, h = r.length; a < h; a++) if (r[a].fn === e && r[a].ctx === n) return;
r.push(s), o.count++
}, _off: function (t, e, n) {
var s, r, a;
if (this._events && (s = this._events[t])) {
if (!e) {
for (r = 0, a = s.length; r < a; r++) s[r].fn = o.Util.falseFn;
return void delete this._events[t]
}
if (n === this && (n = i), s) for (r = 0, a = s.length; r < a; r++) {
var h = s[r];
if (h.ctx === n && h.fn === e) return h.fn = o.Util.falseFn, this._firingCount && (this._events[t] = s = s.slice()), void s.splice(r, 1)
}
}
}, fire: function (t, e, i) {
if (!this.listens(t, i)) return this;
var n = o.Util.extend({}, e, {type: t, target: this});
if (this._events) {
var s = this._events[t];
if (s) {
this._firingCount = this._firingCount + 1 || 1;
for (var r = 0, a = s.length; r < a; r++) {
var h = s[r];
h.fn.call(h.ctx || this, n)
}
this._firingCount--
}
}
return i && this._propagateEvent(n), this
}, listens: function (t, e) {
var i = this._events && this._events[t];
if (i && i.length) return !0;
if (e) for (var n in this._eventParents) if (this._eventParents[n].listens(t, e)) return !0;
return !1
}, once: function (t, e, i) {
if ("object" == typeof t) {
for (var n in t) this.once(n, t[n], e);
return this
}
var s = o.bind(function () {
this.off(t, e, i).off(t, s, i)
}, this);
return this.on(t, e, i).on(t, s, i)
}, addEventParent: function (t) {
return this._eventParents = this._eventParents || {}, this._eventParents[o.stamp(t)] = t, this
}, removeEventParent: function (t) {
return this._eventParents && delete this._eventParents[o.stamp(t)], this
}, _propagateEvent: function (t) {
for (var e in this._eventParents) this._eventParents[e].fire(t.type, o.extend({layer: t.target}, t), !0)
}
});
var s = o.Evented.prototype;
s.addEventListener = s.on, s.removeEventListener = s.clearAllEventListeners = s.off, s.addOneTimeEventListener = s.once, s.fireEvent = s.fire, s.hasEventListeners = s.listens, o.Mixin = {Events: s}, function () {
var i = navigator.userAgent.toLowerCase(), n = e.documentElement, s = "ActiveXObject" in t,
r = i.indexOf("webkit") !== -1, a = i.indexOf("phantom") !== -1, h = i.search("android [23]") !== -1,
l = i.indexOf("chrome") !== -1, u = i.indexOf("gecko") !== -1 && !r && !t.opera && !s,
c = 0 === navigator.platform.indexOf("Win"),
d = "undefined" != typeof orientation || i.indexOf("mobile") !== -1,
_ = !t.PointerEvent && t.MSPointerEvent, m = t.PointerEvent || _, p = s && "transition" in n.style,
f = "WebKitCSSMatrix" in t && "m11" in new t.WebKitCSSMatrix && !h, g = "MozPerspective" in n.style,
v = "OTransition" in n.style,
y = !t.L_NO_TOUCH && (m || "ontouchstart" in t || t.DocumentTouch && e instanceof t.DocumentTouch);
o.Browser = {
ie: s,
ielt9: s && !e.addEventListener,
edge: "msLaunchUri" in navigator && !("documentMode" in e),
webkit: r,
gecko: u,
android: i.indexOf("android") !== -1,
android23: h,
chrome: l,
safari: !l && i.indexOf("safari") !== -1,
win: c,
ie3d: p,
webkit3d: f,
gecko3d: g,
opera12: v,
any3d: !t.L_DISABLE_3D && (p || f || g) && !v && !a,
mobile: d,
mobileWebkit: d && r,
mobileWebkit3d: d && f,
mobileOpera: d && t.opera,
mobileGecko: d && u,
touch: !!y,
msPointer: !!_,
pointer: !!m,
retina: (t.devicePixelRatio || t.screen.deviceXDPI / t.screen.logicalXDPI) > 1
}
}(), o.Point = function (t, e, i) {
this.x = i ? Math.round(t) : t, this.y = i ? Math.round(e) : e
}, o.Point.prototype = {
clone: function () {
return new o.Point(this.x, this.y)
}, add: function (t) {
return this.clone()._add(o.point(t))
}, _add: function (t) {
return this.x += t.x, this.y += t.y, this
}, subtract: function (t) {
return this.clone()._subtract(o.point(t))
}, _subtract: function (t) {
return this.x -= t.x, this.y -= t.y, this
}, divideBy: function (t) {
return this.clone()._divideBy(t)
}, _divideBy: function (t) {
return this.x /= t, this.y /= t, this
}, multiplyBy: function (t) {
return this.clone()._multiplyBy(t)
}, _multiplyBy: function (t) {
return this.x *= t, this.y *= t, this
}, scaleBy: function (t) {
return new o.Point(this.x * t.x, this.y * t.y)
}, unscaleBy: function (t) {
return new o.Point(this.x / t.x, this.y / t.y)
}, round: function () {
return this.clone()._round()
}, _round: function () {
return this.x = Math.round(this.x), this.y = Math.round(this.y), this
}, floor: function () {
return this.clone()._floor()
}, _floor: function () {
return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this
}, ceil: function () {
return this.clone()._ceil()
}, _ceil: function () {
return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this
}, distanceTo: function (t) {
t = o.point(t);
var e = t.x - this.x, i = t.y - this.y;
return Math.sqrt(e * e + i * i)
}, equals: function (t) {
return t = o.point(t), t.x === this.x && t.y === this.y
}, contains: function (t) {
return t = o.point(t), Math.abs(t.x) <= Math.abs(this.x) && Math.abs(t.y) <= Math.abs(this.y)
}, toString: function () {
return "Point(" + o.Util.formatNum(this.x) + ", " + o.Util.formatNum(this.y) + ")"
}
}, o.point = function (t, e, n) {
return t instanceof o.Point ? t : o.Util.isArray(t) ? new o.Point(t[0], t[1]) : t === i || null === t ? t : "object" == typeof t && "x" in t && "y" in t ? new o.Point(t.x, t.y) : new o.Point(t, e, n)
}, o.Bounds = function (t, e) {
if (t) for (var i = e ? [t, e] : t, n = 0, o = i.length; n < o; n++) this.extend(i[n])
}, o.Bounds.prototype = {
extend: function (t) {
return t = o.point(t), this.min || this.max ? (this.min.x = Math.min(t.x, this.min.x), this.max.x = Math.max(t.x, this.max.x), this.min.y = Math.min(t.y, this.min.y), this.max.y = Math.max(t.y, this.max.y)) : (this.min = t.clone(), this.max = t.clone()), this
}, getCenter: function (t) {
return new o.Point((this.min.x + this.max.x) / 2, (this.min.y + this.max.y) / 2, t)
}, getBottomLeft: function () {
return new o.Point(this.min.x, this.max.y)
}, getTopRight: function () {
return new o.Point(this.max.x, this.min.y)
}, getSize: function () {
return this.max.subtract(this.min)
}, contains: function (t) {
var e, i;
return t = "number" == typeof t[0] || t instanceof o.Point ? o.point(t) : o.bounds(t), t instanceof o.Bounds ? (e = t.min, i = t.max) : e = i = t, e.x >= this.min.x && i.x <= this.max.x && e.y >= this.min.y && i.y <= this.max.y
}, intersects: function (t) {
t = o.bounds(t);
var e = this.min, i = this.max, n = t.min, s = t.max, r = s.x >= e.x && n.x <= i.x,
a = s.y >= e.y && n.y <= i.y;
return r && a
}, overlaps: function (t) {
t = o.bounds(t);
var e = this.min, i = this.max, n = t.min, s = t.max, r = s.x > e.x && n.x < i.x,
a = s.y > e.y && n.y < i.y;
return r && a
}, isValid: function () {
return !(!this.min || !this.max)
}
}, o.bounds = function (t, e) {
return !t || t instanceof o.Bounds ? t : new o.Bounds(t, e)
}, o.Transformation = function (t, e, i, n) {
this._a = t, this._b = e, this._c = i, this._d = n
}, o.Transformation.prototype = {
transform: function (t, e) {
return this._transform(t.clone(), e)
}, _transform: function (t, e) {
return e = e || 1, t.x = e * (this._a * t.x + this._b), t.y = e * (this._c * t.y + this._d), t
}, untransform: function (t, e) {
return e = e || 1, new o.Point((t.x / e - this._b) / this._a, (t.y / e - this._d) / this._c)
}
}, o.DomUtil = {
get: function (t) {
return "string" == typeof t ? e.getElementById(t) : t
}, getStyle: function (t, i) {
var n = t.style[i] || t.currentStyle && t.currentStyle[i];
if ((!n || "auto" === n) && e.defaultView) {
var o = e.defaultView.getComputedStyle(t, null);
n = o ? o[i] : null
}
return "auto" === n ? null : n
}, create: function (t, i, n) {
var o = e.createElement(t);
return o.className = i || "", n && n.appendChild(o), o
}, remove: function (t) {
var e = t.parentNode;
e && e.removeChild(t)
}, empty: function (t) {
for (; t.firstChild;) t.removeChild(t.firstChild)
}, toFront: function (t) {
t.parentNode.appendChild(t)
}, toBack: function (t) {
var e = t.parentNode;
e.insertBefore(t, e.firstChild)
}, hasClass: function (t, e) {
if (t.classList !== i) return t.classList.contains(e);
var n = o.DomUtil.getClass(t);
return n.length > 0 && new RegExp("(^|\\s)" + e + "(\\s|$)").test(n)
}, addClass: function (t, e) {
if (t.classList !== i) for (var n = o.Util.splitWords(e), s = 0, r = n.length; s < r; s++) t.classList.add(n[s]); else if (!o.DomUtil.hasClass(t, e)) {
var a = o.DomUtil.getClass(t);
o.DomUtil.setClass(t, (a ? a + " " : "") + e)
}
}, removeClass: function (t, e) {
t.classList !== i ? t.classList.remove(e) : o.DomUtil.setClass(t, o.Util.trim((" " + o.DomUtil.getClass(t) + " ").replace(" " + e + " ", " ")))
}, setClass: function (t, e) {
t.className.baseVal === i ? t.className = e : t.className.baseVal = e
}, getClass: function (t) {
return t.className.baseVal === i ? t.className : t.className.baseVal
}, setOpacity: function (t, e) {
"opacity" in t.style ? t.style.opacity = e : "filter" in t.style && o.DomUtil._setOpacityIE(t, e)
}, _setOpacityIE: function (t, e) {
var i = !1, n = "DXImageTransform.Microsoft.Alpha";
try {
i = t.filters.item(n)
} catch (t) {
if (1 === e) return
}
e = Math.round(100 * e), i ? (i.Enabled = 100 !== e, i.Opacity = e) : t.style.filter += " progid:" + n + "(opacity=" + e + ")"
}, testProp: function (t) {
for (var i = e.documentElement.style, n = 0; n < t.length; n++) if (t[n] in i) return t[n];
return !1
}, setTransform: function (t, e, i) {
var n = e || new o.Point(0, 0);
t.style[o.DomUtil.TRANSFORM] = (o.Browser.ie3d ? "translate(" + n.x + "px," + n.y + "px)" : "translate3d(" + n.x + "px," + n.y + "px,0)") + (i ? " scale(" + i + ")" : "")
}, setPosition: function (t, e) {
t._leaflet_pos = e, o.Browser.any3d ? o.DomUtil.setTransform(t, e) : (t.style.left = e.x + "px", t.style.top = e.y + "px")
}, getPosition: function (t) {
return t._leaflet_pos || new o.Point(0, 0)
}
}, function () {
o.DomUtil.TRANSFORM = o.DomUtil.testProp(["transform", "WebkitTransform", "OTransform", "MozTransform", "msTransform"]);
var i = o.DomUtil.TRANSITION = o.DomUtil.testProp(["webkitTransition", "transition", "OTransition", "MozTransition", "msTransition"]);
if (o.DomUtil.TRANSITION_END = "webkitTransition" === i || "OTransition" === i ? i + "End" : "transitionend", "onselectstart" in e) o.DomUtil.disableTextSelection = function () {
o.DomEvent.on(t, "selectstart", o.DomEvent.preventDefault)
}, o.DomUtil.enableTextSelection = function () {
o.DomEvent.off(t, "selectstart", o.DomEvent.preventDefault)
}; else {
var n = o.DomUtil.testProp(["userSelect", "WebkitUserSelect", "OUserSelect", "MozUserSelect", "msUserSelect"]);
o.DomUtil.disableTextSelection = function () {
if (n) {
var t = e.documentElement.style;
this._userSelect = t[n], t[n] = "none"
}
}, o.DomUtil.enableTextSelection = function () {
n && (e.documentElement.style[n] = this._userSelect, delete this._userSelect)
}
}
o.DomUtil.disableImageDrag = function () {
o.DomEvent.on(t, "dragstart", o.DomEvent.preventDefault)
}, o.DomUtil.enableImageDrag = function () {
o.DomEvent.off(t, "dragstart", o.DomEvent.preventDefault)
}, o.DomUtil.preventOutline = function (e) {
for (; e.tabIndex === -1;) e = e.parentNode;
e && e.style && (o.DomUtil.restoreOutline(), this._outlineElement = e, this._outlineStyle = e.style.outline, e.style.outline = "none", o.DomEvent.on(t, "keydown", o.DomUtil.restoreOutline, this))
}, o.DomUtil.restoreOutline = function () {
this._outlineElement && (this._outlineElement.style.outline = this._outlineStyle, delete this._outlineElement, delete this._outlineStyle, o.DomEvent.off(t, "keydown", o.DomUtil.restoreOutline, this))
}
}(), o.LatLng = function (t, e, n) {
if (isNaN(t) || isNaN(e)) throw new Error("Invalid LatLng object: (" + t + ", " + e + ")");
this.lat = +t, this.lng = +e, n !== i && (this.alt = +n)
}, o.LatLng.prototype = {
equals: function (t, e) {
if (!t) return !1;
t = o.latLng(t);
var n = Math.max(Math.abs(this.lat - t.lat), Math.abs(this.lng - t.lng));
return n <= (e === i ? 1e-9 : e)
}, toString: function (t) {
return "LatLng(" + o.Util.formatNum(this.lat, t) + ", " + o.Util.formatNum(this.lng, t) + ")"
}, distanceTo: function (t) {
return o.CRS.Earth.distance(this, o.latLng(t))
}, wrap: function () {
return o.CRS.Earth.wrapLatLng(this)
}, toBounds: function (t) {
var e = 180 * t / 40075017, i = e / Math.cos(Math.PI / 180 * this.lat);
return o.latLngBounds([this.lat - e, this.lng - i], [this.lat + e, this.lng + i])
}, clone: function () {
return new o.LatLng(this.lat, this.lng, this.alt)
}
}, o.latLng = function (t, e, n) {
return t instanceof o.LatLng ? t : o.Util.isArray(t) && "object" != typeof t[0] ? 3 === t.length ? new o.LatLng(t[0], t[1], t[2]) : 2 === t.length ? new o.LatLng(t[0], t[1]) : null : t === i || null === t ? t : "object" == typeof t && "lat" in t ? new o.LatLng(t.lat, "lng" in t ? t.lng : t.lon, t.alt) : e === i ? null : new o.LatLng(t, e, n)
}, o.LatLngBounds = function (t, e) {
if (t) for (var i = e ? [t, e] : t, n = 0, o = i.length; n < o; n++) this.extend(i[n])
}, o.LatLngBounds.prototype = {
extend: function (t) {
var e, i, n = this._southWest, s = this._northEast;
if (t instanceof o.LatLng) e = t, i = t; else {
if (!(t instanceof o.LatLngBounds)) return t ? this.extend(o.latLng(t) || o.latLngBounds(t)) : this;
if (e = t._southWest, i = t._northEast, !e || !i) return this
}
return n || s ? (n.lat = Math.min(e.lat, n.lat), n.lng = Math.min(e.lng, n.lng), s.lat = Math.max(i.lat, s.lat), s.lng = Math.max(i.lng, s.lng)) : (this._southWest = new o.LatLng(e.lat, e.lng), this._northEast = new o.LatLng(i.lat, i.lng)), this
}, pad: function (t) {
var e = this._southWest, i = this._northEast, n = Math.abs(e.lat - i.lat) * t,
s = Math.abs(e.lng - i.lng) * t;
return new o.LatLngBounds(new o.LatLng(e.lat - n, e.lng - s), new o.LatLng(i.lat + n, i.lng + s))
}, getCenter: function () {
return new o.LatLng((this._southWest.lat + this._northEast.lat) / 2, (this._southWest.lng + this._northEast.lng) / 2)
}, getSouthWest: function () {
return this._southWest
}, getNorthEast: function () {
return this._northEast
}, getNorthWest: function () {
return new o.LatLng(this.getNorth(), this.getWest())
}, getSouthEast: function () {
return new o.LatLng(this.getSouth(), this.getEast())
}, getWest: function () {
return this._southWest.lng
}, getSouth: function () {
return this._southWest.lat
}, getEast: function () {
return this._northEast.lng
}, getNorth: function () {
return this._northEast.lat
}, contains: function (t) {
t = "number" == typeof t[0] || t instanceof o.LatLng ? o.latLng(t) : o.latLngBounds(t);
var e, i, n = this._southWest, s = this._northEast;
return t instanceof o.LatLngBounds ? (e = t.getSouthWest(), i = t.getNorthEast()) : e = i = t, e.lat >= n.lat && i.lat <= s.lat && e.lng >= n.lng && i.lng <= s.lng
}, intersects: function (t) {
t = o.latLngBounds(t);
var e = this._southWest, i = this._northEast, n = t.getSouthWest(), s = t.getNorthEast(),
r = s.lat >= e.lat && n.lat <= i.lat, a = s.lng >= e.lng && n.lng <= i.lng;
return r && a
}, overlaps: function (t) {
t = o.latLngBounds(t);
var e = this._southWest, i = this._northEast, n = t.getSouthWest(), s = t.getNorthEast(),
r = s.lat > e.lat && n.lat < i.lat, a = s.lng > e.lng && n.lng < i.lng;
return r && a
}, toBBoxString: function () {
return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(",")
}, equals: function (t) {
return !!t && (t = o.latLngBounds(t), this._southWest.equals(t.getSouthWest()) && this._northEast.equals(t.getNorthEast()))
}, isValid: function () {
return !(!this._southWest || !this._northEast)
}
}, o.latLngBounds = function (t, e) {
return t instanceof o.LatLngBounds ? t : new o.LatLngBounds(t, e)
}, o.Projection = {}, o.Projection.LonLat = {
project: function (t) {
return new o.Point(t.lng, t.lat)
}, unproject: function (t) {
return new o.LatLng(t.y, t.x)
}, bounds: o.bounds([-180, -90], [180, 90])
}, o.Projection.SphericalMercator = {
R: 6378137, MAX_LATITUDE: 85.0511287798, project: function (t) {
var e = Math.PI / 180, i = this.MAX_LATITUDE, n = Math.max(Math.min(i, t.lat), -i), s = Math.sin(n * e);
return new o.Point(this.R * t.lng * e, this.R * Math.log((1 + s) / (1 - s)) / 2)
}, unproject: function (t) {
var e = 180 / Math.PI;
return new o.LatLng((2 * Math.atan(Math.exp(t.y / this.R)) - Math.PI / 2) * e, t.x * e / this.R)
}, bounds: function () {
var t = 6378137 * Math.PI;
return o.bounds([-t, -t], [t, t])
}()
}, o.CRS = {
latLngToPoint: function (t, e) {
var i = this.projection.project(t), n = this.scale(e);
return this.transformation._transform(i, n)
}, pointToLatLng: function (t, e) {
var i = this.scale(e), n = this.transformation.untransform(t, i);
return this.projection.unproject(n)
}, project: function (t) {
return this.projection.project(t)
}, unproject: function (t) {
return this.projection.unproject(t)
}, scale: function (t) {
return 256 * Math.pow(2, t)
}, zoom: function (t) {
return Math.log(t / 256) / Math.LN2
}, getProjectedBounds: function (t) {
if (this.infinite) return null;
var e = this.projection.bounds, i = this.scale(t), n = this.transformation.transform(e.min, i),
s = this.transformation.transform(e.max, i);
return o.bounds(n, s)
}, infinite: !1, wrapLatLng: function (t) {
var e = this.wrapLng ? o.Util.wrapNum(t.lng, this.wrapLng, !0) : t.lng,
i = this.wrapLat ? o.Util.wrapNum(t.lat, this.wrapLat, !0) : t.lat, n = t.alt;
return o.latLng(i, e, n)
}
}, o.CRS.Simple = o.extend({}, o.CRS, {
projection: o.Projection.LonLat,
transformation: new o.Transformation(1, 0, -1, 0),
scale: function (t) {
return Math.pow(2, t)
},
zoom: function (t) {
return Math.log(t) / Math.LN2
},
distance: function (t, e) {
var i = e.lng - t.lng, n = e.lat - t.lat;
return Math.sqrt(i * i + n * n)
},
infinite: !0
}), o.CRS.Earth = o.extend({}, o.CRS, {
wrapLng: [-180, 180], R: 6371e3, distance: function (t, e) {
var i = Math.PI / 180, n = t.lat * i, o = e.lat * i,
s = Math.sin(n) * Math.sin(o) + Math.cos(n) * Math.cos(o) * Math.cos((e.lng - t.lng) * i);
return this.R * Math.acos(Math.min(s, 1))
}
}), o.CRS.EPSG3857 = o.extend({}, o.CRS.Earth, {
code: "EPSG:3857",
projection: o.Projection.SphericalMercator,
transformation: function () {
var t = .5 / (Math.PI * o.Projection.SphericalMercator.R);
return new o.Transformation(t, .5, -t, .5)
}()
}), o.CRS.EPSG900913 = o.extend({}, o.CRS.EPSG3857, {code: "EPSG:900913"}), o.CRS.EPSG4326 = o.extend({}, o.CRS.Earth, {
code: "EPSG:4326",
projection: o.Projection.LonLat,
transformation: new o.Transformation(1 / 180, 1, -1 / 180, .5)
}), o.Map = o.Evented.extend({
options: {
crs: o.CRS.EPSG3857,
center: i,
zoom: i,
minZoom: i,
maxZoom: i,
layers: [],
maxBounds: i,
renderer: i,
fadeAnimation: !0,
markerZoomAnimation: !0,
transform3DLimit: 8388608,
zoomSnap: 1,
zoomDelta: 1,
trackResize: !0
}, initialize: function (t, e) {
e = o.setOptions(this, e), this._initContainer(t), this._initLayout(), this._onResize = o.bind(this._onResize, this), this._initEvents(), e.maxBounds && this.setMaxBounds(e.maxBounds), e.zoom !== i && (this._zoom = this._limitZoom(e.zoom)), e.center && e.zoom !== i && this.setView(o.latLng(e.center), e.zoom, {reset: !0}), this._handlers = [], this._layers = {}, this._zoomBoundLayers = {}, this._sizeChanged = !0, this.callInitHooks(), this._addLayers(this.options.layers)
}, setView: function (t, e) {
return e = e === i ? this.getZoom() : e, this._resetView(o.latLng(t), e), this
}, setZoom: function (t, e) {
return this._loaded ? this.setView(this.getCenter(), t, {zoom: e}) : (this._zoom = t, this)
}, zoomIn: function (t, e) {
return t = t || (o.Browser.any3d ? this.options.zoomDelta : 1), this.setZoom(this._zoom + t, e)
}, zoomOut: function (t, e) {
return t = t || (o.Browser.any3d ? this.options.zoomDelta : 1), this.setZoom(this._zoom - t, e)
}, setZoomAround: function (t, e, i) {
var n = this.getZoomScale(e), s = this.getSize().divideBy(2),
r = t instanceof o.Point ? t : this.latLngToContainerPoint(t), a = r.subtract(s).multiplyBy(1 - 1 / n),
h = this.containerPointToLatLng(s.add(a));
return this.setView(h, e, {zoom: i})
}, _getBoundsCenterZoom: function (t, e) {
e = e || {}, t = t.getBounds ? t.getBounds() : o.latLngBounds(t);
var i = o.point(e.paddingTopLeft || e.padding || [0, 0]),
n = o.point(e.paddingBottomRight || e.padding || [0, 0]), s = this.getBoundsZoom(t, !1, i.add(n));
s = "number" == typeof e.maxZoom ? Math.min(e.maxZoom, s) : s;
var r = n.subtract(i).divideBy(2), a = this.project(t.getSouthWest(), s),
h = this.project(t.getNorthEast(), s), l = this.unproject(a.add(h).divideBy(2).add(r), s);
return {center: l, zoom: s}
}, fitBounds: function (t, e) {
if (t = o.latLngBounds(t), !t.isValid()) throw new Error("Bounds are not valid.");
var i = this._getBoundsCenterZoom(t, e);
return this.setView(i.center, i.zoom, e)
}, fitWorld: function (t) {
return this.fitBounds([[-90, -180], [90, 180]], t)
}, panTo: function (t, e) {
return this.setView(t, this._zoom, {pan: e})
}, panBy: function (t) {
return this.fire("movestart"), this._rawPanBy(o.point(t)), this.fire("move"), this.fire("moveend")
}, setMaxBounds: function (t) {
return t = o.latLngBounds(t), t.isValid() ? (this.options.maxBounds && this.off("moveend", this._panInsideMaxBounds), this.options.maxBounds = t, this._loaded && this._panInsideMaxBounds(), this.on("moveend", this._panInsideMaxBounds)) : (this.options.maxBounds = null, this.off("moveend", this._panInsideMaxBounds))
}, setMinZoom: function (t) {
return this.options.minZoom = t, this._loaded && this.getZoom() < this.options.minZoom ? this.setZoom(t) : this
}, setMaxZoom: function (t) {
return this.options.maxZoom = t, this._loaded && this.getZoom() > this.options.maxZoom ? this.setZoom(t) : this
}, panInsideBounds: function (t, e) {
this._enforcingBounds = !0;
var i = this.getCenter(), n = this._limitCenter(i, this._zoom, o.latLngBounds(t));
return i.equals(n) || this.panTo(n, e), this._enforcingBounds = !1, this
}, invalidateSize: function (t) {
if (!this._loaded) return this;
t = o.extend({animate: !1, pan: !0}, t === !0 ? {animate: !0} : t);
var e = this.getSize();
this._sizeChanged = !0, this._lastCenter = null;
var i = this.getSize(), n = e.divideBy(2).round(), s = i.divideBy(2).round(), r = n.subtract(s);
return r.x || r.y ? (t.animate && t.pan ? this.panBy(r) : (t.pan && this._rawPanBy(r), this.fire("move"), t.debounceMoveend ? (clearTimeout(this._sizeTimer), this._sizeTimer = setTimeout(o.bind(this.fire, this, "moveend"), 200)) : this.fire("moveend")), this.fire("resize", {
oldSize: e,
newSize: i
})) : this
}, stop: function () {
return this.setZoom(this._limitZoom(this._zoom)), this.options.zoomSnap || this.fire("viewreset"), this._stop()
}, addHandler: function (t, e) {
if (!e) return this;
var i = this[t] = new e(this);
return this._handlers.push(i), this.options[t] && i.enable(), this
}, remove: function () {
if (this._initEvents(!0), this._containerId !== this._container._leaflet_id) throw new Error("Map container is being reused by another instance");
try {
delete this._container._leaflet_id, delete this._containerId
} catch (t) {
this._container._leaflet_id = i, this._containerId = i
}
o.DomUtil.remove(this._mapPane), this._clearControlPos && this._clearControlPos(), this._clearHandlers(), this._loaded && this.fire("unload");
for (var t in this._layers) this._layers[t].remove();
return this
}, createPane: function (t, e) {
var i = "leaflet-pane" + (t ? " leaflet-" + t.replace("Pane", "") + "-pane" : ""),
n = o.DomUtil.create("div", i, e || this._mapPane);
return t && (this._panes[t] = n), n
}, getCenter: function () {
return this._checkIfLoaded(), this._lastCenter && !this._moved() ? this._lastCenter : this.layerPointToLatLng(this._getCenterLayerPoint())
}, getZoom: function () {
return this._zoom
}, getBounds: function () {
var t = this.getPixelBounds(), e = this.unproject(t.getBottomLeft()), i = this.unproject(t.getTopRight());
return new o.LatLngBounds(e, i)
}, getMinZoom: function () {
return this.options.minZoom === i ? this._layersMinZoom || 0 : this.options.minZoom
}, getMaxZoom: function () {
return this.options.maxZoom === i ? this._layersMaxZoom === i ? 1 / 0 : this._layersMaxZoom : this.options.maxZoom
}, getBoundsZoom: function (t, e, i) {
t = o.latLngBounds(t), i = o.point(i || [0, 0]);
var n = this.getZoom() || 0, s = this.getMinZoom(), r = this.getMaxZoom(), a = t.getNorthWest(),
h = t.getSouthEast(), l = this.getSize().subtract(i),
u = this.project(h, n).subtract(this.project(a, n)), c = o.Browser.any3d ? this.options.zoomSnap : 1,
d = Math.min(l.x / u.x, l.y / u.y);
return n = this.getScaleZoom(d, n), c && (n = Math.round(n / (c / 100)) * (c / 100), n = e ? Math.ceil(n / c) * c : Math.floor(n / c) * c), Math.max(s, Math.min(r, n))
}, getSize: function () {
return this._size && !this._sizeChanged || (this._size = new o.Point(this._container.clientWidth, this._container.clientHeight), this._sizeChanged = !1), this._size.clone()
}, getPixelBounds: function (t, e) {
var i = this._getTopLeftPoint(t, e);
return new o.Bounds(i, i.add(this.getSize()))
}, getPixelOrigin: function () {
return this._checkIfLoaded(), this._pixelOrigin
}, getPixelWorldBounds: function (t) {
return this.options.crs.getProjectedBounds(t === i ? this.getZoom() : t)
}, getPane: function (t) {
return "string" == typeof t ? this._panes[t] : t
}, getPanes: function () {
return this._panes
}, getContainer: function () {
return this._container
}, getZoomScale: function (t, e) {
var n = this.options.crs;
return e = e === i ? this._zoom : e, n.scale(t) / n.scale(e)
}, getScaleZoom: function (t, e) {
var n = this.options.crs;
e = e === i ? this._zoom : e;
var o = n.zoom(t * n.scale(e));
return isNaN(o) ? 1 / 0 : o
}, project: function (t, e) {
return e = e === i ? this._zoom : e, this.options.crs.latLngToPoint(o.latLng(t), e)
}, unproject: function (t, e) {
return e = e === i ? this._zoom : e, this.options.crs.pointToLatLng(o.point(t), e)
}, layerPointToLatLng: function (t) {
var e = o.point(t).add(this.getPixelOrigin());
return this.unproject(e)
}, latLngToLayerPoint: function (t) {
var e = this.project(o.latLng(t))._round();
return e._subtract(this.getPixelOrigin())
}, wrapLatLng: function (t) {
return this.options.crs.wrapLatLng(o.latLng(t))
}, distance: function (t, e) {
return this.options.crs.distance(o.latLng(t), o.latLng(e))
}, containerPointToLayerPoint: function (t) {
return o.point(t).subtract(this._getMapPanePos())
}, layerPointToContainerPoint: function (t) {
return o.point(t).add(this._getMapPanePos())
}, containerPointToLatLng: function (t) {
var e = this.containerPointToLayerPoint(o.point(t));
return this.layerPointToLatLng(e)
}, latLngToContainerPoint: function (t) {
return this.layerPointToContainerPoint(this.latLngToLayerPoint(o.latLng(t)))
}, mouseEventToContainerPoint: function (t) {
return o.DomEvent.getMousePosition(t, this._container)
}, mouseEventToLayerPoint: function (t) {
return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))
}, mouseEventToLatLng: function (t) {
return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))
}, _initContainer: function (t) {
var e = this._container = o.DomUtil.get(t);
if (!e) throw new Error("Map container not found.");
if (e._leaflet_id) throw new Error("Map container is already initialized.");
o.DomEvent.addListener(e, "scroll", this._onScroll, this), this._containerId = o.Util.stamp(e)
}, _initLayout: function () {
var t = this._container;
this._fadeAnimated = this.options.fadeAnimation && o.Browser.any3d, o.DomUtil.addClass(t, "leaflet-container" + (o.Browser.touch ? " leaflet-touch" : "") + (o.Browser.retina ? " leaflet-retina" : "") + (o.Browser.ielt9 ? " leaflet-oldie" : "") + (o.Browser.safari ? " leaflet-safari" : "") + (this._fadeAnimated ? " leaflet-fade-anim" : ""));
var e = o.DomUtil.getStyle(t, "position");
"absolute" !== e && "relative" !== e && "fixed" !== e && (t.style.position = "relative"), this._initPanes(), this._initControlPos && this._initControlPos()
}, _initPanes: function () {
var t = this._panes = {};
this._paneRenderers = {}, this._mapPane = this.createPane("mapPane", this._container), o.DomUtil.setPosition(this._mapPane, new o.Point(0, 0)), this.createPane("tilePane"), this.createPane("shadowPane"), this.createPane("overlayPane"), this.createPane("markerPane"), this.createPane("tooltipPane"), this.createPane("popupPane"), this.options.markerZoomAnimation || (o.DomUtil.addClass(t.markerPane, "leaflet-zoom-hide"), o.DomUtil.addClass(t.shadowPane, "leaflet-zoom-hide"))
}, _resetView: function (t, e) {
o.DomUtil.setPosition(this._mapPane, new o.Point(0, 0));
var i = !this._loaded;
this._loaded = !0, e = this._limitZoom(e), this.fire("viewprereset");
var n = this._zoom !== e;
this._moveStart(n)._move(t, e)._moveEnd(n), this.fire("viewreset"), i && this.fire("load")
}, _moveStart: function (t) {
return t && this.fire("zoomstart"), this.fire("movestart")
}, _move: function (t, e, n) {
e === i && (e = this._zoom);
var o = this._zoom !== e;
return this._zoom = e, this._lastCenter = t, this._pixelOrigin = this._getNewPixelOrigin(t), (o || n && n.pinch) && this.fire("zoom", n), this.fire("move", n)
}, _moveEnd: function (t) {
return t && this.fire("zoomend"), this.fire("moveend")
}, _stop: function () {
return o.Util.cancelAnimFrame(this._flyToFrame), this._panAnim && this._panAnim.stop(), this
}, _rawPanBy: function (t) {
o.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(t))
}, _getZoomSpan: function () {
return this.getMaxZoom() - this.getMinZoom()
}, _panInsideMaxBounds: function () {
this._enforcingBounds || this.panInsideBounds(this.options.maxBounds)
}, _checkIfLoaded: function () {
if (!this._loaded) throw new Error("Set map center and zoom first.")
}, _initEvents: function (e) {
if (o.DomEvent) {
this._targets = {}, this._targets[o.stamp(this._container)] = this;
var i = e ? "off" : "on";
o.DomEvent[i](this._container, "click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress", this._handleDOMEvent, this), this.options.trackResize && o.DomEvent[i](t, "resize", this._onResize, this), o.Browser.any3d && this.options.transform3DLimit && this[i]("moveend", this._onMoveEnd)
}
}, _onResize: function () {
o.Util.cancelAnimFrame(this._resizeRequest), this._resizeRequest = o.Util.requestAnimFrame(function () {
this.invalidateSize({debounceMoveend: !0})
}, this)
}, _onScroll: function () {
this._container.scrollTop = 0, this._container.scrollLeft = 0
}, _onMoveEnd: function () {
var t = this._getMapPanePos();
Math.max(Math.abs(t.x), Math.abs(t.y)) >= this.options.transform3DLimit && this._resetView(this.getCenter(), this.getZoom())
}, _findEventTargets: function (t, e) {
for (var i, n = [], s = "mouseout" === e || "mouseover" === e, r = t.target || t.srcElement, a = !1; r;) {
if (i = this._targets[o.stamp(r)], i && ("click" === e || "preclick" === e) && !t._simulated && this._draggableMoved(i)) {
a = !0;
break
}
if (i && i.listens(e, !0)) {
if (s && !o.DomEvent._isExternalTarget(r, t)) break;
if (n.push(i), s) break
}
if (r === this._container) break;
r = r.parentNode
}
return n.length || a || s || !o.DomEvent._isExternalTarget(r, t) || (n = [this]), n
}, _handleDOMEvent: function (t) {
if (this._loaded && !o.DomEvent._skipped(t)) {
var e = "keypress" === t.type && 13 === t.keyCode ? "click" : t.type;
"mousedown" === e && o.DomUtil.preventOutline(t.target || t.srcElement), this._fireDOMEvent(t, e)
}
}, _fireDOMEvent: function (t, e, i) {
if ("click" === t.type) {
var n = o.Util.extend({}, t);
n.type = "preclick", this._fireDOMEvent(n, n.type, i)
}
if (!t._stopped && (i = (i || []).concat(this._findEventTargets(t, e)), i.length)) {
var s = i[0];
"contextmenu" === e && s.listens(e, !0) && o.DomEvent.preventDefault(t);
var r = {originalEvent: t};
if ("keypress" !== t.type) {
var a = s instanceof o.Marker;
r.containerPoint = a ? this.latLngToContainerPoint(s.getLatLng()) : this.mouseEventToContainerPoint(t), r.layerPoint = this.containerPointToLayerPoint(r.containerPoint), r.latlng = a ? s.getLatLng() : this.layerPointToLatLng(r.layerPoint);
}
for (var h = 0; h < i.length; h++) if (i[h].fire(e, r, !0), r.originalEvent._stopped || i[h].options.nonBubblingEvents && o.Util.indexOf(i[h].options.nonBubblingEvents, e) !== -1) return
}
}, _draggableMoved: function (t) {
return t = t.dragging && t.dragging.enabled() ? t : this, t.dragging && t.dragging.moved() || this.boxZoom && this.boxZoom.moved()
}, _clearHandlers: function () {
for (var t = 0, e = this._handlers.length; t < e; t++) this._handlers[t].disable()
}, whenReady: function (t, e) {
return this._loaded ? t.call(e || this, {target: this}) : this.on("load", t, e), this
}, _getMapPanePos: function () {
return o.DomUtil.getPosition(this._mapPane) || new o.Point(0, 0)
}, _moved: function () {
var t = this._getMapPanePos();
return t && !t.equals([0, 0])
}, _getTopLeftPoint: function (t, e) {
var n = t && e !== i ? this._getNewPixelOrigin(t, e) : this.getPixelOrigin();
return n.subtract(this._getMapPanePos())
}, _getNewPixelOrigin: function (t, e) {
var i = this.getSize()._divideBy(2);
return this.project(t, e)._subtract(i)._add(this._getMapPanePos())._round()
}, _latLngToNewLayerPoint: function (t, e, i) {
var n = this._getNewPixelOrigin(i, e);
return this.project(t, e)._subtract(n)
}, _getCenterLayerPoint: function () {
return this.containerPointToLayerPoint(this.getSize()._divideBy(2))
}, _getCenterOffset: function (t) {
return this.latLngToLayerPoint(t).subtract(this._getCenterLayerPoint())
}, _limitCenter: function (t, e, i) {
if (!i) return t;
var n = this.project(t, e), s = this.getSize().divideBy(2), r = new o.Bounds(n.subtract(s), n.add(s)),
a = this._getBoundsOffset(r, i, e);
return a.round().equals([0, 0]) ? t : this.unproject(n.add(a), e)
}, _limitOffset: function (t, e) {
if (!e) return t;
var i = this.getPixelBounds(), n = new o.Bounds(i.min.add(t), i.max.add(t));
return t.add(this._getBoundsOffset(n, e))
}, _getBoundsOffset: function (t, e, i) {
var n = o.bounds(this.project(e.getNorthEast(), i), this.project(e.getSouthWest(), i)),
s = n.min.subtract(t.min), r = n.max.subtract(t.max), a = this._rebound(s.x, -r.x),
h = this._rebound(s.y, -r.y);
return new o.Point(a, h)
}, _rebound: function (t, e) {
return t + e > 0 ? Math.round(t - e) / 2 : Math.max(0, Math.ceil(t)) - Math.max(0, Math.floor(e))
}, _limitZoom: function (t) {
var e = this.getMinZoom(), i = this.getMaxZoom(), n = o.Browser.any3d ? this.options.zoomSnap : 1;
return n && (t = Math.round(t / n) * n), Math.max(e, Math.min(i, t))
}
}), o.map = function (t, e) {
return new o.Map(t, e)
}, o.Layer = o.Evented.extend({
options: {pane: "overlayPane", nonBubblingEvents: []}, addTo: function (t) {
return t.addLayer(this), this
}, remove: function () {
return this.removeFrom(this._map || this._mapToAdd)
}, removeFrom: function (t) {
return t && t.removeLayer(this), this
}, getPane: function (t) {
return this._map.getPane(t ? this.options[t] || t : this.options.pane)
}, addInteractiveTarget: function (t) {
return this._map._targets[o.stamp(t)] = this, this
}, removeInteractiveTarget: function (t) {
return delete this._map._targets[o.stamp(t)], this
}, _layerAdd: function (t) {
var e = t.target;
if (e.hasLayer(this)) {
if (this._map = e, this._zoomAnimated = e._zoomAnimated, this.getEvents) {
var i = this.getEvents();
e.on(i, this), this.once("remove", function () {
e.off(i, this)
}, this)
}
this.onAdd(e), this.getAttribution && this._map.attributionControl && this._map.attributionControl.addAttribution(this.getAttribution()), this.fire("add"), e.fire("layeradd", {layer: this})
}
}
}), o.Map.include({
addLayer: function (t) {
var e = o.stamp(t);
return this._layers[e] ? this : (this._layers[e] = t, t._mapToAdd = this, t.beforeAdd && t.beforeAdd(this), this.whenReady(t._layerAdd, t), this)
}, removeLayer: function (t) {
var e = o.stamp(t);
return this._layers[e] ? (this._loaded && t.onRemove(this), t.getAttribution && this.attributionControl && this.attributionControl.removeAttribution(t.getAttribution()), delete this._layers[e], this._loaded && (this.fire("layerremove", {layer: t}), t.fire("remove")), t._map = t._mapToAdd = null, this) : this
}, hasLayer: function (t) {
return !!t && o.stamp(t) in this._layers
}, eachLayer: function (t, e) {
for (var i in this._layers) t.call(e, this._layers[i]);
return this
}, _addLayers: function (t) {
t = t ? o.Util.isArray(t) ? t : [t] : [];
for (var e = 0, i = t.length; e < i; e++) this.addLayer(t[e])
}, _addZoomLimit: function (t) {
!isNaN(t.options.maxZoom) && isNaN(t.options.minZoom) || (this._zoomBoundLayers[o.stamp(t)] = t, this._updateZoomLevels())
}, _removeZoomLimit: function (t) {
var e = o.stamp(t);
this._zoomBoundLayers[e] && (delete this._zoomBoundLayers[e], this._updateZoomLevels())
}, _updateZoomLevels: function () {
var t = 1 / 0, e = -(1 / 0), n = this._getZoomSpan();
for (var o in this._zoomBoundLayers) {
var s = this._zoomBoundLayers[o].options;
t = s.minZoom === i ? t : Math.min(t, s.minZoom), e = s.maxZoom === i ? e : Math.max(e, s.maxZoom)
}
this._layersMaxZoom = e === -(1 / 0) ? i : e, this._layersMinZoom = t === 1 / 0 ? i : t, n !== this._getZoomSpan() && this.fire("zoomlevelschange")
}
}), o.Projection.Mercator = {
R: 6378137,
R_MINOR: 6356752.314245179,
bounds: o.bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
project: function (t) {
var e = Math.PI / 180, i = this.R, n = t.lat * e, s = this.R_MINOR / i, r = Math.sqrt(1 - s * s),
a = r * Math.sin(n), h = Math.tan(Math.PI / 4 - n / 2) / Math.pow((1 - a) / (1 + a), r / 2);
return n = -i * Math.log(Math.max(h, 1e-10)), new o.Point(t.lng * e * i, n)
},
unproject: function (t) {
for (var e, i = 180 / Math.PI, n = this.R, s = this.R_MINOR / n, r = Math.sqrt(1 - s * s), a = Math.exp(-t.y / n), h = Math.PI / 2 - 2 * Math.atan(a), l = 0, u = .1; l < 15 && Math.abs(u) > 1e-7; l++) e = r * Math.sin(h), e = Math.pow((1 - e) / (1 + e), r / 2), u = Math.PI / 2 - 2 * Math.atan(a * e) - h, h += u;
return new o.LatLng(h * i, t.x * i / n)
}
}, o.CRS.EPSG3395 = o.extend({}, o.CRS.Earth, {
code: "EPSG:3395",
projection: o.Projection.Mercator,
transformation: function () {
var t = .5 / (Math.PI * o.Projection.Mercator.R);
return new o.Transformation(t, .5, -t, .5)
}()
}), o.GridLayer = o.Layer.extend({
options: {
tileSize: 256,
opacity: 1,
updateWhenIdle: o.Browser.mobile,
updateWhenZooming: !0,
updateInterval: 200,
attribution: null,
zIndex: 1,
bounds: null,
minZoom: 0,
maxZoom: i,
noWrap: !1,
pane: "tilePane",
className: "",
keepBuffer: 2
}, initialize: function (t) {
o.setOptions(this, t)
}, onAdd: function () {
this._initContainer(), this._levels = {}, this._tiles = {}, this._resetView(), this._update()
}, beforeAdd: function (t) {
t._addZoomLimit(this)
}, onRemove: function (t) {
this._removeAllTiles(), o.DomUtil.remove(this._container), t._removeZoomLimit(this), this._container = null, this._tileZoom = null
}, bringToFront: function () {
return this._map && (o.DomUtil.toFront(this._container), this._setAutoZIndex(Math.max)), this
}, bringToBack: function () {
return this._map && (o.DomUtil.toBack(this._container), this._setAutoZIndex(Math.min)), this
}, getAttribution: function () {
return this.options.attribution
}, getContainer: function () {
return this._container
}, setOpacity: function (t) {
return this.options.opacity = t, this._updateOpacity(), this
}, setZIndex: function (t) {
return this.options.zIndex = t, this._updateZIndex(), this
}, isLoading: function () {
return this._loading
}, redraw: function () {
return this._map && (this._removeAllTiles(), this._update()), this
}, getEvents: function () {
var t = {
viewprereset: this._invalidateAll,
viewreset: this._resetView,
zoom: this._resetView,
moveend: this._onMoveEnd
};
return this.options.updateWhenIdle || (this._onMove || (this._onMove = o.Util.throttle(this._onMoveEnd, this.options.updateInterval, this)), t.move = this._onMove), this._zoomAnimated && (t.zoomanim = this._animateZoom), t
}, createTile: function () {
return e.createElement("div")
}, getTileSize: function () {
var t = this.options.tileSize;
return t instanceof o.Point ? t : new o.Point(t, t)
}, _updateZIndex: function () {
this._container && this.options.zIndex !== i && null !== this.options.zIndex && (this._container.style.zIndex = this.options.zIndex)
}, _setAutoZIndex: function (t) {
for (var e, i = this.getPane().children, n = -t(-(1 / 0), 1 / 0), o = 0, s = i.length; o < s; o++) e = i[o].style.zIndex, i[o] !== this._container && e && (n = t(n, +e));
isFinite(n) && (this.options.zIndex = n + t(-1, 1), this._updateZIndex())
}, _updateOpacity: function () {
if (this._map && !o.Browser.ielt9) {
o.DomUtil.setOpacity(this._container, this.options.opacity);
var t = +new Date, e = !1, i = !1;
for (var n in this._tiles) {
var s = this._tiles[n];
if (s.current && s.loaded) {
var r = Math.min(1, (t - s.loaded) / 200);
o.DomUtil.setOpacity(s.el, r), r < 1 ? e = !0 : (s.active && (i = !0), s.active = !0)
}
}
i && !this._noPrune && this._pruneTiles(), e && (o.Util.cancelAnimFrame(this._fadeFrame), this._fadeFrame = o.Util.requestAnimFrame(this._updateOpacity, this))
}
}, _initContainer: function () {
this._container || (this._container = o.DomUtil.create("div", "leaflet-layer " + (this.options.className || "")), this._updateZIndex(), this.options.opacity < 1 && this._updateOpacity(), this.getPane().appendChild(this._container))
}, _updateLevels: function () {
var t = this._tileZoom, e = this.options.maxZoom;
if (t === i) return i;
for (var n in this._levels) this._levels[n].el.children.length || n === t ? this._levels[n].el.style.zIndex = e - Math.abs(t - n) : (o.DomUtil.remove(this._levels[n].el), this._removeTilesAtZoom(n), delete this._levels[n]);
var s = this._levels[t], r = this._map;
return s || (s = this._levels[t] = {}, s.el = o.DomUtil.create("div", "leaflet-tile-container leaflet-zoom-animated", this._container), s.el.style.zIndex = e, s.origin = r.project(r.unproject(r.getPixelOrigin()), t).round(), s.zoom = t, this._setZoomTransform(s, r.getCenter(), r.getZoom()), o.Util.falseFn(s.el.offsetWidth)), this._level = s, s
}, _pruneTiles: function () {
if (this._map) {
var t, e, i = this._map.getZoom();
if (i > this.options.maxZoom || i < this.options.minZoom) return void this._removeAllTiles();
for (t in this._tiles) e = this._tiles[t], e.retain = e.current;
for (t in this._tiles) if (e = this._tiles[t], e.current && !e.active) {
var n = e.coords;
this._retainParent(n.x, n.y, n.z, n.z - 5) || this._retainChildren(n.x, n.y, n.z, n.z + 2)
}
for (t in this._tiles) this._tiles[t].retain || this._removeTile(t)
}
}, _removeTilesAtZoom: function (t) {
for (var e in this._tiles) this._tiles[e].coords.z === t && this._removeTile(e)
}, _removeAllTiles: function () {
for (var t in this._tiles) this._removeTile(t)
}, _invalidateAll: function () {
for (var t in this._levels) o.DomUtil.remove(this._levels[t].el), delete this._levels[t];
this._removeAllTiles(), this._tileZoom = null
}, _retainParent: function (t, e, i, n) {
var s = Math.floor(t / 2), r = Math.floor(e / 2), a = i - 1, h = new o.Point(+s, +r);
h.z = +a;
var l = this._tileCoordsToKey(h), u = this._tiles[l];
return u && u.active ? (u.retain = !0, !0) : (u && u.loaded && (u.retain = !0), a > n && this._retainParent(s, r, a, n))
}, _retainChildren: function (t, e, i, n) {
for (var s = 2 * t; s < 2 * t + 2; s++) for (var r = 2 * e; r < 2 * e + 2; r++) {
var a = new o.Point(s, r);
a.z = i + 1;
var h = this._tileCoordsToKey(a), l = this._tiles[h];
l && l.active ? l.retain = !0 : (l && l.loaded && (l.retain = !0), i + 1 < n && this._retainChildren(s, r, i + 1, n))
}
}, _resetView: function (t) {
var e = t && (t.pinch || t.flyTo);
this._setView(this._map.getCenter(), this._map.getZoom(), e, e)
}, _animateZoom: function (t) {
this._setView(t.center, t.zoom, !0, t.noUpdate)
}, _setView: function (t, e, n, o) {
var s = Math.round(e);
(this.options.maxZoom !== i && s > this.options.maxZoom || this.options.minZoom !== i && s < this.options.minZoom) && (s = i);
var r = this.options.updateWhenZooming && s !== this._tileZoom;
o && !r || (this._tileZoom = s, this._abortLoading && this._abortLoading(), this._updateLevels(), this._resetGrid(), s !== i && this._update(t), n || this._pruneTiles(), this._noPrune = !!n), this._setZoomTransforms(t, e)
}, _setZoomTransforms: function (t, e) {
for (var i in this._levels) this._setZoomTransform(this._levels[i], t, e)
}, _setZoomTransform: function (t, e, i) {
var n = this._map.getZoomScale(i, t.zoom),
s = t.origin.multiplyBy(n).subtract(this._map._getNewPixelOrigin(e, i)).round();
o.Browser.any3d ? o.DomUtil.setTransform(t.el, s, n) : o.DomUtil.setPosition(t.el, s)
}, _resetGrid: function () {
var t = this._map, e = t.options.crs, i = this._tileSize = this.getTileSize(), n = this._tileZoom,
o = this._map.getPixelWorldBounds(this._tileZoom);
o && (this._globalTileRange = this._pxBoundsToTileRange(o)), this._wrapX = e.wrapLng && !this.options.noWrap && [Math.floor(t.project([0, e.wrapLng[0]], n).x / i.x), Math.ceil(t.project([0, e.wrapLng[1]], n).x / i.y)], this._wrapY = e.wrapLat && !this.options.noWrap && [Math.floor(t.project([e.wrapLat[0], 0], n).y / i.x), Math.ceil(t.project([e.wrapLat[1], 0], n).y / i.y)]
}, _onMoveEnd: function () {
this._map && !this._map._animatingZoom && this._update()
}, _getTiledPixelBounds: function (t) {
var e = this._map, i = e._animatingZoom ? Math.max(e._animateToZoom, e.getZoom()) : e.getZoom(),
n = e.getZoomScale(i, this._tileZoom), s = e.project(t, this._tileZoom).floor(),
r = e.getSize().divideBy(2 * n);
return new o.Bounds(s.subtract(r), s.add(r))
}, _update: function (t) {
var n = this._map;
if (n) {
var s = n.getZoom();
if (t === i && (t = n.getCenter()), this._tileZoom !== i) {
var r = this._getTiledPixelBounds(t), a = this._pxBoundsToTileRange(r), h = a.getCenter(), l = [],
u = this.options.keepBuffer,
c = new o.Bounds(a.getBottomLeft().subtract([u, -u]), a.getTopRight().add([u, -u]));
for (var d in this._tiles) {
var _ = this._tiles[d].coords;
_.z === this._tileZoom && c.contains(o.point(_.x, _.y)) || (this._tiles[d].current = !1)
}
if (Math.abs(s - this._tileZoom) > 1) return void this._setView(t, s);
for (var m = a.min.y; m <= a.max.y; m++) for (var p = a.min.x; p <= a.max.x; p++) {
var f = new o.Point(p, m);
if (f.z = this._tileZoom, this._isValidTile(f)) {
var g = this._tiles[this._tileCoordsToKey(f)];
g ? g.current = !0 : l.push(f)
}
}
if (l.sort(function (t, e) {
return t.distanceTo(h) - e.distanceTo(h)
}), 0 !== l.length) {
this._loading || (this._loading = !0, this.fire("loading"));
var v = e.createDocumentFragment();
for (p = 0; p < l.length; p++) this._addTile(l[p], v);
this._level.el.appendChild(v)
}
}
}
}, _isValidTile: function (t) {
var e = this._map.options.crs;
if (!e.infinite) {
var i = this._globalTileRange;
if (!e.wrapLng && (t.x < i.min.x || t.x > i.max.x) || !e.wrapLat && (t.y < i.min.y || t.y > i.max.y)) return !1
}
if (!this.options.bounds) return !0;
var n = this._tileCoordsToBounds(t);
return o.latLngBounds(this.options.bounds).overlaps(n)
}, _keyToBounds: function (t) {
return this._tileCoordsToBounds(this._keyToTileCoords(t))
}, _tileCoordsToBounds: function (t) {
var e = this._map, i = this.getTileSize(), n = t.scaleBy(i), s = n.add(i), r = e.unproject(n, t.z),
a = e.unproject(s, t.z);
return this.options.noWrap || (r = e.wrapLatLng(r), a = e.wrapLatLng(a)), new o.LatLngBounds(r, a)
}, _tileCoordsToKey: function (t) {
return t.x + ":" + t.y + ":" + t.z
}, _keyToTileCoords: function (t) {
var e = t.split(":"), i = new o.Point(+e[0], +e[1]);
return i.z = +e[2], i
}, _removeTile: function (t) {
var e = this._tiles[t];
e && (o.DomUtil.remove(e.el), delete this._tiles[t], this.fire("tileunload", {
tile: e.el,
coords: this._keyToTileCoords(t)
}))
}, _initTile: function (t) {
o.DomUtil.addClass(t, "leaflet-tile");
var e = this.getTileSize();
t.style.width = e.x + "px", t.style.height = e.y + "px", t.onselectstart = o.Util.falseFn, t.onmousemove = o.Util.falseFn, o.Browser.ielt9 && this.options.opacity < 1 && o.DomUtil.setOpacity(t, this.options.opacity), o.Browser.android && !o.Browser.android23 && (t.style.WebkitBackfaceVisibility = "hidden")
}, _addTile: function (t, e) {
var i = this._getTilePos(t), n = this._tileCoordsToKey(t),
s = this.createTile(this._wrapCoords(t), o.bind(this._tileReady, this, t));
this._initTile(s), this.createTile.length < 2 && o.Util.requestAnimFrame(o.bind(this._tileReady, this, t, null, s)), o.DomUtil.setPosition(s, i), this._tiles[n] = {
el: s,
coords: t,
current: !0
}, e.appendChild(s), this.fire("tileloadstart", {tile: s, coords: t})
}, _tileReady: function (t, e, i) {
if (this._map) {
e && this.fire("tileerror", {error: e, tile: i, coords: t});
var n = this._tileCoordsToKey(t);
i = this._tiles[n], i && (i.loaded = +new Date, this._map._fadeAnimated ? (o.DomUtil.setOpacity(i.el, 0), o.Util.cancelAnimFrame(this._fadeFrame), this._fadeFrame = o.Util.requestAnimFrame(this._updateOpacity, this)) : (i.active = !0, this._pruneTiles()), e || (o.DomUtil.addClass(i.el, "leaflet-tile-loaded"), this.fire("tileload", {
tile: i.el,
coords: t
})), this._noTilesToLoad() && (this._loading = !1, this.fire("load"), o.Browser.ielt9 || !this._map._fadeAnimated ? o.Util.requestAnimFrame(this._pruneTiles, this) : setTimeout(o.bind(this._pruneTiles, this), 250)))
}
}, _getTilePos: function (t) {
return t.scaleBy(this.getTileSize()).subtract(this._level.origin)
}, _wrapCoords: function (t) {
var e = new o.Point(this._wrapX ? o.Util.wrapNum(t.x, this._wrapX) : t.x, this._wrapY ? o.Util.wrapNum(t.y, this._wrapY) : t.y);
return e.z = t.z, e
}, _pxBoundsToTileRange: function (t) {
var e = this.getTileSize();
return new o.Bounds(t.min.unscaleBy(e).floor(), t.max.unscaleBy(e).ceil().subtract([1, 1]))
}, _noTilesToLoad: function () {
for (var t in this._tiles) if (!this._tiles[t].loaded) return !1;
return !0
}
}), o.gridLayer = function (t) {
return new o.GridLayer(t)
}, o.TileLayer = o.GridLayer.extend({
options: {
minZoom: 0,
maxZoom: 18,
maxNativeZoom: null,
subdomains: "abc",
errorTileUrl: "",
zoomOffset: 0,
tms: !1,
zoomReverse: !1,
detectRetina: !1,
crossOrigin: !1
}, initialize: function (t, e) {
this._url = t, e = o.setOptions(this, e), e.detectRetina && o.Browser.retina && e.maxZoom > 0 && (e.tileSize = Math.floor(e.tileSize / 2), e.zoomReverse ? (e.zoomOffset--, e.minZoom++) : (e.zoomOffset++, e.maxZoom--), e.minZoom = Math.max(0, e.minZoom)), "string" == typeof e.subdomains && (e.subdomains = e.subdomains.split("")), o.Browser.android || this.on("tileunload", this._onTileRemove)
}, setUrl: function (t, e) {
return this._url = t, e || this.redraw(), this
}, createTile: function (t, i) {
var n = e.createElement("img");
return o.DomEvent.on(n, "load", o.bind(this._tileOnLoad, this, i, n)), o.DomEvent.on(n, "error", o.bind(this._tileOnError, this, i, n)), this.options.crossOrigin && (n.crossOrigin = ""), n.alt = "", n.src = this.getTileUrl(t), n
}, getTileUrl: function (t) {
var e = {
r: o.Browser.retina ? "@2x" : "",
s: this._getSubdomain(t),
x: t.x,
y: t.y,
z: this._getZoomForUrl()
};
if (this._map && !this._map.options.crs.infinite) {
var i = this._globalTileRange.max.y - t.y;
this.options.tms && (e.y = i), e["-y"] = i
}
return o.Util.template(this._url, o.extend(e, this.options))
}, _tileOnLoad: function (t, e) {
o.Browser.ielt9 ? setTimeout(o.bind(t, this, null, e), 0) : t(null, e)
}, _tileOnError: function (t, e, i) {
var n = this.options.errorTileUrl;
n && (e.src = n), t(i, e)
}, getTileSize: function () {
var t = this._map, e = o.GridLayer.prototype.getTileSize.call(this),
i = this._tileZoom + this.options.zoomOffset, n = this.options.maxNativeZoom;
return null !== n && i > n ? e.divideBy(t.getZoomScale(n, i)).round() : e
}, _onTileRemove: function (t) {
t.tile.onload = null
}, _getZoomForUrl: function () {
var t = this.options, e = this._tileZoom;
return t.zoomReverse && (e = t.maxZoom - e), e += t.zoomOffset, null !== t.maxNativeZoom ? Math.min(e, t.maxNativeZoom) : e
}, _getSubdomain: function (t) {
var e = Math.abs(t.x + t.y) % this.options.subdomains.length;
return this.options.subdomains[e]
}, _abortLoading: function () {
var t, e;
for (t in this._tiles) this._tiles[t].coords.z !== this._tileZoom && (e = this._tiles[t].el, e.onload = o.Util.falseFn, e.onerror = o.Util.falseFn, e.complete || (e.src = o.Util.emptyImageUrl, o.DomUtil.remove(e)))
}
}), o.tileLayer = function (t, e) {
return new o.TileLayer(t, e)
}, o.TileLayer.WMS = o.TileLayer.extend({
defaultWmsParams: {
service: "WMS",
request: "GetMap",
layers: "",
styles: "",
format: "image/jpeg",
transparent: !1,
version: "1.1.1"
}, options: {crs: null, uppercase: !1}, initialize: function (t, e) {
this._url = t;
var i = o.extend({}, this.defaultWmsParams);
for (var n in e) n in this.options || (i[n] = e[n]);
e = o.setOptions(this, e), i.width = i.height = e.tileSize * (e.detectRetina && o.Browser.retina ? 2 : 1), this.wmsParams = i
}, onAdd: function (t) {
this._crs = this.options.crs || t.options.crs, this._wmsVersion = parseFloat(this.wmsParams.version);
var e = this._wmsVersion >= 1.3 ? "crs" : "srs";
this.wmsParams[e] = this._crs.code, o.TileLayer.prototype.onAdd.call(this, t)
}, getTileUrl: function (t) {
var e = this._tileCoordsToBounds(t), i = this._crs.project(e.getNorthWest()),
n = this._crs.project(e.getSouthEast()),
s = (this._wmsVersion >= 1.3 && this._crs === o.CRS.EPSG4326 ? [n.y, i.x, i.y, n.x] : [i.x, n.y, n.x, i.y]).join(","),
r = o.TileLayer.prototype.getTileUrl.call(this, t);
return r + o.Util.getParamString(this.wmsParams, r, this.options.uppercase) + (this.options.uppercase ? "&BBOX=" : "&bbox=") + s
}, setParams: function (t, e) {
return o.extend(this.wmsParams, t), e || this.redraw(), this
}
}), o.tileLayer.wms = function (t, e) {
return new o.TileLayer.WMS(t, e)
}, o.ImageOverlay = o.Layer.extend({
options: {opacity: 1, alt: "", interactive: !1, attribution: null, crossOrigin: !1},
initialize: function (t, e, i) {
this._url = t, this._bounds = o.latLngBounds(e), o.setOptions(this, i)
},
onAdd: function () {
this._image || (this._initImage(), this.options.opacity < 1 && this._updateOpacity()), this.options.interactive && (o.DomUtil.addClass(this._image, "leaflet-interactive"), this.addInteractiveTarget(this._image)), this.getPane().appendChild(this._image), this._reset()
},
onRemove: function () {
o.DomUtil.remove(this._image), this.options.interactive && this.removeInteractiveTarget(this._image)
},
setOpacity: function (t) {
return this.options.opacity = t, this._image && this._updateOpacity(), this
},
setStyle: function (t) {
return t.opacity && this.setOpacity(t.opacity), this
},
bringToFront: function () {
return this._map && o.DomUtil.toFront(this._image), this
},
bringToBack: function () {
return this._map && o.DomUtil.toBack(this._image), this
},
setUrl: function (t) {
return this._url = t, this._image && (this._image.src = t), this
},
setBounds: function (t) {
return this._bounds = t, this._map && this._reset(), this
},
getAttribution: function () {
return this.options.attribution
},
getEvents: function () {
var t = {zoom: this._reset, viewreset: this._reset};
return this._zoomAnimated && (t.zoomanim = this._animateZoom), t
},
getBounds: function () {
return this._bounds
},
getElement: function () {
return this._image
},
_initImage: function () {
var t = this._image = o.DomUtil.create("img", "leaflet-image-layer " + (this._zoomAnimated ? "leaflet-zoom-animated" : ""));
t.onselectstart = o.Util.falseFn, t.onmousemove = o.Util.falseFn, t.onload = o.bind(this.fire, this, "load"), this.options.crossOrigin && (t.crossOrigin = ""), t.src = this._url, t.alt = this.options.alt
},
_animateZoom: function (t) {
var e = this._map.getZoomScale(t.zoom),
i = this._map._latLngToNewLayerPoint(this._bounds.getNorthWest(), t.zoom, t.center);
o.DomUtil.setTransform(this._image, i, e)
},
_reset: function () {
var t = this._image,
e = new o.Bounds(this._map.latLngToLayerPoint(this._bounds.getNorthWest()), this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
i = e.getSize();
o.DomUtil.setPosition(t, e.min), t.style.width = i.x + "px", t.style.height = i.y + "px"
},
_updateOpacity: function () {
o.DomUtil.setOpacity(this._image, this.options.opacity)
}
}), o.imageOverlay = function (t, e, i) {
return new o.ImageOverlay(t, e, i)
}, o.Icon = o.Class.extend({
initialize: function (t) {
o.setOptions(this, t)
}, createIcon: function (t) {
return this._createIcon("icon", t)
}, createShadow: function (t) {
return this._createIcon("shadow", t)
}, _createIcon: function (t, e) {
var i = this._getIconUrl(t);
if (!i) {
if ("icon" === t) throw new Error("iconUrl not set in Icon options (see the docs).");
return null
}
var n = this._createImg(i, e && "IMG" === e.tagName ? e : null);
return this._setIconStyles(n, t), n
}, _setIconStyles: function (t, e) {
var i = this.options, n = i[e + "Size"];
"number" == typeof n && (n = [n, n]);
var s = o.point(n), r = o.point("shadow" === e && i.shadowAnchor || i.iconAnchor || s && s.divideBy(2, !0));
t.className = "leaflet-marker-" + e + " " + (i.className || ""), r && (t.style.marginLeft = -r.x + "px", t.style.marginTop = -r.y + "px"), s && (t.style.width = s.x + "px", t.style.height = s.y + "px")
}, _createImg: function (t, i) {
return i = i || e.createElement("img"), i.src = t, i
}, _getIconUrl: function (t) {
return o.Browser.retina && this.options[t + "RetinaUrl"] || this.options[t + "Url"]
}
}), o.icon = function (t) {
return new o.Icon(t)
}, o.Icon.Default = o.Icon.extend({
options: {
iconUrl: "marker-icon.png",
iconRetinaUrl: "marker-icon-2x.png",
shadowUrl: "marker-shadow.png",
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
tooltipAnchor: [16, -28],
shadowSize: [41, 41]
}, _getIconUrl: function (t) {
return o.Icon.Default.imagePath || (o.Icon.Default.imagePath = this._detectIconPath()), (this.options.imagePath || o.Icon.Default.imagePath) + o.Icon.prototype._getIconUrl.call(this, t)
}, _detectIconPath: function () {
var t = o.DomUtil.create("div", "leaflet-default-icon-path", e.body),
i = o.DomUtil.getStyle(t, "background-image") || o.DomUtil.getStyle(t, "backgroundImage");
return e.body.removeChild(t), 0 === i.indexOf("url") ? i.replace(/^url\([\"\']?/, "").replace(/marker-icon\.png[\"\']?\)$/, "") : ""
}
}), o.Marker = o.Layer.extend({
options: {
icon: new o.Icon.Default,
interactive: !0,
draggable: !1,
keyboard: !0,
title: "",
alt: "",
zIndexOffset: 0,
opacity: 1,
riseOnHover: !1,
riseOffset: 250,
pane: "markerPane",
nonBubblingEvents: ["click", "dblclick", "mouseover", "mouseout", "contextmenu"]
}, initialize: function (t, e) {
o.setOptions(this, e), this._latlng = o.latLng(t)
}, onAdd: function (t) {
this._zoomAnimated = this._zoomAnimated && t.options.markerZoomAnimation, this._zoomAnimated && t.on("zoomanim", this._animateZoom, this), this._initIcon(), this.update()
}, onRemove: function (t) {
this.dragging && this.dragging.enabled() && (this.options.draggable = !0, this.dragging.removeHooks()), this._zoomAnimated && t.off("zoomanim", this._animateZoom, this), this._removeIcon(), this._removeShadow()
}, getEvents: function () {
return {zoom: this.update, viewreset: this.update}
}, getLatLng: function () {
return this._latlng
}, setLatLng: function (t) {
var e = this._latlng;
return this._latlng = o.latLng(t), this.update(), this.fire("move", {oldLatLng: e, latlng: this._latlng})
}, setZIndexOffset: function (t) {
return this.options.zIndexOffset = t, this.update()
}, setIcon: function (t) {
return this.options.icon = t, this._map && (this._initIcon(), this.update()), this._popup && this.bindPopup(this._popup, this._popup.options), this
}, getElement: function () {
return this._icon
}, update: function () {
if (this._icon) {
var t = this._map.latLngToLayerPoint(this._latlng).round();
this._setPos(t)
}
return this
}, _initIcon: function () {
var t = this.options, e = "leaflet-zoom-" + (this._zoomAnimated ? "animated" : "hide"),
i = t.icon.createIcon(this._icon), n = !1;
i !== this._icon && (this._icon && this._removeIcon(), n = !0, t.title && (i.title = t.title), t.alt && (i.alt = t.alt)), o.DomUtil.addClass(i, e), t.keyboard && (i.tabIndex = "0"), this._icon = i, t.riseOnHover && this.on({
mouseover: this._bringToFront,
mouseout: this._resetZIndex
});
var s = t.icon.createShadow(this._shadow), r = !1;
s !== this._shadow && (this._removeShadow(), r = !0), s && o.DomUtil.addClass(s, e), this._shadow = s, t.opacity < 1 && this._updateOpacity(), n && this.getPane().appendChild(this._icon), this._initInteraction(), s && r && this.getPane("shadowPane").appendChild(this._shadow)
}, _removeIcon: function () {
this.options.riseOnHover && this.off({
mouseover: this._bringToFront,
mouseout: this._resetZIndex
}), o.DomUtil.remove(this._icon), this.removeInteractiveTarget(this._icon), this._icon = null
}, _removeShadow: function () {
this._shadow && o.DomUtil.remove(this._shadow), this._shadow = null
}, _setPos: function (t) {
o.DomUtil.setPosition(this._icon, t), this._shadow && o.DomUtil.setPosition(this._shadow, t), this._zIndex = t.y + this.options.zIndexOffset, this._resetZIndex()
}, _updateZIndex: function (t) {
this._icon.style.zIndex = this._zIndex + t
}, _animateZoom: function (t) {
var e = this._map._latLngToNewLayerPoint(this._latlng, t.zoom, t.center).round();
this._setPos(e)
}, _initInteraction: function () {
if (this.options.interactive && (o.DomUtil.addClass(this._icon, "leaflet-interactive"), this.addInteractiveTarget(this._icon), o.Handler.MarkerDrag)) {
var t = this.options.draggable;
this.dragging && (t = this.dragging.enabled(), this.dragging.disable()), this.dragging = new o.Handler.MarkerDrag(this), t && this.dragging.enable()
}
}, setOpacity: function (t) {
return this.options.opacity = t, this._map && this._updateOpacity(), this
}, _updateOpacity: function () {
var t = this.options.opacity;
o.DomUtil.setOpacity(this._icon, t), this._shadow && o.DomUtil.setOpacity(this._shadow, t)
}, _bringToFront: function () {
this._updateZIndex(this.options.riseOffset)
}, _resetZIndex: function () {
this._updateZIndex(0)
}
}), o.marker = function (t, e) {
return new o.Marker(t, e)
}, o.DivIcon = o.Icon.extend({
options: {iconSize: [12, 12], html: !1, bgPos: null, className: "leaflet-div-icon"},
createIcon: function (t) {
var i = t && "DIV" === t.tagName ? t : e.createElement("div"), n = this.options;
if (i.innerHTML = n.html !== !1 ? n.html : "", n.bgPos) {
var s = o.point(n.bgPos);
i.style.backgroundPosition = -s.x + "px " + -s.y + "px"
}
return this._setIconStyles(i, "icon"), i
},
createShadow: function () {
return null
}
}), o.divIcon = function (t) {
return new o.DivIcon(t)
}, o.DivOverlay = o.Layer.extend({
options: {offset: [0, 7], className: "", pane: "popupPane"}, initialize: function (t, e) {
o.setOptions(this, t), this._source = e
}, onAdd: function (t) {
this._zoomAnimated = t._zoomAnimated, this._container || this._initLayout(), t._fadeAnimated && o.DomUtil.setOpacity(this._container, 0), clearTimeout(this._removeTimeout), this.getPane().appendChild(this._container), this.update(), t._fadeAnimated && o.DomUtil.setOpacity(this._container, 1), this.bringToFront()
}, onRemove: function (t) {
t._fadeAnimated ? (o.DomUtil.setOpacity(this._container, 0), this._removeTimeout = setTimeout(o.bind(o.DomUtil.remove, o.DomUtil, this._container), 200)) : o.DomUtil.remove(this._container)
}, getLatLng: function () {
return this._latlng
}, setLatLng: function (t) {
return this._latlng = o.latLng(t), this._map && (this._updatePosition(), this._adjustPan()), this
}, getContent: function () {
return this._content
}, setContent: function (t) {
return this._content = t, this.update(), this
}, getElement: function () {
return this._container
}, update: function () {
this._map && (this._container.style.visibility = "hidden", this._updateContent(), this._updateLayout(), this._updatePosition(), this._container.style.visibility = "", this._adjustPan())
}, getEvents: function () {
var t = {zoom: this._updatePosition, viewreset: this._updatePosition};
return this._zoomAnimated && (t.zoomanim = this._animateZoom), t
}, isOpen: function () {
return !!this._map && this._map.hasLayer(this)
}, bringToFront: function () {
return this._map && o.DomUtil.toFront(this._container), this
}, bringToBack: function () {
return this._map && o.DomUtil.toBack(this._container), this
}, _updateContent: function () {
if (this._content) {
var t = this._contentNode,
e = "function" == typeof this._content ? this._content(this._source || this) : this._content;
if ("string" == typeof e) t.innerHTML = e; else {
for (; t.hasChildNodes();) t.removeChild(t.firstChild);
t.appendChild(e)
}
this.fire("contentupdate")
}
}, _updatePosition: function () {
if (this._map) {
var t = this._map.latLngToLayerPoint(this._latlng), e = o.point(this.options.offset),
i = this._getAnchor();
this._zoomAnimated ? o.DomUtil.setPosition(this._container, t.add(i)) : e = e.add(t).add(i);
var n = this._containerBottom = -e.y,
s = this._containerLeft = -Math.round(this._containerWidth / 2) + e.x;
this._container.style.bottom = n + "px", this._container.style.left = s + "px"
}
}, _getAnchor: function () {
return [0, 0]
}
}), o.Popup = o.DivOverlay.extend({
options: {
maxWidth: 300,
minWidth: 50,
maxHeight: null,
autoPan: !0,
autoPanPaddingTopLeft: null,
autoPanPaddingBottomRight: null,
autoPanPadding: [5, 5],
keepInView: !1,
closeButton: !0,
autoClose: !0,
className: ""
}, openOn: function (t) {
return t.openPopup(this), this
}, onAdd: function (t) {
o.DivOverlay.prototype.onAdd.call(this, t), t.fire("popupopen", {popup: this}), this._source && (this._source.fire("popupopen", {popup: this}, !0), this._source instanceof o.Path || this._source.on("preclick", o.DomEvent.stopPropagation))
}, onRemove: function (t) {
o.DivOverlay.prototype.onRemove.call(this, t), t.fire("popupclose", {popup: this}), this._source && (this._source.fire("popupclose", {popup: this}, !0), this._source instanceof o.Path || this._source.off("preclick", o.DomEvent.stopPropagation))
}, getEvents: function () {
var t = o.DivOverlay.prototype.getEvents.call(this);
return ("closeOnClick" in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) && (t.preclick = this._close), this.options.keepInView && (t.moveend = this._adjustPan), t
}, _close: function () {
this._map && this._map.closePopup(this)
}, _initLayout: function () {
var t = "leaflet-popup",
e = this._container = o.DomUtil.create("div", t + " " + (this.options.className || "") + " leaflet-zoom-animated");
if (this.options.closeButton) {
var i = this._closeButton = o.DomUtil.create("a", t + "-close-button", e);
i.href = "#close", i.innerHTML = "×", o.DomEvent.on(i, "click", this._onCloseButtonClick, this)
}
var n = this._wrapper = o.DomUtil.create("div", t + "-content-wrapper", e);
this._contentNode = o.DomUtil.create("div", t + "-content", n), o.DomEvent.disableClickPropagation(n).disableScrollPropagation(this._contentNode).on(n, "contextmenu", o.DomEvent.stopPropagation), this._tipContainer = o.DomUtil.create("div", t + "-tip-container", e), this._tip = o.DomUtil.create("div", t + "-tip", this._tipContainer)
}, _updateLayout: function () {
var t = this._contentNode, e = t.style;
e.width = "", e.whiteSpace = "nowrap";
var i = t.offsetWidth;
i = Math.min(i, this.options.maxWidth), i = Math.max(i, this.options.minWidth), e.width = i + 1 + "px", e.whiteSpace = "", e.height = "";
var n = t.offsetHeight, s = this.options.maxHeight, r = "leaflet-popup-scrolled";
s && n > s ? (e.height = s + "px", o.DomUtil.addClass(t, r)) : o.DomUtil.removeClass(t, r), this._containerWidth = this._container.offsetWidth
}, _animateZoom: function (t) {
var e = this._map._latLngToNewLayerPoint(this._latlng, t.zoom, t.center), i = this._getAnchor();
o.DomUtil.setPosition(this._container, e.add(i))
}, _adjustPan: function () {
if (!(!this.options.autoPan || this._map._panAnim && this._map._panAnim._inProgress)) {
var t = this._map, e = parseInt(o.DomUtil.getStyle(this._container, "marginBottom"), 10) || 0,
i = this._container.offsetHeight + e, n = this._containerWidth,
s = new o.Point(this._containerLeft, -i - this._containerBottom);
s._add(o.DomUtil.getPosition(this._container));
var r = t.layerPointToContainerPoint(s), a = o.point(this.options.autoPanPadding),
h = o.point(this.options.autoPanPaddingTopLeft || a),
l = o.point(this.options.autoPanPaddingBottomRight || a), u = t.getSize(), c = 0, d = 0;
r.x + n + l.x > u.x && (c = r.x + n - u.x + l.x), r.x - c - h.x < 0 && (c = r.x - h.x), r.y + i + l.y > u.y && (d = r.y + i - u.y + l.y), r.y - d - h.y < 0 && (d = r.y - h.y), (c || d) && t.fire("autopanstart").panBy([c, d])
}
}, _onCloseButtonClick: function (t) {
this._close(), o.DomEvent.stop(t)
}, _getAnchor: function () {
return o.point(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0])
}
}), o.popup = function (t, e) {
return new o.Popup(t, e)
}, o.Map.mergeOptions({closePopupOnClick: !0}), o.Map.include({
openPopup: function (t, e, i) {
return t instanceof o.Popup || (t = new o.Popup(i).setContent(t)), e && t.setLatLng(e), this.hasLayer(t) ? this : (this._popup && this._popup.options.autoClose && this.closePopup(), this._popup = t, this.addLayer(t))
}, closePopup: function (t) {
return t && t !== this._popup || (t = this._popup, this._popup = null), t && this.removeLayer(t), this
}
}), o.Layer.include({
bindPopup: function (t, e) {
return t instanceof o.Popup ? (o.setOptions(t, e), this._popup = t, t._source = this) : (this._popup && !e || (this._popup = new o.Popup(e, this)), this._popup.setContent(t)), this._popupHandlersAdded || (this.on({
click: this._openPopup,
remove: this.closePopup,
move: this._movePopup
}), this._popupHandlersAdded = !0), this
}, unbindPopup: function () {
return this._popup && (this.off({
click: this._openPopup,
remove: this.closePopup,
move: this._movePopup
}), this._popupHandlersAdded = !1, this._popup = null), this
}, openPopup: function (t, e) {
if (t instanceof o.Layer || (e = t, t = this), t instanceof o.FeatureGroup) for (var i in this._layers) {
t = this._layers[i];
break
}
return e || (e = t.getCenter ? t.getCenter() : t.getLatLng()), this._popup && this._map && (this._popup._source = t, this._popup.update(), this._map.openPopup(this._popup, e)), this
}, closePopup: function () {
return this._popup && this._popup._close(), this
}, togglePopup: function (t) {
return this._popup && (this._popup._map ? this.closePopup() : this.openPopup(t)), this
}, isPopupOpen: function () {
return this._popup.isOpen()
}, setPopupContent: function (t) {
return this._popup && this._popup.setContent(t), this
}, getPopup: function () {
return this._popup
}, _openPopup: function (t) {
var e = t.layer || t.target;
if (this._popup && this._map) return o.DomEvent.stop(t), e instanceof o.Path ? void this.openPopup(t.layer || t.target, t.latlng) : void (this._map.hasLayer(this._popup) && this._popup._source === e ? this.closePopup() : this.openPopup(e, t.latlng))
}, _movePopup: function (t) {
this._popup.setLatLng(t.latlng)
}
}), o.Marker.include({
_getPopupAnchor: function () {
return this.options.icon.options.popupAnchor || [0, 0]
}
}), o.Tooltip = o.DivOverlay.extend({
options: {
pane: "tooltipPane",
offset: [0, 0],
direction: "auto",
permanent: !1,
sticky: !1,
interactive: !1,
opacity: .9
}, onAdd: function (t) {
o.DivOverlay.prototype.onAdd.call(this, t), this.setOpacity(this.options.opacity), t.fire("tooltipopen", {tooltip: this}), this._source && this._source.fire("tooltipopen", {tooltip: this}, !0)
}, onRemove: function (t) {
o.DivOverlay.prototype.onRemove.call(this, t), t.fire("tooltipclose", {tooltip: this}), this._source && this._source.fire("tooltipclose", {tooltip: this}, !0)
}, getEvents: function () {
var t = o.DivOverlay.prototype.getEvents.call(this);
return o.Browser.touch && !this.options.permanent && (t.preclick = this._close), t
}, _close: function () {
this._map && this._map.closeTooltip(this)
}, _initLayout: function () {
var t = "leaflet-tooltip",
e = t + " " + (this.options.className || "") + " leaflet-zoom-" + (this._zoomAnimated ? "animated" : "hide");
this._contentNode = this._container = o.DomUtil.create("div", e)
}, _updateLayout: function () {
}, _adjustPan: function () {
}, _setPosition: function (t) {
var e = this._map, i = this._container, n = e.latLngToContainerPoint(e.getCenter()),
s = e.layerPointToContainerPoint(t), r = this.options.direction, a = i.offsetWidth, h = i.offsetHeight,
l = o.point(this.options.offset), u = this._getAnchor();
"top" === r ? t = t.add(o.point(-a / 2 + l.x, -h + l.y + u.y)) : "bottom" === r ? t = t.subtract(o.point(a / 2 - l.x, -l.y)) : "center" === r ? t = t.subtract(o.point(a / 2 + l.x, h / 2 - u.y + l.y)) : "right" === r || "auto" === r && s.x < n.x ? (r = "right", t = t.add([l.x + u.x, u.y - h / 2 + l.y])) : (r = "left", t = t.subtract(o.point(a + u.x - l.x, h / 2 - u.y - l.y))), o.DomUtil.removeClass(i, "leaflet-tooltip-right"), o.DomUtil.removeClass(i, "leaflet-tooltip-left"), o.DomUtil.removeClass(i, "leaflet-tooltip-top"), o.DomUtil.removeClass(i, "leaflet-tooltip-bottom"), o.DomUtil.addClass(i, "leaflet-tooltip-" + r), o.DomUtil.setPosition(i, t)
}, _updatePosition: function () {
var t = this._map.latLngToLayerPoint(this._latlng);
this._setPosition(t)
}, setOpacity: function (t) {
this.options.opacity = t, this._container && o.DomUtil.setOpacity(this._container, t)
}, _animateZoom: function (t) {
var e = this._map._latLngToNewLayerPoint(this._latlng, t.zoom, t.center);
this._setPosition(e)
}, _getAnchor: function () {
return o.point(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0])
}
}), o.tooltip = function (t, e) {
return new o.Tooltip(t, e)
}, o.Map.include({
openTooltip: function (t, e, i) {
return t instanceof o.Tooltip || (t = new o.Tooltip(i).setContent(t)), e && t.setLatLng(e), this.hasLayer(t) ? this : this.addLayer(t)
}, closeTooltip: function (t) {
return t && this.removeLayer(t), this
}
}), o.Layer.include({
bindTooltip: function (t, e) {
return t instanceof o.Tooltip ? (o.setOptions(t, e), this._tooltip = t, t._source = this) : (this._tooltip && !e || (this._tooltip = o.tooltip(e, this)), this._tooltip.setContent(t)), this._initTooltipInteractions(), this._tooltip.options.permanent && this._map && this._map.hasLayer(this) && this.openTooltip(), this
}, unbindTooltip: function () {
return this._tooltip && (this._initTooltipInteractions(!0), this.closeTooltip(), this._tooltip = null), this
}, _initTooltipInteractions: function (t) {
if (t || !this._tooltipHandlersAdded) {
var e = t ? "off" : "on", i = {remove: this.closeTooltip, move: this._moveTooltip};
this._tooltip.options.permanent ? i.add = this._openTooltip : (i.mouseover = this._openTooltip, i.mouseout = this.closeTooltip, this._tooltip.options.sticky && (i.mousemove = this._moveTooltip), o.Browser.touch && (i.click = this._openTooltip)), this[e](i), this._tooltipHandlersAdded = !t
}
}, openTooltip: function (t, e) {
if (t instanceof o.Layer || (e = t, t = this), t instanceof o.FeatureGroup) for (var i in this._layers) {
t = this._layers[i];
break
}
return e || (e = t.getCenter ? t.getCenter() : t.getLatLng()), this._tooltip && this._map && (this._tooltip._source = t, this._tooltip.update(), this._map.openTooltip(this._tooltip, e), this._tooltip.options.interactive && this._tooltip._container && (o.DomUtil.addClass(this._tooltip._container, "leaflet-clickable"), this.addInteractiveTarget(this._tooltip._container))), this
}, closeTooltip: function () {
return this._tooltip && (this._tooltip._close(), this._tooltip.options.interactive && this._tooltip._container && (o.DomUtil.removeClass(this._tooltip._container, "leaflet-clickable"), this.removeInteractiveTarget(this._tooltip._container))), this
}, toggleTooltip: function (t) {
return this._tooltip && (this._tooltip._map ? this.closeTooltip() : this.openTooltip(t)), this
}, isTooltipOpen: function () {
return this._tooltip.isOpen()
}, setTooltipContent: function (t) {
return this._tooltip && this._tooltip.setContent(t), this
}, getTooltip: function () {
return this._tooltip
}, _openTooltip: function (t) {
var e = t.layer || t.target;
this._tooltip && this._map && this.openTooltip(e, this._tooltip.options.sticky ? t.latlng : i)
}, _moveTooltip: function (t) {
var e, i, n = t.latlng;
this._tooltip.options.sticky && t.originalEvent && (e = this._map.mouseEventToContainerPoint(t.originalEvent), i = this._map.containerPointToLayerPoint(e), n = this._map.layerPointToLatLng(i)), this._tooltip.setLatLng(n)
}
}), o.Marker.include({
_getTooltipAnchor: function () {
return this.options.icon.options.tooltipAnchor || [0, 0]
}
}), o.LayerGroup = o.Layer.extend({
initialize: function (t) {
this._layers = {};
var e, i;
if (t) for (e = 0, i = t.length; e < i; e++) this.addLayer(t[e])
}, addLayer: function (t) {
var e = this.getLayerId(t);
return this._layers[e] = t, this._map && this._map.addLayer(t), this
}, removeLayer: function (t) {
var e = t in this._layers ? t : this.getLayerId(t);
return this._map && this._layers[e] && this._map.removeLayer(this._layers[e]), delete this._layers[e], this
}, hasLayer: function (t) {
return !!t && (t in this._layers || this.getLayerId(t) in this._layers)
}, clearLayers: function () {
for (var t in this._layers) this.removeLayer(this._layers[t]);
return this
}, invoke: function (t) {
var e, i, n = Array.prototype.slice.call(arguments, 1);
for (e in this._layers) i = this._layers[e], i[t] && i[t].apply(i, n);
return this
}, onAdd: function (t) {
for (var e in this._layers) t.addLayer(this._layers[e])
}, onRemove: function (t) {
for (var e in this._layers) t.removeLayer(this._layers[e])
}, eachLayer: function (t, e) {
for (var i in this._layers) t.call(e, this._layers[i]);
return this
}, getLayer: function (t) {
return this._layers[t]
}, getLayers: function () {
var t = [];
for (var e in this._layers) t.push(this._layers[e]);
return t
}, setZIndex: function (t) {
return this.invoke("setZIndex", t)
}, getLayerId: function (t) {
return o.stamp(t)
}
}), o.layerGroup = function (t) {
return new o.LayerGroup(t)
}, o.FeatureGroup = o.LayerGroup.extend({
addLayer: function (t) {
return this.hasLayer(t) ? this : (t.addEventParent(this), o.LayerGroup.prototype.addLayer.call(this, t), this.fire("layeradd", {layer: t}))
}, removeLayer: function (t) {
return this.hasLayer(t) ? (t in this._layers && (t = this._layers[t]), t.removeEventParent(this), o.LayerGroup.prototype.removeLayer.call(this, t), this.fire("layerremove", {layer: t})) : this
}, setStyle: function (t) {
return this.invoke("setStyle", t)
}, bringToFront: function () {
return this.invoke("bringToFront")
}, bringToBack: function () {
return this.invoke("bringToBack")
}, getBounds: function () {
var t = new o.LatLngBounds;
for (var e in this._layers) {
var i = this._layers[e];
t.extend(i.getBounds ? i.getBounds() : i.getLatLng())
}
return t
}
}), o.featureGroup = function (t) {
return new o.FeatureGroup(t)
}, o.Renderer = o.Layer.extend({
options: {padding: .1}, initialize: function (t) {
o.setOptions(this, t), o.stamp(this)
}, onAdd: function () {
this._container || (this._initContainer(), this._zoomAnimated && o.DomUtil.addClass(this._container, "leaflet-zoom-animated")), this.getPane().appendChild(this._container), this._update()
}, onRemove: function () {
o.DomUtil.remove(this._container)
}, getEvents: function () {
var t = {viewreset: this._reset, zoom: this._onZoom, moveend: this._update};
return this._zoomAnimated && (t.zoomanim = this._onAnimZoom), t
}, _onAnimZoom: function (t) {
this._updateTransform(t.center, t.zoom)
}, _onZoom: function () {
this._updateTransform(this._map.getCenter(), this._map.getZoom())
}, _updateTransform: function (t, e) {
var i = this._map.getZoomScale(e, this._zoom), n = o.DomUtil.getPosition(this._container),
s = this._map.getSize().multiplyBy(.5 + this.options.padding), r = this._map.project(this._center, e),
a = this._map.project(t, e), h = a.subtract(r), l = s.multiplyBy(-i).add(n).add(s).subtract(h);
o.Browser.any3d ? o.DomUtil.setTransform(this._container, l, i) : o.DomUtil.setPosition(this._container, l)
}, _reset: function () {
this._update(), this._updateTransform(this._center, this._zoom)
}, _update: function () {
var t = this.options.padding, e = this._map.getSize(),
i = this._map.containerPointToLayerPoint(e.multiplyBy(-t)).round();
this._bounds = new o.Bounds(i, i.add(e.multiplyBy(1 + 2 * t)).round()), this._center = this._map.getCenter(), this._zoom = this._map.getZoom()
}
}), o.Map.include({
getRenderer: function (t) {
var e = t.options.renderer || this._getPaneRenderer(t.options.pane) || this.options.renderer || this._renderer;
return e || (e = this._renderer = this.options.preferCanvas && o.canvas() || o.svg()), this.hasLayer(e) || this.addLayer(e), e
}, _getPaneRenderer: function (t) {
if ("overlayPane" === t || t === i) return !1;
var e = this._paneRenderers[t];
return e === i && (e = o.SVG && o.svg({pane: t}) || o.Canvas && o.canvas({pane: t}), this._paneRenderers[t] = e), e
}
}), o.Path = o.Layer.extend({
options: {
stroke: !0,
color: "#3388ff",
weight: 3,
opacity: 1,
lineCap: "round",
lineJoin: "round",
dashArray: null,
dashOffset: null,
fill: !1,
fillColor: null,
fillOpacity: .2,
fillRule: "evenodd",
interactive: !0
}, beforeAdd: function (t) {
this._renderer = t.getRenderer(this)
}, onAdd: function () {
this._renderer._initPath(this), this._reset(), this._renderer._addPath(this), this._renderer.on("update", this._update, this)
}, onRemove: function () {
this._renderer._removePath(this), this._renderer.off("update", this._update, this)
}, getEvents: function () {
return {zoomend: this._project, viewreset: this._reset}
}, redraw: function () {
return this._map && this._renderer._updatePath(this), this
}, setStyle: function (t) {
return o.setOptions(this, t), this._renderer && this._renderer._updateStyle(this), this
}, bringToFront: function () {
return this._renderer && this._renderer._bringToFront(this), this
}, bringToBack: function () {
return this._renderer && this._renderer._bringToBack(this), this
}, getElement: function () {
return this._path
}, _reset: function () {
this._project(), this._update()
}, _clickTolerance: function () {
return (this.options.stroke ? this.options.weight / 2 : 0) + (o.Browser.touch ? 10 : 0)
}
}), o.LineUtil = {
simplify: function (t, e) {
if (!e || !t.length) return t.slice();
var i = e * e;
return t = this._reducePoints(t, i), t = this._simplifyDP(t, i)
}, pointToSegmentDistance: function (t, e, i) {
return Math.sqrt(this._sqClosestPointOnSegment(t, e, i, !0))
}, closestPointOnSegment: function (t, e, i) {
return this._sqClosestPointOnSegment(t, e, i)
}, _simplifyDP: function (t, e) {
var n = t.length, o = typeof Uint8Array != i + "" ? Uint8Array : Array, s = new o(n);
s[0] = s[n - 1] = 1, this._simplifyDPStep(t, s, e, 0, n - 1);
var r, a = [];
for (r = 0; r < n; r++) s[r] && a.push(t[r]);
return a
}, _simplifyDPStep: function (t, e, i, n, o) {
var s, r, a, h = 0;
for (r = n + 1; r <= o - 1; r++) a = this._sqClosestPointOnSegment(t[r], t[n], t[o], !0), a > h && (s = r, h = a);
h > i && (e[s] = 1, this._simplifyDPStep(t, e, i, n, s), this._simplifyDPStep(t, e, i, s, o))
}, _reducePoints: function (t, e) {
for (var i = [t[0]], n = 1, o = 0, s = t.length; n < s; n++) this._sqDist(t[n], t[o]) > e && (i.push(t[n]), o = n);
return o < s - 1 && i.push(t[s - 1]), i
}, clipSegment: function (t, e, i, n, o) {
var s, r, a, h = n ? this._lastCode : this._getBitCode(t, i), l = this._getBitCode(e, i);
for (this._lastCode = l; ;) {
if (!(h | l)) return [t, e];
if (h & l) return !1;
s = h || l, r = this._getEdgeIntersection(t, e, s, i, o), a = this._getBitCode(r, i), s === h ? (t = r, h = a) : (e = r, l = a)
}
}, _getEdgeIntersection: function (t, e, i, n, s) {
var r, a, h = e.x - t.x, l = e.y - t.y, u = n.min, c = n.max;
return 8 & i ? (r = t.x + h * (c.y - t.y) / l, a = c.y) : 4 & i ? (r = t.x + h * (u.y - t.y) / l, a = u.y) : 2 & i ? (r = c.x, a = t.y + l * (c.x - t.x) / h) : 1 & i && (r = u.x, a = t.y + l * (u.x - t.x) / h), new o.Point(r, a, s)
}, _getBitCode: function (t, e) {
var i = 0;
return t.x < e.min.x ? i |= 1 : t.x > e.max.x && (i |= 2), t.y < e.min.y ? i |= 4 : t.y > e.max.y && (i |= 8), i
}, _sqDist: function (t, e) {
var i = e.x - t.x, n = e.y - t.y;
return i * i + n * n
}, _sqClosestPointOnSegment: function (t, e, i, n) {
var s, r = e.x, a = e.y, h = i.x - r, l = i.y - a, u = h * h + l * l;
return u > 0 && (s = ((t.x - r) * h + (t.y - a) * l) / u, s > 1 ? (r = i.x, a = i.y) : s > 0 && (r += h * s, a += l * s)), h = t.x - r, l = t.y - a, n ? h * h + l * l : new o.Point(r, a)
}
}, o.Polyline = o.Path.extend({
options: {smoothFactor: 1, noClip: !1}, initialize: function (t, e) {
o.setOptions(this, e), this._setLatLngs(t)
}, getLatLngs: function () {
return this._latlngs
}, setLatLngs: function (t) {
return this._setLatLngs(t), this.redraw()
}, isEmpty: function () {
return !this._latlngs.length
}, closestLayerPoint: function (t) {
for (var e, i, n = 1 / 0, s = null, r = o.LineUtil._sqClosestPointOnSegment, a = 0, h = this._parts.length; a < h; a++) for (var l = this._parts[a], u = 1, c = l.length; u < c; u++) {
e = l[u - 1], i = l[u];
var d = r(t, e, i, !0);
d < n && (n = d, s = r(t, e, i))
}
return s && (s.distance = Math.sqrt(n)), s
}, getCenter: function () {
if (!this._map) throw new Error("Must add layer to map before using getCenter()");
var t, e, i, n, o, s, r, a = this._rings[0], h = a.length;
if (!h) return null;
for (t = 0, e = 0; t < h - 1; t++) e += a[t].distanceTo(a[t + 1]) / 2;
if (0 === e) return this._map.layerPointToLatLng(a[0]);
for (t = 0, n = 0; t < h - 1; t++) if (o = a[t], s = a[t + 1], i = o.distanceTo(s), n += i, n > e) return r = (n - e) / i, this._map.layerPointToLatLng([s.x - r * (s.x - o.x), s.y - r * (s.y - o.y)])
}, getBounds: function () {
return this._bounds
}, addLatLng: function (t, e) {
return e = e || this._defaultShape(), t = o.latLng(t), e.push(t), this._bounds.extend(t), this.redraw()
}, _setLatLngs: function (t) {
this._bounds = new o.LatLngBounds, this._latlngs = this._convertLatLngs(t)
}, _defaultShape: function () {
return o.Polyline._flat(this._latlngs) ? this._latlngs : this._latlngs[0]
}, _convertLatLngs: function (t) {
for (var e = [], i = o.Polyline._flat(t), n = 0, s = t.length; n < s; n++) i ? (e[n] = o.latLng(t[n]), this._bounds.extend(e[n])) : e[n] = this._convertLatLngs(t[n]);
return e
}, _project: function () {
var t = new o.Bounds;
this._rings = [], this._projectLatlngs(this._latlngs, this._rings, t);
var e = this._clickTolerance(), i = new o.Point(e, e);
this._bounds.isValid() && t.isValid() && (t.min._subtract(i), t.max._add(i), this._pxBounds = t)
}, _projectLatlngs: function (t, e, i) {
var n, s, r = t[0] instanceof o.LatLng, a = t.length;
if (r) {
for (s = [], n = 0; n < a; n++) s[n] = this._map.latLngToLayerPoint(t[n]), i.extend(s[n]);
e.push(s)
} else for (n = 0; n < a; n++) this._projectLatlngs(t[n], e, i)
}, _clipPoints: function () {
var t = this._renderer._bounds;
if (this._parts = [], this._pxBounds && this._pxBounds.intersects(t)) {
if (this.options.noClip) return void (this._parts = this._rings);
var e, i, n, s, r, a, h, l = this._parts;
for (e = 0, n = 0, s = this._rings.length; e < s; e++) for (h = this._rings[e], i = 0, r = h.length; i < r - 1; i++) a = o.LineUtil.clipSegment(h[i], h[i + 1], t, i, !0), a && (l[n] = l[n] || [], l[n].push(a[0]), a[1] === h[i + 1] && i !== r - 2 || (l[n].push(a[1]), n++))
}
}, _simplifyPoints: function () {
for (var t = this._parts, e = this.options.smoothFactor, i = 0, n = t.length; i < n; i++) t[i] = o.LineUtil.simplify(t[i], e)
}, _update: function () {
this._map && (this._clipPoints(), this._simplifyPoints(), this._updatePath())
}, _updatePath: function () {
this._renderer._updatePoly(this)
}
}), o.polyline = function (t, e) {
return new o.Polyline(t, e)
}, o.Polyline._flat = function (t) {
return !o.Util.isArray(t[0]) || "object" != typeof t[0][0] && "undefined" != typeof t[0][0]
}, o.PolyUtil = {}, o.PolyUtil.clipPolygon = function (t, e, i) {
var n, s, r, a, h, l, u, c, d, _ = [1, 4, 2, 8], m = o.LineUtil;
for (s = 0, u = t.length; s < u; s++) t[s]._code = m._getBitCode(t[s], e);
for (a = 0; a < 4; a++) {
for (c = _[a], n = [], s = 0, u = t.length, r = u - 1; s < u; r = s++) h = t[s], l = t[r], h._code & c ? l._code & c || (d = m._getEdgeIntersection(l, h, c, e, i), d._code = m._getBitCode(d, e), n.push(d)) : (l._code & c && (d = m._getEdgeIntersection(l, h, c, e, i), d._code = m._getBitCode(d, e), n.push(d)), n.push(h));
t = n
}
return t
}, o.Polygon = o.Polyline.extend({
options: {fill: !0}, isEmpty: function () {
return !this._latlngs.length || !this._latlngs[0].length
}, getCenter: function () {
if (!this._map) throw new Error("Must add layer to map before using getCenter()");
var t, e, i, n, o, s, r, a, h, l = this._rings[0], u = l.length;
if (!u) return null;
for (s = r = a = 0, t = 0, e = u - 1; t < u; e = t++) i = l[t], n = l[e], o = i.y * n.x - n.y * i.x, r += (i.x + n.x) * o, a += (i.y + n.y) * o, s += 3 * o;
return h = 0 === s ? l[0] : [r / s, a / s], this._map.layerPointToLatLng(h)
}, _convertLatLngs: function (t) {
var e = o.Polyline.prototype._convertLatLngs.call(this, t), i = e.length;
return i >= 2 && e[0] instanceof o.LatLng && e[0].equals(e[i - 1]) && e.pop(), e
}, _setLatLngs: function (t) {
o.Polyline.prototype._setLatLngs.call(this, t), o.Polyline._flat(this._latlngs) && (this._latlngs = [this._latlngs])
}, _defaultShape: function () {
return o.Polyline._flat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0]
}, _clipPoints: function () {
var t = this._renderer._bounds, e = this.options.weight, i = new o.Point(e, e);
if (t = new o.Bounds(t.min.subtract(i), t.max.add(i)), this._parts = [], this._pxBounds && this._pxBounds.intersects(t)) {
if (this.options.noClip) return void (this._parts = this._rings);
for (var n, s = 0, r = this._rings.length; s < r; s++) n = o.PolyUtil.clipPolygon(this._rings[s], t, !0), n.length && this._parts.push(n)
}
}, _updatePath: function () {
this._renderer._updatePoly(this, !0)
}
}), o.polygon = function (t, e) {
return new o.Polygon(t, e)
}, o.Rectangle = o.Polygon.extend({
initialize: function (t, e) {
o.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(t), e)
}, setBounds: function (t) {
return this.setLatLngs(this._boundsToLatLngs(t))
}, _boundsToLatLngs: function (t) {
return t = o.latLngBounds(t), [t.getSouthWest(), t.getNorthWest(), t.getNorthEast(), t.getSouthEast()]
}
}), o.rectangle = function (t, e) {
return new o.Rectangle(t, e)
}, o.CircleMarker = o.Path.extend({
options: {fill: !0, radius: 10}, initialize: function (t, e) {
o.setOptions(this, e), this._latlng = o.latLng(t), this._radius = this.options.radius
}, setLatLng: function (t) {
return this._latlng = o.latLng(t), this.redraw(), this.fire("move", {latlng: this._latlng})
}, getLatLng: function () {
return this._latlng
}, setRadius: function (t) {
return this.options.radius = this._radius = t, this.redraw()
}, getRadius: function () {
return this._radius
}, setStyle: function (t) {
var e = t && t.radius || this._radius;
return o.Path.prototype.setStyle.call(this, t), this.setRadius(e), this
}, _project: function () {
this._point = this._map.latLngToLayerPoint(this._latlng), this._updateBounds()
}, _updateBounds: function () {
var t = this._radius, e = this._radiusY || t, i = this._clickTolerance(), n = [t + i, e + i];
this._pxBounds = new o.Bounds(this._point.subtract(n), this._point.add(n))
}, _update: function () {
this._map && this._updatePath()
}, _updatePath: function () {
this._renderer._updateCircle(this)
}, _empty: function () {
return this._radius && !this._renderer._bounds.intersects(this._pxBounds)
}
}), o.circleMarker = function (t, e) {
return new o.CircleMarker(t, e)
}, o.Circle = o.CircleMarker.extend({
initialize: function (t, e, i) {
if ("number" == typeof e && (e = o.extend({}, i, {radius: e})), o.setOptions(this, e), this._latlng = o.latLng(t), isNaN(this.options.radius)) throw new Error("Circle radius cannot be NaN");
this._mRadius = this.options.radius
}, setRadius: function (t) {
return this._mRadius = t, this.redraw()
}, getRadius: function () {
return this._mRadius
}, getBounds: function () {
var t = [this._radius, this._radiusY || this._radius];
return new o.LatLngBounds(this._map.layerPointToLatLng(this._point.subtract(t)), this._map.layerPointToLatLng(this._point.add(t)))
}, setStyle: o.Path.prototype.setStyle, _project: function () {
var t = this._latlng.lng, e = this._latlng.lat, i = this._map, n = i.options.crs;
if (n.distance === o.CRS.Earth.distance) {
var s = Math.PI / 180, r = this._mRadius / o.CRS.Earth.R / s, a = i.project([e + r, t]),
h = i.project([e - r, t]), l = a.add(h).divideBy(2), u = i.unproject(l).lat,
c = Math.acos((Math.cos(r * s) - Math.sin(e * s) * Math.sin(u * s)) / (Math.cos(e * s) * Math.cos(u * s))) / s;
(isNaN(c) || 0 === c) && (c = r / Math.cos(Math.PI / 180 * e)), this._point = l.subtract(i.getPixelOrigin()), this._radius = isNaN(c) ? 0 : Math.max(Math.round(l.x - i.project([u, t - c]).x), 1), this._radiusY = Math.max(Math.round(l.y - a.y), 1)
} else {
var d = n.unproject(n.project(this._latlng).subtract([this._mRadius, 0]));
this._point = i.latLngToLayerPoint(this._latlng), this._radius = this._point.x - i.latLngToLayerPoint(d).x
}
this._updateBounds()
}
}), o.circle = function (t, e, i) {
return new o.Circle(t, e, i)
}, o.SVG = o.Renderer.extend({
getEvents: function () {
var t = o.Renderer.prototype.getEvents.call(this);
return t.zoomstart = this._onZoomStart, t
}, _initContainer: function () {
this._container = o.SVG.create("svg"), this._container.setAttribute("pointer-events", "none"), this._rootGroup = o.SVG.create("g"), this._container.appendChild(this._rootGroup)
}, _onZoomStart: function () {
this._update()
}, _update: function () {
if (!this._map._animatingZoom || !this._bounds) {
o.Renderer.prototype._update.call(this);
var t = this._bounds, e = t.getSize(), i = this._container;
this._svgSize && this._svgSize.equals(e) || (this._svgSize = e, i.setAttribute("width", e.x), i.setAttribute("height", e.y)), o.DomUtil.setPosition(i, t.min), i.setAttribute("viewBox", [t.min.x, t.min.y, e.x, e.y].join(" ")), this.fire("update")
}
}, _initPath: function (t) {
var e = t._path = o.SVG.create("path");
t.options.className && o.DomUtil.addClass(e, t.options.className), t.options.interactive && o.DomUtil.addClass(e, "leaflet-interactive"), this._updateStyle(t)
}, _addPath: function (t) {
this._rootGroup.appendChild(t._path), t.addInteractiveTarget(t._path)
}, _removePath: function (t) {
o.DomUtil.remove(t._path), t.removeInteractiveTarget(t._path)
}, _updatePath: function (t) {
t._project(), t._update()
}, _updateStyle: function (t) {
var e = t._path, i = t.options;
e && (i.stroke ? (e.setAttribute("stroke", i.color), e.setAttribute("stroke-opacity", i.opacity), e.setAttribute("stroke-width", i.weight), e.setAttribute("stroke-linecap", i.lineCap), e.setAttribute("stroke-linejoin", i.lineJoin), i.dashArray ? e.setAttribute("stroke-dasharray", i.dashArray) : e.removeAttribute("stroke-dasharray"), i.dashOffset ? e.setAttribute("stroke-dashoffset", i.dashOffset) : e.removeAttribute("stroke-dashoffset")) : e.setAttribute("stroke", "none"), i.fill ? (e.setAttribute("fill", i.fillColor || i.color), e.setAttribute("fill-opacity", i.fillOpacity), e.setAttribute("fill-rule", i.fillRule || "evenodd")) : e.setAttribute("fill", "none"))
}, _updatePoly: function (t, e) {
this._setPath(t, o.SVG.pointsToPath(t._parts, e))
}, _updateCircle: function (t) {
var e = t._point, i = t._radius, n = t._radiusY || i, o = "a" + i + "," + n + " 0 1,0 ",
s = t._empty() ? "M0 0" : "M" + (e.x - i) + "," + e.y + o + 2 * i + ",0 " + o + 2 * -i + ",0 ";
this._setPath(t, s)
}, _setPath: function (t, e) {
t._path.setAttribute("d", e)
}, _bringToFront: function (t) {
o.DomUtil.toFront(t._path)
}, _bringToBack: function (t) {
o.DomUtil.toBack(t._path)
}
}), o.extend(o.SVG, {
create: function (t) {
return e.createElementNS("http://www.w3.org/2000/svg", t)
}, pointsToPath: function (t, e) {
var i, n, s, r, a, h, l = "";
for (i = 0, s = t.length; i < s; i++) {
for (a = t[i], n = 0, r = a.length; n < r; n++) h = a[n], l += (n ? "L" : "M") + h.x + " " + h.y;
l += e ? o.Browser.svg ? "z" : "x" : ""
}
return l || "M0 0"
}
}), o.Browser.svg = !(!e.createElementNS || !o.SVG.create("svg").createSVGRect), o.svg = function (t) {
return o.Browser.svg || o.Browser.vml ? new o.SVG(t) : null
}, o.Browser.vml = !o.Browser.svg && function () {
try {
var t = e.createElement("div");
t.innerHTML = '<v:shape adj="1"/>';
var i = t.firstChild;
return i.style.behavior = "url(#default#VML)", i && "object" == typeof i.adj
} catch (t) {
return !1
}
}(), o.SVG.include(o.Browser.vml ? {
_initContainer: function () {
this._container = o.DomUtil.create("div", "leaflet-vml-container")
}, _update: function () {
this._map._animatingZoom || (o.Renderer.prototype._update.call(this), this.fire("update"))
}, _initPath: function (t) {
var e = t._container = o.SVG.create("shape");
o.DomUtil.addClass(e, "leaflet-vml-shape " + (this.options.className || "")), e.coordsize = "1 1", t._path = o.SVG.create("path"), e.appendChild(t._path), this._updateStyle(t)
}, _addPath: function (t) {
var e = t._container;
this._container.appendChild(e), t.options.interactive && t.addInteractiveTarget(e)
}, _removePath: function (t) {
var e = t._container;
o.DomUtil.remove(e), t.removeInteractiveTarget(e)
}, _updateStyle: function (t) {
var e = t._stroke, i = t._fill, n = t.options, s = t._container;
s.stroked = !!n.stroke, s.filled = !!n.fill, n.stroke ? (e || (e = t._stroke = o.SVG.create("stroke")), s.appendChild(e), e.weight = n.weight + "px", e.color = n.color, e.opacity = n.opacity, n.dashArray ? e.dashStyle = o.Util.isArray(n.dashArray) ? n.dashArray.join(" ") : n.dashArray.replace(/( *, *)/g, " ") : e.dashStyle = "", e.endcap = n.lineCap.replace("butt", "flat"), e.joinstyle = n.lineJoin) : e && (s.removeChild(e), t._stroke = null), n.fill ? (i || (i = t._fill = o.SVG.create("fill")), s.appendChild(i), i.color = n.fillColor || n.color, i.opacity = n.fillOpacity) : i && (s.removeChild(i), t._fill = null)
}, _updateCircle: function (t) {
var e = t._point.round(), i = Math.round(t._radius), n = Math.round(t._radiusY || i);
this._setPath(t, t._empty() ? "M0 0" : "AL " + e.x + "," + e.y + " " + i + "," + n + " 0,23592600")
}, _setPath: function (t, e) {
t._path.v = e
}, _bringToFront: function (t) {
o.DomUtil.toFront(t._container)
}, _bringToBack: function (t) {
o.DomUtil.toBack(t._container)
}
} : {}), o.Browser.vml && (o.SVG.create = function () {
try {
return e.namespaces.add("lvml", "urn:schemas-microsoft-com:vml"), function (t) {
return e.createElement("<lvml:" + t + ' class="lvml">')
}
} catch (t) {
return function (t) {
return e.createElement("<" + t + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')
}
}
}()), o.Canvas = o.Renderer.extend({
onAdd: function () {
o.Renderer.prototype.onAdd.call(this), this._layers = this._layers || {}, this._draw()
}, _initContainer: function () {
var t = this._container = e.createElement("canvas");
o.DomEvent.on(t, "mousemove", o.Util.throttle(this._onMouseMove, 32, this), this).on(t, "click dblclick mousedown mouseup contextmenu", this._onClick, this).on(t, "mouseout", this._handleMouseOut, this), this._ctx = t.getContext("2d")
}, _update: function () {
if (!this._map._animatingZoom || !this._bounds) {
this._drawnLayers = {}, o.Renderer.prototype._update.call(this);
var t = this._bounds, e = this._container, i = t.getSize(), n = o.Browser.retina ? 2 : 1;
o.DomUtil.setPosition(e, t.min), e.width = n * i.x, e.height = n * i.y, e.style.width = i.x + "px", e.style.height = i.y + "px", o.Browser.retina && this._ctx.scale(2, 2), this._ctx.translate(-t.min.x, -t.min.y), this.fire("update")
}
}, _initPath: function (t) {
this._updateDashArray(t), this._layers[o.stamp(t)] = t
}, _addPath: o.Util.falseFn, _removePath: function (t) {
t._removed = !0, this._requestRedraw(t)
}, _updatePath: function (t) {
this._redrawBounds = t._pxBounds, this._draw(!0), t._project(), t._update(), this._draw(), this._redrawBounds = null
}, _updateStyle: function (t) {
this._updateDashArray(t), this._requestRedraw(t)
}, _updateDashArray: function (t) {
if (t.options.dashArray) {
var e, i = t.options.dashArray.split(","), n = [];
for (e = 0; e < i.length; e++) n.push(Number(i[e]));
t.options._dashArray = n
}
}, _requestRedraw: function (t) {
if (this._map) {
var e = (t.options.weight || 0) + 1;
this._redrawBounds = this._redrawBounds || new o.Bounds, this._redrawBounds.extend(t._pxBounds.min.subtract([e, e])), this._redrawBounds.extend(t._pxBounds.max.add([e, e])), this._redrawRequest = this._redrawRequest || o.Util.requestAnimFrame(this._redraw, this)
}
}, _redraw: function () {
this._redrawRequest = null, this._draw(!0), this._draw(), this._redrawBounds = null
}, _draw: function (t) {
this._clear = t;
var e, i = this._redrawBounds;
this._ctx.save(), i && (this._ctx.beginPath(), this._ctx.rect(i.min.x, i.min.y, i.max.x - i.min.x, i.max.y - i.min.y), this._ctx.clip());
for (var n in this._layers) e = this._layers[n], (!i || e._pxBounds && e._pxBounds.intersects(i)) && e._updatePath(), t && e._removed && (delete e._removed, delete this._layers[n]);
this._ctx.restore()
}, _updatePoly: function (t, e) {
var i, n, o, s, r = t._parts, a = r.length, h = this._ctx;
if (a) {
for (this._drawnLayers[t._leaflet_id] = t, h.beginPath(), h.setLineDash && h.setLineDash(t.options && t.options._dashArray || []), i = 0; i < a; i++) {
for (n = 0, o = r[i].length; n < o; n++) s = r[i][n], h[n ? "lineTo" : "moveTo"](s.x, s.y);
e && h.closePath()
}
this._fillStroke(h, t)
}
}, _updateCircle: function (t) {
if (!t._empty()) {
var e = t._point, i = this._ctx, n = t._radius, o = (t._radiusY || n) / n;
this._drawnLayers[t._leaflet_id] = t, 1 !== o && (i.save(), i.scale(1, o)), i.beginPath(), i.arc(e.x, e.y / o, n, 0, 2 * Math.PI, !1), 1 !== o && i.restore(), this._fillStroke(i, t)
}
}, _fillStroke: function (t, e) {
var i = this._clear, n = e.options;
t.globalCompositeOperation = i ? "destination-out" : "source-over", n.fill && (t.globalAlpha = i ? 1 : n.fillOpacity, t.fillStyle = n.fillColor || n.color, t.fill(n.fillRule || "evenodd")), n.stroke && 0 !== n.weight && (t.globalAlpha = i ? 1 : n.opacity, e._prevWeight = t.lineWidth = i ? e._prevWeight + 1 : n.weight, t.strokeStyle = n.color, t.lineCap = n.lineCap, t.lineJoin = n.lineJoin, t.stroke())
}, _onClick: function (t) {
var e, i = this._map.mouseEventToLayerPoint(t), n = [];
for (var s in this._layers) e = this._layers[s], e.options.interactive && e._containsPoint(i) && !this._map._draggableMoved(e) && (o.DomEvent._fakeStop(t), n.push(e));
n.length && this._fireEvent(n, t)
}, _onMouseMove: function (t) {
if (this._map && !this._map.dragging.moving() && !this._map._animatingZoom) {
var e = this._map.mouseEventToLayerPoint(t);
this._handleMouseOut(t, e), this._handleMouseHover(t, e)
}
}, _handleMouseOut: function (t, e) {
var i = this._hoveredLayer;
!i || "mouseout" !== t.type && i._containsPoint(e) || (o.DomUtil.removeClass(this._container, "leaflet-interactive"), this._fireEvent([i], t, "mouseout"), this._hoveredLayer = null)
}, _handleMouseHover: function (t, e) {
var i, n;
for (i in this._drawnLayers) n = this._drawnLayers[i], n.options.interactive && n._containsPoint(e) && (o.DomUtil.addClass(this._container, "leaflet-interactive"), this._fireEvent([n], t, "mouseover"), this._hoveredLayer = n);
this._hoveredLayer && this._fireEvent([this._hoveredLayer], t)
}, _fireEvent: function (t, e, i) {
this._map._fireDOMEvent(e, i || e.type, t)
}, _bringToFront: o.Util.falseFn, _bringToBack: o.Util.falseFn
}), o.Browser.canvas = function () {
return !!e.createElement("canvas").getContext
}(), o.canvas = function (t) {
return o.Browser.canvas ? new o.Canvas(t) : null
}, o.Polyline.prototype._containsPoint = function (t, e) {
var i, n, s, r, a, h, l = this._clickTolerance();
if (!this._pxBounds.contains(t)) return !1;
for (i = 0, r = this._parts.length; i < r; i++) for (h = this._parts[i], n = 0, a = h.length, s = a - 1; n < a; s = n++) if ((e || 0 !== n) && o.LineUtil.pointToSegmentDistance(t, h[s], h[n]) <= l) return !0;
return !1
}, o.Polygon.prototype._containsPoint = function (t) {
var e, i, n, s, r, a, h, l, u = !1;
if (!this._pxBounds.contains(t)) return !1;
for (s = 0, h = this._parts.length; s < h; s++) for (e = this._parts[s], r = 0, l = e.length, a = l - 1; r < l; a = r++) i = e[r], n = e[a], i.y > t.y != n.y > t.y && t.x < (n.x - i.x) * (t.y - i.y) / (n.y - i.y) + i.x && (u = !u);
return u || o.Polyline.prototype._containsPoint.call(this, t, !0)
}, o.CircleMarker.prototype._containsPoint = function (t) {
return t.distanceTo(this._point) <= this._radius + this._clickTolerance()
}, o.GeoJSON = o.FeatureGroup.extend({
initialize: function (t, e) {
o.setOptions(this, e), this._layers = {}, t && this.addData(t)
}, addData: function (t) {
var e, i, n, s = o.Util.isArray(t) ? t : t.features;
if (s) {
for (e = 0, i = s.length; e < i; e++) n = s[e], (n.geometries || n.geometry || n.features || n.coordinates) && this.addData(n);
return this;
}
var r = this.options;
if (r.filter && !r.filter(t)) return this;
var a = o.GeoJSON.geometryToLayer(t, r);
return a ? (a.feature = o.GeoJSON.asFeature(t), a.defaultOptions = a.options, this.resetStyle(a), r.onEachFeature && r.onEachFeature(t, a), this.addLayer(a)) : this
}, resetStyle: function (t) {
return t.options = o.Util.extend({}, t.defaultOptions), this._setLayerStyle(t, this.options.style), this
}, setStyle: function (t) {
return this.eachLayer(function (e) {
this._setLayerStyle(e, t)
}, this)
}, _setLayerStyle: function (t, e) {
"function" == typeof e && (e = e(t.feature)), t.setStyle && t.setStyle(e)
}
}), o.extend(o.GeoJSON, {
geometryToLayer: function (t, e) {
var i, n, s, r, a = "Feature" === t.type ? t.geometry : t, h = a ? a.coordinates : null, l = [],
u = e && e.pointToLayer, c = e && e.coordsToLatLng || this.coordsToLatLng;
if (!h && !a) return null;
switch (a.type) {
case"Point":
return i = c(h), u ? u(t, i) : new o.Marker(i);
case"MultiPoint":
for (s = 0, r = h.length; s < r; s++) i = c(h[s]), l.push(u ? u(t, i) : new o.Marker(i));
return new o.FeatureGroup(l);
case"LineString":
case"MultiLineString":
return n = this.coordsToLatLngs(h, "LineString" === a.type ? 0 : 1, c), new o.Polyline(n, e);
case"Polygon":
case"MultiPolygon":
return n = this.coordsToLatLngs(h, "Polygon" === a.type ? 1 : 2, c), new o.Polygon(n, e);
case"GeometryCollection":
for (s = 0, r = a.geometries.length; s < r; s++) {
var d = this.geometryToLayer({
geometry: a.geometries[s],
type: "Feature",
properties: t.properties
}, e);
d && l.push(d)
}
return new o.FeatureGroup(l);
default:
throw new Error("Invalid GeoJSON object.")
}
}, coordsToLatLng: function (t) {
return new o.LatLng(t[1], t[0], t[2])
}, coordsToLatLngs: function (t, e, i) {
for (var n, o = [], s = 0, r = t.length; s < r; s++) n = e ? this.coordsToLatLngs(t[s], e - 1, i) : (i || this.coordsToLatLng)(t[s]), o.push(n);
return o
}, latLngToCoords: function (t) {
return t.alt !== i ? [t.lng, t.lat, t.alt] : [t.lng, t.lat]
}, latLngsToCoords: function (t, e, i) {
for (var n = [], s = 0, r = t.length; s < r; s++) n.push(e ? o.GeoJSON.latLngsToCoords(t[s], e - 1, i) : o.GeoJSON.latLngToCoords(t[s]));
return !e && i && n.push(n[0]), n
}, getFeature: function (t, e) {
return t.feature ? o.extend({}, t.feature, {geometry: e}) : o.GeoJSON.asFeature(e)
}, asFeature: function (t) {
return "Feature" === t.type ? t : {type: "Feature", properties: {}, geometry: t}
}
});
var r = {
toGeoJSON: function () {
return o.GeoJSON.getFeature(this, {type: "Point", coordinates: o.GeoJSON.latLngToCoords(this.getLatLng())})
}
};
o.Marker.include(r), o.Circle.include(r), o.CircleMarker.include(r), o.Polyline.prototype.toGeoJSON = function () {
var t = !o.Polyline._flat(this._latlngs), e = o.GeoJSON.latLngsToCoords(this._latlngs, t ? 1 : 0);
return o.GeoJSON.getFeature(this, {type: (t ? "Multi" : "") + "LineString", coordinates: e})
}, o.Polygon.prototype.toGeoJSON = function () {
var t = !o.Polyline._flat(this._latlngs), e = t && !o.Polyline._flat(this._latlngs[0]),
i = o.GeoJSON.latLngsToCoords(this._latlngs, e ? 2 : t ? 1 : 0, !0);
return t || (i = [i]), o.GeoJSON.getFeature(this, {type: (e ? "Multi" : "") + "Polygon", coordinates: i})
}, o.LayerGroup.include({
toMultiPoint: function () {
var t = [];
return this.eachLayer(function (e) {
t.push(e.toGeoJSON().geometry.coordinates)
}), o.GeoJSON.getFeature(this, {type: "MultiPoint", coordinates: t})
}, toGeoJSON: function () {
var t = this.feature && this.feature.geometry && this.feature.geometry.type;
if ("MultiPoint" === t) return this.toMultiPoint();
var e = "GeometryCollection" === t, i = [];
return this.eachLayer(function (t) {
if (t.toGeoJSON) {
var n = t.toGeoJSON();
i.push(e ? n.geometry : o.GeoJSON.asFeature(n))
}
}), e ? o.GeoJSON.getFeature(this, {
geometries: i,
type: "GeometryCollection"
}) : {type: "FeatureCollection", features: i}
}
}), o.geoJSON = function (t, e) {
return new o.GeoJSON(t, e)
}, o.geoJson = o.geoJSON;
var a = "_leaflet_events";
o.DomEvent = {
on: function (t, e, i, n) {
if ("object" == typeof e) for (var s in e) this._on(t, s, e[s], i); else {
e = o.Util.splitWords(e);
for (var r = 0, a = e.length; r < a; r++) this._on(t, e[r], i, n)
}
return this
},
off: function (t, e, i, n) {
if ("object" == typeof e) for (var s in e) this._off(t, s, e[s], i); else {
e = o.Util.splitWords(e);
for (var r = 0, a = e.length; r < a; r++) this._off(t, e[r], i, n)
}
return this
},
_on: function (e, i, n, s) {
var r = i + o.stamp(n) + (s ? "_" + o.stamp(s) : "");
if (e[a] && e[a][r]) return this;
var h = function (i) {
return n.call(s || e, i || t.event)
}, l = h;
return o.Browser.pointer && 0 === i.indexOf("touch") ? this.addPointerListener(e, i, h, r) : o.Browser.touch && "dblclick" === i && this.addDoubleTapListener ? this.addDoubleTapListener(e, h, r) : "addEventListener" in e ? "mousewheel" === i ? e.addEventListener("onwheel" in e ? "wheel" : "mousewheel", h, !1) : "mouseenter" === i || "mouseleave" === i ? (h = function (i) {
i = i || t.event, o.DomEvent._isExternalTarget(e, i) && l(i)
}, e.addEventListener("mouseenter" === i ? "mouseover" : "mouseout", h, !1)) : ("click" === i && o.Browser.android && (h = function (t) {
return o.DomEvent._filterClick(t, l)
}), e.addEventListener(i, h, !1)) : "attachEvent" in e && e.attachEvent("on" + i, h), e[a] = e[a] || {}, e[a][r] = h, this
},
_off: function (t, e, i, n) {
var s = e + o.stamp(i) + (n ? "_" + o.stamp(n) : ""), r = t[a] && t[a][s];
return r ? (o.Browser.pointer && 0 === e.indexOf("touch") ? this.removePointerListener(t, e, s) : o.Browser.touch && "dblclick" === e && this.removeDoubleTapListener ? this.removeDoubleTapListener(t, s) : "removeEventListener" in t ? "mousewheel" === e ? t.removeEventListener("onwheel" in t ? "wheel" : "mousewheel", r, !1) : t.removeEventListener("mouseenter" === e ? "mouseover" : "mouseleave" === e ? "mouseout" : e, r, !1) : "detachEvent" in t && t.detachEvent("on" + e, r), t[a][s] = null, this) : this
},
stopPropagation: function (t) {
return t.stopPropagation ? t.stopPropagation() : t.originalEvent ? t.originalEvent._stopped = !0 : t.cancelBubble = !0, o.DomEvent._skipped(t), this
},
disableScrollPropagation: function (t) {
return o.DomEvent.on(t, "mousewheel", o.DomEvent.stopPropagation)
},
disableClickPropagation: function (t) {
var e = o.DomEvent.stopPropagation;
return o.DomEvent.on(t, o.Draggable.START.join(" "), e), o.DomEvent.on(t, {
click: o.DomEvent._fakeStop,
dblclick: e
})
},
preventDefault: function (t) {
return t.preventDefault ? t.preventDefault() : t.returnValue = !1, this
},
stop: function (t) {
return o.DomEvent.preventDefault(t).stopPropagation(t)
},
getMousePosition: function (t, e) {
if (!e) return new o.Point(t.clientX, t.clientY);
var i = e.getBoundingClientRect();
return new o.Point(t.clientX - i.left - e.clientLeft, t.clientY - i.top - e.clientTop)
},
_wheelPxFactor: o.Browser.win && o.Browser.chrome ? 2 : o.Browser.gecko ? t.devicePixelRatio : 1,
getWheelDelta: function (t) {
return o.Browser.edge ? t.wheelDeltaY / 2 : t.deltaY && 0 === t.deltaMode ? -t.deltaY / o.DomEvent._wheelPxFactor : t.deltaY && 1 === t.deltaMode ? 20 * -t.deltaY : t.deltaY && 2 === t.deltaMode ? 60 * -t.deltaY : t.deltaX || t.deltaZ ? 0 : t.wheelDelta ? (t.wheelDeltaY || t.wheelDelta) / 2 : t.detail && Math.abs(t.detail) < 32765 ? 20 * -t.detail : t.detail ? t.detail / -32765 * 60 : 0
},
_skipEvents: {},
_fakeStop: function (t) {
o.DomEvent._skipEvents[t.type] = !0
},
_skipped: function (t) {
var e = this._skipEvents[t.type];
return this._skipEvents[t.type] = !1, e
},
_isExternalTarget: function (t, e) {
var i = e.relatedTarget;
if (!i) return !0;
try {
for (; i && i !== t;) i = i.parentNode
} catch (t) {
return !1
}
return i !== t
},
_filterClick: function (t, e) {
var i = t.timeStamp || t.originalEvent && t.originalEvent.timeStamp,
n = o.DomEvent._lastClick && i - o.DomEvent._lastClick;
return n && n > 100 && n < 500 || t.target._simulatedClick && !t._simulated ? void o.DomEvent.stop(t) : (o.DomEvent._lastClick = i, void e(t))
}
}, o.DomEvent.addListener = o.DomEvent.on, o.DomEvent.removeListener = o.DomEvent.off, o.Draggable = o.Evented.extend({
options: {clickTolerance: 3},
statics: {
START: o.Browser.touch ? ["touchstart", "mousedown"] : ["mousedown"],
END: {mousedown: "mouseup", touchstart: "touchend", pointerdown: "touchend", MSPointerDown: "touchend"},
MOVE: {
mousedown: "mousemove",
touchstart: "touchmove",
pointerdown: "touchmove",
MSPointerDown: "touchmove"
}
},
initialize: function (t, e, i) {
this._element = t, this._dragStartTarget = e || t, this._preventOutline = i
},
enable: function () {
this._enabled || (o.DomEvent.on(this._dragStartTarget, o.Draggable.START.join(" "), this._onDown, this), this._enabled = !0)
},
disable: function () {
this._enabled && (o.DomEvent.off(this._dragStartTarget, o.Draggable.START.join(" "), this._onDown, this), this._enabled = !1, this._moved = !1)
},
_onDown: function (t) {
if (!t._simulated && this._enabled && (this._moved = !1, !o.DomUtil.hasClass(this._element, "leaflet-zoom-anim") && !(o.Draggable._dragging || t.shiftKey || 1 !== t.which && 1 !== t.button && !t.touches) && this._enabled && (o.Draggable._dragging = !0, this._preventOutline && o.DomUtil.preventOutline(this._element), o.DomUtil.disableImageDrag(), o.DomUtil.disableTextSelection(), !this._moving))) {
this.fire("down");
var i = t.touches ? t.touches[0] : t;
this._startPoint = new o.Point(i.clientX, i.clientY), o.DomEvent.on(e, o.Draggable.MOVE[t.type], this._onMove, this).on(e, o.Draggable.END[t.type], this._onUp, this)
}
},
_onMove: function (i) {
if (!i._simulated && this._enabled) {
if (i.touches && i.touches.length > 1) return void (this._moved = !0);
var n = i.touches && 1 === i.touches.length ? i.touches[0] : i, s = new o.Point(n.clientX, n.clientY),
r = s.subtract(this._startPoint);
(r.x || r.y) && (Math.abs(r.x) + Math.abs(r.y) < this.options.clickTolerance || (o.DomEvent.preventDefault(i), this._moved || (this.fire("dragstart"), this._moved = !0, this._startPos = o.DomUtil.getPosition(this._element).subtract(r), o.DomUtil.addClass(e.body, "leaflet-dragging"), this._lastTarget = i.target || i.srcElement, t.SVGElementInstance && this._lastTarget instanceof SVGElementInstance && (this._lastTarget = this._lastTarget.correspondingUseElement), o.DomUtil.addClass(this._lastTarget, "leaflet-drag-target")), this._newPos = this._startPos.add(r), this._moving = !0, o.Util.cancelAnimFrame(this._animRequest), this._lastEvent = i, this._animRequest = o.Util.requestAnimFrame(this._updatePosition, this, !0)))
}
},
_updatePosition: function () {
var t = {originalEvent: this._lastEvent};
this.fire("predrag", t), o.DomUtil.setPosition(this._element, this._newPos), this.fire("drag", t)
},
_onUp: function (t) {
if (!t._simulated && this._enabled) {
o.DomUtil.removeClass(e.body, "leaflet-dragging"), this._lastTarget && (o.DomUtil.removeClass(this._lastTarget, "leaflet-drag-target"), this._lastTarget = null);
for (var i in o.Draggable.MOVE) o.DomEvent.off(e, o.Draggable.MOVE[i], this._onMove, this).off(e, o.Draggable.END[i], this._onUp, this);
o.DomUtil.enableImageDrag(), o.DomUtil.enableTextSelection(), this._moved && this._moving && (o.Util.cancelAnimFrame(this._animRequest), this.fire("dragend", {distance: this._newPos.distanceTo(this._startPos)})), this._moving = !1, o.Draggable._dragging = !1
}
}
}), o.Handler = o.Class.extend({
initialize: function (t) {
this._map = t
}, enable: function () {
return this._enabled ? this : (this._enabled = !0, this.addHooks(), this)
}, disable: function () {
return this._enabled ? (this._enabled = !1, this.removeHooks(), this) : this
}, enabled: function () {
return !!this._enabled
}
}), o.Map.mergeOptions({
dragging: !0,
inertia: !o.Browser.android23,
inertiaDeceleration: 3400,
inertiaMaxSpeed: 1 / 0,
easeLinearity: .2,
worldCopyJump: !1,
maxBoundsViscosity: 0
}), o.Map.Drag = o.Handler.extend({
addHooks: function () {
if (!this._draggable) {
var t = this._map;
this._draggable = new o.Draggable(t._mapPane, t._container), this._draggable.on({
down: this._onDown,
dragstart: this._onDragStart,
drag: this._onDrag,
dragend: this._onDragEnd
}, this), this._draggable.on("predrag", this._onPreDragLimit, this), t.options.worldCopyJump && (this._draggable.on("predrag", this._onPreDragWrap, this), t.on("zoomend", this._onZoomEnd, this), t.whenReady(this._onZoomEnd, this))
}
o.DomUtil.addClass(this._map._container, "leaflet-grab leaflet-touch-drag"), this._draggable.enable(), this._positions = [], this._times = []
}, removeHooks: function () {
o.DomUtil.removeClass(this._map._container, "leaflet-grab"), o.DomUtil.removeClass(this._map._container, "leaflet-touch-drag"), this._draggable.disable()
}, moved: function () {
return this._draggable && this._draggable._moved
}, moving: function () {
return this._draggable && this._draggable._moving
}, _onDown: function () {
this._map._stop()
}, _onDragStart: function () {
var t = this._map;
if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
var e = o.latLngBounds(this._map.options.maxBounds);
this._offsetLimit = o.bounds(this._map.latLngToContainerPoint(e.getNorthWest()).multiplyBy(-1), this._map.latLngToContainerPoint(e.getSouthEast()).multiplyBy(-1).add(this._map.getSize())), this._viscosity = Math.min(1, Math.max(0, this._map.options.maxBoundsViscosity))
} else this._offsetLimit = null;
t.fire("movestart").fire("dragstart"), t.options.inertia && (this._positions = [], this._times = [])
}, _onDrag: function (t) {
if (this._map.options.inertia) {
var e = this._lastTime = +new Date,
i = this._lastPos = this._draggable._absPos || this._draggable._newPos;
this._positions.push(i), this._times.push(e), e - this._times[0] > 50 && (this._positions.shift(), this._times.shift())
}
this._map.fire("move", t).fire("drag", t)
}, _onZoomEnd: function () {
var t = this._map.getSize().divideBy(2), e = this._map.latLngToLayerPoint([0, 0]);
this._initialWorldOffset = e.subtract(t).x, this._worldWidth = this._map.getPixelWorldBounds().getSize().x
}, _viscousLimit: function (t, e) {
return t - (t - e) * this._viscosity
}, _onPreDragLimit: function () {
if (this._viscosity && this._offsetLimit) {
var t = this._draggable._newPos.subtract(this._draggable._startPos), e = this._offsetLimit;
t.x < e.min.x && (t.x = this._viscousLimit(t.x, e.min.x)), t.y < e.min.y && (t.y = this._viscousLimit(t.y, e.min.y)), t.x > e.max.x && (t.x = this._viscousLimit(t.x, e.max.x)), t.y > e.max.y && (t.y = this._viscousLimit(t.y, e.max.y)), this._draggable._newPos = this._draggable._startPos.add(t)
}
}, _onPreDragWrap: function () {
var t = this._worldWidth, e = Math.round(t / 2), i = this._initialWorldOffset,
n = this._draggable._newPos.x, o = (n - e + i) % t + e - i, s = (n + e + i) % t - e - i,
r = Math.abs(o + i) < Math.abs(s + i) ? o : s;
this._draggable._absPos = this._draggable._newPos.clone(), this._draggable._newPos.x = r
}, _onDragEnd: function (t) {
var e = this._map, i = e.options, n = !i.inertia || this._times.length < 2;
if (e.fire("dragend", t), n) e.fire("moveend"); else {
var s = this._lastPos.subtract(this._positions[0]), r = (this._lastTime - this._times[0]) / 1e3,
a = i.easeLinearity, h = s.multiplyBy(a / r), l = h.distanceTo([0, 0]),
u = Math.min(i.inertiaMaxSpeed, l), c = h.multiplyBy(u / l), d = u / (i.inertiaDeceleration * a),
_ = c.multiplyBy(-d / 2).round();
_.x || _.y ? (_ = e._limitOffset(_, e.options.maxBounds), o.Util.requestAnimFrame(function () {
e.panBy(_, {duration: d, easeLinearity: a, noMoveStart: !0, animate: !0})
})) : e.fire("moveend")
}
}
}), o.Map.addInitHook("addHandler", "dragging", o.Map.Drag), o.Map.mergeOptions({doubleClickZoom: !0}), o.Map.DoubleClickZoom = o.Handler.extend({
addHooks: function () {
this._map.on("dblclick", this._onDoubleClick, this)
}, removeHooks: function () {
this._map.off("dblclick", this._onDoubleClick, this)
}, _onDoubleClick: function (t) {
var e = this._map, i = e.getZoom(), n = e.options.zoomDelta, o = t.originalEvent.shiftKey ? i - n : i + n;
"center" === e.options.doubleClickZoom ? e.setZoom(o) : e.setZoomAround(t.containerPoint, o)
}
}), o.Map.addInitHook("addHandler", "doubleClickZoom", o.Map.DoubleClickZoom), o.Map.mergeOptions({
scrollWheelZoom: !0,
wheelDebounceTime: 40,
wheelPxPerZoomLevel: 60
}), o.Map.ScrollWheelZoom = o.Handler.extend({
addHooks: function () {
o.DomEvent.on(this._map._container, "mousewheel", this._onWheelScroll, this), this._delta = 0
}, removeHooks: function () {
o.DomEvent.off(this._map._container, "mousewheel", this._onWheelScroll, this)
}, _onWheelScroll: function (t) {
var e = o.DomEvent.getWheelDelta(t), i = this._map.options.wheelDebounceTime;
this._delta += e, this._lastMousePos = this._map.mouseEventToContainerPoint(t), this._startTime || (this._startTime = +new Date);
var n = Math.max(i - (+new Date - this._startTime), 0);
clearTimeout(this._timer), this._timer = setTimeout(o.bind(this._performZoom, this), n), o.DomEvent.stop(t)
}, _performZoom: function () {
var t = this._map, e = t.getZoom(), i = this._map.options.zoomSnap || 0;
t._stop();
var n = this._delta / (4 * this._map.options.wheelPxPerZoomLevel),
o = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(n)))) / Math.LN2, s = i ? Math.ceil(o / i) * i : o,
r = t._limitZoom(e + (this._delta > 0 ? s : -s)) - e;
this._delta = 0, this._startTime = null, r && ("center" === t.options.scrollWheelZoom ? t.setZoom(e + r) : t.setZoomAround(this._lastMousePos, e + r))
}
}), o.Map.addInitHook("addHandler", "scrollWheelZoom", o.Map.ScrollWheelZoom), o.extend(o.DomEvent, {
_touchstart: o.Browser.msPointer ? "MSPointerDown" : o.Browser.pointer ? "pointerdown" : "touchstart",
_touchend: o.Browser.msPointer ? "MSPointerUp" : o.Browser.pointer ? "pointerup" : "touchend",
addDoubleTapListener: function (t, e, i) {
function n(t) {
var e;
if (e = o.Browser.pointer ? o.DomEvent._pointersCount : t.touches.length, !(e > 1)) {
var i = Date.now(), n = i - (r || i);
a = t.touches ? t.touches[0] : t, h = n > 0 && n <= l, r = i
}
}
function s() {
if (h && !a.cancelBubble) {
if (o.Browser.pointer) {
var t, i, n = {};
for (i in a) t = a[i], n[i] = t && t.bind ? t.bind(a) : t;
a = n
}
a.type = "dblclick", e(a), r = null
}
}
var r, a, h = !1, l = 250, u = "_leaflet_", c = this._touchstart, d = this._touchend;
return t[u + c + i] = n, t[u + d + i] = s, t[u + "dblclick" + i] = e, t.addEventListener(c, n, !1), t.addEventListener(d, s, !1), o.Browser.edge || t.addEventListener("dblclick", e, !1), this
},
removeDoubleTapListener: function (t, e) {
var i = "_leaflet_", n = t[i + this._touchstart + e], s = t[i + this._touchend + e],
r = t[i + "dblclick" + e];
return t.removeEventListener(this._touchstart, n, !1), t.removeEventListener(this._touchend, s, !1), o.Browser.edge || t.removeEventListener("dblclick", r, !1), this
}
}), o.extend(o.DomEvent, {
POINTER_DOWN: o.Browser.msPointer ? "MSPointerDown" : "pointerdown",
POINTER_MOVE: o.Browser.msPointer ? "MSPointerMove" : "pointermove",
POINTER_UP: o.Browser.msPointer ? "MSPointerUp" : "pointerup",
POINTER_CANCEL: o.Browser.msPointer ? "MSPointerCancel" : "pointercancel",
TAG_WHITE_LIST: ["INPUT", "SELECT", "OPTION"],
_pointers: {},
_pointersCount: 0,
addPointerListener: function (t, e, i, n) {
return "touchstart" === e ? this._addPointerStart(t, i, n) : "touchmove" === e ? this._addPointerMove(t, i, n) : "touchend" === e && this._addPointerEnd(t, i, n), this
},
removePointerListener: function (t, e, i) {
var n = t["_leaflet_" + e + i];
return "touchstart" === e ? t.removeEventListener(this.POINTER_DOWN, n, !1) : "touchmove" === e ? t.removeEventListener(this.POINTER_MOVE, n, !1) : "touchend" === e && (t.removeEventListener(this.POINTER_UP, n, !1), t.removeEventListener(this.POINTER_CANCEL, n, !1)), this
},
_addPointerStart: function (t, i, n) {
var s = o.bind(function (t) {
if ("mouse" !== t.pointerType && t.pointerType !== t.MSPOINTER_TYPE_MOUSE) {
if (!(this.TAG_WHITE_LIST.indexOf(t.target.tagName) < 0)) return;
o.DomEvent.preventDefault(t)
}
this._handlePointer(t, i)
}, this);
if (t["_leaflet_touchstart" + n] = s, t.addEventListener(this.POINTER_DOWN, s, !1), !this._pointerDocListener) {
var r = o.bind(this._globalPointerUp, this);
e.documentElement.addEventListener(this.POINTER_DOWN, o.bind(this._globalPointerDown, this), !0), e.documentElement.addEventListener(this.POINTER_MOVE, o.bind(this._globalPointerMove, this), !0), e.documentElement.addEventListener(this.POINTER_UP, r, !0), e.documentElement.addEventListener(this.POINTER_CANCEL, r, !0), this._pointerDocListener = !0
}
},
_globalPointerDown: function (t) {
this._pointers[t.pointerId] = t, this._pointersCount++
},
_globalPointerMove: function (t) {
this._pointers[t.pointerId] && (this._pointers[t.pointerId] = t)
},
_globalPointerUp: function (t) {
delete this._pointers[t.pointerId], this._pointersCount--
},
_handlePointer: function (t, e) {
t.touches = [];
for (var i in this._pointers) t.touches.push(this._pointers[i]);
t.changedTouches = [t], e(t)
},
_addPointerMove: function (t, e, i) {
var n = o.bind(function (t) {
(t.pointerType !== t.MSPOINTER_TYPE_MOUSE && "mouse" !== t.pointerType || 0 !== t.buttons) && this._handlePointer(t, e)
}, this);
t["_leaflet_touchmove" + i] = n, t.addEventListener(this.POINTER_MOVE, n, !1)
},
_addPointerEnd: function (t, e, i) {
var n = o.bind(function (t) {
this._handlePointer(t, e)
}, this);
t["_leaflet_touchend" + i] = n, t.addEventListener(this.POINTER_UP, n, !1), t.addEventListener(this.POINTER_CANCEL, n, !1)
}
}), o.Map.mergeOptions({
touchZoom: o.Browser.touch && !o.Browser.android23,
bounceAtZoomLimits: !0
}), o.Map.TouchZoom = o.Handler.extend({
addHooks: function () {
o.DomUtil.addClass(this._map._container, "leaflet-touch-zoom"), o.DomEvent.on(this._map._container, "touchstart", this._onTouchStart, this)
}, removeHooks: function () {
o.DomUtil.removeClass(this._map._container, "leaflet-touch-zoom"), o.DomEvent.off(this._map._container, "touchstart", this._onTouchStart, this)
}, _onTouchStart: function (t) {
var i = this._map;
if (t.touches && 2 === t.touches.length && !i._animatingZoom && !this._zooming) {
var n = i.mouseEventToContainerPoint(t.touches[0]), s = i.mouseEventToContainerPoint(t.touches[1]);
this._centerPoint = i.getSize()._divideBy(2), this._startLatLng = i.containerPointToLatLng(this._centerPoint), "center" !== i.options.touchZoom && (this._pinchStartLatLng = i.containerPointToLatLng(n.add(s)._divideBy(2))), this._startDist = n.distanceTo(s), this._startZoom = i.getZoom(), this._moved = !1, this._zooming = !0, i._stop(), o.DomEvent.on(e, "touchmove", this._onTouchMove, this).on(e, "touchend", this._onTouchEnd, this), o.DomEvent.preventDefault(t)
}
}, _onTouchMove: function (t) {
if (t.touches && 2 === t.touches.length && this._zooming) {
var e = this._map, i = e.mouseEventToContainerPoint(t.touches[0]),
n = e.mouseEventToContainerPoint(t.touches[1]), s = i.distanceTo(n) / this._startDist;
if (this._zoom = e.getScaleZoom(s, this._startZoom), !e.options.bounceAtZoomLimits && (this._zoom < e.getMinZoom() && s < 1 || this._zoom > e.getMaxZoom() && s > 1) && (this._zoom = e._limitZoom(this._zoom)), "center" === e.options.touchZoom) {
if (this._center = this._startLatLng, 1 === s) return
} else {
var r = i._add(n)._divideBy(2)._subtract(this._centerPoint);
if (1 === s && 0 === r.x && 0 === r.y) return;
this._center = e.unproject(e.project(this._pinchStartLatLng, this._zoom).subtract(r), this._zoom)
}
this._moved || (e._moveStart(!0), this._moved = !0), o.Util.cancelAnimFrame(this._animRequest);
var a = o.bind(e._move, e, this._center, this._zoom, {pinch: !0, round: !1});
this._animRequest = o.Util.requestAnimFrame(a, this, !0), o.DomEvent.preventDefault(t)
}
}, _onTouchEnd: function () {
return this._moved && this._zooming ? (this._zooming = !1, o.Util.cancelAnimFrame(this._animRequest), o.DomEvent.off(e, "touchmove", this._onTouchMove).off(e, "touchend", this._onTouchEnd), void (this._map.options.zoomAnimation ? this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), !0, this._map.options.zoomSnap) : this._map._resetView(this._center, this._map._limitZoom(this._zoom)))) : void (this._zooming = !1)
}
}), o.Map.addInitHook("addHandler", "touchZoom", o.Map.TouchZoom), o.Map.mergeOptions({
tap: !0,
tapTolerance: 15
}), o.Map.Tap = o.Handler.extend({
addHooks: function () {
o.DomEvent.on(this._map._container, "touchstart", this._onDown, this)
}, removeHooks: function () {
o.DomEvent.off(this._map._container, "touchstart", this._onDown, this)
}, _onDown: function (t) {
if (t.touches) {
if (o.DomEvent.preventDefault(t), this._fireClick = !0, t.touches.length > 1) return this._fireClick = !1, void clearTimeout(this._holdTimeout);
var i = t.touches[0], n = i.target;
this._startPos = this._newPos = new o.Point(i.clientX, i.clientY), n.tagName && "a" === n.tagName.toLowerCase() && o.DomUtil.addClass(n, "leaflet-active"), this._holdTimeout = setTimeout(o.bind(function () {
this._isTapValid() && (this._fireClick = !1, this._onUp(), this._simulateEvent("contextmenu", i))
}, this), 1e3), this._simulateEvent("mousedown", i), o.DomEvent.on(e, {
touchmove: this._onMove,
touchend: this._onUp
}, this)
}
}, _onUp: function (t) {
if (clearTimeout(this._holdTimeout), o.DomEvent.off(e, {
touchmove: this._onMove,
touchend: this._onUp
}, this), this._fireClick && t && t.changedTouches) {
var i = t.changedTouches[0], n = i.target;
n && n.tagName && "a" === n.tagName.toLowerCase() && o.DomUtil.removeClass(n, "leaflet-active"), this._simulateEvent("mouseup", i), this._isTapValid() && this._simulateEvent("click", i)
}
}, _isTapValid: function () {
return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance
}, _onMove: function (t) {
var e = t.touches[0];
this._newPos = new o.Point(e.clientX, e.clientY), this._simulateEvent("mousemove", e)
}, _simulateEvent: function (i, n) {
var o = e.createEvent("MouseEvents");
o._simulated = !0, n.target._simulatedClick = !0, o.initMouseEvent(i, !0, !0, t, 1, n.screenX, n.screenY, n.clientX, n.clientY, !1, !1, !1, !1, 0, null), n.target.dispatchEvent(o)
}
}), o.Browser.touch && !o.Browser.pointer && o.Map.addInitHook("addHandler", "tap", o.Map.Tap), o.Map.mergeOptions({boxZoom: !0}), o.Map.BoxZoom = o.Handler.extend({
initialize: function (t) {
this._map = t, this._container = t._container, this._pane = t._panes.overlayPane
}, addHooks: function () {
o.DomEvent.on(this._container, "mousedown", this._onMouseDown, this)
}, removeHooks: function () {
o.DomEvent.off(this._container, "mousedown", this._onMouseDown, this)
}, moved: function () {
return this._moved
}, _resetState: function () {
this._moved = !1
}, _onMouseDown: function (t) {
return !(!t.shiftKey || 1 !== t.which && 1 !== t.button) && (this._resetState(), o.DomUtil.disableTextSelection(), o.DomUtil.disableImageDrag(), this._startPoint = this._map.mouseEventToContainerPoint(t), void o.DomEvent.on(e, {
contextmenu: o.DomEvent.stop,
mousemove: this._onMouseMove,
mouseup: this._onMouseUp,
keydown: this._onKeyDown
}, this))
}, _onMouseMove: function (t) {
this._moved || (this._moved = !0, this._box = o.DomUtil.create("div", "leaflet-zoom-box", this._container), o.DomUtil.addClass(this._container, "leaflet-crosshair"), this._map.fire("boxzoomstart")), this._point = this._map.mouseEventToContainerPoint(t);
var e = new o.Bounds(this._point, this._startPoint), i = e.getSize();
o.DomUtil.setPosition(this._box, e.min), this._box.style.width = i.x + "px", this._box.style.height = i.y + "px"
}, _finish: function () {
this._moved && (o.DomUtil.remove(this._box), o.DomUtil.removeClass(this._container, "leaflet-crosshair")), o.DomUtil.enableTextSelection(), o.DomUtil.enableImageDrag(), o.DomEvent.off(e, {
contextmenu: o.DomEvent.stop,
mousemove: this._onMouseMove,
mouseup: this._onMouseUp,
keydown: this._onKeyDown
}, this)
}, _onMouseUp: function (t) {
if ((1 === t.which || 1 === t.button) && (this._finish(), this._moved)) {
setTimeout(o.bind(this._resetState, this), 0);
var e = new o.LatLngBounds(this._map.containerPointToLatLng(this._startPoint), this._map.containerPointToLatLng(this._point));
this._map.fitBounds(e).fire("boxzoomend", {boxZoomBounds: e})
}
}, _onKeyDown: function (t) {
27 === t.keyCode && this._finish()
}
}), o.Map.addInitHook("addHandler", "boxZoom", o.Map.BoxZoom), o.Map.mergeOptions({
keyboard: !0,
keyboardPanDelta: 80
}), o.Map.Keyboard = o.Handler.extend({
keyCodes: {
left: [37],
right: [39],
down: [40],
up: [38],
zoomIn: [187, 107, 61, 171],
zoomOut: [189, 109, 54, 173]
}, initialize: function (t) {
this._map = t, this._setPanDelta(t.options.keyboardPanDelta), this._setZoomDelta(t.options.zoomDelta)
}, addHooks: function () {
var t = this._map._container;
t.tabIndex <= 0 && (t.tabIndex = "0"), o.DomEvent.on(t, {
focus: this._onFocus,
blur: this._onBlur,
mousedown: this._onMouseDown
}, this), this._map.on({focus: this._addHooks, blur: this._removeHooks}, this)
}, removeHooks: function () {
this._removeHooks(), o.DomEvent.off(this._map._container, {
focus: this._onFocus,
blur: this._onBlur,
mousedown: this._onMouseDown
}, this), this._map.off({focus: this._addHooks, blur: this._removeHooks}, this)
}, _onMouseDown: function () {
if (!this._focused) {
var i = e.body, n = e.documentElement, o = i.scrollTop || n.scrollTop, s = i.scrollLeft || n.scrollLeft;
this._map._container.focus(), t.scrollTo(s, o)
}
}, _onFocus: function () {
this._focused = !0, this._map.fire("focus")
}, _onBlur: function () {
this._focused = !1, this._map.fire("blur")
}, _setPanDelta: function (t) {
var e, i, n = this._panKeys = {}, o = this.keyCodes;
for (e = 0, i = o.left.length; e < i; e++) n[o.left[e]] = [-1 * t, 0];
for (e = 0, i = o.right.length; e < i; e++) n[o.right[e]] = [t, 0];
for (e = 0, i = o.down.length; e < i; e++) n[o.down[e]] = [0, t];
for (e = 0, i = o.up.length; e < i; e++) n[o.up[e]] = [0, -1 * t]
}, _setZoomDelta: function (t) {
var e, i, n = this._zoomKeys = {}, o = this.keyCodes;
for (e = 0, i = o.zoomIn.length; e < i; e++) n[o.zoomIn[e]] = t;
for (e = 0, i = o.zoomOut.length; e < i; e++) n[o.zoomOut[e]] = -t
}, _addHooks: function () {
o.DomEvent.on(e, "keydown", this._onKeyDown, this)
}, _removeHooks: function () {
o.DomEvent.off(e, "keydown", this._onKeyDown, this)
}, _onKeyDown: function (t) {
if (!(t.altKey || t.ctrlKey || t.metaKey)) {
var e, i = t.keyCode, n = this._map;
if (i in this._panKeys) {
if (n._panAnim && n._panAnim._inProgress) return;
e = this._panKeys[i], t.shiftKey && (e = o.point(e).multiplyBy(3)), n.panBy(e), n.options.maxBounds && n.panInsideBounds(n.options.maxBounds)
} else if (i in this._zoomKeys) n.setZoom(n.getZoom() + (t.shiftKey ? 3 : 1) * this._zoomKeys[i]); else {
if (27 !== i) return;
n.closePopup()
}
o.DomEvent.stop(t)
}
}
}), o.Map.addInitHook("addHandler", "keyboard", o.Map.Keyboard), o.Handler.MarkerDrag = o.Handler.extend({
initialize: function (t) {
this._marker = t
}, addHooks: function () {
var t = this._marker._icon;
this._draggable || (this._draggable = new o.Draggable(t, t, !0)), this._draggable.on({
dragstart: this._onDragStart,
drag: this._onDrag,
dragend: this._onDragEnd
}, this).enable(), o.DomUtil.addClass(t, "leaflet-marker-draggable")
}, removeHooks: function () {
this._draggable.off({
dragstart: this._onDragStart,
drag: this._onDrag,
dragend: this._onDragEnd
}, this).disable(), this._marker._icon && o.DomUtil.removeClass(this._marker._icon, "leaflet-marker-draggable")
}, moved: function () {
return this._draggable && this._draggable._moved
}, _onDragStart: function () {
this._oldLatLng = this._marker.getLatLng(), this._marker.closePopup().fire("movestart").fire("dragstart")
}, _onDrag: function (t) {
var e = this._marker, i = e._shadow, n = o.DomUtil.getPosition(e._icon), s = e._map.layerPointToLatLng(n);
i && o.DomUtil.setPosition(i, n), e._latlng = s, t.latlng = s, t.oldLatLng = this._oldLatLng, e.fire("move", t).fire("drag", t)
}, _onDragEnd: function (t) {
delete this._oldLatLng, this._marker.fire("moveend").fire("dragend", t)
}
}), o.Control = o.Class.extend({
options: {position: "topright"}, initialize: function (t) {
o.setOptions(this, t)
}, getPosition: function () {
return this.options.position
}, setPosition: function (t) {
var e = this._map;
return e && e.removeControl(this), this.options.position = t, e && e.addControl(this), this
}, getContainer: function () {
return this._container
}, addTo: function (t) {
this.remove(), this._map = t;
var e = this._container = this.onAdd(t), i = this.getPosition(), n = t._controlCorners[i];
return o.DomUtil.addClass(e, "leaflet-control"), i.indexOf("bottom") !== -1 ? n.insertBefore(e, n.firstChild) : n.appendChild(e), this
}, remove: function () {
return this._map ? (o.DomUtil.remove(this._container), this.onRemove && this.onRemove(this._map), this._map = null, this) : this
}, _refocusOnMap: function (t) {
this._map && t && t.screenX > 0 && t.screenY > 0 && this._map.getContainer().focus()
}
}), o.control = function (t) {
return new o.Control(t)
}, o.Map.include({
addControl: function (t) {
return t.addTo(this), this
}, removeControl: function (t) {
return t.remove(), this
}, _initControlPos: function () {
function t(t, s) {
var r = i + t + " " + i + s;
e[t + s] = o.DomUtil.create("div", r, n)
}
var e = this._controlCorners = {}, i = "leaflet-",
n = this._controlContainer = o.DomUtil.create("div", i + "control-container", this._container);
t("top", "left"), t("top", "right"), t("bottom", "left"), t("bottom", "right")
}, _clearControlPos: function () {
o.DomUtil.remove(this._controlContainer)
}
}), o.Control.Zoom = o.Control.extend({
options: {
position: "topleft",
zoomInText: "+",
zoomInTitle: "Zoom in",
zoomOutText: "-",
zoomOutTitle: "Zoom out"
}, onAdd: function (t) {
var e = "leaflet-control-zoom", i = o.DomUtil.create("div", e + " leaflet-bar"), n = this.options;
return this._zoomInButton = this._createButton(n.zoomInText, n.zoomInTitle, e + "-in", i, this._zoomIn), this._zoomOutButton = this._createButton(n.zoomOutText, n.zoomOutTitle, e + "-out", i, this._zoomOut), this._updateDisabled(), t.on("zoomend zoomlevelschange", this._updateDisabled, this), i
}, onRemove: function (t) {
t.off("zoomend zoomlevelschange", this._updateDisabled, this)
}, disable: function () {
return this._disabled = !0, this._updateDisabled(), this
}, enable: function () {
return this._disabled = !1, this._updateDisabled(), this
}, _zoomIn: function (t) {
!this._disabled && this._map._zoom < this._map.getMaxZoom() && this._map.zoomIn(this._map.options.zoomDelta * (t.shiftKey ? 3 : 1))
}, _zoomOut: function (t) {
!this._disabled && this._map._zoom > this._map.getMinZoom() && this._map.zoomOut(this._map.options.zoomDelta * (t.shiftKey ? 3 : 1))
}, _createButton: function (t, e, i, n, s) {
var r = o.DomUtil.create("a", i, n);
return r.innerHTML = t, r.href = "#", r.title = e, o.DomEvent.on(r, "mousedown dblclick", o.DomEvent.stopPropagation).on(r, "click", o.DomEvent.stop).on(r, "click", s, this).on(r, "click", this._refocusOnMap, this), r
}, _updateDisabled: function () {
var t = this._map, e = "leaflet-disabled";
o.DomUtil.removeClass(this._zoomInButton, e), o.DomUtil.removeClass(this._zoomOutButton, e), (this._disabled || t._zoom === t.getMinZoom()) && o.DomUtil.addClass(this._zoomOutButton, e), (this._disabled || t._zoom === t.getMaxZoom()) && o.DomUtil.addClass(this._zoomInButton, e)
}
}), o.Map.mergeOptions({zoomControl: !0}), o.Map.addInitHook(function () {
this.options.zoomControl && (this.zoomControl = new o.Control.Zoom, this.addControl(this.zoomControl))
}), o.control.zoom = function (t) {
return new o.Control.Zoom(t)
}, o.Control.Attribution = o.Control.extend({
options: {
position: "bottomright",
prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
}, initialize: function (t) {
o.setOptions(this, t), this._attributions = {}
}, onAdd: function (t) {
t.attributionControl = this, this._container = o.DomUtil.create("div", "leaflet-control-attribution"), o.DomEvent && o.DomEvent.disableClickPropagation(this._container);
for (var e in t._layers) t._layers[e].getAttribution && this.addAttribution(t._layers[e].getAttribution());
return this._update(), this._container
}, setPrefix: function (t) {
return this.options.prefix = t, this._update(), this
}, addAttribution: function (t) {
return t ? (this._attributions[t] || (this._attributions[t] = 0), this._attributions[t]++, this._update(), this) : this
}, removeAttribution: function (t) {
return t ? (this._attributions[t] && (this._attributions[t]--, this._update()), this) : this
}, _update: function () {
if (this._map) {
var t = [];
for (var e in this._attributions) this._attributions[e] && t.push(e);
var i = [];
this.options.prefix && i.push(this.options.prefix), t.length && i.push(t.join(", ")), this._container.innerHTML = i.join(" | ")
}
}
}), o.Map.mergeOptions({attributionControl: !0}), o.Map.addInitHook(function () {
this.options.attributionControl && (new o.Control.Attribution).addTo(this)
}), o.control.attribution = function (t) {
return new o.Control.Attribution(t)
}, o.Control.Scale = o.Control.extend({
options: {position: "bottomleft", maxWidth: 100, metric: !0, imperial: !0}, onAdd: function (t) {
var e = "leaflet-control-scale", i = o.DomUtil.create("div", e), n = this.options;
return this._addScales(n, e + "-line", i), t.on(n.updateWhenIdle ? "moveend" : "move", this._update, this), t.whenReady(this._update, this), i
}, onRemove: function (t) {
t.off(this.options.updateWhenIdle ? "moveend" : "move", this._update, this)
}, _addScales: function (t, e, i) {
t.metric && (this._mScale = o.DomUtil.create("div", e, i)), t.imperial && (this._iScale = o.DomUtil.create("div", e, i))
}, _update: function () {
var t = this._map, e = t.getSize().y / 2,
i = t.distance(t.containerPointToLatLng([0, e]), t.containerPointToLatLng([this.options.maxWidth, e]));
this._updateScales(i)
}, _updateScales: function (t) {
this.options.metric && t && this._updateMetric(t), this.options.imperial && t && this._updateImperial(t)
}, _updateMetric: function (t) {
var e = this._getRoundNum(t), i = e < 1e3 ? e + " m" : e / 1e3 + " km";
this._updateScale(this._mScale, i, e / t)
}, _updateImperial: function (t) {
var e, i, n, o = 3.2808399 * t;
o > 5280 ? (e = o / 5280, i = this._getRoundNum(e), this._updateScale(this._iScale, i + " mi", i / e)) : (n = this._getRoundNum(o), this._updateScale(this._iScale, n + " ft", n / o))
}, _updateScale: function (t, e, i) {
t.style.width = Math.round(this.options.maxWidth * i) + "px", t.innerHTML = e
}, _getRoundNum: function (t) {
var e = Math.pow(10, (Math.floor(t) + "").length - 1), i = t / e;
return i = i >= 10 ? 10 : i >= 5 ? 5 : i >= 3 ? 3 : i >= 2 ? 2 : 1, e * i
}
}), o.control.scale = function (t) {
return new o.Control.Scale(t)
}, o.Control.Layers = o.Control.extend({
options: {collapsed: !0, position: "topright", autoZIndex: !0, hideSingleBase: !1},
initialize: function (t, e, i) {
o.setOptions(this, i), this._layers = [], this._lastZIndex = 0, this._handlingClick = !1;
for (var n in t) this._addLayer(t[n], n);
for (n in e) this._addLayer(e[n], n, !0)
},
onAdd: function (t) {
return this._initLayout(), this._update(), this._map = t, t.on("zoomend", this._checkDisabledLayers, this), this._container
},
onRemove: function () {
this._map.off("zoomend", this._checkDisabledLayers, this);
for (var t = 0; t < this._layers.length; t++) this._layers[t].layer.off("add remove", this._onLayerChange, this)
},
addBaseLayer: function (t, e) {
return this._addLayer(t, e), this._map ? this._update() : this
},
addOverlay: function (t, e) {
return this._addLayer(t, e, !0), this._map ? this._update() : this
},
removeLayer: function (t) {
t.off("add remove", this._onLayerChange, this);
var e = this._getLayer(o.stamp(t));
return e && this._layers.splice(this._layers.indexOf(e), 1), this._map ? this._update() : this
},
expand: function () {
o.DomUtil.addClass(this._container, "leaflet-control-layers-expanded"), this._form.style.height = null;
var t = this._map.getSize().y - (this._container.offsetTop + 50);
return t < this._form.clientHeight ? (o.DomUtil.addClass(this._form, "leaflet-control-layers-scrollbar"), this._form.style.height = t + "px") : o.DomUtil.removeClass(this._form, "leaflet-control-layers-scrollbar"), this._checkDisabledLayers(), this
},
collapse: function () {
return o.DomUtil.removeClass(this._container, "leaflet-control-layers-expanded"), this
},
_initLayout: function () {
var t = "leaflet-control-layers", e = this._container = o.DomUtil.create("div", t);
e.setAttribute("aria-haspopup", !0), o.DomEvent.disableClickPropagation(e), o.Browser.touch || o.DomEvent.disableScrollPropagation(e);
var i = this._form = o.DomUtil.create("form", t + "-list");
if (this.options.collapsed) {
o.Browser.android || o.DomEvent.on(e, {mouseenter: this.expand, mouseleave: this.collapse}, this);
var n = this._layersLink = o.DomUtil.create("a", t + "-toggle", e);
n.href = "#", n.title = "Layers", o.Browser.touch ? o.DomEvent.on(n, "click", o.DomEvent.stop).on(n, "click", this.expand, this) : o.DomEvent.on(n, "focus", this.expand, this), o.DomEvent.on(i, "click", function () {
setTimeout(o.bind(this._onInputClick, this), 0)
}, this), this._map.on("click", this.collapse, this)
} else this.expand();
this._baseLayersList = o.DomUtil.create("div", t + "-base", i), this._separator = o.DomUtil.create("div", t + "-separator", i), this._overlaysList = o.DomUtil.create("div", t + "-overlays", i), e.appendChild(i)
},
_getLayer: function (t) {
for (var e = 0; e < this._layers.length; e++) if (this._layers[e] && o.stamp(this._layers[e].layer) === t) return this._layers[e]
},
_addLayer: function (t, e, i) {
t.on("add remove", this._onLayerChange, this), this._layers.push({
layer: t,
name: e,
overlay: i
}), this.options.autoZIndex && t.setZIndex && (this._lastZIndex++, t.setZIndex(this._lastZIndex))
},
_update: function () {
if (!this._container) return this;
o.DomUtil.empty(this._baseLayersList), o.DomUtil.empty(this._overlaysList);
var t, e, i, n, s = 0;
for (i = 0; i < this._layers.length; i++) n = this._layers[i], this._addItem(n), e = e || n.overlay, t = t || !n.overlay, s += n.overlay ? 0 : 1;
return this.options.hideSingleBase && (t = t && s > 1, this._baseLayersList.style.display = t ? "" : "none"), this._separator.style.display = e && t ? "" : "none", this
},
_onLayerChange: function (t) {
this._handlingClick || this._update();
var e = this._getLayer(o.stamp(t.target)),
i = e.overlay ? "add" === t.type ? "overlayadd" : "overlayremove" : "add" === t.type ? "baselayerchange" : null;
i && this._map.fire(i, e)
},
_createRadioElement: function (t, i) {
var n = '<input type="radio" class="leaflet-control-layers-selector" name="' + t + '"' + (i ? ' checked="checked"' : "") + "/>",
o = e.createElement("div");
return o.innerHTML = n, o.firstChild
},
_addItem: function (t) {
var i, n = e.createElement("label"), s = this._map.hasLayer(t.layer);
t.overlay ? (i = e.createElement("input"), i.type = "checkbox", i.className = "leaflet-control-layers-selector", i.defaultChecked = s) : i = this._createRadioElement("leaflet-base-layers", s), i.layerId = o.stamp(t.layer), o.DomEvent.on(i, "click", this._onInputClick, this);
var r = e.createElement("span");
r.innerHTML = " " + t.name;
var a = e.createElement("div");
n.appendChild(a), a.appendChild(i), a.appendChild(r);
var h = t.overlay ? this._overlaysList : this._baseLayersList;
return h.appendChild(n), this._checkDisabledLayers(), n
},
_onInputClick: function () {
var t, e, i, n = this._form.getElementsByTagName("input"), o = [], s = [];
this._handlingClick = !0;
for (var r = n.length - 1; r >= 0; r--) t = n[r], e = this._getLayer(t.layerId).layer, i = this._map.hasLayer(e), t.checked && !i ? o.push(e) : !t.checked && i && s.push(e);
for (r = 0; r < s.length; r++) this._map.removeLayer(s[r]);
for (r = 0; r < o.length; r++) this._map.addLayer(o[r]);
this._handlingClick = !1, this._refocusOnMap()
},
_checkDisabledLayers: function () {
for (var t, e, n = this._form.getElementsByTagName("input"), o = this._map.getZoom(), s = n.length - 1; s >= 0; s--) t = n[s], e = this._getLayer(t.layerId).layer, t.disabled = e.options.minZoom !== i && o < e.options.minZoom || e.options.maxZoom !== i && o > e.options.maxZoom
},
_expand: function () {
return this.expand()
},
_collapse: function () {
return this.collapse()
}
}), o.control.layers = function (t, e, i) {
return new o.Control.Layers(t, e, i)
}, o.PosAnimation = o.Evented.extend({
run: function (t, e, i, n) {
this.stop(), this._el = t, this._inProgress = !0, this._duration = i || .25, this._easeOutPower = 1 / Math.max(n || .5, .2), this._startPos = o.DomUtil.getPosition(t), this._offset = e.subtract(this._startPos), this._startTime = +new Date, this.fire("start"), this._animate()
}, stop: function () {
this._inProgress && (this._step(!0), this._complete())
}, _animate: function () {
this._animId = o.Util.requestAnimFrame(this._animate, this), this._step()
}, _step: function (t) {
var e = +new Date - this._startTime, i = 1e3 * this._duration;
e < i ? this._runFrame(this._easeOut(e / i), t) : (this._runFrame(1), this._complete())
}, _runFrame: function (t, e) {
var i = this._startPos.add(this._offset.multiplyBy(t));
e && i._round(), o.DomUtil.setPosition(this._el, i), this.fire("step")
}, _complete: function () {
o.Util.cancelAnimFrame(this._animId), this._inProgress = !1, this.fire("end")
}, _easeOut: function (t) {
return 1 - Math.pow(1 - t, this._easeOutPower)
}
}), o.Map.include({
setView: function (t, e, n) {
if (e = e === i ? this._zoom : this._limitZoom(e), t = this._limitCenter(o.latLng(t), e, this.options.maxBounds), n = n || {}, this._stop(), this._loaded && !n.reset && n !== !0) {
n.animate !== i && (n.zoom = o.extend({animate: n.animate}, n.zoom), n.pan = o.extend({
animate: n.animate,
duration: n.duration
}, n.pan));
var s = this._zoom !== e ? this._tryAnimatedZoom && this._tryAnimatedZoom(t, e, n.zoom) : this._tryAnimatedPan(t, n.pan);
if (s) return clearTimeout(this._sizeTimer), this
}
return this._resetView(t, e), this
}, panBy: function (t, e) {
if (t = o.point(t).round(), e = e || {}, !t.x && !t.y) return this.fire("moveend");
if (e.animate !== !0 && !this.getSize().contains(t)) return this._resetView(this.unproject(this.project(this.getCenter()).add(t)), this.getZoom()), this;
if (this._panAnim || (this._panAnim = new o.PosAnimation, this._panAnim.on({
step: this._onPanTransitionStep,
end: this._onPanTransitionEnd
}, this)), e.noMoveStart || this.fire("movestart"), e.animate !== !1) {
o.DomUtil.addClass(this._mapPane, "leaflet-pan-anim");
var i = this._getMapPanePos().subtract(t).round();
this._panAnim.run(this._mapPane, i, e.duration || .25, e.easeLinearity)
} else this._rawPanBy(t), this.fire("move").fire("moveend");
return this
}, _onPanTransitionStep: function () {
this.fire("move")
}, _onPanTransitionEnd: function () {
o.DomUtil.removeClass(this._mapPane, "leaflet-pan-anim"), this.fire("moveend")
}, _tryAnimatedPan: function (t, e) {
var i = this._getCenterOffset(t)._floor();
return !((e && e.animate) !== !0 && !this.getSize().contains(i)) && (this.panBy(i, e), !0)
}
}), o.Map.mergeOptions({zoomAnimation: !0, zoomAnimationThreshold: 4});
var h = o.DomUtil.TRANSITION && o.Browser.any3d && !o.Browser.mobileOpera;
h && o.Map.addInitHook(function () {
this._zoomAnimated = this.options.zoomAnimation, this._zoomAnimated && (this._createAnimProxy(), o.DomEvent.on(this._proxy, o.DomUtil.TRANSITION_END, this._catchTransitionEnd, this))
}), o.Map.include(h ? {
_createAnimProxy: function () {
var t = this._proxy = o.DomUtil.create("div", "leaflet-proxy leaflet-zoom-animated");
this._panes.mapPane.appendChild(t), this.on("zoomanim", function (e) {
var i = o.DomUtil.TRANSFORM, n = t.style[i];
o.DomUtil.setTransform(t, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1)), n === t.style[i] && this._animatingZoom && this._onZoomTransitionEnd()
}, this), this.on("load moveend", function () {
var e = this.getCenter(), i = this.getZoom();
o.DomUtil.setTransform(t, this.project(e, i), this.getZoomScale(i, 1))
}, this)
}, _catchTransitionEnd: function (t) {
this._animatingZoom && t.propertyName.indexOf("transform") >= 0 && this._onZoomTransitionEnd()
}, _nothingToAnimate: function () {
return !this._container.getElementsByClassName("leaflet-zoom-animated").length
}, _tryAnimatedZoom: function (t, e, i) {
if (this._animatingZoom) return !0;
if (i = i || {}, !this._zoomAnimated || i.animate === !1 || this._nothingToAnimate() || Math.abs(e - this._zoom) > this.options.zoomAnimationThreshold) return !1;
var n = this.getZoomScale(e), s = this._getCenterOffset(t)._divideBy(1 - 1 / n);
return !(i.animate !== !0 && !this.getSize().contains(s)) && (o.Util.requestAnimFrame(function () {
this._moveStart(!0)._animateZoom(t, e, !0)
}, this), !0)
}, _animateZoom: function (t, e, i, n) {
i && (this._animatingZoom = !0, this._animateToCenter = t, this._animateToZoom = e, o.DomUtil.addClass(this._mapPane, "leaflet-zoom-anim")), this.fire("zoomanim", {
center: t,
zoom: e,
noUpdate: n
}), setTimeout(o.bind(this._onZoomTransitionEnd, this), 250)
}, _onZoomTransitionEnd: function () {
this._animatingZoom && (o.DomUtil.removeClass(this._mapPane, "leaflet-zoom-anim"), this._animatingZoom = !1, this._move(this._animateToCenter, this._animateToZoom), o.Util.requestAnimFrame(function () {
this._moveEnd(!0)
}, this))
}
} : {}), o.Map.include({
flyTo: function (t, e, n) {
function s(t) {
var e = t ? -1 : 1, i = t ? v : g, n = v * v - g * g + e * L * L * y * y, o = 2 * i * L * y, s = n / o,
r = Math.sqrt(s * s + 1) - s, a = r < 1e-9 ? -18 : Math.log(r);
return a
}
function r(t) {
return (Math.exp(t) - Math.exp(-t)) / 2
}
function a(t) {
return (Math.exp(t) + Math.exp(-t)) / 2
}
function h(t) {
return r(t) / a(t)
}
function l(t) {
return g * (a(x) / a(x + P * t))
}
function u(t) {
return g * (a(x) * h(x + P * t) - r(x)) / L
}
function c(t) {
return 1 - Math.pow(1 - t, 1.5)
}
function d() {
var i = (Date.now() - b) / T, n = c(i) * w;
i <= 1 ? (this._flyToFrame = o.Util.requestAnimFrame(d, this), this._move(this.unproject(_.add(m.subtract(_).multiplyBy(u(n) / y)), f), this.getScaleZoom(g / l(n), f), {flyTo: !0})) : this._move(t, e)._moveEnd(!0)
}
if (n = n || {}, n.animate === !1 || !o.Browser.any3d) return this.setView(t, e, n);
this._stop();
var _ = this.project(this.getCenter()), m = this.project(t), p = this.getSize(), f = this._zoom;
t = o.latLng(t), e = e === i ? f : e;
var g = Math.max(p.x, p.y), v = g * this.getZoomScale(f, e), y = m.distanceTo(_) || 1, P = 1.42, L = P * P,
x = s(0), b = Date.now(), w = (s(1) - x) / P, T = n.duration ? 1e3 * n.duration : 1e3 * w * .8;
return this._moveStart(!0), d.call(this), this
}, flyToBounds: function (t, e) {
var i = this._getBoundsCenterZoom(t, e);
return this.flyTo(i.center, i.zoom, e)
}
}), o.Map.include({
_defaultLocateOptions: {timeout: 1e4, watch: !1}, locate: function (t) {
if (t = this._locateOptions = o.extend({}, this._defaultLocateOptions, t), !("geolocation" in navigator)) return this._handleGeolocationError({
code: 0,
message: "Geolocation not supported."
}), this;
var e = o.bind(this._handleGeolocationResponse, this), i = o.bind(this._handleGeolocationError, this);
return t.watch ? this._locationWatchId = navigator.geolocation.watchPosition(e, i, t) : navigator.geolocation.getCurrentPosition(e, i, t), this
}, stopLocate: function () {
return navigator.geolocation && navigator.geolocation.clearWatch && navigator.geolocation.clearWatch(this._locationWatchId), this._locateOptions && (this._locateOptions.setView = !1), this
}, _handleGeolocationError: function (t) {
var e = t.code,
i = t.message || (1 === e ? "permission denied" : 2 === e ? "position unavailable" : "timeout");
this._locateOptions.setView && !this._loaded && this.fitWorld(), this.fire("locationerror", {
code: e,
message: "Geolocation error: " + i + "."
})
}, _handleGeolocationResponse: function (t) {
var e = t.coords.latitude, i = t.coords.longitude, n = new o.LatLng(e, i),
s = n.toBounds(t.coords.accuracy), r = this._locateOptions;
if (r.setView) {
var a = this.getBoundsZoom(s);
this.setView(n, r.maxZoom ? Math.min(a, r.maxZoom) : a)
}
var h = {latlng: n, bounds: s, timestamp: t.timestamp};
for (var l in t.coords) "number" == typeof t.coords[l] && (h[l] = t.coords[l]);
this.fire("locationfound", h)
}
})
}(window, document);
|
//
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <iTunesStore/ISOperation.h>
@class ExternalDownloadManifest, NSOrderedSet, NSURLRequest, SSDownloadManifestResponse;
@interface LoadExternalDownloadManifestOperation : ISOperation
{
NSOrderedSet *_downloadIDs; // 96 = 0x60
ExternalDownloadManifest *_manifest; // 104 = 0x68
long long _manifestFormat; // 112 = 0x70
_Bool _shouldHideUserPrompts; // 120 = 0x78
NSURLRequest *_urlRequest; // 128 = 0x80
}
- (void).cxx_destruct; // IMP=0x0000000100089574
- (void)_showDialogForError:(id)arg1; // IMP=0x00000001000891b4
- (_Bool)_showConfirmationPromptForManifest:(id)arg1 response:(id)arg2; // IMP=0x0000000100088b3c
- (_Bool)_runForPurchaseFormatWithURLRequest:(id)arg1 error:(id *)arg2; // IMP=0x000000010008846c
- (_Bool)_runForPublicFormatWithURLRequest:(id)arg1 error:(id *)arg2; // IMP=0x0000000100087fb8
- (void)_processValidDownloads:(id)arg1; // IMP=0x0000000100087990
- (_Bool)_handlePublicResponseForOperation:(id)arg1 error:(id *)arg2; // IMP=0x00000001000874fc
- (void)run; // IMP=0x0000000100086ea0
@property(copy) NSURLRequest *URLRequest;
@property _Bool shouldHideUserPrompts;
@property long long manifestFormat;
@property(readonly) SSDownloadManifestResponse *manifestResponse;
@property(readonly) ExternalDownloadManifest *manifest;
- (id)initWithRequest:(id)arg1; // IMP=0x0000000100086974
@end
|
#
# Builtin Definitions
#
from __future__ import absolute_import
from .Symtab import BuiltinScope, StructOrUnionScope
from .Code import UtilityCode
from .TypeSlots import Signature
from . import PyrexTypes
from . import Options
# C-level implementations of builtin types, functions and methods
iter_next_utility_code = UtilityCode.load("IterNext", "ObjectHandling.c")
getattr_utility_code = UtilityCode.load("GetAttr", "ObjectHandling.c")
getattr3_utility_code = UtilityCode.load("GetAttr3", "Builtins.c")
pyexec_utility_code = UtilityCode.load("PyExec", "Builtins.c")
pyexec_globals_utility_code = UtilityCode.load("PyExecGlobals", "Builtins.c")
globals_utility_code = UtilityCode.load("Globals", "Builtins.c")
builtin_utility_code = {
'StopAsyncIteration': UtilityCode.load_cached("StopAsyncIteration", "Coroutine.c"),
}
# mapping from builtins to their C-level equivalents
class _BuiltinOverride(object):
def __init__(self, py_name, args, ret_type, cname, py_equiv="*",
utility_code=None, sig=None, func_type=None,
is_strict_signature=False, builtin_return_type=None):
self.py_name, self.cname, self.py_equiv = py_name, cname, py_equiv
self.args, self.ret_type = args, ret_type
self.func_type, self.sig = func_type, sig
self.builtin_return_type = builtin_return_type
self.is_strict_signature = is_strict_signature
self.utility_code = utility_code
def build_func_type(self, sig=None, self_arg=None):
if sig is None:
sig = Signature(self.args, self.ret_type)
sig.exception_check = False # not needed for the current builtins
func_type = sig.function_type(self_arg)
if self.is_strict_signature:
func_type.is_strict_signature = True
if self.builtin_return_type:
func_type.return_type = builtin_types[self.builtin_return_type]
return func_type
class BuiltinAttribute(object):
def __init__(self, py_name, cname=None, field_type=None, field_type_name=None):
self.py_name = py_name
self.cname = cname or py_name
self.field_type_name = field_type_name # can't do the lookup before the type is declared!
self.field_type = field_type
def declare_in_type(self, self_type):
if self.field_type_name is not None:
# lazy type lookup
field_type = builtin_scope.lookup(self.field_type_name).type
else:
field_type = self.field_type or PyrexTypes.py_object_type
entry = self_type.scope.declare(self.py_name, self.cname, field_type, None, 'private')
entry.is_variable = True
class BuiltinFunction(_BuiltinOverride):
def declare_in_scope(self, scope):
func_type, sig = self.func_type, self.sig
if func_type is None:
func_type = self.build_func_type(sig)
scope.declare_builtin_cfunction(self.py_name, func_type, self.cname,
self.py_equiv, self.utility_code)
class BuiltinMethod(_BuiltinOverride):
def declare_in_type(self, self_type):
method_type, sig = self.func_type, self.sig
if method_type is None:
# override 'self' type (first argument)
self_arg = PyrexTypes.CFuncTypeArg("", self_type, None)
self_arg.not_none = True
self_arg.accept_builtin_subtypes = True
method_type = self.build_func_type(sig, self_arg)
self_type.scope.declare_builtin_cfunction(
self.py_name, method_type, self.cname, utility_code=self.utility_code)
builtin_function_table = [
# name, args, return, C API func, py equiv = "*"
BuiltinFunction('abs', "d", "d", "fabs",
is_strict_signature = True),
BuiltinFunction('abs', "f", "f", "fabsf",
is_strict_signature = True),
BuiltinFunction('abs', "i", "i", "abs",
is_strict_signature = True),
BuiltinFunction('abs', "l", "l", "labs",
is_strict_signature = True),
BuiltinFunction('abs', None, None, "__Pyx_abs_longlong",
utility_code = UtilityCode.load("abs_longlong", "Builtins.c"),
func_type = PyrexTypes.CFuncType(
PyrexTypes.c_longlong_type, [
PyrexTypes.CFuncTypeArg("arg", PyrexTypes.c_longlong_type, None)
],
is_strict_signature = True, nogil=True)),
] + list(
BuiltinFunction('abs', None, None, "/*abs_{0}*/".format(t.specialization_name()),
func_type = PyrexTypes.CFuncType(
t,
[PyrexTypes.CFuncTypeArg("arg", t, None)],
is_strict_signature = True, nogil=True))
for t in (PyrexTypes.c_uint_type, PyrexTypes.c_ulong_type, PyrexTypes.c_ulonglong_type)
) + list(
BuiltinFunction('abs', None, None, "__Pyx_c_abs{0}".format(t.funcsuffix),
func_type = PyrexTypes.CFuncType(
t.real_type, [
PyrexTypes.CFuncTypeArg("arg", t, None)
],
is_strict_signature = True, nogil=True))
for t in (PyrexTypes.c_float_complex_type,
PyrexTypes.c_double_complex_type,
PyrexTypes.c_longdouble_complex_type)
) + [
BuiltinFunction('abs', "O", "O", "PyNumber_Absolute"),
#('all', "", "", ""),
#('any', "", "", ""),
#('ascii', "", "", ""),
#('bin', "", "", ""),
BuiltinFunction('callable', "O", "b", "__Pyx_PyCallable_Check",
utility_code = UtilityCode.load("CallableCheck", "ObjectHandling.c")),
#('chr', "", "", ""),
#('cmp', "", "", "", ""), # int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
#('compile', "", "", ""), # PyObject* Py_CompileString( char *str, char *filename, int start)
BuiltinFunction('delattr', "OO", "r", "PyObject_DelAttr"),
BuiltinFunction('dir', "O", "O", "PyObject_Dir"),
BuiltinFunction('divmod', "OO", "O", "PyNumber_Divmod"),
BuiltinFunction('exec', "O", "O", "__Pyx_PyExecGlobals",
utility_code = pyexec_globals_utility_code),
BuiltinFunction('exec', "OO", "O", "__Pyx_PyExec2",
utility_code = pyexec_utility_code),
BuiltinFunction('exec', "OOO", "O", "__Pyx_PyExec3",
utility_code = pyexec_utility_code),
#('eval', "", "", ""),
#('execfile', "", "", ""),
#('filter', "", "", ""),
BuiltinFunction('getattr3', "OOO", "O", "__Pyx_GetAttr3", "getattr",
utility_code=getattr3_utility_code), # Pyrex legacy
BuiltinFunction('getattr', "OOO", "O", "__Pyx_GetAttr3",
utility_code=getattr3_utility_code),
BuiltinFunction('getattr', "OO", "O", "__Pyx_GetAttr",
utility_code=getattr_utility_code),
BuiltinFunction('hasattr', "OO", "b", "__Pyx_HasAttr",
utility_code = UtilityCode.load("HasAttr", "Builtins.c")),
BuiltinFunction('hash', "O", "h", "PyObject_Hash"),
#('hex', "", "", ""),
#('id', "", "", ""),
#('input', "", "", ""),
BuiltinFunction('intern', "O", "O", "__Pyx_Intern",
utility_code = UtilityCode.load("Intern", "Builtins.c")),
BuiltinFunction('isinstance', "OO", "b", "PyObject_IsInstance"),
BuiltinFunction('issubclass', "OO", "b", "PyObject_IsSubclass"),
BuiltinFunction('iter', "OO", "O", "PyCallIter_New"),
BuiltinFunction('iter', "O", "O", "PyObject_GetIter"),
BuiltinFunction('len', "O", "z", "PyObject_Length"),
BuiltinFunction('locals', "", "O", "__pyx_locals"),
#('map', "", "", ""),
#('max', "", "", ""),
#('min', "", "", ""),
BuiltinFunction('next', "O", "O", "__Pyx_PyIter_Next",
utility_code = iter_next_utility_code), # not available in Py2 => implemented here
BuiltinFunction('next', "OO", "O", "__Pyx_PyIter_Next2",
utility_code = iter_next_utility_code), # not available in Py2 => implemented here
#('oct', "", "", ""),
#('open', "ss", "O", "PyFile_FromString"), # not in Py3
] + [
BuiltinFunction('ord', None, None, "__Pyx_long_cast",
func_type=PyrexTypes.CFuncType(
PyrexTypes.c_long_type, [PyrexTypes.CFuncTypeArg("c", c_type, None)],
is_strict_signature=True))
for c_type in [PyrexTypes.c_py_ucs4_type, PyrexTypes.c_py_unicode_type]
] + [
BuiltinFunction('ord', None, None, "__Pyx_uchar_cast",
func_type=PyrexTypes.CFuncType(
PyrexTypes.c_uchar_type, [PyrexTypes.CFuncTypeArg("c", c_type, None)],
is_strict_signature=True))
for c_type in [PyrexTypes.c_char_type, PyrexTypes.c_schar_type, PyrexTypes.c_uchar_type]
] + [
BuiltinFunction('ord', None, None, "__Pyx_PyObject_Ord",
utility_code=UtilityCode.load_cached("object_ord", "Builtins.c"),
func_type=PyrexTypes.CFuncType(
PyrexTypes.c_long_type, [
PyrexTypes.CFuncTypeArg("c", PyrexTypes.py_object_type, None)
],
exception_value="(long)(Py_UCS4)-1")),
BuiltinFunction('pow', "OOO", "O", "PyNumber_Power"),
BuiltinFunction('pow', "OO", "O", "__Pyx_PyNumber_Power2",
utility_code = UtilityCode.load("pow2", "Builtins.c")),
#('range', "", "", ""),
#('raw_input', "", "", ""),
#('reduce', "", "", ""),
BuiltinFunction('reload', "O", "O", "PyImport_ReloadModule"),
BuiltinFunction('repr', "O", "O", "PyObject_Repr", builtin_return_type='str'),
#('round', "", "", ""),
BuiltinFunction('setattr', "OOO", "r", "PyObject_SetAttr"),
#('sum', "", "", ""),
#('sorted', "", "", ""),
#('type', "O", "O", "PyObject_Type"),
#('unichr', "", "", ""),
#('unicode', "", "", ""),
#('vars', "", "", ""),
#('zip', "", "", ""),
# Can't do these easily until we have builtin type entries.
#('typecheck', "OO", "i", "PyObject_TypeCheck", False),
#('issubtype', "OO", "i", "PyType_IsSubtype", False),
# Put in namespace append optimization.
BuiltinFunction('__Pyx_PyObject_Append', "OO", "O", "__Pyx_PyObject_Append"),
# This is conditionally looked up based on a compiler directive.
BuiltinFunction('__Pyx_Globals', "", "O", "__Pyx_Globals",
utility_code=globals_utility_code),
]
# Builtin types
# bool
# buffer
# classmethod
# dict
# enumerate
# file
# float
# int
# list
# long
# object
# property
# slice
# staticmethod
# super
# str
# tuple
# type
# xrange
builtin_types_table = [
("type", "PyType_Type", []),
# This conflicts with the C++ bool type, and unfortunately
# C++ is too liberal about PyObject* <-> bool conversions,
# resulting in unintuitive runtime behavior and segfaults.
# ("bool", "PyBool_Type", []),
("int", "PyInt_Type", []),
("long", "PyLong_Type", []),
("float", "PyFloat_Type", []),
("complex", "PyComplex_Type", [BuiltinAttribute('cval', field_type_name = 'Py_complex'),
BuiltinAttribute('real', 'cval.real', field_type = PyrexTypes.c_double_type),
BuiltinAttribute('imag', 'cval.imag', field_type = PyrexTypes.c_double_type),
]),
("basestring", "PyBaseString_Type", [
BuiltinMethod("join", "TO", "T", "__Pyx_PyBaseString_Join",
utility_code=UtilityCode.load("StringJoin", "StringTools.c")),
]),
("bytearray", "PyByteArray_Type", [
]),
("bytes", "PyBytes_Type", [BuiltinMethod("__contains__", "TO", "b", "PySequence_Contains"),
BuiltinMethod("join", "TO", "O", "__Pyx_PyBytes_Join",
utility_code=UtilityCode.load("StringJoin", "StringTools.c")),
]),
("str", "PyString_Type", [BuiltinMethod("__contains__", "TO", "b", "PySequence_Contains"),
BuiltinMethod("join", "TO", "O", "__Pyx_PyString_Join",
builtin_return_type='basestring',
utility_code=UtilityCode.load("StringJoin", "StringTools.c")),
]),
("unicode", "PyUnicode_Type", [BuiltinMethod("__contains__", "TO", "b", "PyUnicode_Contains"),
BuiltinMethod("join", "TO", "T", "PyUnicode_Join"),
]),
("tuple", "PyTuple_Type", [BuiltinMethod("__contains__", "TO", "b", "PySequence_Contains"),
]),
("list", "PyList_Type", [BuiltinMethod("__contains__", "TO", "b", "PySequence_Contains"),
BuiltinMethod("insert", "TzO", "r", "PyList_Insert"),
BuiltinMethod("reverse", "T", "r", "PyList_Reverse"),
BuiltinMethod("append", "TO", "r", "__Pyx_PyList_Append",
utility_code=UtilityCode.load("ListAppend", "Optimize.c")),
BuiltinMethod("extend", "TO", "r", "__Pyx_PyList_Extend",
utility_code=UtilityCode.load("ListExtend", "Optimize.c")),
]),
("dict", "PyDict_Type", [BuiltinMethod("__contains__", "TO", "b", "PyDict_Contains"),
BuiltinMethod("has_key", "TO", "b", "PyDict_Contains"),
BuiltinMethod("items", "T", "O", "__Pyx_PyDict_Items",
utility_code=UtilityCode.load("py_dict_items", "Builtins.c")),
BuiltinMethod("keys", "T", "O", "__Pyx_PyDict_Keys",
utility_code=UtilityCode.load("py_dict_keys", "Builtins.c")),
BuiltinMethod("values", "T", "O", "__Pyx_PyDict_Values",
utility_code=UtilityCode.load("py_dict_values", "Builtins.c")),
BuiltinMethod("iteritems", "T", "O", "__Pyx_PyDict_IterItems",
utility_code=UtilityCode.load("py_dict_iteritems", "Builtins.c")),
BuiltinMethod("iterkeys", "T", "O", "__Pyx_PyDict_IterKeys",
utility_code=UtilityCode.load("py_dict_iterkeys", "Builtins.c")),
BuiltinMethod("itervalues", "T", "O", "__Pyx_PyDict_IterValues",
utility_code=UtilityCode.load("py_dict_itervalues", "Builtins.c")),
BuiltinMethod("viewitems", "T", "O", "__Pyx_PyDict_ViewItems",
utility_code=UtilityCode.load("py_dict_viewitems", "Builtins.c")),
BuiltinMethod("viewkeys", "T", "O", "__Pyx_PyDict_ViewKeys",
utility_code=UtilityCode.load("py_dict_viewkeys", "Builtins.c")),
BuiltinMethod("viewvalues", "T", "O", "__Pyx_PyDict_ViewValues",
utility_code=UtilityCode.load("py_dict_viewvalues", "Builtins.c")),
BuiltinMethod("clear", "T", "r", "__Pyx_PyDict_Clear",
utility_code=UtilityCode.load("py_dict_clear", "Optimize.c")),
BuiltinMethod("copy", "T", "T", "PyDict_Copy")]),
("slice", "PySlice_Type", [BuiltinAttribute('start'),
BuiltinAttribute('stop'),
BuiltinAttribute('step'),
]),
# ("file", "PyFile_Type", []), # not in Py3
("set", "PySet_Type", [BuiltinMethod("__contains__", "TO", "b", "PySequence_Contains"),
BuiltinMethod("clear", "T", "r", "PySet_Clear"),
# discard() and remove() have a special treatment for unhashable values
BuiltinMethod("discard", "TO", "r", "__Pyx_PySet_Discard",
utility_code=UtilityCode.load("py_set_discard", "Optimize.c")),
BuiltinMethod("remove", "TO", "r", "__Pyx_PySet_Remove",
utility_code=UtilityCode.load("py_set_remove", "Optimize.c")),
# update is actually variadic (see Github issue #1645)
# BuiltinMethod("update", "TO", "r", "__Pyx_PySet_Update",
# utility_code=UtilityCode.load_cached("PySet_Update", "Builtins.c")),
BuiltinMethod("add", "TO", "r", "PySet_Add"),
BuiltinMethod("pop", "T", "O", "PySet_Pop")]),
("frozenset", "PyFrozenSet_Type", []),
("Exception", "((PyTypeObject*)PyExc_Exception)[0]", []),
("StopAsyncIteration", "((PyTypeObject*)__Pyx_PyExc_StopAsyncIteration)[0]", []),
]
types_that_construct_their_instance = set([
# some builtin types do not always return an instance of
# themselves - these do:
'type', 'bool', 'long', 'float', 'complex',
'bytes', 'unicode', 'bytearray',
'tuple', 'list', 'dict', 'set', 'frozenset'
# 'str', # only in Py3.x
# 'file', # only in Py2.x
])
builtin_structs_table = [
('Py_buffer', 'Py_buffer',
[("buf", PyrexTypes.c_void_ptr_type),
("obj", PyrexTypes.py_object_type),
("len", PyrexTypes.c_py_ssize_t_type),
("itemsize", PyrexTypes.c_py_ssize_t_type),
("readonly", PyrexTypes.c_bint_type),
("ndim", PyrexTypes.c_int_type),
("format", PyrexTypes.c_char_ptr_type),
("shape", PyrexTypes.c_py_ssize_t_ptr_type),
("strides", PyrexTypes.c_py_ssize_t_ptr_type),
("suboffsets", PyrexTypes.c_py_ssize_t_ptr_type),
("smalltable", PyrexTypes.CArrayType(PyrexTypes.c_py_ssize_t_type, 2)),
("internal", PyrexTypes.c_void_ptr_type),
]),
('Py_complex', 'Py_complex',
[('real', PyrexTypes.c_double_type),
('imag', PyrexTypes.c_double_type),
])
]
# set up builtin scope
builtin_scope = BuiltinScope()
def init_builtin_funcs():
for bf in builtin_function_table:
bf.declare_in_scope(builtin_scope)
builtin_types = {}
def init_builtin_types():
global builtin_types
for name, cname, methods in builtin_types_table:
utility = builtin_utility_code.get(name)
if name == 'frozenset':
objstruct_cname = 'PySetObject'
elif name == 'bytearray':
objstruct_cname = 'PyByteArrayObject'
elif name == 'bool':
objstruct_cname = None
elif name == 'Exception':
objstruct_cname = "PyBaseExceptionObject"
elif name == 'StopAsyncIteration':
objstruct_cname = "PyBaseExceptionObject"
else:
objstruct_cname = 'Py%sObject' % name.capitalize()
the_type = builtin_scope.declare_builtin_type(name, cname, utility, objstruct_cname)
builtin_types[name] = the_type
for method in methods:
method.declare_in_type(the_type)
def init_builtin_structs():
for name, cname, attribute_types in builtin_structs_table:
scope = StructOrUnionScope(name)
for attribute_name, attribute_type in attribute_types:
scope.declare_var(attribute_name, attribute_type, None,
attribute_name, allow_pyobject=True)
builtin_scope.declare_struct_or_union(
name, "struct", scope, 1, None, cname = cname)
def init_builtins():
init_builtin_structs()
init_builtin_types()
init_builtin_funcs()
builtin_scope.declare_var(
'__debug__', PyrexTypes.c_const_type(PyrexTypes.c_bint_type),
pos=None, cname='(!Py_OptimizeFlag)', is_cdef=True)
global list_type, tuple_type, dict_type, set_type, frozenset_type
global bytes_type, str_type, unicode_type, basestring_type, slice_type
global float_type, bool_type, type_type, complex_type, bytearray_type
type_type = builtin_scope.lookup('type').type
list_type = builtin_scope.lookup('list').type
tuple_type = builtin_scope.lookup('tuple').type
dict_type = builtin_scope.lookup('dict').type
set_type = builtin_scope.lookup('set').type
frozenset_type = builtin_scope.lookup('frozenset').type
slice_type = builtin_scope.lookup('slice').type
bytes_type = builtin_scope.lookup('bytes').type
str_type = builtin_scope.lookup('str').type
unicode_type = builtin_scope.lookup('unicode').type
basestring_type = builtin_scope.lookup('basestring').type
bytearray_type = builtin_scope.lookup('bytearray').type
float_type = builtin_scope.lookup('float').type
bool_type = builtin_scope.lookup('bool').type
complex_type = builtin_scope.lookup('complex').type
init_builtins()
|
#
# Copied From [mmdetection](https://github.com/open-mmlab/mmdetection/tree/master/mmdet/ops/dcn)
#
|
/* @flow */
import config from '../config'
import { warn } from './debug'
import { inBrowser } from './env'
export function handleError (err: Error, vm: any, info: string) {
if (vm) {
let cur = vm
while ((cur = cur.$parent)) {
const hooks = cur.$options.errorCaptured
if (hooks) {
for (let i = 0; i < hooks.length; i++) {
try {
const capture = hooks[i].call(cur, err, vm, info) === false
if (capture) return
} catch (e) {
globalHandleError(e, cur, 'errorCaptured hook')
}
}
}
}
}
globalHandleError(err, vm, info)
}
function globalHandleError (err, vm, info) {
if (config.errorHandler) {
try {
return config.errorHandler.call(null, err, vm, info)
} catch (e) {
logError(e, null, 'config.errorHandler')
}
}
logError(err, vm, info)
}
function logError (err, vm, info) {
if (process.env.NODE_ENV !== 'production') {
warn(`Error in ${info}: "${err.toString()}"`, vm)
}
/* istanbul ignore else */
if (inBrowser && typeof console !== 'undefined') {
console.error(err)
} else {
throw err
}
}
|
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
import {
green, lightBlue, orange, red,
} from '@material-ui/core/colors';
import ButtonBase from '@material-ui/core/ButtonBase';
import { fade } from '@material-ui/core/styles/colorManipulator';
import GaugeBar from './GaugeBar';
import droneX from './DroneX.png';
const styles = theme => ({
flexContaner: {
display: 'flex',
flexDirection: 'row',
},
card: {
width: 300,
display: 'flex',
},
details: {
display: 'flex',
flexDirection: 'column',
},
content: {
flex: '1 0 auto',
},
cover: {
margin: 8,
width: 64,
height: 64,
},
controls: {
display: 'flex',
alignItems: 'center',
paddingLeft: theme.spacing(1),
paddingBottom: theme.spacing(1),
},
playIcon: {
height: 38,
width: 38,
},
status: {
margin: 8,
width: 200,
// flex: 1,
},
buttonBase: {
position: 'relative',
textAlign: 'left',
},
});
function CharCard(props) {
const { classes, theme } = props;
const labelColor = fade(theme.palette.background.paper, 0.7);
const textColor = theme.palette.text.primary;
return (
<ButtonBase
focusRipple
className={classes.buttonBase}
style={{
// width: '30%',
padding: 0,
}}
onClick={props.onClick}
>
<Card className={classes.card}>
<CardMedia
className={classes.cover}
image={droneX}
title="Live from space album cover"
/>
<div className={classes.status}>
<div className={classes.flexContaner}>
<div style={{
height: 10,
width: 10,
margin: 7,
// boxSizing: 'border-box',
borderWidth: 1,
borderColor: textColor,
borderStyle: 'solid',
backgroundColor: green[700],
borderRadius: '50%',
}}
/>
<Typography variant="body1" gutterBottom>
BPK-01
</Typography>
</div>
<GaugeBar
textColor={textColor}
labelColor={labelColor}
segments={[
{ name: '1', percent: 50, color: green[700] },
{ name: '2', percent: 50, color: green[400] },
]}
/>
<GaugeBar
textColor={textColor}
labelColor={labelColor}
segments={[
{ name: '1', percent: 50, color: lightBlue[700] },
{ name: '2', percent: 30, color: lightBlue[400] },
]}
/>
<GaugeBar
textColor={textColor}
labelColor={labelColor}
segments={[
{ name: '1', percent: 40, color: orange[700] },
{ name: '2', percent: 40, color: orange[400] },
]}
/>
<GaugeBar
textColor={textColor}
labelColor={labelColor}
segments={[
{ name: '1', percent: 30, color: red[700] },
{ name: '2', percent: 30, color: red[400] },
]}
/>
</div>
</Card>
</ButtonBase>
);
}
export default withStyles(styles, { withTheme: true })(CharCard);
|
describe('content-loader', () => {
let el
const elemTag = 'h-content-loader'
const expect = chai.expect
beforeEach(() => {
el = document.createElement(elemTag)
document.body.appendChild(el)
})
afterEach(() => {
document.body.removeChild(el)
el = null
})
describe('interface', () => {
it('should be defined', async () => {
let elem = document.querySelector(elemTag)
expect(elem).to.not.be.undefined
expect(window.customElements.get(elemTag)).to.not.be.undefined
})
it('should be an Element node ', async () => {
let elem = document.querySelector(elemTag)
expect(elem.nodeType).to.equal(Node.ELEMENT_NODE)
})
})
describe('component', () => {
it('should be loading when set to true', async () => {
el.loading()
expect(el.isLoading()).to.be.true
})
it('should not be loading when set to false', async () => {
el.done()
expect(el.isLoading()).to.be.false
})
})
})
|
Index: Electrum-DASH-3.2.3/setup.py
===================================================================
--- Electrum-DASH-3.2.3.orig/setup.py
+++ Electrum-DASH-3.2.3/setup.py
@@ -77,6 +77,7 @@ setup(
'electrum_dash',
'electrum_dash.gui',
'electrum_dash.gui.qt',
+ 'electrum_dash.plugins',
] + [('electrum_dash.plugins.'+pkg) for pkg in find_packages('electrum_dash/plugins')],
package_dir={
'electrum_dash': 'electrum_dash'
|
//Code Quiz
//Store user info
const user = 0;
var highScore = 50; //var highScore = 50; ; //Score add fix for ticking timer
let quiz = 0;
let index = 0; //Question number // Track the question answered.
let theRightAnswer = true; //var quizStatus = true; // know the status of the quiz. Quiz is not running = false, running = true
let currentQuestion = {};
const questionContainer = document.querySelector("#question-container");
const startBtn = document.querySelector("#startQuizBtn");
const questionBoxEl = document.querySelector("#questionBox");
const answerBtn = document.querySelector("#answerBtn");
// const nextBtn = document.querySelector("#nextBtn");
// const submitBtn = document.querySelector("#submitBtn");
var score = 0; //Max Value by decreasing each wrong answer
var finalAnswerCheck = 0 // If last answer was wrong it will be validated outside of the time interval and then display as enabled = 1
var checkTimes = 1 // Check timer times call for function on last question
var answerNumber = 0; // Track next answers to show
const viewUserScores = document.querySelector("#view-high-scores")
const counter = document.querySelector("#counter");
const choiceA = document.querySelector("#choiceA");
const choiceB = document.querySelector("#choiceB");
const choiceC = document.querySelector("#choiceC");
const choiceD = document.querySelector("#choiceD");
var mainDivEl = document.getElementById('mainDiv'); // Main div container for all elements except for header elements
// const introPage = document.querySelector("#intro-page");
const timerDisplay = document.querySelector("#timer");
const submitScore = document.querySelector("#submitScore");
const enterInitialsEl = document.createElement("enterInitials"); // Enter initials
var enterInitialsTextAreaEl = document.createElement("enterInitialsTextArea"); // TextArea
const answerCorrectWrong = document.querySelector("#answerCorrectWrong");
const finalScoreDisplayEl = document.createElement("finalScoreDisplay"); // Display Question
// var secondsLeft = 1 * questions.length;
var timer = 60; // this is a Global variable called timer and its assigment is a counter
// const score = document.getElementById('score');
// const user = document.getElementById('user');
// answerCorrectWrong = document.querySelector("click", ".answer");
//Score variable
choiceA.style.display ='none'
choiceB.style.display ='none'
choiceC.style.display ='none'
choiceD.style.display ='none'
submitScore.style.display = "none";
answerCorrectWrong.style.display = "none";
enterInitialsTextArea.style.display = "none";
//creat question Object//not sure if i need to create answer object integrated with question or should i create anwser object on its own
// var questions = [
// correct{
// 0 : "Who is the bootcamp instructor?",
// 1 : "Gary",
// 2 : "Eugene",
// 3 : "Nick",
// 4 : "Jean",
// 5 : "answerA",
// },
// {
// question: "What college is the bootcamp hosted from?",
// answerA: "University of Texas",
// answerB: "University of Texas at Denton",
// answerC: "Southern Methodist University",
// answerD: "lorem ipsumn slindkdkn",
// correctAns: "answerC",
// },
// {
// question: "how long did it take Jonathan to program Code Quiz assigned?",
// answerA: "1 Day",
// answerB: "4 hours",
// answerC: "A week",
// answerD: "Three Weeks",
// correctAns: "answerB",
// },
// {
// question: "Jonathan is the best programer in the entire world.",
// answerA: "True",
// answerB: "False",
// answerC: "None of the above statements",
// answerD: "if you chose anything but a you're a hater",
// correctAns: "answerA",
// },
// {
// question: "What is the syntax to declare a function named 'flashLight'?",
// answerA: "myFunction flashLight",
// answerB: "Function flashLight",
// answerC: "function flashLight()",
// answerD: "this is a function(){}",
// correctAns: "answerC",
// },
// {
// question: "How do you center text in css?",
// answerA: "i need my text centered asap",
// answerB: "Pease center my text",
// answerC: "center text",
// answerD: "text-align: center;",
// correctAns: "answerC",
// },
// ];
// var questionObject = {
// }
var questionsObject = {
// Object that holds correct answers.
correct: {
0: "Commonly used datatypes DO NOT include?",
1: "The condition statement if/else is enclosed with the following:",
2: "Arrays can be used to store the following", // Button #4 for
3: "A very useful tool to debug arrays is:", // Button #3
4: "Strings must be enclosed with:",
},
};
var answersObject = {
// Object that holds correct answers.
answers: {
0: {
0: "Strings",
1: "Boolean",
2: "Alerts",
3: "Numbers",
},
1: {
0: "Parentheses",
1: "Curly Brackets",
2: "Quotes",
3: "Square Brackets",
},
2: {
// Button #3
0: "Javascript",
1: "Terminal/bash",
2: "For loops",
3: "Console.log",
},
3: {
// Answer to question 5 --> Button #2
0: "Commas",
1: "Curly brackets",
2: "Quotes",
3: "Parentheses",
},
4: {
// Button #4
0: "Number of strings",
1: "Other arrays",
2: "Booleans",
3: "All of the above",
},
},
};
//Initialize the display timer at default value
timerDisplay.textContent = timer;
viewUserScores.addEventListener('click', function() { //view users scores
var users = "";
var test = "";
var highScores = "";
for (let i = 0; i < localStorage.length; i++) {
const getUserScore = [];
users = localStorage.getItem(localStorage.key(i));
test = users.substring(0,4)
if(test == 'quiz') {
getUserScore = user.split(",");
var userName = checkUserValue[0]
highScores += "User" + userName.substring(4) + "high score is: " + getUserScore[1] + "\n"
}
window.alert(highScores);
}
})
//Click the start button and the quiz starts
submitScore.addEventListener('click', function() {
var quizLocalStorage = "quiz";
var quizUserDetails = "";
var value = [];
// If good input the value will be assign properly
quizUserDetails = quizLocalStorage + enterInitialsTextAreaEl.value
value = [quizUserDetails,highScore] // Create an array for validation
//Add test entry @local storage in order to be able to get the local storage.
// If user clears the data at local storage the below code will not work unless ther is at least on entry.
if (!localStorage.length) {
localStorage.setItem("test", "test");
}
for (var i = 0; i < localStorage.length; i++){
var checkUser = "";
var checkUserValue = [];
// Assign value again
quizUserDetails = quizLocalStorage + enterInitialsTextArea.value;
// Check if assigned value exist in the local storage
checkUser = quizLocalStorage + enterInitialsTextArea.value;
// quizInitial + score will be checked against the input from the user to validate if exist already in local storage
if (checkUser == null) {// New user, no need to split
localStorage.setItem(quizUserDetails, value); //Value is equal to
window.alert("Your score of " + highScore + "has been submitted!")
break;
} else if (checkUser != null){
checkUserValue = checkUser.split(","); //Split since the object exist in local storage
}
if ( quizUserDetails == checkUserValue[0] && highScore == checkUserValue[1] ) {
// Only insert if the current highScore is higher,
// otherwise let the user know they had a higher score already
localStorage.setItem(quizUserDetails, value); // Value us equal to
window.alert(highScore + " " + "is the lates entry for user initial " + enterInitialsTextArea + ". Entry will not be added.")
break;
} else if (enterInitialsTextArea.value == " ") {
window.alert("Please enter an initial");
break;
} else if (quizUserDetails = checkUserValue[0] && highScore > checkUserValue[1]){
// New high score submitted!
localStorage.setItem(quizUserDetails, value); // Value is equal to
window.alert("New high score of " + highScore + " has been submitted!.\nYour previous score was " + checkUserValue[1])
break;
} else if ( quizUserDetails == checkUserValue[0] && highScore < checkUserValue[1] ) {
// Your previous code was higher!
localStorage.setItem(quizUserDetails, value); // Value is equal to
window.alert("Your previous code of " + checkUserValue[1] + " was higher. Entry will not be added.");
break;
} else { // New entry all together
localStorage.setItem(quizUserDetails, value); // Value is equal to
window.alert("Your score of " + highScore + " has been submitted!")
break;
}
}
})
choiceA.addEventListener("mouseover", function() {
answerCorrectWrong.style.display='none';
});
choiceB.addEventListener("mouseover", function() {
answerCorrectWrong.style.display='none';
});
choiceC.addEventListener("mouseover", function() {
answerCorrectWrong.style.display='none';
});
choiceD.addEventListener("mouseover", function() {
answerCorrectWrong.style.display='none';
});
submitScore.addEventListener("mouseover", function() {
answerCorrectWrong.style.display='none';
});
startBtn.addEventListener("click", function() {
// Debugger;
startBtn.style.display = 'none';
questionBox.style.display = 'none'
finalScoreDisplay.style.display = 'none'
enterInitials.style.display='none';
score = 0; // Score is 0 again.
timer=60;
timerDisplay.textContent = timer; //Counter to display once more to make look smoother.
finalAnswerCheck = 0; // Check if last question and wrong.
checkTimes = 1; // Check timer for funciton patch.
// introPage.classList.add("hide");
// questionContainer.classList.remove("hide");
// showQuestions();
var timeInterval = setInterval(function(){
if (score === 1) {
highScore -= 10
}
score = 0; //move the score back to 0 to chek for another wrong answer.
if (timer >= 1 && finalAnswerCheck !== 1) {
//Assign text to content to the question from our object
questionBox.textContent = questionsObject.correct[index];
questionBox.style.display = ""; // Allow the questions to be displayed
choiceA.style.display = ""; // Allow our buttons to appear
choiceB.style.display = "";
choiceC.style.display = "";
choiceD.style.display = "";
//Display asnwers to the question
choiceA.textContent = answersObject.answers[answerNumber][0];
choiceB.textContent = answersObject.answers[answerNumber][1];
choiceC.textContent = answersObject.answers[answerNumber][2];
choiceD.textContent = answersObject.answers[answerNumber][3];
gridContainer.appendChild(questionBoxEl);
gridContainer.appendChild(choiceA);
gridContainer.appendChild(finalScoreDisplayEl);
timer -= 1;
timerDisplay.textContent = timer;
console.log("time left:" + timer);
choiceA.addEventListener("click", function () {
if (
questionBox.textContent ===
"The condition statement if/else is enclosed with the following:" &&
choiceA.textContent === "Parentheses"
) {
console.log("Correct");
// timer += 1; // Add a second for a correct answer as it will take one second to move to the next question
index = 2; // Move to the next question which is the third questions
answerNumber = 4;
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Correct!";
answerCorrectWrong.style.borderTop = "solid #808080";
answerCorrectWrongGrid.appendChild(answerCorrectWrong);
} else {
//Assign wrong values based incorrect answers.
switch (choiceA.textContent) {
case "Strings":
console.log("Inside the case now this question 1");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 1; // Move to the next question which is the second question
answerNumber = 1;
break;
case "Number of strings":
console.log("Inside the case now this question 1");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 3; // Move to the next question which is the second question
answerNumber = 2;
break;
case "Javascript":
console.log("Inside the case now this question 1");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 4; // Move to the next question which is the second question
answerNumber = 3;
break;
case "Commas":
console.log("Correct");
//timer += 1; // Add a second for a correct answer as it will take one second to move to the next question
//index = 2; // Move to the next question
//game over
answerCorrectWrong.style.display = ""; // Enables text content on correct and wrong answers
answerCorrectWrong.textContent = "Correct!";
answerCorrectWrong.style.borderTop = "solid #808080";
answerCorrectWrongGrid.appendChild(answerCorrectWrong);
//window.alert("Game Over"); Game is over at this point.
index = 0; // Game is over, no more questions to show.
answerNumber = 0; // Game is over, no more answers to show.
console.log("I'm here" + timeInterval);
choiceA.style.display = "none";
choiceB.style.display = "none";
choiceC.style.display = "none";
choiceD.style.display = "none";
answerCorrectWrong.style.display = "none"; // When time is over correct or wrong will go away.
startBtn.style.display = "none"; // Remove Start Quiz button.
//answerCorrectWrong.style.display=""; // Enables text content on correct and wrong answers
questionBox.textContent = "You have finished the quiz!";
finalScoreDisplay.style.display = ""; // Allow display for final score
enterInitials.style.display = ""; // Display Message Enter initials
enterInitialsTextArea.style.display = ""; // Capture user score once submitted is clicked.
finalAnswerCheck = 1; // Final Wrong
lastQuestionWrong();
finalScoreDisplay.textContent =
"Your final score is: " + highScore; // Assign the latest high score.
enterInitials.textContent = "Enter initials: ";
submitScore.style.display = "";
submitScore.textContent = "Submit";
//Exit the quiz/timer.
clearInterval(timeInterval);
break;
}
}
});
choiceB.addEventListener("click", function () {
if (
questionBox.textContent === "Strings must be enclosed with:" &&
choiceB.textContent === "Curly brackets"
) {
console.log("Correct");
//timer += 1; // Add a second for a correct answer as it will take one second to move to the next question
//index = 2; // Move to the next question
//game over
answerCorrectWrong.style.display = ""; // Enables text content on correct and wrong answers
answerCorrectWrong.textContent = "Correct!";
answerCorrectWrong.style.borderTop = "solid #808080";
answerCorrectWrongGrid.appendChild(answerCorrectWrong);
//window.alert("Game Over"); Game is over at this point.
index = 0; // Game is over, no more questions to show.
answerNumber = 0; // Game is over, no more answers to show.
console.log("I'm here" + timeInterval);
choiceA.style.display = "none";
choiceB.style.display = "none";
choiceC.style.display = "none";
choiceD.style.display = "none";
answerCorrectWrong.style.display = "none"; // When time is over correct or wrong will go away.
startBtn.style.display = "none"; // Remove Start Quiz button.
//answerCorrectWrong.style.display=""; // Enables text content on correct and wrong answers
questionBox.textContent = "You have finished the quiz!";
finalScoreDisplay.style.display = ""; // Allow display for final score
enterInitials.style.display = ""; // Display Message Enter initials
enterInitialsTextArea.style.display = ""; // Capture user score once submitted is clicked.
finalScoreDisplay.textContent = "Your final score is: " + highScore; // Assign the latest high score.
enterInitials.textContent = "Enter initials: ";
submitScore.style.display = "";
submitScore.textContent = "Submit";
//Exit the quiz/timer.
clearInterval(timeInterval);
} else {
switch (choiceB.textContent) {
case "Boolean":
console.log("Inside the case now this is question 2");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 1; // Move to the next question which is the second question
answerNumber = 1;
break;
case "Curly Brackets":
console.log("Inside the case now this is question 2");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 2; // Move to the next question which is the second question
answerNumber = 4;
console.log(score);
break;
case "Other arrays":
console.log("Inside the case now this is question 2");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 3; // Move to the next question which is the second question
answerNumber = 2;
break;
case "Terminal/bash":
console.log("Inside the case now this is question 2");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 4; // Move to the next question which is the second question
answerNumber = 3;
break;
}
}
});
choiceC.addEventListener("click", function () {
if (
questionBox.textContent ===
"Commonly used datatypes DO NOT include?" &&
choiceC.textContent === "Alerts"
) {
console.log("Correct");
//timer += 1; // Add a second for a correct answer as it will take one second to move to the next question
index = 1; // Move to the next question which is the second question
answerNumber = 1;
answerCorrectWrong.style.display = ""; // Enables text content on correct and wrong answers
answerCorrectWrong.textContent = "Correct!";
answerCorrectWrong.style.borderTop = "solid #808080";
answerCorrectWrongGrid.appendChild(answerCorrectWrong);
} else if (
questionBox.textContent ===
"A very useful tool to debug arrays is:" &&
choiceC.textContent === "For loops"
) {
console.log("Correct");
//timer += 1; // Add a second for a correct answer as it will take one second to move to the next question
index = 4; // Move to the next question which is the fifth question
answerNumber = 3;
answerCorrectWrong.style.display = ""; // Enables text content on correct and wrong answers
answerCorrectWrong.textContent = "Correct!";
answerCorrectWrong.style.borderTop = "solid #808080";
answerCorrectWrongGrid.appendChild(answerCorrectWrong);
} else if (
questionBox.textContent ===
"The condition statement if/else is enclosed with the following:" &&
choiceC.textContent === "Quotes"
) {
console.log("Inside the case now this is question 3");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 2; // Move to the next question which is the second question
answerNumber = 4;
} else {
switch (choiceC.textContent) {
case "Booleans":
console.log("Inside the case now this is question 3");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080#808080";
score = 1; // Give user a 10+ score
index = 3; // Move to the next question which is the second question
answerNumber = 2;
break;
case "Quotes":
console.log("Inside the case now this is question 3");
score = 1; // Give user a 10+ score
index = 0; // Game is over, no more questions to show.
answerNumber = 0; // Game is over, no more answers to show.
console.log("I'm here" + timeInterval);
choiceA.style.display = "none";
choiceB.style.display = "none";
choiceC.style.display = "none";
choiceD.style.display = "none";
answerCorrectWrong.style.display = "none"; // When time is over correct or wrong will go away.
startBtn.style.display = "none"; // Remove Start Quiz button.
//answerCorrectWrong.style.display=""; // Enables text content on correct and wrong answers
questionBox.textContent = "You have finished the quiz!";
finalScoreDisplay.style.display = ""; // Allow display for final score
enterInitials.style.display = ""; // Display Message Enter initials
enterInitialsTextArea.style.display = ""; // Capture user score once submitted is clicked.
finalAnswerCheck = 1; // Final Wrong
lastQuestionWrong();
finalScoreDisplay.textContent =
"Your final score is: " + highScore; // Assign the latest high score.
enterInitials.textContent = "Enter initials: ";
submitScore.style.display = "";
submitScore.textContent = "Submit";
//Exit the quiz/timer.
clearInterval(timeInterval);
break;
}
}
});
choiceD.addEventListener("click", function () {
if (
questionBox.textContent ===
"Arrays can be used to store the following" &&
choiceD.textContent === "All of the above"
) {
console.log("Correct");
// timer += 1; // Add a second for a correct answer as it will take one second to move to the next question
//Game is overquestionNumber = 4; // Move to the next question
index = 3; // Move to the next question which is the fourth question
answerNumber = 2;
answerCorrectWrong.style.display = ""; // Enables text content on correct and wrong answers
answerCorrectWrong.textContent = "Correct!";
answerCorrectWrong.style.borderTop = "solid #808080";
answerCorrectWrongGrid.appendChild(answerCorrectWrong);
} else {
switch (choiceD.textContent) {
case "Numbers":
console.log("Inside the case now this is question4");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 1; // Move to the next question which is the second question
answerNumber = 1;
break;
case "Square Brackets":
console.log("Inside the case now this is question4");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 2; // Move to the next question which is the second question
answerNumber = 4;
break;
case "Console.log":
console.log("Inside the case now this is question4");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
index = 4; // Move to the next question which is the second question
answerNumber = 3;
break;
case "Parentheses":
console.log("Inside the case now this is question4");
answerCorrectWrong.style.display = "";
answerCorrectWrong.textContent = "Wrong!";
answerCorrectWrong.style.borderTop = "solid #808080";
score = 1; // Give user a 10+ score
//index = 4; // Move to the next question which is the second question
//answerNumber = 3;
index = 0; // Game is over, no more questions to show.
answerNumber = 0; // Game is over, no more answers to show.
console.log("I'm here" + timeInterval);
choiceA.style.display = "none";
choiceB.style.display = "none";
choiceC.style.display = "none";
choiceD.style.display = "none";
answerCorrectWrong.style.display = "none"; // When time is over correct or wrong will go away.
startBtn.style.display = "none"; // Remove Start Quiz button.
//answerCorrectWrong.style.display=""; // Enables text content on correct and wrong answers
questionBox.textContent = "You have finished the quiz!";
finalScoreDisplay.style.display = ""; // Allow display for final score
enterInitials.style.display = ""; // Display Message Enter initials
enterInitialsTextArea.style.display = ""; // Capture user score once submitted is clicked.
finalAnswerCheck = 1; // Final Wrong
lastQuestionWrong();
finalScoreDisplay.textContent =
"Your final score is: " + highScore; // Assign the latest high score.
enterInitials.textContent = "Enter initials: ";
submitScore.style.display = "";
submitScore.textContent = "Submit";
//Exit the quiz/timer.
clearInterval(timeInterval);
break;
}
}
});
}
else if(timer === 0){
console.log("I'm here" + timeInterval);
index = 0; // Reset all questions
answerNumber = 0; // Reset all possible answers.
choiceA.style.display = 'none';
choiceB.style.display = 'none';
choiceC.style.display = 'none';
choiceD.style.display = 'none';
answerCorrectWrong.style.display='none'; // When time is over correct or wrong will go away.
//answerCorrectWrong.style.display=""; // Enables text content on correct and wrong answers
questionBox.textContent = "Game Over!. Try again by clicking on \"Click Start Quiz\"";
startBtn.style.display = "";
clearInterval(timeInterval);
gridContainer.appendChild(questionBoxEl);
displayMessage();
}
}, 1000)
});
function lastQuestionWrong () {
if (finalAnswerCheck === 1 && checkTimes === 1) {
highScore -= 10;
checkTimes = 2;
return highScore
}
}
// })
// // A timer starts
// // var timer = setInterval(() => {
// // secondsLeft--;
// // timerEl.textContent = secondsLeft + " seconds left on quiz.";
// // let indexQuestion = questions
// // if (index === indexQuestion.length) {
// // clearInterval();
// // timerEl.textContent = "Done!";
// // } else {
// // timerEl.textContent = indexQuestion[index];
// // index++;
// // }
// // }, 1000);
// })
// function showQuestions() {
// }
// tieTogether = () => {
// index++;
// showQuestions(index);
// index;
// }
// // const choiceBtn = answerBtn.querySelector('.choiceBtn');
// // for (let i = 0; i < choiceBtn.length; i++) {
// // choiceBtn[i].setAttribute('theCorrectAnswer(this)');
// // }
// // function theCorrectAnswer.apply() {
// // // let userAns = correctAns;
// // // let answer = questions[index].correctAns
// // if(answer == questions[index].correctAns) {
// // console.log('Answer is correct!')
// // }
// // }
|
#!/usr/bin/env python
import os
import sys
SCRIPT_DIR, SCRIPT_FILE = os.path.split(os.path.abspath(__file__))
os.environ.update({
'APP_MODULE': 'imcrypt',
'APP_SETTINGS': 'imcrypt.config.base',
'APP_DIR': os.path.join(SCRIPT_DIR, 'imcrypt'),
'PUBLIC_DIR': os.path.join(SCRIPT_DIR, 'public'),
'SCRIPT_DIR': SCRIPT_DIR
})
os.chdir(os.environ['APP_DIR'])
try:
from watson.framework import applications
from watson.common import imports
except:
sys.stdout.write(
'You must have Watson installed, please run `pip install watson-framework`\n')
sys.exit(1)
if __name__ == '__main__':
config = imports.import_module(os.environ['APP_SETTINGS'])
application = applications.Console(config)
application()
|
module.exports = {
test: 'custom-default'
};
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import math
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QTransform, QPolygonF, QPen
from PyQt5.QtCore import QPointF, Qt, QTimer
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.angle = 0
self.x = 0
self.points = []
self.timer = QTimer()
self.timer.setInterval(50)
self.timer.timeout.connect(self._do_tick)
self.timer.start()
def _do_tick(self):
self.angle += 5
self.x += 5
if self.x > self.width():
self.x = 0
self.points.clear()
# Перерисование окна
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
height = 500
y0 = height / 4
amplitude = height / 2
frequency = 0.04
x = self.x
y = y0 + math.sin(x * frequency) * amplitude / 2 + amplitude / 2
triangle_points = [
QPointF(0, 0), QPointF(0, 50), QPointF(50, 50)
]
for p in triangle_points:
p.setX(p.x() + x)
p.setY(p.y() + y)
polygon = QPolygonF(triangle_points)
center = polygon.boundingRect().center()
self.points.append(center)
painter.save()
painter.setPen(QPen(Qt.red, 2))
p1 = self.points[0]
for p2 in self.points[1:]:
painter.drawLine(p1, p2)
p1 = p2
painter.restore()
transform = QTransform() \
.translate(center.x(), center.y())\
.rotate(self.angle)\
.translate(-center.x(), -center.y())
p = transform.map(polygon)
painter.setBrush(Qt.blue)
painter.drawPolygon(p)
if __name__ == '__main__':
app = QApplication([])
mw = MainWindow()
mw.show()
app.exec()
|
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
FOUNDATION_EXPORT double Pods_VCLoadTimeProfiler_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_VCLoadTimeProfiler_ExampleVersionString[];
|
//
// OEXRegistrationFieldEmailView.h
// edXVideoLocker
//
// Created by Jotiram Bhagat on 14/02/15.
// Copyright (c) 2015 edX. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "OEXRegistrationFormTextField.h"
@interface OEXRegistrationFieldEmailView : OEXRegistrationFormTextField
@end
|
from django.urls import path, include
from .views import *
app_name = "jobs"
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('about/', AboutView.as_view(), name='about'),
path('search/', SearchView.as_view(), name='search'),
path('employer/dashboard/', include([
path('', Dashboard.as_view(), name='employer-dashboard'),
path('all-applicants', ApplicantsListView.as_view(), name='employer-all-applicants'),
# path('applicants/<int:job_id>', ApplicantPerJobView.as_view(), name='employer-dashboard-applicants'),
path('mark-filled/<int:job_id>', filled, name='job-mark-filled'),
path('delete/<int:job_id>', delete, name='job-delete'),
])),
path('apply-job/<int:job_id>', ApplyJobView.as_view(), name='apply-job'),
path('jobs', JobListView.as_view(), name='jobs'),
path('jobs/<int:id>', JobDetailView.as_view(), name='jobs-detail'),
path('employer/jobs/create', JobCreateView.as_view(), name='employer-jobs-create'),
]
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import unicode_literals
import inspect
import json
import os
import pytest
import re
import six
import sys
from textwrap import dedent
from dockerfile_parse import DockerfileParser
from tests.fixtures import dfparser, instruction
NON_ASCII = "žluťoučký"
class TestDockerfileParser(object):
def test_all_versions_match(self):
def read_version(fp, regex):
with open(fp, "r") as fd:
content = fd.read()
found = re.findall(regex, content)
if len(found) == 1:
return found[0]
else:
raise Exception("Version not found!")
import dockerfile_parse
from dockerfile_parse import __version__ as module_version
fp = inspect.getfile(dockerfile_parse)
project_dir = os.path.dirname(os.path.dirname(fp))
specfile = os.path.join(project_dir, "python-dockerfile-parse.spec")
setup_py = os.path.join(project_dir, "setup.py")
spec_version = read_version(specfile, r"\nVersion:\s*(.+?)\s*\n")
setup_py_version = read_version(setup_py, r"version=['\"](.+)['\"]")
assert spec_version == module_version
assert setup_py_version == module_version
def test_dockerfileparser(self, dfparser, tmpdir):
df_content = dedent("""\
FROM fedora
LABEL label={0}""".format(NON_ASCII))
df_lines = ["FROM fedora\n", "LABEL label={0}".format(NON_ASCII)]
dfparser.content = ""
dfparser.content = df_content
assert dfparser.content == df_content
assert dfparser.lines == df_lines
assert [isinstance(line, six.text_type) for line in dfparser.lines]
dfparser.content = ""
dfparser.lines = df_lines
assert dfparser.content == df_content
assert dfparser.lines == df_lines
assert [isinstance(line, six.text_type) for line in dfparser.lines]
with open(os.path.join(str(tmpdir), 'Dockerfile'), 'wb') as fp:
fp.write(df_content.encode('utf-8'))
dfparser = DockerfileParser(str(tmpdir))
assert dfparser.content == df_content
assert dfparser.lines == df_lines
assert [isinstance(line, six.text_type) for line in dfparser.lines]
def test_constructor_cache(self, tmpdir):
tmpdir_path = str(tmpdir.realpath())
df1 = DockerfileParser(tmpdir_path)
df1.lines = ["From fedora:latest\n", "LABEL a b\n"]
df2 = DockerfileParser(tmpdir_path, True)
assert df2.cached_content
def test_dockerfile_structure(self, dfparser):
dfparser.lines = ["# comment\n", # should be ignored
" From \\\n", # mixed-case
" base\n", # extra ws, continuation line
" # comment\n",
" label foo \\\n", # extra ws
" # comment\n", # should be ignored
" bar \n", # extra ws, continuation line
"USER {0}\n".format(NON_ASCII),
"# comment \\\n", # extra ws
"# comment \\ \n", # extra ws with a space
"# comment \\\\ \n", # two backslashes
"RUN command1\n",
"RUN command2 && \\\n",
" # comment\n",
" command3\n"]
assert dfparser.structure == [{'instruction': 'FROM',
'startline': 1, # 0-based
'endline': 2,
'content': ' From \\\n base\n',
'value': 'base'},
{'instruction': 'LABEL',
'startline': 4,
'endline': 6,
'content': ' label foo \\\n bar \n',
'value': 'foo bar'},
{'instruction': 'USER',
'startline': 7,
'endline': 7,
'content': 'USER {0}\n'.format(NON_ASCII),
'value': '{0}'.format(NON_ASCII)},
{'instruction': 'RUN',
'startline': 11,
'endline': 11,
'content': 'RUN command1\n',
'value': 'command1'},
{'instruction': 'RUN',
'startline': 12,
'endline': 14,
'content': 'RUN command2 && \\\n command3\n',
'value': 'command2 && command3'}]
def test_dockerfile_json(self, dfparser):
dfparser.content = dedent("""\
# comment
From base
LABEL foo="bar baz"
USER {0}""").format(NON_ASCII)
expected = json.dumps([{"FROM": "base"},
{"LABEL": "foo=\"bar baz\""},
{"USER": "{0}".format(NON_ASCII)}])
assert dfparser.json == expected
def test_get_baseimg_from_df(self, dfparser):
dfparser.lines = ["From fedora:latest\n",
"LABEL a b\n"]
base_img = dfparser.baseimage
assert base_img.startswith('fedora')
def test_get_parent_env(self, tmpdir):
tmpdir_path = str(tmpdir.realpath())
p_env = {"bar": "baz"}
df1 = DockerfileParser(tmpdir_path, env_replace=True, parent_env=p_env)
df1.lines = [
"FROM parent\n",
"ENV foo=\"$bar\"\n",
"LABEL label=\"$foo $bar\"\n"
]
# Even though we inherit an ENV, this .envs count should only be for the
# ENVs defined in *this* Dockerfile as we're parsing the Dockerfile and
# the parent_env is only to satisfy use of inhereted ENVs.
assert len(df1.envs) == 1
assert df1.envs.get('foo') == 'baz'
assert len(df1.labels) == 1
assert df1.labels.get('label') == 'baz baz'
def test_get_parent_env_from_scratch(self, tmpdir):
tmpdir_path = str(tmpdir.realpath())
p_env = {"bar": "baz"}
df1 = DockerfileParser(tmpdir_path, env_replace=True, parent_env=p_env)
df1.lines = [
"FROM scratch\n",
]
assert not df1.envs
@pytest.mark.parametrize(('instr_value', 'expected'), [
('"name1"=\'value 1\' "name2"=myself name3=""',
{'name1': 'value 1',
'name2': 'myself',
'name3': ''}),
('name5=5', {'name5': '5'}),
('"name6"=6', {'name6': '6'}),
('name7', {'name7': ''}),
('"name8"', {'name8': ''}),
('"name9"="asd \\ \\n qwe"', {'name9': 'asd \\ \\n qwe'}),
('"name10"="{0}"'.format(NON_ASCII), {'name10': NON_ASCII}),
('"name1 1"=1', {'name1 1': '1'}),
('"name12"=12 \ \n "name13"=13', {'name12': '12', 'name13': '13'}),
('name14=1\ 4', {'name14': '1 4'}),
('name15="with = in value"', {'name15': 'with = in value'}),
# old syntax (without =)
('name101 101', {'name101': '101'}),
('name102 1 02', {'name102': '1 02'}),
('"name103" 1 03', {'name103': '1 03'}),
('name104 "1" 04', {'name104': '1 04'}),
('name105 1 \'05\'', {'name105': '1 05'}),
('name106 1 \'0\' 6', {'name106': '1 0 6'}),
('name107 1 0\ 7', {'name107': '1 0 7'}),
('name108 "with = in value"', {'name108': 'with = in value'}),
('name109 "\\"quoted\\""', {'name109': '"quoted"'}),
])
def test_get_instructions_from_df(self, dfparser, instruction, instr_value,
expected):
dfparser.content = "{0} {1}\n".format(instruction, instr_value)
if instruction == 'LABEL':
instructions = dfparser.labels
elif instruction == 'ENV':
instructions = dfparser.envs
assert instructions == expected
def test_modify_instruction(self, dfparser):
FROM = ('ubuntu', 'fedora:latest')
CMD = ('old cmd', 'new command')
df_content = dedent("""\
FROM {0}
CMD {1}""").format(FROM[0], CMD[0])
dfparser.content = df_content
assert dfparser.baseimage == FROM[0]
dfparser.baseimage = FROM[1]
assert dfparser.baseimage == FROM[1]
assert dfparser.cmd == CMD[0]
dfparser.cmd = CMD[1]
assert dfparser.cmd == CMD[1]
def test_modify_from_multistage(self, dfparser):
BASE_FROM = 'base:${CODE_VERSION}'
STAGED_FROM = 'extras:${CODE_VERSION}'
UPDATED_BASE_FROM = 'bass:${CODE_VERSION}'
BASE_CMD = '/code/run-app'
STAGED_CMD = '/code/run-extras'
UPDATED_STAGED_CMD = '/code/run-main-actors'
df_content = dedent("""\
ARG CODE_VERSION=latest
FROM {0}
CMD {1}
FROM {2}
CMD {3}""").format(BASE_FROM, BASE_CMD, STAGED_FROM, STAGED_CMD)
INDEX_FIRST_FROM = 1
INDEX_SECOND_FROM = 4
INDEX_FIRST_CMD = 2
INDEX_SECOND_CMD = 5
dfparser.content = df_content
assert dfparser.baseimage == BASE_FROM
assert dfparser.lines[INDEX_FIRST_FROM].strip() == 'FROM {0}'.format(BASE_FROM)
assert dfparser.lines[INDEX_SECOND_FROM].strip() == 'FROM {0}'.format(STAGED_FROM)
assert dfparser.cmd == STAGED_CMD # Last command overrides base command
assert dfparser.lines[INDEX_FIRST_CMD].strip() == 'CMD {0}'.format(BASE_CMD)
assert dfparser.lines[INDEX_SECOND_CMD].strip() == 'CMD {0}'.format(STAGED_CMD)
dfparser.baseimage = UPDATED_BASE_FROM
assert dfparser.baseimage == UPDATED_BASE_FROM
assert dfparser.lines[INDEX_FIRST_FROM].strip() == 'FROM {0}'.format(UPDATED_BASE_FROM)
assert dfparser.lines[INDEX_SECOND_FROM].strip() == 'FROM {0}'.format(STAGED_FROM)
assert dfparser.cmd == STAGED_CMD # Last command overrides base command
assert dfparser.lines[INDEX_FIRST_CMD].strip() == 'CMD {0}'.format(BASE_CMD)
assert dfparser.lines[INDEX_SECOND_CMD].strip() == 'CMD {0}'.format(STAGED_CMD)
# Unlike FROM, updates to CMD should update all instructions. Might need
# revisiting for additional support of multistage builds.
dfparser.cmd = UPDATED_STAGED_CMD
assert dfparser.cmd == UPDATED_STAGED_CMD
assert dfparser.lines[INDEX_FIRST_CMD].strip() == 'CMD {0}'.format(UPDATED_STAGED_CMD)
assert dfparser.lines[INDEX_SECOND_CMD].strip() == 'CMD {0}'.format(UPDATED_STAGED_CMD)
def test_add_del_instruction(self, dfparser):
df_content = dedent("""\
CMD xyz
LABEL a=b c=d
LABEL x=\"y z\"
ENV h i
ENV j='k' l=m
""")
dfparser.content = df_content
dfparser._add_instruction('FROM', 'fedora')
assert dfparser.baseimage == 'fedora'
dfparser._delete_instructions('FROM')
assert dfparser.baseimage is None
dfparser._add_instruction('FROM', 'fedora')
assert dfparser.baseimage == 'fedora'
dfparser._delete_instructions('FROM', 'fedora')
assert dfparser.baseimage is None
dfparser._add_instruction('LABEL', ('Name', 'self'))
assert len(dfparser.labels) == 4
assert dfparser.labels.get('Name') == 'self'
dfparser._delete_instructions('LABEL')
assert dfparser.labels == {}
dfparser._add_instruction('ENV', ('Name', 'self'))
assert len(dfparser.envs) == 4
assert dfparser.envs.get('Name') == 'self'
dfparser._delete_instructions('ENV')
assert dfparser.envs == {}
assert dfparser.cmd == 'xyz'
@pytest.mark.parametrize(('existing',
'delete_key',
'expected'), [
# Delete non-existing key
(['a b\n',
'x="y z"\n'],
'name',
KeyError()),
# Simple remove
(['a b\n',
'x="y z"\n'],
'a',
['x="y z"\n']),
# Simple remove
(['a b\n',
'x="y z"\n'],
'x',
['a b\n']),
# Remove first of two instructions on the same line
(['a b\n',
'x="y z"\n',
'"first"="first" "second"="second"\n'],
'first',
['a b\n',
'x="y z"\n',
'"second"="second"\n']),
# Remove second of two instructions on the same line
(['a b\n',
'x="y z"\n',
'"first"="first" "second"="second"\n'],
'second',
['a b\n',
'x="y z"\n',
'"first"="first"\n']),
])
def test_delete_instruction(self, dfparser, instruction, existing, delete_key, expected):
existing = [instruction + ' ' + i for i in existing]
if isinstance(expected, list):
expected = [instruction + ' ' + i for i in expected]
dfparser.lines = ["FROM xyz\n"] + existing
if isinstance(expected, KeyError):
with pytest.raises(KeyError):
dfparser._delete_instructions(instruction, delete_key)
else:
dfparser._delete_instructions(instruction, delete_key)
assert set(dfparser.lines[1:]) == set(expected)
@pytest.mark.parametrize(('existing',
'new',
'expected'), [
# Simple test: set an instruction
(['a b\n',
'x="y z"\n'],
{'Name': 'New shiny project'},
['Name=\'New shiny project\'\n']),
# Set two instructions
(['a b\n',
'x="y z"\n'],
{'something': 'nothing', 'mine': 'yours'},
['something=nothing\n', 'mine=yours\n']),
# Set instructions to what they already were: should be no difference
(['a b\n',
'x="y z"\n',
'"first"="first" second=\'second value\'\n'],
{'a': 'b', 'x': 'y z', 'first': 'first', 'second': 'second value'},
['a b\n',
'x="y z"\n',
'"first"="first" second=\'second value\'\n']),
# Adjust one label of a multi-value LABEL/ENV statement
(['a b\n',
'first=\'first value\' "second"=second\n',
'x="y z"\n'],
{'first': 'changed', 'second': 'second'},
['first=changed "second"=second\n']),
# Delete one label of a multi-value LABEL/ENV statement
(['a b\n',
'x="y z"\n',
'first=first second=second\n'],
{'second': 'second'},
['second=second\n']),
# Nested quotes
(['"ownership"="Alice\'s label" other=value\n'],
{'ownership': "Alice's label"},
# Keeps existing key quoting style
['"ownership"="Alice\'s label"\n']),
# Modify a single value that needs quoting
(['foo bar\n'],
{'foo': 'extra bar'},
["foo 'extra bar'\n"]),
])
def test_setter(self, dfparser, instruction, existing, new, expected):
existing = [instruction + ' ' + i for i in existing]
if isinstance(expected, list):
expected = [instruction + ' ' + i for i in expected]
dfparser.lines = ["FROM xyz\n"] + existing
if instruction == 'LABEL':
dfparser.labels = new
assert dfparser.labels == new
elif instruction == 'ENV':
dfparser.envs = new
assert dfparser.envs == new
assert set(dfparser.lines[1:]) == set(expected)
@pytest.mark.parametrize(('old_instructions', 'key', 'new_value', 'expected'), [
# Simple case, no '=' or quotes
('Release 1', 'Release', '2', 'Release 2'),
# No '=' but quotes (which are kept)
('"Release" "2"', 'Release', '3', '"Release" 3'),
# Simple case, '=' but no quotes
('Release=1', 'Release', '6', 'Release=6'),
# '=' and quotes, with space in the value
('"Name"=\'alpha alpha\' Version=1', 'Name', 'beta delta', '"Name"=\'beta delta\' Version=1'),
('Name=foo', 'Name', 'new value', "Name='new value'"),
# ' ' and quotes
('"Name" alpha alpha', 'Name', 'beta delta', "\"Name\" 'beta delta'"),
# '=', multiple labels, no quotes
('Name=foo Release=3', 'Release', '4', 'Name=foo Release=4'),
# '=', multiple labels and quotes
('Name=\'foo bar\' "Release"="4"', 'Release', '5', 'Name=\'foo bar\' "Release"=5'),
# Release that's not entirely numeric
('Version=1.1', 'Version', '2.1', 'Version=2.1'),
])
def test_setter_direct(self, dfparser, instruction, old_instructions, key, new_value, expected):
df_content = dedent("""\
FROM xyz
LABEL a b
LABEL x=\"y z\"
ENV c d
ENV e=\"f g\"
{0} {1}
""").format(instruction, old_instructions)
dfparser.content = df_content
if instruction == 'LABEL':
dfparser.labels[key] = new_value
assert dfparser.labels[key] == new_value
assert dfparser.lines[-1] == '{0} {1}\n'.format(instruction, expected)
del dfparser.labels[key]
assert not dfparser.labels.get(key)
elif instruction == 'ENV':
dfparser.envs[key] = new_value
assert dfparser.envs[key] == new_value
assert dfparser.lines[-1] == '{0} {1}\n'.format(instruction, expected)
del dfparser.envs[key]
assert not dfparser.labels.get(key)
@pytest.mark.parametrize('separator', [' ', '='])
@pytest.mark.parametrize(('label', 'expected'), [
# Expected substitutions
('$V', 'v'),
('"$V"', 'v'),
('$V-foo', 'v-foo'),
('"$V-foo"', 'v-foo'),
('"$V"-foo', 'v-foo'),
('${V}', 'v'),
('${V}-foo', 'v-foo'),
('$V-{foo}', 'v-{foo}'),
('$VS', 'spam maps'),
# These should not be substituted, only dequoted
("'$V'", "$V"),
("\\$V", "$V"),
# Try to trip up the parser
('\\"$V', '"v'),
("\\'$V", "'v"),
('$V}', 'v}'),
('${}', ''),
("'\\'$V'\\'", "\\v\\"),
])
def test_env_replace(self, dfparser, label, expected, separator):
dfparser.lines = ["FROM fedora\n",
"ENV V=v\n",
"ENV VS='spam maps'\n",
"LABEL TEST{0}{1}\n".format(separator, label)]
assert dfparser.labels['TEST'] == expected
@pytest.mark.parametrize('separator', [' ', '='])
@pytest.mark.parametrize(('label', 'expected'), [
# These would have been substituted with env_replace=True
('$V', '$V'),
('"$V"', '$V'),
('$V-foo', '$V-foo'),
('"$V-foo"', '$V-foo'),
('"$V"-foo', '$V-foo'),
])
def test_env_noreplace(self, dfparser, label, expected, separator):
"""
Make sure environment replacement can be disabled.
"""
dfparser.env_replace = False
dfparser.lines = ["FROM fedora\n",
"ENV V=v\n",
"LABEL TEST{0}{1}\n".format(separator, label)]
assert dfparser.labels['TEST'] == expected
@pytest.mark.parametrize('label', [
'${V',
'"${V"',
'${{{{V}',
])
def test_env_invalid(self, dfparser, label):
"""
These tests are invalid, but the parser should at least terminate
even if it raises an exception.
"""
dfparser.lines = ["FROM fedora\n",
"ENV v=v\n",
"LABEL TEST={0}\n".format(label)]
try:
dfparser.labels['TEST']
except:
pass
@pytest.mark.xfail
@pytest.mark.parametrize(('label', 'expected'), [
('${V:-foo}', 'foo'),
('${V:+foo}', 'v'),
('${UNDEF:+foo}', 'foo'),
('${UNDEF:+${V}}', 'v'),
])
def test_env_replace_notimplemented(self, dfparser, label, expected):
"""
Test for syntax we don't support yet but should.
"""
dfparser.lines = ["FROM fedora\n",
"ENV V=v\n",
"LABEL TEST={0}\n".format(label)]
assert dfparser.labels['TEST'] == expected
def test_path_and_fileobj_together(self):
with pytest.raises(ValueError):
DockerfileParser(path='.', fileobj=six.StringIO())
def test_nonseekable_fileobj(self):
with pytest.raises(AttributeError):
DockerfileParser(fileobj=sys.stdin)
def test_context_structure_per_line(self, dfparser, instruction):
dfparser.content = dedent("""\
FROM fedora:25
{0} multi.label1="value1" \\
multi.label2="value2" \\
other="value3"
{0} 2multi.label1="othervalue1" 2multi.label2="othervalue2" other="othervalue3"
{0} "com.example.vendor"="ACME Incorporated"
{0} com.example.label-with-value="foo"
{0} version="1.0"
{0} description="This text illustrates \\
that label-values can span multiple lines."
{0} key="with = in the value"
""").format(instruction)
c = dfparser.context_structure
assert c[1].get_line_value(context_type=instruction) == {
"multi.label1": "value1",
"multi.label2": "value2",
"other": "value3"
}
assert c[2].get_line_value(context_type=instruction) == {
"2multi.label1": "othervalue1",
"2multi.label2": "othervalue2",
"other": "othervalue3"
}
assert c[3].get_line_value(context_type=instruction) == {
"com.example.vendor": "ACME Incorporated"
}
assert c[4].get_line_value(context_type=instruction) == {
"com.example.label-with-value": "foo"
}
assert c[5].get_line_value(context_type=instruction) == {
"version": "1.0"
}
assert c[6].get_line_value(context_type=instruction) == {
"description": "This text illustrates that label-values can span multiple lines."
}
assert c[7].get_line_value(context_type=instruction) == {
"key": "with = in the value"
}
def test_context_structure(self, dfparser, instruction):
dfparser.content = dedent("""\
FROM fedora:25
{0} multi.label1="value1" \\
multi.label2="value2" \\
other="value3"
{0} 2multi.label1="othervalue1" 2multi.label2="othervalue2" other="othervalue3"
{0} "com.example.vendor"="ACME Incorporated"
{0} com.example.label-with-value="foo"
{0} version="1.0"
{0} description="This text illustrates \\
that label-values can span multiple lines."
""").format(instruction)
c = dfparser.context_structure
assert c[1].get_values(context_type=instruction) == {
"multi.label1": "value1",
"multi.label2": "value2",
"other": "value3"
}
assert c[2].get_values(context_type=instruction) == {
"multi.label1": "value1",
"multi.label2": "value2",
"other": "othervalue3",
"2multi.label1": "othervalue1",
"2multi.label2": "othervalue2"
}
assert c[3].get_values(context_type=instruction) == {
"multi.label1": "value1",
"multi.label2": "value2",
"other": "othervalue3",
"2multi.label1": "othervalue1",
"2multi.label2": "othervalue2",
"com.example.vendor": "ACME Incorporated"
}
assert c[4].get_values(context_type=instruction) == {
"multi.label1": "value1",
"multi.label2": "value2",
"other": "othervalue3",
"2multi.label1": "othervalue1",
"2multi.label2": "othervalue2",
"com.example.vendor": "ACME Incorporated",
"com.example.label-with-value": "foo"
}
assert c[5].get_values(context_type=instruction) == {
"multi.label1": "value1",
"multi.label2": "value2",
"other": "othervalue3",
"2multi.label1": "othervalue1",
"2multi.label2": "othervalue2",
"com.example.vendor": "ACME Incorporated",
"com.example.label-with-value": "foo",
"version": "1.0"
}
assert c[6].get_values(context_type=instruction) == {"multi.label1": "value1",
"multi.label2": "value2",
"other": "othervalue3",
"2multi.label1": "othervalue1",
"2multi.label2": "othervalue2",
"com.example.vendor": "ACME Incorporated",
"com.example.label-with-value": "foo",
"version": "1.0",
"description": "This text illustrates that label-values can span multiple lines."
}
def test_context_structure_mixed(self, dfparser, instruction):
dfparser.content = dedent("""\
FROM fedora:25
{0} key=value
RUN touch /tmp/a
{0} key2=value2""").format(instruction)
c = dfparser.context_structure
assert c[0].get_values(context_type=instruction) == {}
assert c[1].get_values(context_type=instruction) == {"key": "value"}
assert c[2].get_values(context_type=instruction) == {"key": "value"}
assert c[3].get_values(context_type=instruction) == {"key": "value",
"key2": "value2"}
def test_context_structure_mixed_env_label(self, dfparser):
dfparser.content = dedent("""\
FROM fedora:25
ENV key=value
RUN touch /tmp/a
LABEL key2=value2""")
c = dfparser.context_structure
assert c[0].get_values(context_type="ENV") == {}
assert c[0].get_values(context_type="LABEL") == {}
assert c[1].get_values(context_type="ENV") == {"key": "value"}
assert c[1].get_values(context_type="LABEL") == {}
assert c[2].get_values(context_type="ENV") == {"key": "value"}
assert c[2].get_values(context_type="LABEL") == {}
assert c[3].get_values(context_type="ENV") == {"key": "value"}
assert c[3].get_values(context_type="LABEL") == {"key2": "value2"}
def test_expand_concatenated_variables(self, dfparser):
dfparser.content = dedent("""\
FROM scratch
ENV NAME=name VER=1
LABEL component="$NAME$VER"
""")
assert dfparser.labels['component'] == 'name1'
def test_label_env_key(self, dfparser):
"""
Verify keys may be substituted with values containing space.
Surprisingly, Docker allows environment variable substitution even
in the keys of labels, and not only that but it allows them to
contain spaces.
"""
dfparser.content = dedent("""\
FROM scratch
ENV FOOBAR="foo bar"
LABEL "$FOOBAR"="baz"
""")
assert dfparser.labels['foo bar'] == 'baz'
@pytest.mark.parametrize('value', [
'a=b c',
])
def test_label_invalid(self, dfparser, value):
dfparser.content = '\n'.join([
"FROM scratch",
"LABEL {0}".format(value),
])
with pytest.raises(Exception):
dfparser.labels
def test_remove_whitespace(self, tmpdir):
"""
Verify keys are parsed correctly even if there is no final newline.
"""
with open(os.path.join(str(tmpdir), 'Dockerfile'), 'w') as fp:
fp.write('FROM scratch')
tmpdir_path = str(tmpdir.realpath())
df1 = DockerfileParser(tmpdir_path)
df1.labels['foo'] = 'bar'
df2 = DockerfileParser(tmpdir_path, True)
assert df2.baseimage == 'scratch'
assert df2.labels['foo'] == 'bar'
|
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '../..'))
import numpy as np
import pandas as pd
import pystan
import pickle
from python.tools import (
clean_folder
)
################
## Parameters ##
################
output_folder = './estimate_R/output/construct_STAN_models'
input_folder = './estimate_R/input/construct_STAN_models'
min_T = 20
inflation_factor = 1.0 # Factor by which variances are inflated for priors
mean_mu0 = 0.25 # Prior for initial state: mean
std_dev_mu0 = 0.15 # Prior for initial state: standard devitaion
#########################################
## Calibrate priors using KF estimates ##
#########################################
clean_folder(output_folder)
df = pd.read_csv('{}/optim_res.csv'.format(input_folder))
# The local-level model estimated by frequentist Kalman filtering
# does not include a seasonal component. For calibration
# of the priors for full estimation that includes a seasonal
# component, we allocate fraction of the variance of the irregular
# component (estimated by frequentist Kalman filtering) to the "true" irregular
# component, and remainder to the seasonal component
df['precision_irregular'] = 0.50 * (1 / df['sigma2_irregular'])
df['precision_seasonal'] = 0.50 * (1 / df['sigma2_irregular'])
# Remove the World aggregate when calibrating
mask = df['Country/Region'] == 'World'
df = df.loc[~mask, ]
# Calibration step
priors = []
for var_name in ['precision_irregular', 'precision_seasonal', 'signal_to_noise']:
# Inflate variance of variables keeping mean constant
df[var_name] = ((inflation_factor ** 0.5) * df[var_name]
- (inflation_factor ** 0.5 - 1) * df[var_name].mean())
# Calculate implied parameters for
# gamma distribution
alpha = df[var_name].mean() ** 2 / df[var_name].var()
beta = df[var_name].mean() / df[var_name].var()
priors.append({'var_name': var_name,
'alpha': alpha,
'beta': beta})
priors = pd.DataFrame(priors)
##################################################
## STAN code for the model: WITH MISSING values ##
##################################################
s_code_missing = """
data {{
int<lower=0> N_obs;
int<lower=0> N_mis;
int<lower=1, upper=N_obs + N_mis> ii_obs[N_obs];
int<lower=1, upper=N_obs + N_mis> ii_mis[N_mis];
real y_obs[N_obs];
}}
transformed data {{
int<lower=0> N = N_obs + N_mis;
}}
parameters {{
real y_mis[N_mis]; // To deal with missing values;
real mu_zero; // see https://mc-stan.org/docs/2_18/stan-users-guide/sliced-missing-data.html
real mu[N];
real<lower=0> precision_irregular; // Precision (inverse of variance) of irregular component
real<lower=0> signal_to_noise; // Signal-to-noise ratio
real s[N]; // Intraweek seasonality component
real<lower=0> precision_seasonal; // Precision (inverse of variance) of seasonal component
}}
transformed parameters {{
real y[N]; // To deal with missing values
real<lower=0> precision_level; // Precision (inverse of variance) of level component
precision_level = precision_irregular / signal_to_noise;
y[ii_obs] = y_obs;
y[ii_mis] = y_mis;
}}
model {{
// Priors
precision_irregular ~ gamma({alpha_irregular}, {beta_irregular});
signal_to_noise ~ gamma({alpha_signal_to_noise}, {beta_signal_to_noise});
mu_zero ~ normal({mean_mu0}, {std_dev_mu0});
precision_seasonal ~ gamma({alpha_seasonal}, {beta_seasonal});
// initial state
mu[1] ~ normal(mu_zero, precision_level ^ (-0.5));
// intraweek seasonality component
for(i in 7:N) {{
s[i] ~ normal(-s[i-1]-s[i-2]-s[i-3]-s[i-4]-s[i-5]-s[i-6], precision_seasonal ^ (-0.5));
// Ensures that E(s[i] + s_[i-1] + ... s[i- 6]) = 0
// See https://tharte.github.io/mbt/mbt.html#sec-3-9
}}
// state equation
for(i in 2:N) {{
mu[i] ~ normal(mu[i-1], precision_level ^ (-0.5));
}}
// observation equation
for(i in 1:N) {{
y[i] ~ normal(mu[i] + s[i], precision_irregular ^ (-0.5));
}}
}}
"""
s_code_missing = s_code_missing.format(mean_mu0 = mean_mu0,
std_dev_mu0 = std_dev_mu0,
alpha_irregular = priors.loc[priors['var_name'] == 'precision_irregular', 'alpha'].values[0],
beta_irregular = priors.loc[priors['var_name'] == 'precision_irregular', 'beta'].values[0],
alpha_seasonal = priors.loc[priors['var_name'] == 'precision_seasonal', 'alpha'].values[0],
beta_seasonal = priors.loc[priors['var_name'] == 'precision_seasonal', 'beta'].values[0],
alpha_signal_to_noise = priors.loc[priors['var_name'] == 'signal_to_noise', 'alpha'].values[0],
beta_signal_to_noise = priors.loc[priors['var_name'] == 'signal_to_noise', 'beta'].values[0])
with open('{}/stan_code_missing.txt'.format(output_folder), 'w+') as text_file:
text_file.write(s_code_missing)
stm_missing = pystan.StanModel(model_code = s_code_missing)
with open('{}/model_missing.pkl'.format(output_folder), 'wb') as f:
pickle.dump(stm_missing, f)
#####################################################
## STAN code for the model: WITHOUT MISSING values ##
#####################################################
s_code_no_missing = """
data {{
int<lower=0> N_obs;
real y_obs[N_obs];
}}
transformed data {{
int<lower=0> N = N_obs;
}}
parameters {{
real mu_zero;
real mu[N];
real<lower=0> precision_irregular; // Precision (inverse of variance) of irregular component
real<lower=0> signal_to_noise; // Signal-to-noise ratio
real s[N]; // Intraweek seasonality component
real<lower=0> precision_seasonal; // Precision (inverse of variance) of seasonal component
}}
transformed parameters {{
real y[N];
real<lower=0> precision_level; // Precision (inverse of variance) of level component
precision_level = precision_irregular / signal_to_noise;
y = y_obs;
}}
model {{
// Priors
precision_irregular ~ gamma({alpha_irregular}, {beta_irregular});
signal_to_noise ~ gamma({alpha_signal_to_noise}, {beta_signal_to_noise});
mu_zero ~ normal({mean_mu0}, {std_dev_mu0});
precision_seasonal ~ gamma({alpha_seasonal}, {beta_seasonal});
// initial state
mu[1] ~ normal(mu_zero, precision_level ^ (-0.5));
// intraweek seasonality component
for(i in 7:N) {{
s[i] ~ normal(-s[i-1]-s[i-2]-s[i-3]-s[i-4]-s[i-5]-s[i-6], precision_seasonal ^ (-0.5));
// Ensures that E(s[i] + s_[i-1] + ... s[i- 6]) = 0
// See https://tharte.github.io/mbt/mbt.html#sec-3-9
}}
// state equation
for(i in 2:N) {{
mu[i] ~ normal(mu[i-1], precision_level ^ (-0.5));
}}
// observation equation
for(i in 1:N) {{
y[i] ~ normal(mu[i] + s[i], precision_irregular ^ (-0.5));
}}
}}
"""
s_code_no_missing = s_code_no_missing.format(mean_mu0 = mean_mu0,
std_dev_mu0 = std_dev_mu0,
alpha_irregular = priors.loc[priors['var_name'] == 'precision_irregular', 'alpha'].values[0],
beta_irregular = priors.loc[priors['var_name'] == 'precision_irregular', 'beta'].values[0],
alpha_seasonal = priors.loc[priors['var_name'] == 'precision_seasonal', 'alpha'].values[0],
beta_seasonal = priors.loc[priors['var_name'] == 'precision_seasonal', 'beta'].values[0],
alpha_signal_to_noise = priors.loc[priors['var_name'] == 'signal_to_noise', 'alpha'].values[0],
beta_signal_to_noise = priors.loc[priors['var_name'] == 'signal_to_noise', 'beta'].values[0])
with open('{}/stan_code_no_missing.txt'.format(output_folder), 'w+') as text_file:
text_file.write(s_code_no_missing)
stm_no_missing = pystan.StanModel(model_code = s_code_no_missing)
with open('{}/model_no_missing.pkl'.format(output_folder), 'wb') as f:
pickle.dump(stm_no_missing, f)
|
/**
* @copyright (c) 2016-2021 Ing. Buero Rothfuss
* Riedlinger Str. 8
* 70327 Stuttgart
* Germany
* http://www.rothfuss-web.de
*
* @author <a href="mailto:armin@rothfuss-web.de">Armin Rothfuss</a>
*
* Project gui++ lib
*
* @brief view to scroll child views
*
* @license MIT license. See accompanying file LICENSE.
*/
#pragma once
// --------------------------------------------------------------------------
//
// Library includes
//
#include <gui/layout/layout_container.h>
#include <gui/ctrl/scroll_bar.h>
namespace gui {
namespace layout {
// --------------------------------------------------------------------------
class GUIPP_CTRL_EXPORT scroll_view_base {
public:
typedef layout_base super;
scroll_view_base ();
scroll_view_base (const scroll_view_base&) = default;
scroll_view_base (scroll_view_base&&) = default;
void init (ctrl::vertical_scroll_bar* vscroll,
ctrl::horizontal_scroll_bar* hscroll,
win::window* edge);
core::rectangle layout (const core::rectangle& new_size, const core::rectangle& required) const;
static core::rectangle get_vscroll_area (const core::rectangle&, bool hscroll_bar_enabled);
static core::rectangle get_hscroll_area (const core::rectangle&, bool vscroll_bar_enabled);
static core::rectangle get_edge_area (const core::rectangle&);
static core::rectangle get_client_area (const core::rectangle&);
protected:
ctrl::vertical_scroll_bar* vscroll;
ctrl::horizontal_scroll_bar* hscroll;
win::window* edge;
};
// --------------------------------------------------------------------------
class GUIPP_CTRL_EXPORT scroll_view : public scroll_view_base {
public:
typedef scroll_view_base super;
scroll_view ();
scroll_view (const scroll_view&);
scroll_view (scroll_view&&) noexcept ;
void layout (const core::rectangle& new_size) const;
void set_in_scroll_event (bool);
bool is_in_scroll_event () const;
void set_main (win::container* main);
void add (const std::vector<std::reference_wrapper<win::window>>&);
private:
const win::move_event::function me;
const win::size_event::function se;
win::container* main;
bool in_scroll_event;
void handle_child_move (const core::point&) const;
void handle_child_size (const core::size&) const;
};
// --------------------------------------------------------------------------
} // namespace layout
namespace ctrl {
// --------------------------------------------------------------------------
class GUIPP_CTRL_EXPORT scroll_view_base : public win::layout_container<layout::scroll_view> {
public:
typedef win::layout_container<layout::scroll_view> super;
typedef core::point::type type;
scroll_view_base ();
void set_scroll_pos (const core::point& pt);
core::point get_scroll_pos () const;
void enable_vscroll_bar (bool enable);
void enable_hscroll_bar (bool enable);
bool is_vscroll_bar_enabled () const;
bool is_hscroll_bar_enabled () const;
void move_children (type dx, type dy);
protected:
void create_children (const core::rectangle& place);
vertical_scroll_bar& get_vscroll ();
horizontal_scroll_bar& get_hscroll ();
window& get_edge ();
private:
core::point current_pos;
vertical_scroll_bar vscroll;
horizontal_scroll_bar hscroll;
client_control edge;
};
// --------------------------------------------------------------------------
template<os::color B = IF_WIN32_ELSE((os::color)(COLOR_WINDOW + 1), color::white)>
class scroll_view : public scroll_view_base {
public:
typedef scroll_view_base super;
typedef win::window_class<scroll_view, B> clazz;
void create (win::container& parent,
const core::rectangle& place = core::rectangle::def);
};
} // namespace ctrl
} // gui
#include <gui/ctrl/scroll_view.inl>
|
# -*- coding: utf-8 -*-
import datetime
import warnings
from operator import attrgetter
import numpy as np
from .base import MetricGenerator
from ..base import Property
from ..measures import EuclideanWeighted
from ..types.metric import SingleTimeMetric, TimeRangeMetric
from ..types.time import TimeRange
class SIAPMetrics(MetricGenerator):
"""SIAP Metrics
Computes the Single Integrated Air Picture (SIAP) metrics as defined by the Systems Engineering
Task Force. The implementation provided here is derived from [1] and focuses on providing the
SIAP attribute measures.
The SIAP metrics provided require provision of ground truth information.
Additionally, when relevant metadata properties :attr:`track_id` and :attr:`truth_id` are
provided, calculates the ID-based SIAPS: ID Completeness (CID), ID Correctness (IDC) and ID
Ambiguity (IDA).
This implementation assumes that track and ground truth path IDs are implemented via metadata,
whereby the strings :attr:`track_id` and :attr:`truth_id` are keys to track and truth metadata
entries with ID data respectively.
In the original paper the calculations are dependent upon :math:`m` which corresponds to the
identifying number of the sense capability which is being assessed. This is not used in this
implementation, with the assumption being that the fused sensor set is being assessed.
Note:
:class:`~.Track` types store metadata outside of their `states` attribute. Therefore the ID
SIAPs make metadata comparisons via the tracks last ID metadata value (as calling
`track.metadata` will return the track's metadata at the end of its life). To provide a better
implementation, one might modify :class:`~.Track` types to contain a list of `state` types that
hold their own metadata.
Reference
[1] Single Integrated Air Picture (SIAP) Metrics Implementation,
Votruba et al, 29-10-2001
"""
position_weighting: np.ndarray = Property(default=None,
doc="Weighting(s) to be used by euclidean measure "
"in position kinematic accuracy calculations. "
"If None, weights are all 1")
velocity_weighting: np.ndarray = Property(default=None,
doc="Weighting(s) to be used by euclidean measure "
"in velocity kinematic accuracy calculations. "
"If None, weights are all 1")
position_mapping: np.ndarray = Property(default=None,
doc="Mapping array which specifies which elements "
"within state space state vectors correspond to "
"position")
velocity_mapping: np.ndarray = Property(default=None,
doc="Mapping array which specifies which elements "
"within state space state vectors correspond to "
"velocity")
truth_id: str = Property(default=None,
doc="Metadata key for ID of each ground truth path in dataset")
track_id: str = Property(default=None,
doc="Metadata key for ID of each track in dataset")
def compute_metric(self, manager, *args, **kwargs):
"""Compute metric
Parameters
----------
manager : MetricManager
containing the data to be used to create the metric(s)
Returns
-------
: list of :class:`~.Metric` objects
Generated metrics
"""
C = self.C_time_range(manager)
A = self.A_time_range(manager)
S = self.S_time_range(manager)
LT = self.LT(manager)
LS = self.LS(manager)
nt = self.num_tracks(manager)
nj = self.num_truths(manager)
metrics = [C, A, S, LT, LS, nt, nj]
timestamped_metrics = {'time-based SIAP C': [],
'time-based SIAP A': [],
'time-based SIAP S': []}
timestamps = manager.list_timestamps()
for timestamp in timestamps:
timestamped_metrics['time-based SIAP C'].append(self.C_single_time(manager, timestamp))
timestamped_metrics['time-based SIAP A'].append(self.A_single_time(manager, timestamp))
timestamped_metrics['time-based SIAP S'].append(self.S_single_time(manager, timestamp))
t_metrics = [TimeRangeMetric(title=key,
value=value,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
for key, value in timestamped_metrics.items()]
if self.position_mapping is not None:
PA = self.PA(manager)
metrics.append(PA)
t_PA = []
for timestamp in timestamps:
t_PA.append(self.PA_single_time(manager, timestamp))
metrics.append(TimeRangeMetric(title='time-based SIAP PA',
value=t_PA,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self))
if self.velocity_mapping is not None:
VA = self.VA(manager)
metrics.append(VA)
t_VA = []
for timestamp in timestamps:
t_VA.append(self.VA_single_time(manager, timestamp))
metrics.append(TimeRangeMetric(title='time-based SIAP VA',
value=t_VA,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self))
metrics.extend(t_metrics)
if self.track_id is not None:
CID = self.CID_time_range(manager)
metrics.append(CID)
t_CID = []
for timestamp in timestamps:
t_CID.append(self.CID_single_time(manager, timestamp))
metrics.append(TimeRangeMetric(title='time-based SIAP CID',
value=t_CID,
time_range=TimeRange(min(timestamps),
max(timestamps)),
generator=self))
if self.truth_id is not None:
IDC = self.IDC_time_range(manager)
IDA = self.IDA_time_range(manager)
metrics.extend([IDC, IDA])
t_IDC = []
t_IDA = []
for timestamp in timestamps:
t_IDC.append(self.IDC_single_time(manager, timestamp))
t_IDA.append(self.IDA_single_time(manager, timestamp))
metrics.append(TimeRangeMetric(title='time-based SIAP IDC',
value=t_IDC,
time_range=TimeRange(min(timestamps),
max(timestamps)),
generator=self))
metrics.append(TimeRangeMetric(title='time-based SIAP IDA',
value=t_IDA,
time_range=TimeRange(min(timestamps),
max(timestamps)),
generator=self))
return metrics
@staticmethod
def _warn_no_truth(manager):
if len(manager.groundtruth_paths) == 0:
warnings.warn("No truth to generate SIAP Metric", stacklevel=2)
@staticmethod
def _warn_no_tracks(manager):
if len(manager.tracks) == 0:
warnings.warn("No tracks to generate SIAP Metric", stacklevel=2)
def C_single_time(self, manager, timestamp):
r"""SIAP metric C "Completeness" at a specific time
Returns an assessment of the number of true targets currently being tracked compared to the
number of true targets at a specific timestamp, :math:`{t}`. The output is a percentage,
range :math:`0:1`, with a target score of 1
.. math::
C_{t} = \frac{J{T_m}({t})}{J({t})}
where
:math:`J{T_m}({t})` is the number of objects being tracked at timestamp :math:`{t}`
and
:math:`J({t})` is the number of true objects at timestamp :math:`{t}`.
Parameters
----------
manager : MetricManager
containing the data to be used to create the metric(s)
timestamp: datetime.datetime
timestamp at which to compute the metric
Returns
-------
SingleTimeMetric
Contains the metric information
"""
numerator = self._jt_t(manager, timestamp)
try:
C = numerator / self._j_t(manager, timestamp)
except ZeroDivisionError:
C = 0
return SingleTimeMetric(title="SIAP C at timestamp",
value=C,
timestamp=timestamp,
generator=self)
def C_time_range(self, manager):
r"""SIAP metric C "Completeness" over time
Returns an assessment of the number of targets currently being tracked compared to the
number of true targets over the time range of the dataset. The output is a percentage,
range :math:`0:1`, with a score of 1
.. math::
C = \frac{\sum_{t_{start}}^{t_{end}}J{T_m}({t})}
{\sum_{t_{start}}^{t_{end}}J({t})}
where
:math:`J{T_m}({t})` is the number of objects being tracked at
timestamp :math:`{t}`
and
:math:`J({t})` is the number of true objects at timestamp
:math:`{t}`.
Parameters
----------
manager : MetricManager
Containing the data to be used to create the metric(s)
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
try:
C = self._jt_sum(manager, timestamps) / self._j_sum(
manager, timestamps)
except ZeroDivisionError:
self._warn_no_truth(manager)
C = 0
return TimeRangeMetric(
title="SIAP C",
value=C,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def A_single_time(self, manager, timestamp):
r"""SIAP metric A "Ambiguity" at a specific time
Returns an assessment of the number of tracks which are assigned to true objects against
the total number of tracks, at a specific timestamp, :math:`{t}`. The output is unbounded
with a range of :math:`0:\infty`. The optimal target score for Ambiguity is 1.
.. math::
A_{t} = \frac{N{A}({t})}{J{T_m}({t})}
where
:math:`N{A}({t})` is the number of tracks assigned to true objects at timestamp
:math:`{t}`
and
:math:`J{T_m}({t})` is the number of objects being tracked at timestamp :math:`{t}`.
Parameters
----------
manager : MetricManager
containing the data to be used to create the metric(s)
timestamp: datetime.datetime
timestamp at which to compute the metric
Returns
-------
SingleTimeMetric
Contains the metric information
"""
try:
A = self._na_t(manager, timestamp) / self._jt_t(manager, timestamp)
except ZeroDivisionError:
A = 1
return SingleTimeMetric(title="SIAP A at timestamp",
value=A,
timestamp=timestamp,
generator=self)
def A_time_range(self, manager):
r"""SIAP metric A "Ambiguity" over time
Returns a percentage value which assesses the number of tracks which are assigned to true
objects against the total number of tracks. The output is unbounded
with a range of :math:`0:\infty`. The optimal target score for Ambiguity is 1.
.. math::
A = \frac{\sum_{t_{start}}^{t_{end}}N{A}({t})}
{\sum_{t_{start}}^{t_{end}}J{T_m}({t})}
where
:math:`N{A}({t})` is the number of tracks assigned to true objects at timestamp
:math:`{t}`
and
:math:`J{T_m}({t})` is the number of objects being tracked at timestamp :math:`{t}`.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
try:
A = self._na_sum(manager, timestamps) / self._jt_sum(manager, timestamps)
except ZeroDivisionError:
self._warn_no_truth(manager)
self._warn_no_tracks(manager)
A = 1
return TimeRangeMetric(
title="SIAP A",
value=A,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def S_single_time(self, manager, timestamp):
r"""SIAP metric S "Spuriousness" at a specific time
Returns an assessment of the number of tracks that are deemed to be spurious, i.e.
unassigned to true objects, at a specific timestamp, :math:`{t}`. The output is a
percentage, range :math:`0:1`, with a target score of 0.
.. math::
S_{t} = \frac{N({t}) - N{A}({t})}{N({t})}
where
:math:`N{A}({t})` is the number of tracks assigned to true objects at timestamp
:math:`{t}`
and
:math:`N({t})` is the number of tracks timestamp :math:`{t}`.
Parameters
----------
manager : MetricManager
containing the data to be used to create the metric(s)
timestamp: datetime.datetime
timestamp at which to compute the metric
Returns
-------
SingleTimeMetric
Contains the metric information
"""
numerator = self._n_t(manager, timestamp) - self._na_t(manager, timestamp)
try:
S = numerator / self._n_t(manager, timestamp)
except ZeroDivisionError:
S = 0
return SingleTimeMetric(title="SIAP S at timestamp",
value=S,
timestamp=timestamp,
generator=self)
def S_time_range(self, manager):
r"""SIAP metric S Spuriousness" over time
The average percentage of tracks that are deemed to be spurious, i.e. unassigned to true
objects. The output is a percentage, range :math:`0:1`, with a target score of 0.
.. math::
S = \frac{\sum_{t_{start}}^{t_{end}}[N({t}) - N{A}({t})]}
{\sum_{t_{start}}^{t_{end}}N({t})}
where
:math:`N{A}({t})` is the number of tracks assigned to true objects at timestamp
:math:`{t}`
and
:math:`N({t})` is the number of tracks timestamp :math:`{t}`.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
numerator = self._n_sum(manager, timestamps) - self._na_sum(manager, timestamps)
try:
S = numerator / self._n_sum(manager, timestamps)
except ZeroDivisionError:
self._warn_no_tracks(manager)
S = 0
return TimeRangeMetric(
title="SIAP S",
value=S,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def LT(self, manager):
r"""SIAP metric LT over time
Returns :math:`1/{R}` where :math:`{R}` is the average number of excess tracks assigned.
The output is unbounded with a range of :math:`0:\infty`, target score
is :math:`LT = \infty`.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
r = self._r(manager)
if r == 0:
value = np.inf
self._warn_no_truth(manager)
self._warn_no_tracks(manager)
else:
value = 1 / r
timestamps = manager.list_timestamps()
return TimeRangeMetric(
title="SIAP LT",
value=value,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def LS(self, manager):
r"""SIAP metric LS over time
Returns the percentage of time that true objects have been tracked across the
dataset. The output is a percentage, range :math:`0:1`, with a target score of 1.
.. math::
LS = \frac{\sum_{j=1}^{J}T{L}_{j}}{\sum_{j=1}^{J}T_{j}}
where
:math:`\sum_{j=1}^{J}T{L}_{j}` is the total time of the longest track on object
:math:`j`.
and
:math:`\sum_{j=1}^{J}T_{j}` is the total duration of true object :math:`j`.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
numerator = sum(self._tl_j(manager, truth).total_seconds()
for truth in manager.groundtruth_paths)
denominator = sum(self._t_j(truth).total_seconds()
for truth in manager.groundtruth_paths)
timestamps = manager.list_timestamps()
try:
LS = numerator / denominator
except ZeroDivisionError:
self._warn_no_truth(manager)
LS = 0
return TimeRangeMetric(
title="SIAP LS",
value=LS,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def PA_single_time(self, manager, timestamp):
r"""SIAP metric PA at a specific time
Returns an assessment of the average assigned track positional accuracy at a specific
timestamp, :math:`{t}`. The output is a distance measure, range :math:`0:\infty`, with a
target score of 0.
.. math::
PA_{t} = \frac{{\sum_{n\in D(t)}PA_{n}(t)}}{NA(t)}
where
:math:`D(t)` is the set of tracks held at timestamp :math:`t` :math:`PA_{n}(t)` is the
Euclidean distance of track n to its associated truth at timestamp :math:`{t}`
and
:math:`N{A}({t})` is the number of tracks assigned to true objects at timestamp
:math:`{t}`.
Parameters
----------
manager : MetricManager
containing the data to be used to create the metric(s)
timestamp: datetime.datetime
timestamp at which to compute the metric
Returns
-------
SingleTimeMetric
Contains the metric information
"""
numerator = self._assoc_distances_sum_t(manager,
timestamp,
self.position_mapping,
self.position_weighting)
try:
PA = numerator / self._na_t(manager, timestamp)
except ZeroDivisionError:
PA = 0
return SingleTimeMetric(title="SIAP PA at timestamp",
value=PA,
timestamp=timestamp,
generator=self)
def PA(self, manager):
r"""SIAP metric PA over time
The average positional accuracy of associated tracks .The output is a distance measure,
range :math:`0:\infty`, with a target score of 0.
.. math::
PA = \frac{\sum_{t_{start}}^{t_{end}}{\sum_{n\in D(t)}PA_{n}(t)}}
{\sum_{t_{start}}^{t_{end}}{NA(t)}}
where
:math:`D(t)` is the set of tracks held at timestamp :math:`t` :math:`PA_{n}(t)` is the
Euclidean distance of track n to its associated truth at timestamp :math:`{t}`
and
:math:`N{A}({t})` is the number of tracks assigned to true objects at timestamp
:math:`{t}`.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
numerator = sum(self._assoc_distances_sum_t(manager,
timestamp,
self.position_mapping,
self.position_weighting)
for timestamp in timestamps)
try:
PA = numerator / self._na_sum(manager, timestamps)
except ZeroDivisionError:
PA = 0
return TimeRangeMetric(
title="SIAP PA",
value=PA,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def VA_single_time(self, manager, timestamp):
r"""SIAP metric VA at a specific time
Returns an assessment of the average assigned track velocity accuracy at a specific
timestamp, :math:`{t}`. The output is a distance measure, range :math:`0:\infty`, with a
target score of 0.
.. math::
VA_{t} = \frac{{\sum_{n\in D(t)}VA_{n}(t)}}{NA(t)}
where
:math:`D(t)` is the set of tracks held at timestamp :math:`t`, :math:`VA_{n}(t)` is the
Euclidean distance of track n's velocity components to its associated truth's
corresponding velocities at timestamp :math:`{t}`
and
:math:`N{A}({t})` is the number of tracks assigned to true objects at timestamp
:math:`{t}`.
Parameters
----------
manager : MetricManager
containing the data to be used to create the metric(s)
timestamp: datetime.datetime
timestamp at which to compute the metric
Returns
-------
SingleTimeMetric
Contains the metric information
"""
numerator = self._assoc_distances_sum_t(manager,
timestamp,
self.velocity_mapping,
self.velocity_weighting)
try:
VA = numerator / self._na_t(manager, timestamp)
except ZeroDivisionError:
VA = 0
return SingleTimeMetric(title="SIAP VA at timestamp",
value=VA,
timestamp=timestamp,
generator=self)
def VA(self, manager):
r"""SIAP metric VA over time
The average velocity accuracy of associated tracks.The output is a distance
measure, range :math:`0:\infty`, with a target score of 0.
.. math::
VA = \frac{\sum_{t_{start}}^{t_{end}}{\sum_{n\in D(t)}VA_{n}(t)}}
{\sum_{t_{start}}^{t_{end}}{NA(t)}}
where
:math:`D(t)` is the set of tracks held at timestamp :math:`t` :math:`VA_{n}(t)` is the
Euclidean distance of track n's velocity components to its associated truth's
corresponding velocities at timestamp :math:`{t}`
and
:math:`N{A}({t})` is the number of tracks assigned to true objects at timestamp
:math:`{t}`.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
numerator = sum(self._assoc_distances_sum_t(manager,
timestamp,
self.velocity_mapping,
self.velocity_weighting)
for timestamp in timestamps)
try:
VA = numerator / self._na_sum(manager, timestamps)
except ZeroDivisionError:
VA = 0
return TimeRangeMetric(
title="SIAP VA",
value=VA,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def num_tracks(self, manager):
"""Calculates the number of tracks stored in the metric manager
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
nt = len(manager.tracks)
return TimeRangeMetric(
title="SIAP nt",
value=nt,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def num_truths(self, manager):
"""Calculates the number of truths stored in the metric manager
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
nj = len(manager.groundtruth_paths)
return TimeRangeMetric(
title="SIAP nj",
value=nj,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def CID_single_time(self, manager, timestamp):
r"""SIAP metric CID at a specific time
Returns an assessment of the number of targets currently being tracked with assigned tracks
with known IDs, compared to the number of targets being tracked at a specific timestamp,
:math:`{t}`. The output is a percentage, range math:`0:1`, with a target score of 1.
.. math::
CID_{t} = \frac{J{T}({t}) - J{U}({t})}{JT({t})}
where
:math:`J{T}({t})` is the number of true objects being tracked at timestamp :math:`{t}`
and
:math:`J{U}({t})` is the number of number of truths tracked with unknown ID at
timestamp :math:`{t}`.
Parameters
----------
manager : MetricManager
containing the data to be used to create the metric(s)
timestamp: datetime.datetime
timestamp at which to compute the metric
Returns
-------
SingleTimeMetric
Contains the metric information
"""
numerator = self._jt_t(manager, timestamp) - self._ju_t(manager, timestamp)
try:
CID = numerator / self._jt_t(manager, timestamp)
except ZeroDivisionError:
CID = 0
return SingleTimeMetric(title="SIAP CID at timestamp",
value=CID,
timestamp=timestamp,
generator=self)
def CID_time_range(self, manager):
r"""SIAP metric CID over time
The average percentage of targets being tracked with assigned tracks with known IDs across
the dataset. The output is a percentage, range math:`0:1`, with a target score of 1.
.. math::
CID = \frac{\sum_{t_{start}}^{t_{end}}[J{T}({t}) - J{U}({T})]}
{\sum_{t_{start}}^{t_{end}}J{T}({t})}
where
:math:`J{T}({t})` is the number of true objects being tracked at timestamp :math:`{t}`
and
:math:`J{U}({t})` is the number of number of truths tracked with unknown ID at
timestamp :math:`{t}`.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
numerator = sum({self._jt_t(manager, timestamp) - self._ju_t(manager, timestamp)
for timestamp in timestamps})
try:
CID = numerator / self._jt_sum(manager, timestamps)
except ZeroDivisionError:
self._warn_no_truth(manager)
self._warn_no_tracks(manager)
CID = 0
return TimeRangeMetric(
title="SIAP CID",
value=CID,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def IDC_single_time(self, manager, timestamp):
r"""SIAP metric IDc at a specific time
Returns an assessment of the number of targets currently being tracked with the
correct ID, compared to the number of targets being tracked at a specific
timestamp, :math:`{t}`. The output is a percentage, range math:`0:1`, with a
target score of 1.
.. math::
IDC_{t} = \frac{J{C}({t})}{JT({t})}
where
:math:`J{C}({t})` is the number of number of truths tracked with correct ID at
timestamp :math:`{t}`
and
:math:`J{T}({t})` is the number of true objects being tracked at timestamp :math:`{t}`.
Parameters
----------
manager : MetricManager
containing the data to be used to create the metric(s)
timestamp: datetime.datetime
timestamp at which to compute the metric
Returns
-------
SingleTimeMetric
Contains the metric information
"""
numerator = self._jc_t(manager, timestamp)
try:
IDC = numerator / self._jt_t(manager, timestamp)
except ZeroDivisionError:
IDC = 0
return SingleTimeMetric(title="SIAP IDC at timestamp",
value=IDC,
timestamp=timestamp,
generator=self)
def IDC_time_range(self, manager):
r"""SIAP metric IDC over time
The average percentage of targets being tracked with the correct ID across
the dataset. The output is a percentage, range math:`0:1`, with a target score of 1.
.. math::
IDC = \frac{\sum_{t_{start}}^{t_{end}}J{C}({t})}{\sum_{t_{start}}^{t_{end}}J{T}({t})}
where
:math:`J{C}({t})` is the number of number of truths tracked with correct ID at
timestamp :math:`{t}`
and
:math:`J{T}({t})` is the number of true objects being tracked at timestamp :math:`{t}`.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
numerator = self._jc_sum(manager, timestamps)
try:
IDC = numerator / self._jt_sum(manager, timestamps)
except ZeroDivisionError:
self._warn_no_truth(manager)
self._warn_no_tracks(manager)
IDC = 0
return TimeRangeMetric(
title="SIAP IDC",
value=IDC,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def IDA_single_time(self, manager, timestamp):
r"""SIAP metric IDc at a specific time
Returns an assessment of the number of targets currently being tracked with ambiguous ID,
compared to the number of targets being tracked at a specific timestamp, :math:`{t}`.
An object’s ID is considered ambiguous if it has multiple tracks with correct and incorrect
IDs. The output is a percentage, range math:`0:1`, with a target score of 0.
.. math::
IDA_{t} = \frac{J{A}({t})}{JT({t})}
where
:math:`J{A}({t}) = J{T}({t}) - J{C}({t}) - J{I}({t}) - J{U}({t})` is the number of
number of truths tracked with ambiguous ID at timestamp :math:`{t}`,
:math:`J{C}({t}), J{I}({t}), J{U}({t})` are the number of truths tracked with correct,
incorrect and unkown (no) ID at timestamp :math:`t` respectively.
and
:math:`J{T}({t})` is the number of true objects being tracked at timestamp :math:`{t}`.
Parameters
----------
manager : MetricManager
containing the data to be used to create the metric(s)
timestamp: datetime.datetime
timestamp at which to compute the metric
Returns
-------
SingleTimeMetric
Contains the metric information
"""
numerator = self._ja_t(manager, timestamp)
try:
IDA = numerator / self._jt_t(manager, timestamp)
except ZeroDivisionError:
IDA = 0
return SingleTimeMetric(title="SIAP IDA at timestamp",
value=IDA,
timestamp=timestamp,
generator=self)
def IDA_time_range(self, manager):
r"""SIAP metric IDC over time
The average percentage of targets being tracked with ambiguous ID across the dataset.
The output is a percentage, range math:`0:1`, with a target score of 0.
.. math::
IDA = \frac{\sum_{t_{start}}^{t_{end}}J{A}({t})}{\sum_{t_{start}}^{t_{end}}J{T}({t})}
where
:math:`J{A}({t}) = J{T}({t}) - J{C}({t}) - J{I}({t}) - J{U}({t})` is the number of
number of truths tracked with ambiguous ID at timestamp :math:`{t}`,
:math:`J{C}({t}), J{I}({t}), J{U}({t})` are the number of truths tracked with correct,
incorrect and unkown (no) ID at timestamp :math:`t` respectively.
and
:math:`J{T}({t})` is the number of true objects being tracked at timestamp :math:`{t}`.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
TimeRangeMetric
Contains the metric information
"""
timestamps = manager.list_timestamps()
numerator = self._ja_sum(manager, timestamps)
try:
IDA = numerator / self._jt_sum(manager, timestamps)
except ZeroDivisionError:
self._warn_no_truth(manager)
self._warn_no_tracks(manager)
IDA = 0
return TimeRangeMetric(
title="SIAP IDA",
value=IDA,
time_range=TimeRange(min(timestamps), max(timestamps)),
generator=self)
def _assoc_distances_sum_t(self, manager, timestamp, mapping, weighting):
"""Sum of spatial (positon or velocity) distance between each truth and its associations
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamp: datetime.datetime
Timestamp at which to compute the metric
mapping: np.ndarray
Indices of the required positon/velocity components of the state space
weighting: np.ndarray
The weighting to be used by the Euclidean measure
Returns
-------
int
Sum of Euclidean distances (of position or velocity) of each truth to its associated
tracks in manager at timestamp
"""
measure = EuclideanWeighted(mapping=mapping, weighting=weighting)
distance_sum = 0
for assoc in manager.association_set.associations_at_timestamp(timestamp):
track, truth = assoc.objects
distance_sum += measure(track[timestamp], truth[timestamp])
return distance_sum
def _j_t(self, manager, timestamp):
"""Number of truth objects at timestamp
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamp: datetime.datetime
Timestamp at which to compute the metric
Returns
-------
int
Number of truth objects in manager with a state at timestamp
"""
return sum(
1
for path in manager.groundtruth_paths
if timestamp in (state.timestamp for state in path))
def _j_sum(self, manager, timestamps):
"""Sum number of truth objects over all timestamps
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamps: iterable of :class:`datetime.datetime`
Timestamps over which to compute the metric
Returns
-------
int
Sum number of truth objects over all timestamps
"""
return sum(self._j_t(manager, timestamp) for timestamp in timestamps)
def _jt_t(self, manager, timestamp):
"""Number of truth objects being tracked at time timestamp
Parameters
----------
manager: MetricManager
Contains the data to be used to create the metric
timestamp: datetime.datetime
Timestamp over which to compute the metric
Returns
-------
int
Number of truth objects with states at timestamp
"""
assocs = manager.association_set.associations_at_timestamp(timestamp)
n_associated_truths = 0
for truth in manager.groundtruth_paths:
for assoc in assocs:
if truth in assoc.objects:
n_associated_truths += 1
break
return n_associated_truths
def _jt_sum(self, manager, timestamps):
"""Sum number of truth objects being tracked at a given timestamp
over list of timestamps
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamps: iterable of :class:`datetime.datetime`
Timestamps over which to compute the metric
Returns
-------
int
total number of truth objects
"""
return sum(self._jt_t(manager, timestamp)
for timestamp in timestamps)
def _na_t(self, manager, timestamp):
"""Number of associated tracks at a timestamp
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamp: datetime.datetime
Timestamp over which to compute the metric
Returns
-------
int
Number of associated tracks
"""
assocs = manager.association_set.associations_at_timestamp(timestamp)
n_associated_tracks = 0
for track in manager.tracks:
for assoc in assocs:
if track in assoc.objects:
n_associated_tracks += 1
break
return n_associated_tracks
def _na_sum(self, manager, timestamps):
"""Sum of number of associated tracks at a timestamp over list of
timestamps
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamps: iterable of :class:`datetime.datetime`
Timestamps over which to compute the metric
Returns
-------
int
Sum of the number of associated tracks
"""
return sum(self._na_t(manager, timestamp) for timestamp in timestamps)
def _n_t(self, manager, timestamp):
"""Number of tracks at timestamp
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamp: datetime.datetime
Timestamp over which to compute the metric
Returns
-------
int
Number of tracks
"""
return sum(
1
for track in manager.tracks
if timestamp in (state.timestamp for state in track.states))
def _n_sum(self, manager, timestamps):
"""Sum of number of tracks over timestamps
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamps: iterable of :class:`datetime.datetime`
Timestamps over which to compute the metric
Returns
-------
int
Sum number of tracks
"""
return sum(self._n_t(manager, timestamp) for timestamp in timestamps)
def _tt_j(self, manager, truth):
"""Total time that object is tracked for
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
truth: GroundTruthPath
Truth object to compute the metric for
Returns
-------
datetime.timedelta
The duration that an object is tracked for
"""
assocs = manager.association_set.associations_including_objects(
[truth])
timestamps = sorted(s.timestamp for s in truth)
total_time = datetime.timedelta(0)
for i_timestamp, timestamp in enumerate(timestamps[:-1]):
for assoc in assocs:
# If both timestamps are in one association then add the
# difference to the total difference and stop looking
if timestamp in assoc.time_range \
and timestamps[i_timestamp + 1] in assoc.time_range:
total_time += (timestamps[i_timestamp + 1] - timestamp)
break
return total_time
def _nu_j(self, manager, truth):
"""Minimum number of tracks needed to track truth over the timestamps
that truth is tracked for
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
truth: GroundTruthPath
Truth object to compute the metric for
Returns
-------
int
Minimum number of tracks needed to track truth over the timestamps
that truth is tracked for
"""
# Starting at the beginning of the truth find the track associated at that timestamp with
# the longest length, increase the track count by one and move time to the end of that
# track. Repeat until the end of the truth is reached. If no tracks present at a point then
# move on to the next timestamp index in the truth.
assocs = sorted(manager.association_set.associations_including_objects([truth]),
key=attrgetter('time_range.end_timestamp'),
reverse=True)
if len(assocs) == 0:
return 0
truth_timestamps = sorted(i.timestamp for i in truth.states)
n_truth_needed = 0
i_timestamp = 0
while i_timestamp < len(truth_timestamps):
current_time = truth_timestamps[i_timestamp]
assoc_at_time = next((assoc for assoc in assocs if current_time in assoc.time_range),
None)
if not assoc_at_time:
i_timestamp += 1
else:
end_time = assoc_at_time.time_range.end_timestamp
n_truth_needed += 1
# If not yet at the end of the truth timestamps indices, move on to the next
try:
# Move to next timestamp index after current association's end timestamp
i_timestamp = truth_timestamps.index(end_time, i_timestamp + 1) + 1
except ValueError:
break
return n_truth_needed
def _tl_j(self, manager, truth):
"""Total time of the longest track on the truth
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
truth: GroundTruthPath
Truth object to compute the metric for
Returns
-------
datetime.timedelta
The length of the longest track
"""
assocs = manager.association_set.associations_including_objects(
[truth])
if not assocs:
return datetime.timedelta(0)
else:
return max(assoc.time_range.duration for assoc in assocs)
def _r(self, manager):
"""Average number of excess tracks assigned
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
Returns
-------
int
Average number of excess tracks assigned
"""
numerator = sum(self._nu_j(manager, truth) - 1
for truth in manager.groundtruth_paths)
denominator = sum(self._tt_j(manager, truth).total_seconds()
for truth in manager.groundtruth_paths)
try:
return numerator / denominator
except ZeroDivisionError:
# No truth or tracks
return 0
def _t_j(self, truth):
"""Total time truth exists for
Parameters
----------
truth: GroundTruthPath
Truth object to compute the metric for
Returns
-------
datetime.timedelta
The time the truth object exists for
"""
timestamps = [s.timestamp for s in truth.states]
return max(timestamps) - min(timestamps)
def _check_j_t(self, manager, timestamp, check_function):
"""Calculate the number of truths whose assigned tracks at timestamp :math:`t` all satisfy
the conditions given by the check_function.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamp: datetime.datetime
Timestamp over which to compute the metric
check_function: function
Function which takes track, truth as argument and returns a boolean
Returns
-------
int
Number of truths whose assigned tracks satisfy the check_function at timestamp
"""
count = 0
# Get all associations at timestamp
assocs = manager.association_set.associations_at_timestamp(timestamp)
for truth in manager.groundtruth_paths:
truth_assocs = [assoc.objects for assoc in assocs if truth in assoc.objects]
tracks = set()
for (track, alt_track) in truth_assocs:
# Assoc objects are track and truth (don't know which order, so check)
if track is truth:
track = alt_track
tracks.add(track)
if len(tracks) == 0:
continue
if all(check_function(track, truth, timestamp) for track in tracks):
count += 1
return count
def _get_track_id(self, track, timestamp):
state = track[timestamp]
index = track.index(state)
metadata = track.metadatas[index]
return metadata.get(self.track_id)
def _ju_check(self, track, truth, timestamp):
return self._get_track_id(track, timestamp) is None
def _ju_t(self, manager, timestamp):
"""Calculate the number of truths tracked with unknown ID at timestamp
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamp: datetime.datetime
Timestamp over which to compute the metric
Returns
-------
int
Number of truths assigned tracks with the unknown (no) ID at timestamp
"""
return self._check_j_t(manager, timestamp, self._ju_check)
def _ju_sum(self, manager, timestamps):
"""Calculate the sum of the number of truths tracked with unknown ID over all timestamps
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamps: iterable of :class:`datetime.datetime`
Timestamps over which to compute the metric
Returns
-------
int
Sum number of truths assigned tracks with unknown (no) ID over all timestamps
"""
return sum(self._ju_t(manager, timestamp) for timestamp in timestamps)
def _jc_check(self, track, truth, timestamp):
track_id = self._get_track_id(track, timestamp)
truth_id = truth.metadata.get(self.truth_id)
return track_id is not None and truth_id is not None and track_id == truth_id
def _jc_t(self, manager, timestamp):
"""Calculate the number of truths tracked with correct ID at timestamp
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamp: datetime.datetime
Timestamp over which to compute the metric
Returns
-------
int
Number of truths assigned tracks with the correct ID at timestamp
"""
return self._check_j_t(manager, timestamp, self._jc_check)
def _jc_sum(self, manager, timestamps):
"""Calculate the sum of the number of truths tracked with correct ID over all timestamps
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamps: iterable of :class:`datetime.datetime`
Timestamps over which to compute the metric
Returns
-------
int
Sum number of truths assigned tracks with the correct ID over all timestamps
"""
return sum(self._jc_t(manager, timestamp) for timestamp in timestamps)
def _ji_check(self, track, truth, timestamp):
track_id = self._get_track_id(track, timestamp)
truth_id = truth.metadata.get(self.truth_id)
return track_id is not None and track_id != truth_id
def _ji_t(self, manager, timestamp):
"""Calculate the number of truths tracked with incorrect ID at timestamp
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamp: datetime.datetime
Timestamp over which to compute the metric
Returns
-------
int
Number of truths assigned tracks with the incorrect ID at timestamp
"""
return self._check_j_t(manager, timestamp, self._ji_check)
def _ji_sum(self, manager, timestamps):
"""Calculate the sum of the number of truths tracked with incorrect ID over all timestamps
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamps: iterable of :class:`datetime.datetime`
Timestamps over which to compute the metric
Returns
-------
int
Sum number of truths assigned tracks with the incorrect ID over all timestamps
"""
return sum(self._ji_t(manager, timestamp) for timestamp in timestamps)
def _ja_t(self, manager, timestamp):
"""Calculate the number of truths with ambiguous ID at timestamp
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamp: datetime.datetime
Timestamp over which to compute the metric
Returns
-------
int
Number of truths assigned tracks with a mix of ID correctness at timestamp
"""
jt = self._jt_t(manager, timestamp)
jc = self._jc_t(manager, timestamp)
ji = self._ji_t(manager, timestamp)
ju = self._ju_t(manager, timestamp)
return jt - jc - ji - ju
def _ja_sum(self, manager, timestamps):
"""Calculate the sum of the number of truths tracked with ambiguous ID over all timestamps
eg. A truth that has one track with correct ID, and one with unknown ID assigned to it
would be counted.
Parameters
----------
manager: MetricManager
Containing the data to be used to create the metric
timestamps: iterable of :class:`datetime.datetime`
Timestamps over which to compute the metric
Returns
-------
int
Sum number of truths assigned tracks with a mix of ID correctness over all timestamps
"""
return sum(self._ja_t(manager, timestamp) for timestamp in timestamps)
|
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.Vue = require('vue');
import App from './App.vue';
const app = new Vue({
el: '#app',
render: h => h(App)
});
|
#!/usr/bin/env python
import sys
from time import sleep
import pprint
from pyhocon import ConfigFactory
import confluent_kafka.admin as kad
class WrapKafkaAdmin:
def __init__(self, conf):
self.conf = conf
kafka_conf = {'bootstrap.servers': conf.KAFKA_BROKERS}
kafka_admin = kad.AdminClient(kafka_conf)
self.admin = kafka_admin
def list_topics(self):
pprint.pprint(self.admin.list_topics().topics) # LIST
def create_topics(self):
topic_list = []
for topic_name in self.conf.topics:
topic = self.conf.topics[topic_name]
print(topic)
topic_list.append(kad.NewTopic(
topic.name,
topic.num_partitions,
topic.replication_factor)
)
# new_topic = kad.NewTopic('topic100', 3, 2)
# Number-of-partitions = 1
# Number-of-replicas = 1
a = self.admin.create_topics(topic_list) # CREATE (a list(), so you can create multiple).
# pprint.pprint(a)
sleep(3)
self.list_topics()
def delete_topics(self):
topics_for_deletion = [a for a in self.conf.topics_for_deletion]
future_dict = self.admin.delete_topics(topics_for_deletion)
print('delete futures:')
for k, v in future_dict.items():
print(f'future key: {k} value: {v}')
sleep(5)
self.list_topics()
if __name__ == "__main__":
_conf = ConfigFactory.parse_file('./Kafka.conf')
ar = sys.argv
kafka_wrapper = WrapKafkaAdmin(_conf)
if len(ar) == 1:
kafka_wrapper.create_topics()
elif len(ar) > 1:
action = sys.argv[1]
if action == 'del':
kafka_wrapper.delete_topics()
elif action == 'list':
kafka_wrapper.list_topics()
|
"""ARK View"""
__docformat__ = "numpy"
import os
import pandas as pd
from tabulate import tabulate
from gamestonk_terminal.stocks.due_diligence import ark_model
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.rich_config import console
def display_ark_trades(
ticker: str, num: int = 20, export: str = "", show_ticker: bool = False
):
"""Display ARK trades for ticker
Parameters
----------
ticker : str
Ticker to get trades for
num: int
Number of rows to show
export : str, optional
Format to export data
show_ticker: bool
Flag to show ticker in table
"""
ark_holdings = ark_model.get_ark_trades_by_ticker(ticker)
if ark_holdings.empty:
console.print(
"Issue getting data from cathiesark.com. Likely no trades found.\n"
)
return
# Since this is for a given ticker, no need to show it
if not show_ticker:
ark_holdings = ark_holdings.drop(columns=["ticker"])
ark_holdings["Total"] = ark_holdings["Total"] / 1_000_000
ark_holdings.rename(
columns={"Close": "Close ($)", "Total": "Total ($1M)"}, inplace=True
)
ark_holdings.index = pd.Series(ark_holdings.index).apply(
lambda x: x.strftime("%Y-%m-%d")
)
if gtff.USE_TABULATE_DF:
print(
tabulate(
ark_holdings.head(num),
headers=ark_holdings.columns,
showindex=True,
floatfmt=("", ".4f", ".4f", ".4f", "", ".2f", ".2f", ".3f"),
tablefmt="fancy_grid",
)
)
else:
console.print(ark_holdings.head(num).to_string())
console.print("")
export_data(
export, os.path.dirname(os.path.abspath(__file__)), "arktrades", ark_holdings
)
|
{
step1Title:"Step 1: Select a Data Source",
step2Title:"Step 2: Make Selections",
step3Title:"Step 3: Customize Selections",
step4Title:"Step 4: Report Settings",
goBtnTxt:"Go",
okBtnTxt:"Ok",
cancelBtnTxt:"Cancel",
searchBtnTxt:"Search",
backBtnTxt:"Back",
nextBtnTxt:"Next",
saveBtnTxt:"Save",
saveAsBtnTxt:"Save As ...",
cancelBtnTxt:"Cancel",
invalidPageNum:"Not a valid page number: %{0}",
levelTitle:"Level %{0}",
addColumnsToGrps:"Add column(s) to Groups list",
addColumnsToDetails:"Add column(s) to Details list",
addColumnsToFilters:"Add column(s) to Filters list",
deleteFromFilters:"Delete from Filters list",
portraitBtnTxt:"Portrait",
landscapeBtnTxt:"Landscape",
letterSizeBtnTxt:"Letter",
legalSizeBtnTxt:"Legal",
waqrLoadFailed:"Unable to load Adhoc Reporting Interface: %{0}",
reportTemplateLoadFailed:"Unable to load the report template: %{0}",
invalidGrpListItem:"Invalid group list item.",
invalidGrpHdr:"Invalid Item type, expecting RSGroupHeader.",
invalidDetailItem:"Invalid Item type, expecting RSDetailItem.",
invalidFilterItem:"Invalid Item type, expecting RSFilterItem.",
invalidGrpItem:"Invalid Item type, expecting RSGroupItem.",
pg3SaveErrorMsg:"Error while writing wizard page 3 to ReportSpec: %{0}",
selectBusinessModelWarn:"Select a Data Source before proceeding",
selectBusinessModelMsg:"Select a Data Source from the Available Data Source(s).",
addDetailsMsg:"Add a column from the Available Items to the Details list.",
invalidFileName:"%{0} is an invalid filename. Valid filenames cannot include the characters: /\?%*:|\"<>",
invalidBranchElement:"Invalid element in document, branch element has isDir attribute set to false.",
searchDlgTitle:"Search",
availItemsTitle:"Select one or more columns and add them to the Groups, Details, or Filters list",
searchTooltip:"Search for column value",
addConstraintBtnTxt:"Add a Constraint",
constraintIdxOutOfRange:"Constraint index %{0} out of range.",
unknownComparator:"Unknown comparator in constraint: %{0}.",
addConstraintsBtnHoverTxt:"Select a Group, Detail, or Filter column, and click to add a constraint.",
deleteConstraintsBtnHoverTxt:"Select a column in the constraints table, and click to delete it.",
searchWildcardHelpMsg:"Use * in your search text to specify a wildcard.",
dragHereMsg:"[drag item here]",
alignGrpHdrDefaultBtnTxt:"Default",
alignGrpHdrTopBtnTxt:"Top",
alignGrpHdrMiddleBtnTxt:"Middle",
alignGrpHdrBottomBtnTxt:"Bottom",
alignGrpItemDefaultBtnTxt:"Default",
alignGrpItemLeftBtnTxt:"Left",
alignGrpItemCenterBtnTxt:"Center",
alignGrpItemRightBtnTxt:"Right",
noGrpPgBrkBtnTxt:"None",
alignDetailItemDefaultBtnTxt:"Default",
alignDetailItemLeftBtnTxt:"Left",
alignDetailItemCenterBtnTxt:"Center",
alignDetailItemRightBtnTxt:"Right",
pgBrkBeforeGrpBtnTxt:"Before Group",
pgBrkAfterGrpBtnTxt:"After Group",
unknownColumnType:"Unknown column type: %{0}",
invalidGroupNum:"Failed to locate group header for group num: %{0}",
selectModelTitle:"Select a Data Source",
step1DetailsTitle:"Business Model Details",
availModelsTitle:"Available",
loadingViewsProgressMsg:"Loading Data Source(s) ...",
businessViewTitle:"Business View",
descTitle:"Description",
defineTmpltTitle:"Apply a Template",
tmpltDetailsTitle:"Template Details",
availTmpltsTitle:"Templates",
thumbnailTitle:"Thumbnail",
step2AvailItemsTitle:"Available Items",
DISTINCT_SELECTIONS_LABEL:"Distinct Selections",
selectedItemsTitle:"Selected Items",
step2GroupsTitle:"Groups",
step2DetailsTitle:"Details",
step2FiltersTitle:"Filters",
step3GroupsTitle:"Groups",
step3DetailsTitle:"Details",
step3FiltersTitle:"Filters",
step3GrpsGeneralTitle:"General",
step3GrpsFormatTitle:"Formatting",
step3GrpsLvlNameTitle:"Level Name",
step3GrpOptionsTitle:"Options",
step3RepeatGrpHdr:"Repeat Group Header",
step3ShowTotals:"Show Totals",
step3PgBrkTitle:"Page Break",
step3GrpAlignTitle:"Alignment",
step3GrpsFormatTitle2:"Formatting",
step3FormatListNumericLabel:"Numeric Format",
step3FormatListDateLabel:"Date Format",
step3FormatListEmptyLabel:"",
step3GrpAlignTitle2:"Alignment",
step3DetailsFormatTitle:"Formatting",
step3CalcsTitle:"Calculation",
step3DetailsAlignTitle:"Alignment",
step3DetailsUseCalcFunc:"Use Function",
STEP3_GROUP_LEVEL_NAME_TOOLTIP: "Provide a label in the group header (optional)",
STEP3_GROUP_TOTAL_LABEL_TOOLTIP: "Provide a label for the summary row in the report.",
STEP3_SHOW_GROUP_SUMMARY_TOOLTIP: "Check to display summary information (count, sum, average, etc.) for Details columns.",
STEP3_REPEAT_GROUP_HEADER_TOOLTIP: "Check to repeat the group header on each page of a pdf report.",
STEP3_SELECT_AN_ITEM_TOOLTIP: "Select an item from the Groups, Details, or Filters list.",
STEP3_ADD_CONSTRAINT_TOOLTIP: "Select an item from the Groups, Details or Filters list, and then click 'Add a Constraint'",
STEP3_GROUPS_EDIT_SORT_COLUMN_TOOLTIP: "Select an item from the Groups list. Then select 'ascending' or 'descending'.",
STEP3_DETAILS_EDIT_SORT_COLUMN_TOOLTIP: "Select an item from the Details list. Click the 'Add' button. Then select 'ascending' or 'descending'.",
STEP3_ADD_DETAILS_SORT: "Select an item in the Details list, and click 'Add'",
STEP3_CANNOT_EDIT_GROUPS_SORT: "You can not add to, delete from, or reorder the Group sort columns.",
STEP3_DETAIL_EDITOR_TOOLTIP: "Configure the detail item's attributes.",
STEP3_GROUP_ITEM_EDITOR_TOOLTIP: "Configure the group item's attributes.",
STEP3_GROUP_HEADER_EDITOR_TOOLTIP: "Configure the group header's attributes.",
VALUE_MUST_BE_NUMERIC: "Value must be a number.",
VALUE_MUST_BE_NONEMPTY: "Value cannot be empty.",
/* begin aggregation functions */
aggrFuncNone:"None",
aggrFuncSum:"Sum",
aggrFuncCount:"Count",
aggrFuncAverage:"Average",
aggrFuncMin:"Min",
aggrFuncMax:"Max",
/* end aggregation functions */
step3ConstraintsTitle:"Constraints",
step3SortColumns:"Sort Columns",
step3ConstraintCurrSettings:"Current Settings",
step3GroupColumnSorterTitle:"Sort Group Columns",
step3DetailColumnSorterTitle:"Sort Detail Columns",
step4GeneralTitle:"General",
step4OrientationTitle:"Orientation",
step4PaperTitle:"Paper",
step4ReportDescTitle:"Report Description",
step4HdrTitle:"Header",
step4ReportTitle:"Report",
step4PgTitle:"Page",
step4FooterTitle:"Footer",
step4FooterRptTitle:"Report",
step4FooterPgTitle:"Page",
saveDlgSaveAsPrompt:"Save As:",
saveDlgWherePrompt:"Where:",
saveDlgSelectSltnTitle:"Select a Solution",
saveDlgOutputTypeTitle:"Output Type",
srchDlgResultsTitle:"Search Results",
previewFormatPrompt:"Preview As:",
CONSTRAINTS_INVALID:"The values for the highlighted constraints are invalid. Please hover the mouse pointer over the constraint for details.",
unableToLoadEmptyViewId:"Unable to load business view with an empty view Id.",
unableToLoadEmptyDomainId:"Unable to load business view with an empty domain Id.",
youMayContinue:"You may now continue.",
close:"close",
unableToSelectModel:"Unable to select a Data Source. The reportSpec document is missing either the domain Id or the model Id.",
loadingDescription: "Loading Model Description ...",
loadingView: "Loading Business View ...",
searching: "Searching ...",
saving: "Saving ...",
working: "Working ...",
badSortInfo:"ReportSpec load error: sort information specified for a column that is not in the Groups or Details columns.",
saveLabel:"Save",
openLabel:"Open",
ascLabel:"ascending",
descLabel:"descending",
ascLabelUpper:"Asc",
descLabelUpper:"Desc",
columnLabel:"Column",
tableLabel:"Table",
overwriteFile:"The solution file %{0} already exists. Would you like to overwrite?",
invalidColumnType:"Invalid column type requested for constraint control: %{0}.",
EXACTLY_MATCHES:"exactly matches",
CONTAINS:"contains",
ENDS_WITH:"ends with",
BEGINS_WITH:"begins with",
DOES_NOT_CONTAIN:"does not contain",
ON:"on",
ON_OR_AFTER:"on or after",
ON_OR_BEFORE:"on or before",
AFTER:"after",
BEFORE:"before",
NOT_ON:"not on",
STEP3_SHOW_GROUP_SUMMARY:"Show Group Summary",
STEP3_GROUP_TOTAL_LABEL:"Group Summary Label",
DEFAULT_GROUP_TOTAL_LABEL:"Total",
FREE_FORM:"Free Form",
BUILDER: "Builder",
MQL_PARSE_FAILED: "MQL Parser error: failed trying to parse: \"%{0}\".",
REPORT_FILE_FAILED_TO_LOAD: "Error: the report definition file contains invalid data. Reason: %{0}",
INVALID_COMPARATOR_NAME: "Invalid comparator function name: %{0}.",
UNRECOGNIZED_PAGE_BREAK_VALUE: "Unrecognized value for page break on group header: %{0}.",
INVALID_REPOSITORY_BROWSER_STATE: "RepositoryBrowser is in an invalid state. Cannot complete save operation.",
PARTIAL_MQL_PARSE_FAILURE: "The Builder was unable to parse parts of the MQL in the Free Form editor. Some or all of the MQL from the Free Form editor will be lost. Would you like to continue?",
/* begin number format */
NUMBER_FORMAT_NEG_MONEY_LABEL: "$ 1,234; -$ 1,234",
NUMBER_FORMAT_PAREN_MONEY_LABEL: "$ 1,234; ($ 1,234)",
NUMBER_FORMAT_NEG_DECIMAL_MONEY_LABEL: "$ 1,234.56; -$ 1,234.56",
NUMBER_FORMAT_NEG_MONEY: "$ #,###;-$ #,###",
NUMBER_FORMAT_PAREN_MONEY: "$ #,###;($ #,###)",
NUMBER_FORMAT_NEG_DECIMAL_MONEY: "$ #,###.##;-$ #,###.##",
/* end number format */
ERROR_NO_BUSINESS_MODELS: "There are either no Data Source(s) defined in the metadata, or you do not have permission to access any of the Data Source(s). Please create one or more Data Source(s) using the Metadata Editor and then publish them to the Pentaho server. Or, use the Metadata Editor to give the appropriate user permission to access to the Data Source.",
SOLUTION_REPOSITORY: "Solution Repository",
step1_div:"Select Data Source",
step2_div:"Make Selections",
step3_div:"Customize Selections",
step4_div:"Report Settings"
dataaccessAddButtonText:"Add",
dataaccessDeleteButtonText:"Delete",
deleteModelWarningMessage:"All content associated to selected Data Source will no longer work."
}
|
//
// JXCategoryListScrollView.h
// JXCategoryView
//
// Created by jiaxin on 2018/9/12.
// Copyright © 2018年 jiaxin. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "JXCategoryViewDefines.h"
#import "JXCategoryBaseView.h"
@class JXCategoryListContainerView;
/**
列表容器视图的类型
- ScrollView: UIScrollView。优势:没有其他副作用。劣势:视图内存占用相对大一点。
- CollectionView: 使用UICollectionView。优势:因为列表被添加到cell上,视图的内存占用更少,适合内存要求特别高的场景。劣势:因为cell重用机制的问题,导致列表下拉刷新视图,会因为被removeFromSuperview而被隐藏。需要参考`LoadDataListCollectionListViewController`类做特殊处理。
*/
typedef NS_ENUM(NSUInteger, JXCategoryListContainerType) {
JXCategoryListContainerType_ScrollView,
JXCategoryListContainerType_CollectionView,
};
@protocol JXCategoryListContentViewDelegate <NSObject>
/**
如果列表是VC,就返回VC.view
如果列表是View,就返回View自己
@return 返回列表视图
*/
- (UIView *)listView;
@optional
/**
可选实现,列表将要显示的时候调用
*/
- (void)listWillAppear;
/**
可选实现,列表显示的时候调用
*/
- (void)listDidAppear;
/**
可选实现,列表将要消失的时候调用
*/
- (void)listWillDisappear;
/**
可选实现,列表消失的时候调用
*/
- (void)listDidDisappear;
@end
@protocol JXCategoryListContainerViewDelegate <NSObject>
/**
返回list的数量
@param listContainerView 列表的容器视图
@return list的数量
*/
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView;
/**
根据index返回一个对应列表实例,需要是遵从`JXCategoryListContentViewDelegate`协议的对象。
你可以代理方法调用的时候初始化对应列表,达到懒加载的效果。这也是默认推荐的初始化列表方法。你也可以提前创建好列表,等该代理方法回调的时候再返回也可以,达到预加载的效果。
如果列表是用自定义UIView封装的,就让自定义UIView遵从`JXCategoryListContentViewDelegate`协议,该方法返回自定义UIView即可。
如果列表是用自定义UIViewController封装的,就让自定义UIViewController遵从`JXCategoryListContentViewDelegate`协议,该方法返回自定义UIViewController即可。
@param listContainerView 列表的容器视图
@param index 目标下标
@return 遵从JXCategoryListContentViewDelegate协议的list实例
*/
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index;
@optional
/**
返回自定义UIScrollView或UICollectionView的Class
某些特殊情况需要自己处理UIScrollView内部逻辑。比如项目用了FDFullscreenPopGesture,需要处理手势相关代理。
@param listContainerView JXCategoryListContainerView
@return 自定义UIScrollView实例
*/
- (Class)scrollViewClassInlistContainerView:(JXCategoryListContainerView *)listContainerView;
/**
控制能否初始化对应index的列表。有些业务需求,需要在某些情况才允许初始化某些列表,通过通过该代理实现控制。
*/
- (BOOL)listContainerView:(JXCategoryListContainerView *)listContainerView canInitListAtIndex:(NSInteger)index;
- (void)listContainerViewDidScroll:(UIScrollView *)scrollView;
@end
@interface JXCategoryListContainerView : UIView <JXCategoryViewListContainer>
@property (nonatomic, assign, readonly) JXCategoryListContainerType containerType;
@property (nonatomic, strong, readonly) UIScrollView *scrollView;
@property (nonatomic, strong, readonly) NSDictionary <NSNumber *, id<JXCategoryListContentViewDelegate>> *validListDict; //已经加载过的列表字典。key是index,value是对应的列表
/**
滚动切换的时候,滚动距离超过一页的多少百分比,就触发列表的初始化。默认0.01(即列表显示了一点就触发加载)。范围0~1,开区间不包括0和1
*/
@property (nonatomic, assign) CGFloat initListPercent;
@property (nonatomic, strong) UIColor * itemColor;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE;
- (instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE;
- (instancetype)initWithType:(JXCategoryListContainerType)type delegate:(id<JXCategoryListContainerViewDelegate>)delegate NS_DESIGNATED_INITIALIZER;
@end
|
/*
* File: bHYPRE_BoomerAMG_Module.h
* Symbol: bHYPRE.BoomerAMG-v1.0.0
* Symbol Type: class
* Babel Version: 1.0.4
* Description: expose a constructor for the Python wrapper
*
* WARNING: Automatically generated; only changes within splicers preserved
*
*/
/*
* THIS CODE IS AUTOMATICALLY GENERATED BY THE BABEL
* COMPILER. DO NOT EDIT THIS!
*
* External clients need an entry point to wrap a pointer
* to an instance of bHYPRE.BoomerAMG.
* This header files defines two methods that such clients
* will need.
* bHYPRE_BoomerAMG__import
* This should be called in the client's init
* module method.
* bHYPRE_BoomerAMG__wrap
* This will wrap an IOR in a Python object.
*/
#ifndef included_bHYPRE_BoomerAMG_MODULE
#define included_bHYPRE_BoomerAMG_MODULE
#include <Python.h>
#include "sidlType.h"
#ifdef HAVE_PTHREAD
#include <pthread.h>
#endif /* HAVE_PTHREAD */
#ifdef __cplusplus
extern "C" {
#endif
struct sidl__array;
/* Forward declaration of IOR structure */
struct bHYPRE_BoomerAMG__object;
struct bHYPRE_BoomerAMG__array;
struct sidl_BaseInterface__object;
#define bHYPRE_BoomerAMG__wrap_NUM 0
#define bHYPRE_BoomerAMG__wrap_RETURN PyObject *
#define bHYPRE_BoomerAMG__wrap_PROTO (struct bHYPRE_BoomerAMG__object *sidlobj)
#define bHYPRE_BoomerAMG__convert_NUM 1
#define bHYPRE_BoomerAMG__convert_RETURN int
#define bHYPRE_BoomerAMG__convert_PROTO (PyObject *obj, struct bHYPRE_BoomerAMG__object **sidlobj)
#define bHYPRE_BoomerAMG__convert_python_array_NUM 2
#define bHYPRE_BoomerAMG__convert_python_array_RETURN int
#define bHYPRE_BoomerAMG__convert_python_array_PROTO (PyObject *obj, struct bHYPRE_BoomerAMG__array **sidlarray)
#define bHYPRE_BoomerAMG__convert_sidl_array_NUM 3
#define bHYPRE_BoomerAMG__convert_sidl_array_RETURN PyObject *
#define bHYPRE_BoomerAMG__convert_sidl_array_PROTO (struct sidl__array *sidlarray)
#define bHYPRE_BoomerAMG__weakRef_NUM 4
#define bHYPRE_BoomerAMG__weakRef_RETURN PyObject *
#define bHYPRE_BoomerAMG__weakRef_PROTO (struct bHYPRE_BoomerAMG__object *sidlobj)
#define bHYPRE_BoomerAMG_deref_NUM 5
#define bHYPRE_BoomerAMG_deref_RETURN void
#define bHYPRE_BoomerAMG_deref_PROTO (struct bHYPRE_BoomerAMG__object *sidlobj)
#define bHYPRE_BoomerAMG__newRef_NUM 6
#define bHYPRE_BoomerAMG__newRef_RETURN PyObject *
#define bHYPRE_BoomerAMG__newRef_PROTO (struct bHYPRE_BoomerAMG__object *sidlobj)
#define bHYPRE_BoomerAMG__addRef_NUM 7
#define bHYPRE_BoomerAMG__addRef_RETURN void
#define bHYPRE_BoomerAMG__addRef_PROTO (struct bHYPRE_BoomerAMG__object *sidlobj)
#define bHYPRE_BoomerAMG_PyType_NUM 8
#define bHYPRE_BoomerAMG_PyType_RETURN PyTypeObject *
#define bHYPRE_BoomerAMG_PyType_PROTO (void)
#define bHYPRE_BoomerAMG__connectI_NUM 9
#define bHYPRE_BoomerAMG__connectI_RETURN struct bHYPRE_BoomerAMG__object*
#define bHYPRE_BoomerAMG__connectI_PROTO (const char* url, sidl_bool ar, struct sidl_BaseInterface__object ** _ex)
#define bHYPRE_BoomerAMG__rmicast_NUM 10
#define bHYPRE_BoomerAMG__rmicast_RETURN struct bHYPRE_BoomerAMG__object*
#define bHYPRE_BoomerAMG__rmicast_PROTO (void* bi, struct sidl_BaseInterface__object ** _ex)
#define bHYPRE_BoomerAMG__API_NUM 11
#ifdef bHYPRE_BoomerAMG_INTERNAL
#define bHYPRE_BoomerAMG__import() ;
/*
* This declaration is not for clients.
*/
static bHYPRE_BoomerAMG__wrap_RETURN
bHYPRE_BoomerAMG__wrap
bHYPRE_BoomerAMG__wrap_PROTO;
static bHYPRE_BoomerAMG__convert_RETURN
bHYPRE_BoomerAMG__convert
bHYPRE_BoomerAMG__convert_PROTO;
static bHYPRE_BoomerAMG__convert_python_array_RETURN
bHYPRE_BoomerAMG__convert_python_array
bHYPRE_BoomerAMG__convert_python_array_PROTO;
static bHYPRE_BoomerAMG__convert_sidl_array_RETURN
bHYPRE_BoomerAMG__convert_sidl_array
bHYPRE_BoomerAMG__convert_sidl_array_PROTO;
static bHYPRE_BoomerAMG__weakRef_RETURN
bHYPRE_BoomerAMG__weakRef
bHYPRE_BoomerAMG__weakRef_PROTO;
static bHYPRE_BoomerAMG_deref_RETURN
bHYPRE_BoomerAMG_deref
bHYPRE_BoomerAMG_deref_PROTO;
static bHYPRE_BoomerAMG__newRef_RETURN
bHYPRE_BoomerAMG__newRef
bHYPRE_BoomerAMG__newRef_PROTO;
static bHYPRE_BoomerAMG__addRef_RETURN
bHYPRE_BoomerAMG__addRef
bHYPRE_BoomerAMG__addRef_PROTO;
static bHYPRE_BoomerAMG_PyType_RETURN
bHYPRE_BoomerAMG_PyType
bHYPRE_BoomerAMG_PyType_PROTO;
#else
static void **bHYPRE_BoomerAMG__API = NULL;
#define bHYPRE_BoomerAMG__wrap \
(*((bHYPRE_BoomerAMG__wrap_RETURN (*) \
bHYPRE_BoomerAMG__wrap_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG__wrap_NUM])))
#define bHYPRE_BoomerAMG__convert \
(*((bHYPRE_BoomerAMG__convert_RETURN (*) \
bHYPRE_BoomerAMG__convert_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG__convert_NUM])))
#define bHYPRE_BoomerAMG__convert_python_array \
(*((bHYPRE_BoomerAMG__convert_python_array_RETURN (*) \
bHYPRE_BoomerAMG__convert_python_array_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG__convert_python_array_NUM])))
#define bHYPRE_BoomerAMG__convert_sidl_array \
(*((bHYPRE_BoomerAMG__convert_sidl_array_RETURN (*) \
bHYPRE_BoomerAMG__convert_sidl_array_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG__convert_sidl_array_NUM])))
#define bHYPRE_BoomerAMG__weakRef \
(*((bHYPRE_BoomerAMG__weakRef_RETURN (*) \
bHYPRE_BoomerAMG__weakRef_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG__weakRef_NUM])))
#define bHYPRE_BoomerAMG_deref \
(*((bHYPRE_BoomerAMG_deref_RETURN (*) \
bHYPRE_BoomerAMG_deref_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG_deref_NUM])))
#define bHYPRE_BoomerAMG__newRef \
(*((bHYPRE_BoomerAMG__newRef_RETURN (*) \
bHYPRE_BoomerAMG__newRef_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG__newRef_NUM])))
#define bHYPRE_BoomerAMG__addRef \
(*((bHYPRE_BoomerAMG__addRef_RETURN (*) \
bHYPRE_BoomerAMG__addRef_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG__addRef_NUM])))
#define bHYPRE_BoomerAMG_PyType \
(*((bHYPRE_BoomerAMG_PyType_RETURN (*) \
bHYPRE_BoomerAMG_PyType_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG_PyType_NUM])))
#define bHYPRE_BoomerAMG__connectI \
(*((bHYPRE_BoomerAMG__connectI_RETURN (*) \
bHYPRE_BoomerAMG__connectI_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG__connectI_NUM])))
#define bHYPRE_BoomerAMG__rmicast \
(*((bHYPRE_BoomerAMG__rmicast_RETURN (*) \
bHYPRE_BoomerAMG__rmicast_PROTO) \
(bHYPRE_BoomerAMG__API \
[bHYPRE_BoomerAMG__rmicast_NUM])))
#ifdef HAVE_PTHREAD
#define bHYPRE_BoomerAMG__import() \
{ \
pthread_mutex_t __sidl_pyapi_mutex = PTHREAD_MUTEX_INITIALIZER; \
pthread_mutex_lock(&__sidl_pyapi_mutex); \
if (!bHYPRE_BoomerAMG__API) { \
PyObject *module = PyImport_ImportModule("bHYPRE.BoomerAMG"); \
if (module != NULL) { \
PyObject *module_dict = PyModule_GetDict(module); \
PyObject *c_api_object = \
PyDict_GetItemString(module_dict, "_C_API"); \
if (c_api_object && PyCObject_Check(c_api_object)) { \
bHYPRE_BoomerAMG__API = \
(void **)PyCObject_AsVoidPtr(c_api_object); \
} \
else { fprintf(stderr, "babel: bHYPRE_BoomerAMG__import failed to lookup _C_API (%p %p %s).\n", c_api_object, c_api_object ? c_api_object->ob_type : NULL, c_api_object ? c_api_object->ob_type->tp_name : ""); }\
Py_DECREF(module); \
} else { fprintf(stderr, "babel: bHYPRE_BoomerAMG__import failed to import its module.\n"); }\
}\
pthread_mutex_unlock(&__sidl_pyapi_mutex); \
pthread_mutex_destroy(&__sidl_pyapi_mutex); \
}
#else /* !HAVE_PTHREAD */
#define bHYPRE_BoomerAMG__import() \
if (!bHYPRE_BoomerAMG__API) { \
PyObject *module = PyImport_ImportModule("bHYPRE.BoomerAMG"); \
if (module != NULL) { \
PyObject *module_dict = PyModule_GetDict(module); \
PyObject *c_api_object = \
PyDict_GetItemString(module_dict, "_C_API"); \
if (c_api_object && PyCObject_Check(c_api_object)) { \
bHYPRE_BoomerAMG__API = \
(void **)PyCObject_AsVoidPtr(c_api_object); \
} \
else { fprintf(stderr, "babel: bHYPRE_BoomerAMG__import failed to lookup _C_API (%p %p %s).\n", c_api_object, c_api_object ? c_api_object->ob_type : NULL, c_api_object ? c_api_object->ob_type->tp_name : ""); }\
Py_DECREF(module); \
} else { fprintf(stderr, "babel: bHYPRE_BoomerAMG__import failed to import its module.\n"); }\
}
#endif /* HAVE_PTHREAD */
#endif
#ifdef __cplusplus
}
#endif
#endif
|
const jwt = require('jsonwebtoken');
const config = require('./config');
module.exports = async (ctx, next) => {
let url = ctx.request.url;
console.log('url =', url);
if (url.indexOf('login') === -1 && url.indexOf('register') === -1) {
console.log('check token');
// 检验是否存在 token
const authorization = ctx.get('Authorization');
if (authorization === '') {
ctx.status = 401;
ctx.body = {
msg: "no token"
};
return
}
const token = authorization.split(' ')[1];
// 检验 token 是否已过期
try {
await jwt.verify(token, config.key);
let decoded = jwt.decode(token);
ctx.username = decoded.username;
ctx.req.username = decoded.username;
console.log('decoded=', decoded);
} catch (err) {
ctx.status = 401;
ctx.body = {
msg: "invalid token"
};
return
}
}
await next()
};
|
import { randomInt } from 'crypto';
/**
*
* @param {*} min inclusive min
* @param {*} max
* @param {*} inclusive incusive or exclusive max
* @returns
*/
export function randomMath(min = 0, max = 0, inclusive = false) {
if (max === min) {
return max;
}
if (min > max) {
const temp = max;
max = min;
min = temp;
}
if (inclusive) {
max++;
}
return Math.floor(Math.random() * (max - min)) + min;
}
/**
*
* @param {*} min inclusive min
* @param {*} max
* @param {*} inclusive incusive or exclusive max
* @returns
*/
export function randomCrypto(min = 0, max = 0, inclusive = false) {
if (max === min) {
return max;
}
if (min > max) {
const temp = max;
max = min;
min = temp;
}
if (inclusive) {
max++;
}
return randomInt(min, max);
}
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Intel IXP4xx Ethernet driver for Linux
*
* Copyright (C) 2007 Krzysztof Halasa <khc@pm.waw.pl>
*
* Ethernet port config (0x00 is not present on IXP42X):
*
* logical port 0x00 0x10 0x20
* NPE 0 (NPE-A) 1 (NPE-B) 2 (NPE-C)
* physical PortId 2 0 1
* TX queue 23 24 25
* RX-free queue 26 27 28
* TX-done queue is always 31, per-port RX and TX-ready queues are configurable
*
* Queue entries:
* bits 0 -> 1 - NPE ID (RX and TX-done)
* bits 0 -> 2 - priority (TX, per 802.1D)
* bits 3 -> 4 - port ID (user-set?)
* bits 5 -> 31 - physical descriptor address
*/
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/etherdevice.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/net_tstamp.h>
#include <linux/of.h>
#include <linux/of_mdio.h>
#include <linux/phy.h>
#include <linux/platform_data/eth_ixp4xx.h>
#include <linux/platform_device.h>
#include <linux/ptp_classify.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/soc/ixp4xx/npe.h>
#include <linux/soc/ixp4xx/qmgr.h>
#include <linux/soc/ixp4xx/cpu.h>
#include "ixp46x_ts.h"
#define DEBUG_DESC 0
#define DEBUG_RX 0
#define DEBUG_TX 0
#define DEBUG_PKT_BYTES 0
#define DEBUG_MDIO 0
#define DEBUG_CLOSE 0
#define DRV_NAME "ixp4xx_eth"
#define MAX_NPES 3
#define RX_DESCS 64 /* also length of all RX queues */
#define TX_DESCS 16 /* also length of all TX queues */
#define TXDONE_QUEUE_LEN 64 /* dwords */
#define POOL_ALLOC_SIZE (sizeof(struct desc) * (RX_DESCS + TX_DESCS))
#define REGS_SIZE 0x1000
#define MAX_MRU 1536 /* 0x600 */
#define RX_BUFF_SIZE ALIGN((NET_IP_ALIGN) + MAX_MRU, 4)
#define NAPI_WEIGHT 16
#define MDIO_INTERVAL (3 * HZ)
#define MAX_MDIO_RETRIES 100 /* microseconds, typically 30 cycles */
#define MAX_CLOSE_WAIT 1000 /* microseconds, typically 2-3 cycles */
#define NPE_ID(port_id) ((port_id) >> 4)
#define PHYSICAL_ID(port_id) ((NPE_ID(port_id) + 2) % 3)
#define TX_QUEUE(port_id) (NPE_ID(port_id) + 23)
#define RXFREE_QUEUE(port_id) (NPE_ID(port_id) + 26)
#define TXDONE_QUEUE 31
#define PTP_SLAVE_MODE 1
#define PTP_MASTER_MODE 2
#define PORT2CHANNEL(p) NPE_ID(p->id)
/* TX Control Registers */
#define TX_CNTRL0_TX_EN 0x01
#define TX_CNTRL0_HALFDUPLEX 0x02
#define TX_CNTRL0_RETRY 0x04
#define TX_CNTRL0_PAD_EN 0x08
#define TX_CNTRL0_APPEND_FCS 0x10
#define TX_CNTRL0_2DEFER 0x20
#define TX_CNTRL0_RMII 0x40 /* reduced MII */
#define TX_CNTRL1_RETRIES 0x0F /* 4 bits */
/* RX Control Registers */
#define RX_CNTRL0_RX_EN 0x01
#define RX_CNTRL0_PADSTRIP_EN 0x02
#define RX_CNTRL0_SEND_FCS 0x04
#define RX_CNTRL0_PAUSE_EN 0x08
#define RX_CNTRL0_LOOP_EN 0x10
#define RX_CNTRL0_ADDR_FLTR_EN 0x20
#define RX_CNTRL0_RX_RUNT_EN 0x40
#define RX_CNTRL0_BCAST_DIS 0x80
#define RX_CNTRL1_DEFER_EN 0x01
/* Core Control Register */
#define CORE_RESET 0x01
#define CORE_RX_FIFO_FLUSH 0x02
#define CORE_TX_FIFO_FLUSH 0x04
#define CORE_SEND_JAM 0x08
#define CORE_MDC_EN 0x10 /* MDIO using NPE-B ETH-0 only */
#define DEFAULT_TX_CNTRL0 (TX_CNTRL0_TX_EN | TX_CNTRL0_RETRY | \
TX_CNTRL0_PAD_EN | TX_CNTRL0_APPEND_FCS | \
TX_CNTRL0_2DEFER)
#define DEFAULT_RX_CNTRL0 RX_CNTRL0_RX_EN
#define DEFAULT_CORE_CNTRL CORE_MDC_EN
/* NPE message codes */
#define NPE_GETSTATUS 0x00
#define NPE_EDB_SETPORTADDRESS 0x01
#define NPE_EDB_GETMACADDRESSDATABASE 0x02
#define NPE_EDB_SETMACADDRESSSDATABASE 0x03
#define NPE_GETSTATS 0x04
#define NPE_RESETSTATS 0x05
#define NPE_SETMAXFRAMELENGTHS 0x06
#define NPE_VLAN_SETRXTAGMODE 0x07
#define NPE_VLAN_SETDEFAULTRXVID 0x08
#define NPE_VLAN_SETPORTVLANTABLEENTRY 0x09
#define NPE_VLAN_SETPORTVLANTABLERANGE 0x0A
#define NPE_VLAN_SETRXQOSENTRY 0x0B
#define NPE_VLAN_SETPORTIDEXTRACTIONMODE 0x0C
#define NPE_STP_SETBLOCKINGSTATE 0x0D
#define NPE_FW_SETFIREWALLMODE 0x0E
#define NPE_PC_SETFRAMECONTROLDURATIONID 0x0F
#define NPE_PC_SETAPMACTABLE 0x11
#define NPE_SETLOOPBACK_MODE 0x12
#define NPE_PC_SETBSSIDTABLE 0x13
#define NPE_ADDRESS_FILTER_CONFIG 0x14
#define NPE_APPENDFCSCONFIG 0x15
#define NPE_NOTIFY_MAC_RECOVERY_DONE 0x16
#define NPE_MAC_RECOVERY_START 0x17
#ifdef __ARMEB__
typedef struct sk_buff buffer_t;
#define free_buffer dev_kfree_skb
#define free_buffer_irq dev_consume_skb_irq
#else
typedef void buffer_t;
#define free_buffer kfree
#define free_buffer_irq kfree
#endif
struct eth_regs {
u32 tx_control[2], __res1[2]; /* 000 */
u32 rx_control[2], __res2[2]; /* 010 */
u32 random_seed, __res3[3]; /* 020 */
u32 partial_empty_threshold, __res4; /* 030 */
u32 partial_full_threshold, __res5; /* 038 */
u32 tx_start_bytes, __res6[3]; /* 040 */
u32 tx_deferral, rx_deferral, __res7[2];/* 050 */
u32 tx_2part_deferral[2], __res8[2]; /* 060 */
u32 slot_time, __res9[3]; /* 070 */
u32 mdio_command[4]; /* 080 */
u32 mdio_status[4]; /* 090 */
u32 mcast_mask[6], __res10[2]; /* 0A0 */
u32 mcast_addr[6], __res11[2]; /* 0C0 */
u32 int_clock_threshold, __res12[3]; /* 0E0 */
u32 hw_addr[6], __res13[61]; /* 0F0 */
u32 core_control; /* 1FC */
};
struct port {
struct eth_regs __iomem *regs;
struct ixp46x_ts_regs __iomem *timesync_regs;
int phc_index;
struct npe *npe;
struct net_device *netdev;
struct napi_struct napi;
struct eth_plat_info *plat;
buffer_t *rx_buff_tab[RX_DESCS], *tx_buff_tab[TX_DESCS];
struct desc *desc_tab; /* coherent */
dma_addr_t desc_tab_phys;
int id; /* logical port ID */
int speed, duplex;
u8 firmware[4];
int hwts_tx_en;
int hwts_rx_en;
};
/* NPE message structure */
struct msg {
#ifdef __ARMEB__
u8 cmd, eth_id, byte2, byte3;
u8 byte4, byte5, byte6, byte7;
#else
u8 byte3, byte2, eth_id, cmd;
u8 byte7, byte6, byte5, byte4;
#endif
};
/* Ethernet packet descriptor */
struct desc {
u32 next; /* pointer to next buffer, unused */
#ifdef __ARMEB__
u16 buf_len; /* buffer length */
u16 pkt_len; /* packet length */
u32 data; /* pointer to data buffer in RAM */
u8 dest_id;
u8 src_id;
u16 flags;
u8 qos;
u8 padlen;
u16 vlan_tci;
#else
u16 pkt_len; /* packet length */
u16 buf_len; /* buffer length */
u32 data; /* pointer to data buffer in RAM */
u16 flags;
u8 src_id;
u8 dest_id;
u16 vlan_tci;
u8 padlen;
u8 qos;
#endif
#ifdef __ARMEB__
u8 dst_mac_0, dst_mac_1, dst_mac_2, dst_mac_3;
u8 dst_mac_4, dst_mac_5, src_mac_0, src_mac_1;
u8 src_mac_2, src_mac_3, src_mac_4, src_mac_5;
#else
u8 dst_mac_3, dst_mac_2, dst_mac_1, dst_mac_0;
u8 src_mac_1, src_mac_0, dst_mac_5, dst_mac_4;
u8 src_mac_5, src_mac_4, src_mac_3, src_mac_2;
#endif
};
#define rx_desc_phys(port, n) ((port)->desc_tab_phys + \
(n) * sizeof(struct desc))
#define rx_desc_ptr(port, n) (&(port)->desc_tab[n])
#define tx_desc_phys(port, n) ((port)->desc_tab_phys + \
((n) + RX_DESCS) * sizeof(struct desc))
#define tx_desc_ptr(port, n) (&(port)->desc_tab[(n) + RX_DESCS])
#ifndef __ARMEB__
static inline void memcpy_swab32(u32 *dest, u32 *src, int cnt)
{
int i;
for (i = 0; i < cnt; i++)
dest[i] = swab32(src[i]);
}
#endif
static DEFINE_SPINLOCK(mdio_lock);
static struct eth_regs __iomem *mdio_regs; /* mdio command and status only */
static struct mii_bus *mdio_bus;
static struct device_node *mdio_bus_np;
static int ports_open;
static struct port *npe_port_tab[MAX_NPES];
static struct dma_pool *dma_pool;
static int ixp_ptp_match(struct sk_buff *skb, u16 uid_hi, u32 uid_lo, u16 seqid)
{
u8 *data = skb->data;
unsigned int offset;
u16 *hi, *id;
u32 lo;
if (ptp_classify_raw(skb) != PTP_CLASS_V1_IPV4)
return 0;
offset = ETH_HLEN + IPV4_HLEN(data) + UDP_HLEN;
if (skb->len < offset + OFF_PTP_SEQUENCE_ID + sizeof(seqid))
return 0;
hi = (u16 *)(data + offset + OFF_PTP_SOURCE_UUID);
id = (u16 *)(data + offset + OFF_PTP_SEQUENCE_ID);
memcpy(&lo, &hi[1], sizeof(lo));
return (uid_hi == ntohs(*hi) &&
uid_lo == ntohl(lo) &&
seqid == ntohs(*id));
}
static void ixp_rx_timestamp(struct port *port, struct sk_buff *skb)
{
struct skb_shared_hwtstamps *shhwtstamps;
struct ixp46x_ts_regs *regs;
u64 ns;
u32 ch, hi, lo, val;
u16 uid, seq;
if (!port->hwts_rx_en)
return;
ch = PORT2CHANNEL(port);
regs = port->timesync_regs;
val = __raw_readl(®s->channel[ch].ch_event);
if (!(val & RX_SNAPSHOT_LOCKED))
return;
lo = __raw_readl(®s->channel[ch].src_uuid_lo);
hi = __raw_readl(®s->channel[ch].src_uuid_hi);
uid = hi & 0xffff;
seq = (hi >> 16) & 0xffff;
if (!ixp_ptp_match(skb, htons(uid), htonl(lo), htons(seq)))
goto out;
lo = __raw_readl(®s->channel[ch].rx_snap_lo);
hi = __raw_readl(®s->channel[ch].rx_snap_hi);
ns = ((u64) hi) << 32;
ns |= lo;
ns <<= TICKS_NS_SHIFT;
shhwtstamps = skb_hwtstamps(skb);
memset(shhwtstamps, 0, sizeof(*shhwtstamps));
shhwtstamps->hwtstamp = ns_to_ktime(ns);
out:
__raw_writel(RX_SNAPSHOT_LOCKED, ®s->channel[ch].ch_event);
}
static void ixp_tx_timestamp(struct port *port, struct sk_buff *skb)
{
struct skb_shared_hwtstamps shhwtstamps;
struct ixp46x_ts_regs *regs;
struct skb_shared_info *shtx;
u64 ns;
u32 ch, cnt, hi, lo, val;
shtx = skb_shinfo(skb);
if (unlikely(shtx->tx_flags & SKBTX_HW_TSTAMP && port->hwts_tx_en))
shtx->tx_flags |= SKBTX_IN_PROGRESS;
else
return;
ch = PORT2CHANNEL(port);
regs = port->timesync_regs;
/*
* This really stinks, but we have to poll for the Tx time stamp.
* Usually, the time stamp is ready after 4 to 6 microseconds.
*/
for (cnt = 0; cnt < 100; cnt++) {
val = __raw_readl(®s->channel[ch].ch_event);
if (val & TX_SNAPSHOT_LOCKED)
break;
udelay(1);
}
if (!(val & TX_SNAPSHOT_LOCKED)) {
shtx->tx_flags &= ~SKBTX_IN_PROGRESS;
return;
}
lo = __raw_readl(®s->channel[ch].tx_snap_lo);
hi = __raw_readl(®s->channel[ch].tx_snap_hi);
ns = ((u64) hi) << 32;
ns |= lo;
ns <<= TICKS_NS_SHIFT;
memset(&shhwtstamps, 0, sizeof(shhwtstamps));
shhwtstamps.hwtstamp = ns_to_ktime(ns);
skb_tstamp_tx(skb, &shhwtstamps);
__raw_writel(TX_SNAPSHOT_LOCKED, ®s->channel[ch].ch_event);
}
static int hwtstamp_set(struct net_device *netdev, struct ifreq *ifr)
{
struct hwtstamp_config cfg;
struct ixp46x_ts_regs *regs;
struct port *port = netdev_priv(netdev);
int ret;
int ch;
if (copy_from_user(&cfg, ifr->ifr_data, sizeof(cfg)))
return -EFAULT;
if (cfg.flags) /* reserved for future extensions */
return -EINVAL;
ret = ixp46x_ptp_find(&port->timesync_regs, &port->phc_index);
if (ret)
return ret;
ch = PORT2CHANNEL(port);
regs = port->timesync_regs;
if (cfg.tx_type != HWTSTAMP_TX_OFF && cfg.tx_type != HWTSTAMP_TX_ON)
return -ERANGE;
switch (cfg.rx_filter) {
case HWTSTAMP_FILTER_NONE:
port->hwts_rx_en = 0;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
port->hwts_rx_en = PTP_SLAVE_MODE;
__raw_writel(0, ®s->channel[ch].ch_control);
break;
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
port->hwts_rx_en = PTP_MASTER_MODE;
__raw_writel(MASTER_MODE, ®s->channel[ch].ch_control);
break;
default:
return -ERANGE;
}
port->hwts_tx_en = cfg.tx_type == HWTSTAMP_TX_ON;
/* Clear out any old time stamps. */
__raw_writel(TX_SNAPSHOT_LOCKED | RX_SNAPSHOT_LOCKED,
®s->channel[ch].ch_event);
return copy_to_user(ifr->ifr_data, &cfg, sizeof(cfg)) ? -EFAULT : 0;
}
static int hwtstamp_get(struct net_device *netdev, struct ifreq *ifr)
{
struct hwtstamp_config cfg;
struct port *port = netdev_priv(netdev);
cfg.flags = 0;
cfg.tx_type = port->hwts_tx_en ? HWTSTAMP_TX_ON : HWTSTAMP_TX_OFF;
switch (port->hwts_rx_en) {
case 0:
cfg.rx_filter = HWTSTAMP_FILTER_NONE;
break;
case PTP_SLAVE_MODE:
cfg.rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_SYNC;
break;
case PTP_MASTER_MODE:
cfg.rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ;
break;
default:
WARN_ON_ONCE(1);
return -ERANGE;
}
return copy_to_user(ifr->ifr_data, &cfg, sizeof(cfg)) ? -EFAULT : 0;
}
static int ixp4xx_mdio_cmd(struct mii_bus *bus, int phy_id, int location,
int write, u16 cmd)
{
int cycles = 0;
if (__raw_readl(&mdio_regs->mdio_command[3]) & 0x80) {
printk(KERN_ERR "%s: MII not ready to transmit\n", bus->name);
return -1;
}
if (write) {
__raw_writel(cmd & 0xFF, &mdio_regs->mdio_command[0]);
__raw_writel(cmd >> 8, &mdio_regs->mdio_command[1]);
}
__raw_writel(((phy_id << 5) | location) & 0xFF,
&mdio_regs->mdio_command[2]);
__raw_writel((phy_id >> 3) | (write << 2) | 0x80 /* GO */,
&mdio_regs->mdio_command[3]);
while ((cycles < MAX_MDIO_RETRIES) &&
(__raw_readl(&mdio_regs->mdio_command[3]) & 0x80)) {
udelay(1);
cycles++;
}
if (cycles == MAX_MDIO_RETRIES) {
printk(KERN_ERR "%s #%i: MII write failed\n", bus->name,
phy_id);
return -1;
}
#if DEBUG_MDIO
printk(KERN_DEBUG "%s #%i: mdio_%s() took %i cycles\n", bus->name,
phy_id, write ? "write" : "read", cycles);
#endif
if (write)
return 0;
if (__raw_readl(&mdio_regs->mdio_status[3]) & 0x80) {
#if DEBUG_MDIO
printk(KERN_DEBUG "%s #%i: MII read failed\n", bus->name,
phy_id);
#endif
return 0xFFFF; /* don't return error */
}
return (__raw_readl(&mdio_regs->mdio_status[0]) & 0xFF) |
((__raw_readl(&mdio_regs->mdio_status[1]) & 0xFF) << 8);
}
static int ixp4xx_mdio_read(struct mii_bus *bus, int phy_id, int location)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&mdio_lock, flags);
ret = ixp4xx_mdio_cmd(bus, phy_id, location, 0, 0);
spin_unlock_irqrestore(&mdio_lock, flags);
#if DEBUG_MDIO
printk(KERN_DEBUG "%s #%i: MII read [%i] -> 0x%X\n", bus->name,
phy_id, location, ret);
#endif
return ret;
}
static int ixp4xx_mdio_write(struct mii_bus *bus, int phy_id, int location,
u16 val)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&mdio_lock, flags);
ret = ixp4xx_mdio_cmd(bus, phy_id, location, 1, val);
spin_unlock_irqrestore(&mdio_lock, flags);
#if DEBUG_MDIO
printk(KERN_DEBUG "%s #%i: MII write [%i] <- 0x%X, err = %i\n",
bus->name, phy_id, location, val, ret);
#endif
return ret;
}
static int ixp4xx_mdio_register(struct eth_regs __iomem *regs)
{
int err;
if (!(mdio_bus = mdiobus_alloc()))
return -ENOMEM;
mdio_regs = regs;
__raw_writel(DEFAULT_CORE_CNTRL, &mdio_regs->core_control);
mdio_bus->name = "IXP4xx MII Bus";
mdio_bus->read = &ixp4xx_mdio_read;
mdio_bus->write = &ixp4xx_mdio_write;
snprintf(mdio_bus->id, MII_BUS_ID_SIZE, "ixp4xx-eth-0");
err = of_mdiobus_register(mdio_bus, mdio_bus_np);
if (err)
mdiobus_free(mdio_bus);
return err;
}
static void ixp4xx_mdio_remove(void)
{
mdiobus_unregister(mdio_bus);
mdiobus_free(mdio_bus);
}
static void ixp4xx_adjust_link(struct net_device *dev)
{
struct port *port = netdev_priv(dev);
struct phy_device *phydev = dev->phydev;
if (!phydev->link) {
if (port->speed) {
port->speed = 0;
printk(KERN_INFO "%s: link down\n", dev->name);
}
return;
}
if (port->speed == phydev->speed && port->duplex == phydev->duplex)
return;
port->speed = phydev->speed;
port->duplex = phydev->duplex;
if (port->duplex)
__raw_writel(DEFAULT_TX_CNTRL0 & ~TX_CNTRL0_HALFDUPLEX,
&port->regs->tx_control[0]);
else
__raw_writel(DEFAULT_TX_CNTRL0 | TX_CNTRL0_HALFDUPLEX,
&port->regs->tx_control[0]);
netdev_info(dev, "%s: link up, speed %u Mb/s, %s duplex\n",
dev->name, port->speed, port->duplex ? "full" : "half");
}
static inline void debug_pkt(struct net_device *dev, const char *func,
u8 *data, int len)
{
#if DEBUG_PKT_BYTES
int i;
netdev_debug(dev, "%s(%i) ", func, len);
for (i = 0; i < len; i++) {
if (i >= DEBUG_PKT_BYTES)
break;
printk("%s%02X",
((i == 6) || (i == 12) || (i >= 14)) ? " " : "",
data[i]);
}
printk("\n");
#endif
}
static inline void debug_desc(u32 phys, struct desc *desc)
{
#if DEBUG_DESC
printk(KERN_DEBUG "%X: %X %3X %3X %08X %2X < %2X %4X %X"
" %X %X %02X%02X%02X%02X%02X%02X < %02X%02X%02X%02X%02X%02X\n",
phys, desc->next, desc->buf_len, desc->pkt_len,
desc->data, desc->dest_id, desc->src_id, desc->flags,
desc->qos, desc->padlen, desc->vlan_tci,
desc->dst_mac_0, desc->dst_mac_1, desc->dst_mac_2,
desc->dst_mac_3, desc->dst_mac_4, desc->dst_mac_5,
desc->src_mac_0, desc->src_mac_1, desc->src_mac_2,
desc->src_mac_3, desc->src_mac_4, desc->src_mac_5);
#endif
}
static inline int queue_get_desc(unsigned int queue, struct port *port,
int is_tx)
{
u32 phys, tab_phys, n_desc;
struct desc *tab;
if (!(phys = qmgr_get_entry(queue)))
return -1;
phys &= ~0x1F; /* mask out non-address bits */
tab_phys = is_tx ? tx_desc_phys(port, 0) : rx_desc_phys(port, 0);
tab = is_tx ? tx_desc_ptr(port, 0) : rx_desc_ptr(port, 0);
n_desc = (phys - tab_phys) / sizeof(struct desc);
BUG_ON(n_desc >= (is_tx ? TX_DESCS : RX_DESCS));
debug_desc(phys, &tab[n_desc]);
BUG_ON(tab[n_desc].next);
return n_desc;
}
static inline void queue_put_desc(unsigned int queue, u32 phys,
struct desc *desc)
{
debug_desc(phys, desc);
BUG_ON(phys & 0x1F);
qmgr_put_entry(queue, phys);
/* Don't check for queue overflow here, we've allocated sufficient
length and queues >= 32 don't support this check anyway. */
}
static inline void dma_unmap_tx(struct port *port, struct desc *desc)
{
#ifdef __ARMEB__
dma_unmap_single(&port->netdev->dev, desc->data,
desc->buf_len, DMA_TO_DEVICE);
#else
dma_unmap_single(&port->netdev->dev, desc->data & ~3,
ALIGN((desc->data & 3) + desc->buf_len, 4),
DMA_TO_DEVICE);
#endif
}
static void eth_rx_irq(void *pdev)
{
struct net_device *dev = pdev;
struct port *port = netdev_priv(dev);
#if DEBUG_RX
printk(KERN_DEBUG "%s: eth_rx_irq\n", dev->name);
#endif
qmgr_disable_irq(port->plat->rxq);
napi_schedule(&port->napi);
}
static int eth_poll(struct napi_struct *napi, int budget)
{
struct port *port = container_of(napi, struct port, napi);
struct net_device *dev = port->netdev;
unsigned int rxq = port->plat->rxq, rxfreeq = RXFREE_QUEUE(port->id);
int received = 0;
#if DEBUG_RX
netdev_debug(dev, "eth_poll\n");
#endif
while (received < budget) {
struct sk_buff *skb;
struct desc *desc;
int n;
#ifdef __ARMEB__
struct sk_buff *temp;
u32 phys;
#endif
if ((n = queue_get_desc(rxq, port, 0)) < 0) {
#if DEBUG_RX
netdev_debug(dev, "eth_poll napi_complete\n");
#endif
napi_complete(napi);
qmgr_enable_irq(rxq);
if (!qmgr_stat_below_low_watermark(rxq) &&
napi_reschedule(napi)) { /* not empty again */
#if DEBUG_RX
netdev_debug(dev, "eth_poll napi_reschedule succeeded\n");
#endif
qmgr_disable_irq(rxq);
continue;
}
#if DEBUG_RX
netdev_debug(dev, "eth_poll all done\n");
#endif
return received; /* all work done */
}
desc = rx_desc_ptr(port, n);
#ifdef __ARMEB__
if ((skb = netdev_alloc_skb(dev, RX_BUFF_SIZE))) {
phys = dma_map_single(&dev->dev, skb->data,
RX_BUFF_SIZE, DMA_FROM_DEVICE);
if (dma_mapping_error(&dev->dev, phys)) {
dev_kfree_skb(skb);
skb = NULL;
}
}
#else
skb = netdev_alloc_skb(dev,
ALIGN(NET_IP_ALIGN + desc->pkt_len, 4));
#endif
if (!skb) {
dev->stats.rx_dropped++;
/* put the desc back on RX-ready queue */
desc->buf_len = MAX_MRU;
desc->pkt_len = 0;
queue_put_desc(rxfreeq, rx_desc_phys(port, n), desc);
continue;
}
/* process received frame */
#ifdef __ARMEB__
temp = skb;
skb = port->rx_buff_tab[n];
dma_unmap_single(&dev->dev, desc->data - NET_IP_ALIGN,
RX_BUFF_SIZE, DMA_FROM_DEVICE);
#else
dma_sync_single_for_cpu(&dev->dev, desc->data - NET_IP_ALIGN,
RX_BUFF_SIZE, DMA_FROM_DEVICE);
memcpy_swab32((u32 *)skb->data, (u32 *)port->rx_buff_tab[n],
ALIGN(NET_IP_ALIGN + desc->pkt_len, 4) / 4);
#endif
skb_reserve(skb, NET_IP_ALIGN);
skb_put(skb, desc->pkt_len);
debug_pkt(dev, "eth_poll", skb->data, skb->len);
ixp_rx_timestamp(port, skb);
skb->protocol = eth_type_trans(skb, dev);
dev->stats.rx_packets++;
dev->stats.rx_bytes += skb->len;
netif_receive_skb(skb);
/* put the new buffer on RX-free queue */
#ifdef __ARMEB__
port->rx_buff_tab[n] = temp;
desc->data = phys + NET_IP_ALIGN;
#endif
desc->buf_len = MAX_MRU;
desc->pkt_len = 0;
queue_put_desc(rxfreeq, rx_desc_phys(port, n), desc);
received++;
}
#if DEBUG_RX
netdev_debug(dev, "eth_poll(): end, not all work done\n");
#endif
return received; /* not all work done */
}
static void eth_txdone_irq(void *unused)
{
u32 phys;
#if DEBUG_TX
printk(KERN_DEBUG DRV_NAME ": eth_txdone_irq\n");
#endif
while ((phys = qmgr_get_entry(TXDONE_QUEUE)) != 0) {
u32 npe_id, n_desc;
struct port *port;
struct desc *desc;
int start;
npe_id = phys & 3;
BUG_ON(npe_id >= MAX_NPES);
port = npe_port_tab[npe_id];
BUG_ON(!port);
phys &= ~0x1F; /* mask out non-address bits */
n_desc = (phys - tx_desc_phys(port, 0)) / sizeof(struct desc);
BUG_ON(n_desc >= TX_DESCS);
desc = tx_desc_ptr(port, n_desc);
debug_desc(phys, desc);
if (port->tx_buff_tab[n_desc]) { /* not the draining packet */
port->netdev->stats.tx_packets++;
port->netdev->stats.tx_bytes += desc->pkt_len;
dma_unmap_tx(port, desc);
#if DEBUG_TX
printk(KERN_DEBUG "%s: eth_txdone_irq free %p\n",
port->netdev->name, port->tx_buff_tab[n_desc]);
#endif
free_buffer_irq(port->tx_buff_tab[n_desc]);
port->tx_buff_tab[n_desc] = NULL;
}
start = qmgr_stat_below_low_watermark(port->plat->txreadyq);
queue_put_desc(port->plat->txreadyq, phys, desc);
if (start) { /* TX-ready queue was empty */
#if DEBUG_TX
printk(KERN_DEBUG "%s: eth_txdone_irq xmit ready\n",
port->netdev->name);
#endif
netif_wake_queue(port->netdev);
}
}
}
static int eth_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct port *port = netdev_priv(dev);
unsigned int txreadyq = port->plat->txreadyq;
int len, offset, bytes, n;
void *mem;
u32 phys;
struct desc *desc;
#if DEBUG_TX
netdev_debug(dev, "eth_xmit\n");
#endif
if (unlikely(skb->len > MAX_MRU)) {
dev_kfree_skb(skb);
dev->stats.tx_errors++;
return NETDEV_TX_OK;
}
debug_pkt(dev, "eth_xmit", skb->data, skb->len);
len = skb->len;
#ifdef __ARMEB__
offset = 0; /* no need to keep alignment */
bytes = len;
mem = skb->data;
#else
offset = (uintptr_t)skb->data & 3; /* keep 32-bit alignment */
bytes = ALIGN(offset + len, 4);
if (!(mem = kmalloc(bytes, GFP_ATOMIC))) {
dev_kfree_skb(skb);
dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
memcpy_swab32(mem, (u32 *)((uintptr_t)skb->data & ~3), bytes / 4);
#endif
phys = dma_map_single(&dev->dev, mem, bytes, DMA_TO_DEVICE);
if (dma_mapping_error(&dev->dev, phys)) {
dev_kfree_skb(skb);
#ifndef __ARMEB__
kfree(mem);
#endif
dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
n = queue_get_desc(txreadyq, port, 1);
BUG_ON(n < 0);
desc = tx_desc_ptr(port, n);
#ifdef __ARMEB__
port->tx_buff_tab[n] = skb;
#else
port->tx_buff_tab[n] = mem;
#endif
desc->data = phys + offset;
desc->buf_len = desc->pkt_len = len;
/* NPE firmware pads short frames with zeros internally */
wmb();
queue_put_desc(TX_QUEUE(port->id), tx_desc_phys(port, n), desc);
if (qmgr_stat_below_low_watermark(txreadyq)) { /* empty */
#if DEBUG_TX
netdev_debug(dev, "eth_xmit queue full\n");
#endif
netif_stop_queue(dev);
/* we could miss TX ready interrupt */
/* really empty in fact */
if (!qmgr_stat_below_low_watermark(txreadyq)) {
#if DEBUG_TX
netdev_debug(dev, "eth_xmit ready again\n");
#endif
netif_wake_queue(dev);
}
}
#if DEBUG_TX
netdev_debug(dev, "eth_xmit end\n");
#endif
ixp_tx_timestamp(port, skb);
skb_tx_timestamp(skb);
#ifndef __ARMEB__
dev_kfree_skb(skb);
#endif
return NETDEV_TX_OK;
}
static void eth_set_mcast_list(struct net_device *dev)
{
struct port *port = netdev_priv(dev);
struct netdev_hw_addr *ha;
u8 diffs[ETH_ALEN], *addr;
int i;
static const u8 allmulti[] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };
if ((dev->flags & IFF_ALLMULTI) && !(dev->flags & IFF_PROMISC)) {
for (i = 0; i < ETH_ALEN; i++) {
__raw_writel(allmulti[i], &port->regs->mcast_addr[i]);
__raw_writel(allmulti[i], &port->regs->mcast_mask[i]);
}
__raw_writel(DEFAULT_RX_CNTRL0 | RX_CNTRL0_ADDR_FLTR_EN,
&port->regs->rx_control[0]);
return;
}
if ((dev->flags & IFF_PROMISC) || netdev_mc_empty(dev)) {
__raw_writel(DEFAULT_RX_CNTRL0 & ~RX_CNTRL0_ADDR_FLTR_EN,
&port->regs->rx_control[0]);
return;
}
eth_zero_addr(diffs);
addr = NULL;
netdev_for_each_mc_addr(ha, dev) {
if (!addr)
addr = ha->addr; /* first MAC address */
for (i = 0; i < ETH_ALEN; i++)
diffs[i] |= addr[i] ^ ha->addr[i];
}
for (i = 0; i < ETH_ALEN; i++) {
__raw_writel(addr[i], &port->regs->mcast_addr[i]);
__raw_writel(~diffs[i], &port->regs->mcast_mask[i]);
}
__raw_writel(DEFAULT_RX_CNTRL0 | RX_CNTRL0_ADDR_FLTR_EN,
&port->regs->rx_control[0]);
}
static int eth_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
if (!netif_running(dev))
return -EINVAL;
if (cpu_is_ixp46x()) {
if (cmd == SIOCSHWTSTAMP)
return hwtstamp_set(dev, req);
if (cmd == SIOCGHWTSTAMP)
return hwtstamp_get(dev, req);
}
return phy_mii_ioctl(dev->phydev, req, cmd);
}
/* ethtool support */
static void ixp4xx_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct port *port = netdev_priv(dev);
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
snprintf(info->fw_version, sizeof(info->fw_version), "%u:%u:%u:%u",
port->firmware[0], port->firmware[1],
port->firmware[2], port->firmware[3]);
strlcpy(info->bus_info, "internal", sizeof(info->bus_info));
}
static int ixp4xx_get_ts_info(struct net_device *dev,
struct ethtool_ts_info *info)
{
struct port *port = netdev_priv(dev);
if (port->phc_index < 0)
ixp46x_ptp_find(&port->timesync_regs, &port->phc_index);
info->phc_index = port->phc_index;
if (info->phc_index < 0) {
info->so_timestamping =
SOF_TIMESTAMPING_TX_SOFTWARE |
SOF_TIMESTAMPING_RX_SOFTWARE |
SOF_TIMESTAMPING_SOFTWARE;
return 0;
}
info->so_timestamping =
SOF_TIMESTAMPING_TX_HARDWARE |
SOF_TIMESTAMPING_RX_HARDWARE |
SOF_TIMESTAMPING_RAW_HARDWARE;
info->tx_types =
(1 << HWTSTAMP_TX_OFF) |
(1 << HWTSTAMP_TX_ON);
info->rx_filters =
(1 << HWTSTAMP_FILTER_NONE) |
(1 << HWTSTAMP_FILTER_PTP_V1_L4_SYNC) |
(1 << HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ);
return 0;
}
static const struct ethtool_ops ixp4xx_ethtool_ops = {
.get_drvinfo = ixp4xx_get_drvinfo,
.nway_reset = phy_ethtool_nway_reset,
.get_link = ethtool_op_get_link,
.get_ts_info = ixp4xx_get_ts_info,
.get_link_ksettings = phy_ethtool_get_link_ksettings,
.set_link_ksettings = phy_ethtool_set_link_ksettings,
};
static int request_queues(struct port *port)
{
int err;
err = qmgr_request_queue(RXFREE_QUEUE(port->id), RX_DESCS, 0, 0,
"%s:RX-free", port->netdev->name);
if (err)
return err;
err = qmgr_request_queue(port->plat->rxq, RX_DESCS, 0, 0,
"%s:RX", port->netdev->name);
if (err)
goto rel_rxfree;
err = qmgr_request_queue(TX_QUEUE(port->id), TX_DESCS, 0, 0,
"%s:TX", port->netdev->name);
if (err)
goto rel_rx;
err = qmgr_request_queue(port->plat->txreadyq, TX_DESCS, 0, 0,
"%s:TX-ready", port->netdev->name);
if (err)
goto rel_tx;
/* TX-done queue handles skbs sent out by the NPEs */
if (!ports_open) {
err = qmgr_request_queue(TXDONE_QUEUE, TXDONE_QUEUE_LEN, 0, 0,
"%s:TX-done", DRV_NAME);
if (err)
goto rel_txready;
}
return 0;
rel_txready:
qmgr_release_queue(port->plat->txreadyq);
rel_tx:
qmgr_release_queue(TX_QUEUE(port->id));
rel_rx:
qmgr_release_queue(port->plat->rxq);
rel_rxfree:
qmgr_release_queue(RXFREE_QUEUE(port->id));
printk(KERN_DEBUG "%s: unable to request hardware queues\n",
port->netdev->name);
return err;
}
static void release_queues(struct port *port)
{
qmgr_release_queue(RXFREE_QUEUE(port->id));
qmgr_release_queue(port->plat->rxq);
qmgr_release_queue(TX_QUEUE(port->id));
qmgr_release_queue(port->plat->txreadyq);
if (!ports_open)
qmgr_release_queue(TXDONE_QUEUE);
}
static int init_queues(struct port *port)
{
int i;
if (!ports_open) {
dma_pool = dma_pool_create(DRV_NAME, &port->netdev->dev,
POOL_ALLOC_SIZE, 32, 0);
if (!dma_pool)
return -ENOMEM;
}
port->desc_tab = dma_pool_zalloc(dma_pool, GFP_KERNEL, &port->desc_tab_phys);
if (!port->desc_tab)
return -ENOMEM;
memset(port->rx_buff_tab, 0, sizeof(port->rx_buff_tab)); /* tables */
memset(port->tx_buff_tab, 0, sizeof(port->tx_buff_tab));
/* Setup RX buffers */
for (i = 0; i < RX_DESCS; i++) {
struct desc *desc = rx_desc_ptr(port, i);
buffer_t *buff; /* skb or kmalloc()ated memory */
void *data;
#ifdef __ARMEB__
if (!(buff = netdev_alloc_skb(port->netdev, RX_BUFF_SIZE)))
return -ENOMEM;
data = buff->data;
#else
if (!(buff = kmalloc(RX_BUFF_SIZE, GFP_KERNEL)))
return -ENOMEM;
data = buff;
#endif
desc->buf_len = MAX_MRU;
desc->data = dma_map_single(&port->netdev->dev, data,
RX_BUFF_SIZE, DMA_FROM_DEVICE);
if (dma_mapping_error(&port->netdev->dev, desc->data)) {
free_buffer(buff);
return -EIO;
}
desc->data += NET_IP_ALIGN;
port->rx_buff_tab[i] = buff;
}
return 0;
}
static void destroy_queues(struct port *port)
{
int i;
if (port->desc_tab) {
for (i = 0; i < RX_DESCS; i++) {
struct desc *desc = rx_desc_ptr(port, i);
buffer_t *buff = port->rx_buff_tab[i];
if (buff) {
dma_unmap_single(&port->netdev->dev,
desc->data - NET_IP_ALIGN,
RX_BUFF_SIZE, DMA_FROM_DEVICE);
free_buffer(buff);
}
}
for (i = 0; i < TX_DESCS; i++) {
struct desc *desc = tx_desc_ptr(port, i);
buffer_t *buff = port->tx_buff_tab[i];
if (buff) {
dma_unmap_tx(port, desc);
free_buffer(buff);
}
}
dma_pool_free(dma_pool, port->desc_tab, port->desc_tab_phys);
port->desc_tab = NULL;
}
if (!ports_open && dma_pool) {
dma_pool_destroy(dma_pool);
dma_pool = NULL;
}
}
static int eth_open(struct net_device *dev)
{
struct port *port = netdev_priv(dev);
struct npe *npe = port->npe;
struct msg msg;
int i, err;
if (!npe_running(npe)) {
err = npe_load_firmware(npe, npe_name(npe), &dev->dev);
if (err)
return err;
if (npe_recv_message(npe, &msg, "ETH_GET_STATUS")) {
netdev_err(dev, "%s not responding\n", npe_name(npe));
return -EIO;
}
port->firmware[0] = msg.byte4;
port->firmware[1] = msg.byte5;
port->firmware[2] = msg.byte6;
port->firmware[3] = msg.byte7;
}
memset(&msg, 0, sizeof(msg));
msg.cmd = NPE_VLAN_SETRXQOSENTRY;
msg.eth_id = port->id;
msg.byte5 = port->plat->rxq | 0x80;
msg.byte7 = port->plat->rxq << 4;
for (i = 0; i < 8; i++) {
msg.byte3 = i;
if (npe_send_recv_message(port->npe, &msg, "ETH_SET_RXQ"))
return -EIO;
}
msg.cmd = NPE_EDB_SETPORTADDRESS;
msg.eth_id = PHYSICAL_ID(port->id);
msg.byte2 = dev->dev_addr[0];
msg.byte3 = dev->dev_addr[1];
msg.byte4 = dev->dev_addr[2];
msg.byte5 = dev->dev_addr[3];
msg.byte6 = dev->dev_addr[4];
msg.byte7 = dev->dev_addr[5];
if (npe_send_recv_message(port->npe, &msg, "ETH_SET_MAC"))
return -EIO;
memset(&msg, 0, sizeof(msg));
msg.cmd = NPE_FW_SETFIREWALLMODE;
msg.eth_id = port->id;
if (npe_send_recv_message(port->npe, &msg, "ETH_SET_FIREWALL_MODE"))
return -EIO;
if ((err = request_queues(port)) != 0)
return err;
if ((err = init_queues(port)) != 0) {
destroy_queues(port);
release_queues(port);
return err;
}
port->speed = 0; /* force "link up" message */
phy_start(dev->phydev);
for (i = 0; i < ETH_ALEN; i++)
__raw_writel(dev->dev_addr[i], &port->regs->hw_addr[i]);
__raw_writel(0x08, &port->regs->random_seed);
__raw_writel(0x12, &port->regs->partial_empty_threshold);
__raw_writel(0x30, &port->regs->partial_full_threshold);
__raw_writel(0x08, &port->regs->tx_start_bytes);
__raw_writel(0x15, &port->regs->tx_deferral);
__raw_writel(0x08, &port->regs->tx_2part_deferral[0]);
__raw_writel(0x07, &port->regs->tx_2part_deferral[1]);
__raw_writel(0x80, &port->regs->slot_time);
__raw_writel(0x01, &port->regs->int_clock_threshold);
/* Populate queues with buffers, no failure after this point */
for (i = 0; i < TX_DESCS; i++)
queue_put_desc(port->plat->txreadyq,
tx_desc_phys(port, i), tx_desc_ptr(port, i));
for (i = 0; i < RX_DESCS; i++)
queue_put_desc(RXFREE_QUEUE(port->id),
rx_desc_phys(port, i), rx_desc_ptr(port, i));
__raw_writel(TX_CNTRL1_RETRIES, &port->regs->tx_control[1]);
__raw_writel(DEFAULT_TX_CNTRL0, &port->regs->tx_control[0]);
__raw_writel(0, &port->regs->rx_control[1]);
__raw_writel(DEFAULT_RX_CNTRL0, &port->regs->rx_control[0]);
napi_enable(&port->napi);
eth_set_mcast_list(dev);
netif_start_queue(dev);
qmgr_set_irq(port->plat->rxq, QUEUE_IRQ_SRC_NOT_EMPTY,
eth_rx_irq, dev);
if (!ports_open) {
qmgr_set_irq(TXDONE_QUEUE, QUEUE_IRQ_SRC_NOT_EMPTY,
eth_txdone_irq, NULL);
qmgr_enable_irq(TXDONE_QUEUE);
}
ports_open++;
/* we may already have RX data, enables IRQ */
napi_schedule(&port->napi);
return 0;
}
static int eth_close(struct net_device *dev)
{
struct port *port = netdev_priv(dev);
struct msg msg;
int buffs = RX_DESCS; /* allocated RX buffers */
int i;
ports_open--;
qmgr_disable_irq(port->plat->rxq);
napi_disable(&port->napi);
netif_stop_queue(dev);
while (queue_get_desc(RXFREE_QUEUE(port->id), port, 0) >= 0)
buffs--;
memset(&msg, 0, sizeof(msg));
msg.cmd = NPE_SETLOOPBACK_MODE;
msg.eth_id = port->id;
msg.byte3 = 1;
if (npe_send_recv_message(port->npe, &msg, "ETH_ENABLE_LOOPBACK"))
netdev_crit(dev, "unable to enable loopback\n");
i = 0;
do { /* drain RX buffers */
while (queue_get_desc(port->plat->rxq, port, 0) >= 0)
buffs--;
if (!buffs)
break;
if (qmgr_stat_empty(TX_QUEUE(port->id))) {
/* we have to inject some packet */
struct desc *desc;
u32 phys;
int n = queue_get_desc(port->plat->txreadyq, port, 1);
BUG_ON(n < 0);
desc = tx_desc_ptr(port, n);
phys = tx_desc_phys(port, n);
desc->buf_len = desc->pkt_len = 1;
wmb();
queue_put_desc(TX_QUEUE(port->id), phys, desc);
}
udelay(1);
} while (++i < MAX_CLOSE_WAIT);
if (buffs)
netdev_crit(dev, "unable to drain RX queue, %i buffer(s)"
" left in NPE\n", buffs);
#if DEBUG_CLOSE
if (!buffs)
netdev_debug(dev, "draining RX queue took %i cycles\n", i);
#endif
buffs = TX_DESCS;
while (queue_get_desc(TX_QUEUE(port->id), port, 1) >= 0)
buffs--; /* cancel TX */
i = 0;
do {
while (queue_get_desc(port->plat->txreadyq, port, 1) >= 0)
buffs--;
if (!buffs)
break;
} while (++i < MAX_CLOSE_WAIT);
if (buffs)
netdev_crit(dev, "unable to drain TX queue, %i buffer(s) "
"left in NPE\n", buffs);
#if DEBUG_CLOSE
if (!buffs)
netdev_debug(dev, "draining TX queues took %i cycles\n", i);
#endif
msg.byte3 = 0;
if (npe_send_recv_message(port->npe, &msg, "ETH_DISABLE_LOOPBACK"))
netdev_crit(dev, "unable to disable loopback\n");
phy_stop(dev->phydev);
if (!ports_open)
qmgr_disable_irq(TXDONE_QUEUE);
destroy_queues(port);
release_queues(port);
return 0;
}
static const struct net_device_ops ixp4xx_netdev_ops = {
.ndo_open = eth_open,
.ndo_stop = eth_close,
.ndo_start_xmit = eth_xmit,
.ndo_set_rx_mode = eth_set_mcast_list,
.ndo_eth_ioctl = eth_ioctl,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
#ifdef CONFIG_OF
static struct eth_plat_info *ixp4xx_of_get_platdata(struct device *dev)
{
struct device_node *np = dev->of_node;
struct of_phandle_args queue_spec;
struct of_phandle_args npe_spec;
struct device_node *mdio_np;
struct eth_plat_info *plat;
int ret;
plat = devm_kzalloc(dev, sizeof(*plat), GFP_KERNEL);
if (!plat)
return NULL;
ret = of_parse_phandle_with_fixed_args(np, "intel,npe-handle", 1, 0,
&npe_spec);
if (ret) {
dev_err(dev, "no NPE engine specified\n");
return NULL;
}
/* NPE ID 0x00, 0x10, 0x20... */
plat->npe = (npe_spec.args[0] << 4);
/* Check if this device has an MDIO bus */
mdio_np = of_get_child_by_name(np, "mdio");
if (mdio_np) {
plat->has_mdio = true;
mdio_bus_np = mdio_np;
/* DO NOT put the mdio_np, it will be used */
}
/* Get the rx queue as a resource from queue manager */
ret = of_parse_phandle_with_fixed_args(np, "queue-rx", 1, 0,
&queue_spec);
if (ret) {
dev_err(dev, "no rx queue phandle\n");
return NULL;
}
plat->rxq = queue_spec.args[0];
/* Get the txready queue as resource from queue manager */
ret = of_parse_phandle_with_fixed_args(np, "queue-txready", 1, 0,
&queue_spec);
if (ret) {
dev_err(dev, "no txready queue phandle\n");
return NULL;
}
plat->txreadyq = queue_spec.args[0];
return plat;
}
#else
static struct eth_plat_info *ixp4xx_of_get_platdata(struct device *dev)
{
return NULL;
}
#endif
static int ixp4xx_eth_probe(struct platform_device *pdev)
{
struct phy_device *phydev = NULL;
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
struct eth_plat_info *plat;
struct net_device *ndev;
struct port *port;
int err;
if (np) {
plat = ixp4xx_of_get_platdata(dev);
if (!plat)
return -ENODEV;
} else {
plat = dev_get_platdata(dev);
if (!plat)
return -ENODEV;
plat->npe = pdev->id;
switch (plat->npe) {
case IXP4XX_ETH_NPEA:
/* If the MDIO bus is not up yet, defer probe */
break;
case IXP4XX_ETH_NPEB:
/* On all except IXP43x, NPE-B is used for the MDIO bus.
* If there is no NPE-B in the feature set, bail out,
* else we have the MDIO bus here.
*/
if (!cpu_is_ixp43x()) {
if (!(ixp4xx_read_feature_bits() &
IXP4XX_FEATURE_NPEB_ETH0))
return -ENODEV;
/* Else register the MDIO bus on NPE-B */
plat->has_mdio = true;
}
break;
case IXP4XX_ETH_NPEC:
/* IXP43x lacks NPE-B and uses NPE-C for the MDIO bus
* access, if there is no NPE-C, no bus, nothing works,
* so bail out.
*/
if (cpu_is_ixp43x()) {
if (!(ixp4xx_read_feature_bits() &
IXP4XX_FEATURE_NPEC_ETH))
return -ENODEV;
/* Else register the MDIO bus on NPE-B */
plat->has_mdio = true;
}
break;
default:
return -ENODEV;
}
}
if (!(ndev = devm_alloc_etherdev(dev, sizeof(struct port))))
return -ENOMEM;
SET_NETDEV_DEV(ndev, dev);
port = netdev_priv(ndev);
port->netdev = ndev;
port->id = plat->npe;
port->phc_index = -1;
/* Get the port resource and remap */
port->regs = devm_platform_get_and_ioremap_resource(pdev, 0, NULL);
if (IS_ERR(port->regs))
return PTR_ERR(port->regs);
/* Register the MDIO bus if we have it */
if (plat->has_mdio) {
err = ixp4xx_mdio_register(port->regs);
if (err) {
dev_err(dev, "failed to register MDIO bus\n");
return err;
}
}
/* If the instance with the MDIO bus has not yet appeared,
* defer probing until it gets probed.
*/
if (!mdio_bus)
return -EPROBE_DEFER;
ndev->netdev_ops = &ixp4xx_netdev_ops;
ndev->ethtool_ops = &ixp4xx_ethtool_ops;
ndev->tx_queue_len = 100;
/* Inherit the DMA masks from the platform device */
ndev->dev.dma_mask = dev->dma_mask;
ndev->dev.coherent_dma_mask = dev->coherent_dma_mask;
netif_napi_add(ndev, &port->napi, eth_poll, NAPI_WEIGHT);
if (!(port->npe = npe_request(NPE_ID(port->id))))
return -EIO;
port->plat = plat;
npe_port_tab[NPE_ID(port->id)] = port;
eth_hw_addr_set(ndev, plat->hwaddr);
platform_set_drvdata(pdev, ndev);
__raw_writel(DEFAULT_CORE_CNTRL | CORE_RESET,
&port->regs->core_control);
udelay(50);
__raw_writel(DEFAULT_CORE_CNTRL, &port->regs->core_control);
udelay(50);
if (np) {
phydev = of_phy_get_and_connect(ndev, np, ixp4xx_adjust_link);
} else {
phydev = mdiobus_get_phy(mdio_bus, plat->phy);
if (!phydev) {
err = -ENODEV;
dev_err(dev, "could not connect phydev (%d)\n", err);
goto err_free_mem;
}
err = phy_connect_direct(ndev, phydev, ixp4xx_adjust_link,
PHY_INTERFACE_MODE_MII);
if (err)
goto err_free_mem;
}
if (!phydev) {
err = -ENODEV;
dev_err(dev, "no phydev\n");
goto err_free_mem;
}
phydev->irq = PHY_POLL;
if ((err = register_netdev(ndev)))
goto err_phy_dis;
netdev_info(ndev, "%s: MII PHY %i on %s\n", ndev->name, plat->phy,
npe_name(port->npe));
return 0;
err_phy_dis:
phy_disconnect(phydev);
err_free_mem:
npe_port_tab[NPE_ID(port->id)] = NULL;
npe_release(port->npe);
return err;
}
static int ixp4xx_eth_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct phy_device *phydev = ndev->phydev;
struct port *port = netdev_priv(ndev);
unregister_netdev(ndev);
phy_disconnect(phydev);
ixp4xx_mdio_remove();
npe_port_tab[NPE_ID(port->id)] = NULL;
npe_release(port->npe);
return 0;
}
static const struct of_device_id ixp4xx_eth_of_match[] = {
{
.compatible = "intel,ixp4xx-ethernet",
},
{ },
};
static struct platform_driver ixp4xx_eth_driver = {
.driver = {
.name = DRV_NAME,
.of_match_table = of_match_ptr(ixp4xx_eth_of_match),
},
.probe = ixp4xx_eth_probe,
.remove = ixp4xx_eth_remove,
};
module_platform_driver(ixp4xx_eth_driver);
MODULE_AUTHOR("Krzysztof Halasa");
MODULE_DESCRIPTION("Intel IXP4xx Ethernet driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:ixp4xx_eth");
|
from __future__ import print_function
import contextlib
import functools
import os
import sys
import random
import re
import time
import subprocess
from lxml import etree
from lxml.cssselect import CSSSelector, SelectorSyntaxError, ExpressionError
try:
from urllib.parse import urljoin
from urllib.request import urlopen
except ImportError:
from urlparse import urljoin
from urllib import urlopen
try:
unicode
except NameError:
unicode = str
INLINE = 'inline'
LINK = 'link'
RE_FIND_MEDIA = re.compile('(@media.+?)(\{)', re.DOTALL | re.MULTILINE)
RE_NESTS = re.compile('@(-|keyframes).*?({)', re.DOTALL | re.M)
RE_CLASS_DEF = re.compile('\.([\w-]+)')
RE_SELECTOR_TAGS = re.compile('(^|\s)(\w+)')
RE_ID_DEF = re.compile('#([\w-]+)')
MOUSE_PSEUDO_CLASSES = re.compile(
':(link|hover|active|focus|visited)$', re.M | re.I
)
BEFOREAFTER_PSEUDO_CLASSES = re.compile(
':(before|after)$', re.M | re.I
)
VENDOR_PREFIXED_PSEUDO_CLASSES = re.compile(
':-(webkit|moz)-'
)
# For matching things like "foo:bar" and '"foo:ing":bar' because it's
# not enough to just do a split on ':' since the ':' might be inside
# quotation marks. E.g. 'a[href^="javascript:"]'
PSEUDO_SELECTOR = re.compile(
r':(?=([^"\'\\]*(\\.|["\']([^"\'\\]*\\.)*[^"\'\\]*[\'"]))*[^"\']*$)'
)
EXCEPTIONAL_SELECTORS = (
'html',
)
DOWNLOAD_JS = os.path.join(
os.path.dirname(__file__),
'download.js'
)
class ParserError(Exception):
"""happens when we fail to parse the HTML."""
class DownloadError(Exception):
"""happens when we fail to down the URL."""
def _get_random_string():
p = 'abcdefghijklmopqrstuvwxyz'
pl = list(p)
random.shuffle(pl)
return ''.join(pl)
class Processor(object):
def __init__(self,
debug=False,
preserve_remote_urls=True,
phantomjs=False,
phantomjs_options=None,
optimize_lookup=True):
self.debug = debug
self.preserve_remote_urls = preserve_remote_urls
self.blocks = {}
self.inlines = []
self.links = []
self._bodies = []
self.optimize_lookup = optimize_lookup
self._all_ids = set()
self._all_classes = set()
self._all_tags = set()
self.phantomjs = phantomjs
self.phantomjs_options = phantomjs_options
self._downloaded = {}
def download(self, url):
if url in self._downloaded:
return self._downloaded[url]
try:
with contextlib.closing(urlopen(url)) as response:
if response.getcode() is not None:
if response.getcode() != 200:
raise DownloadError(
'%s -- %s ' % (url, response.getcode())
)
content = response.read()
content = unicode(content, get_charset(response))
self._downloaded[url] = content
return content
except IOError:
raise IOError(url)
def download_with_phantomjs(self, url):
if self.phantomjs is True:
# otherwise, assume it's a path
phantomjs = 'phantomjs'
elif not os.path.isfile(self.phantomjs):
raise IOError('%s is not a path to phantomjs' % self.phantomjs)
else:
phantomjs = self.phantomjs
command = [phantomjs]
if self.phantomjs_options:
if 'load-images' not in self.phantomjs_options:
# not entirely sure if this helps but there can't be any point
# at all to download image for mincss
self.phantomjs_options['load-images'] = 'no'
for key, value in self.phantomjs_options.items():
command.append('--%s=%s' % (key, value))
command.append(DOWNLOAD_JS)
assert ' ' not in url
command.append(url)
t0 = time.time()
process = subprocess.Popen(
' '.join(command),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = process.communicate()
t1 = time.time()
if self.debug:
print('Took', t1 - t0, 'seconds to download with PhantomJS')
return unicode(out, 'utf-8')
def process(self, *urls):
for url in urls:
self.process_url(url)
for identifier in sorted(self.blocks.keys()):
content = self.blocks[identifier]
no_mincss = identifier[-1]
if no_mincss:
processed = content
else:
processed = self._process_content(content, self._bodies)
if identifier[1] == INLINE:
line, _, url, _ = identifier
self.inlines.append(
InlineResult(
line,
url,
content,
processed,
)
)
else:
_, _, url, href, _ = identifier
self.links.append(
LinkResult(
href,
content,
processed
)
)
def process_url(self, url):
if self.phantomjs:
html = self.download_with_phantomjs(url)
else:
html = self.download(url)
self.process_html(html.strip(), url=url)
def _find_all_ids_classes_and_tags(self, element):
for each in element:
identifier = each.attrib.get('id')
if identifier:
self._all_ids.add(identifier)
classes = each.attrib.get('class')
if classes:
for class_ in classes.split():
self._all_classes.add(class_)
self._all_tags.add(each.tag)
# recurse!
self._find_all_ids_classes_and_tags(each)
def process_html(self, html, url):
parser = etree.HTMLParser(encoding='utf-8')
tree = etree.fromstring(html.encode('utf-8'), parser).getroottree()
page = tree.getroot()
if page is None:
print(repr(html))
raise ParserError('Could not parse the html')
lines = html.splitlines()
body, = CSSSelector('body')(page)
self._bodies.append(body)
if self.optimize_lookup:
self._all_tags.add('body')
self._find_all_ids_classes_and_tags(body)
for style in CSSSelector('style')(page):
try:
first_line = style.text.strip().splitlines()[0]
except IndexError:
# meaning the inline style tag was just whitespace
continue
except AttributeError:
# happend when the style tag has absolute nothing it
# not even whitespace
continue
no_mincss = False
try:
data_attrib = style.attrib['data-mincss'].lower()
if data_attrib == 'ignore':
continue
elif data_attrib == 'no':
no_mincss = True
except KeyError:
# happens if the attribute key isn't there
pass
for i, line in enumerate(lines, start=1):
if line.count(first_line):
key = (i, INLINE, url, no_mincss)
self.blocks[key] = style.text
break
i = 0
for link in CSSSelector('link')(page):
if (
link.attrib.get('rel', '') == 'stylesheet' or
link.attrib['href'].lower().split('?')[0].endswith('.css')
):
no_mincss = False
try:
data_attrib = link.attrib['data-mincss'].lower()
if data_attrib == 'ignore':
continue
if data_attrib == 'no':
no_mincss = True
except KeyError:
# happens if the attribute key isn't there
pass
link_url = self.make_absolute_url(url, link.attrib['href'])
key = (i, LINK, link_url, link.attrib['href'], no_mincss)
i += 1
self.blocks[key] = self.download(link_url)
if self.preserve_remote_urls:
self.blocks[key] = self._rewrite_urls(
self.blocks[key],
link_url
)
def _rewrite_urls(self, content, link_url):
"""Suppose you run mincss on www.example.org and it references:
<link href="http://cdn.example.org">
and in the CSS it references an image as:
background: url(/foo.png)
Then rewrite this to become:
background: url(http://cdn.example.org/foo.png)
"""
css_url_regex = re.compile('url\(([^\)]+)\)')
def css_url_replacer(match, href=None):
filename = match.groups()[0]
bail = match.group()
if (
(filename.startswith('"') and filename.endswith('"')) or
(filename.startswith("'") and filename.endswith("'"))
):
filename = filename[1:-1]
if 'data:image' in filename or '://' in filename:
return bail
if filename == '.':
# this is a known IE hack in CSS
return bail
new_filename = urljoin(href, filename)
return 'url("%s")' % new_filename
content = css_url_regex.sub(
functools.partial(css_url_replacer, href=link_url),
content
)
return content
def _process_content(self, content, bodies):
# Find all of the unique media queries
comments = []
_css_comments = re.compile(r'/\*.*?\*/', re.MULTILINE | re.DOTALL)
no_mincss_blocks = []
def commentmatcher(match):
whole = match.group()
# are we in a block or outside
nearest_close = content[:match.start()].rfind('}')
nearest_open = content[:match.start()].rfind('{')
next_close = content[match.end():].find('}')
next_open = content[match.end():].find('{')
outside = False
if nearest_open == -1 and nearest_close == -1:
# it's at the very beginning of the file
outside = True
elif next_open == -1 and next_close == -1:
# it's at the very end of the file
outside = True
elif nearest_close == -1 and nearest_open > -1:
outside = False
elif nearest_close > -1 and nearest_open > -1:
outside = nearest_close > nearest_open
else:
raise Exception('can this happen?!')
if outside:
temp_key = '@%scomment{}' % _get_random_string()
else:
temp_key = '%sinnercomment' % _get_random_string()
if re.findall(r'\bno mincss\b', match.group()):
no_mincss_blocks.append(temp_key)
comments.append(
(temp_key, whole)
)
return temp_key
content = _css_comments.sub(commentmatcher, content)
if no_mincss_blocks:
no_mincss_regex = re.compile(
'|'.join(re.escape(x) for x in no_mincss_blocks)
)
else:
no_mincss_regex = None
nests = [(m.group(1), m) for m in RE_NESTS.finditer(content)]
_nests = []
for _, m in nests:
__, whole = self._get_contents(m, content)
_nests.append(whole)
# once all nests have been spotted, temporarily replace them
queries = [(m.group(1), m) for m in RE_FIND_MEDIA.finditer(content)]
inner_improvements = []
for nest in _nests:
temp_key = '@%snest{}' % _get_random_string()
inner_improvements.append(
(temp_key, nest, nest)
)
# Consolidate the media queries
for (query, m) in queries:
inner, whole = self._get_contents(m, content)
improved_inner = self._process_content(inner, bodies)
if improved_inner.strip():
improved = query.rstrip() + ' {' + improved_inner + '}'
else:
improved = ''
temp_key = '@%s{}' % _get_random_string()
inner_improvements.append(
(temp_key, whole, improved)
)
for temp_key, old, __ in inner_improvements:
assert old in content, old
content = content.replace(old, temp_key, 1)
_regex = re.compile('((.*?){(.*?)})', re.DOTALL | re.M)
_already_found = set()
_already_tried = set()
def matcher(match):
whole, selectors, bulk = match.groups()
selectors = selectors.split('*/')[-1].lstrip()
if selectors.strip().startswith('@'):
return whole
if no_mincss_regex and no_mincss_regex.findall(bulk):
return no_mincss_regex.sub('', whole)
improved = selectors
perfect = True
selectors_split = [
x.strip() for x in
selectors.split(',')
if x.strip() and not x.strip().startswith(':')
]
for selector in selectors_split:
s = selector.strip()
if s in EXCEPTIONAL_SELECTORS:
continue
simplified = self._simplified_selector(s)
if simplified.endswith('>'):
# Things like "foo.bar > :first-child" is valid,
# but once simplified you're left with
# "foo.bar >" which can never be found because
# it's an invalid selector. Best to avoid.
found = True
elif simplified in _already_found:
found = True
elif simplified in _already_tried:
found = False
else:
found = self._found(bodies, simplified)
if found:
_already_found.add(simplified)
else:
_already_tried.add(simplified)
perfect = False
improved = re.sub(
'%s,?\s*' % re.escape(s),
'',
improved,
count=1
)
if perfect:
return whole
if improved != selectors:
if not improved.strip():
return ''
else:
improved = re.sub(',\s*$', ' ', improved)
whole = whole.replace(selectors, improved)
return whole
fixed = _regex.sub(matcher, content)
for temp_key, __, improved in inner_improvements:
assert temp_key in fixed
fixed = fixed.replace(temp_key, improved)
for temp_key, whole in comments:
# note, `temp_key` might not be in the `fixed` thing because the
# comment could have been part of a selector that is entirely
# removed
fixed = fixed.replace(temp_key, whole)
return fixed
def _get_contents(self, match, original_content):
# we are starting the character after the first opening brace
open_braces = 1
position = match.end()
content = ''
while open_braces > 0:
c = original_content[position]
if c == '{':
open_braces += 1
if c == '}':
open_braces -= 1
content += c
position += 1
return (
content[:-1].strip(),
# the last closing brace gets captured, drop it
original_content[match.start():position]
)
def _found(self, bodies, selector):
if self._all_ids:
try:
id_ = RE_ID_DEF.findall(selector)[0]
if id_ not in self._all_ids:
# don't bother then
return False
except IndexError:
pass
if self._all_classes:
for class_ in RE_CLASS_DEF.findall(selector):
if class_ not in self._all_classes:
# don't bother then
return False
# If the last part of the selector is a tag like
# ".foo blockquote" or "sometag" then we can look for it
# in plain HTML as a form of optimization
if not re.findall('[^\w \.]', selector):
# It's a trivial selector. Like "tag.myclass",
# or ".one.two". Let's look for some cheap wins
if self._all_tags:
# If the selector is quite simple, we can fish out
# all tags mentioned in it and do a quick lookup using
# simply the tag name.
for prefix, tag in RE_SELECTOR_TAGS.findall(selector):
if tag not in self._all_tags:
# If the tag doesn't even exist in the HTML,
# don't bother.
return False
return self._selector_query_found(bodies, selector)
@staticmethod
def _simplified_selector(selector):
# If the select has something like :active or :hover,
# then evaluate it as if it's without that pseudo class
return PSEUDO_SELECTOR.split(selector)[0].strip()
def _selector_query_found(self, bodies, selector):
if '}' in selector:
# XXX does this ever happen any more?
return
if selector.endswith('>'):
# It's
return False
for body in bodies:
try:
for _ in CSSSelector(selector)(body):
return True
except SelectorSyntaxError:
print('TROUBLEMAKER', file=sys.stderr)
print(repr(selector), file=sys.stderr)
return True # better be safe and let's keep it
except ExpressionError:
print('EXPRESSIONERROR', file=sys.stderr)
print(repr(selector), file=sys.stderr)
return True # better be safe and let's keep it
return False
@staticmethod
def make_absolute_url(url, href):
return urljoin(url, href)
class _Result(object):
def __init__(self, before, after):
self.before = before
self.after = after
class InlineResult(_Result):
def __init__(self, line, url, *args):
self.line = line
self.url = url
super(InlineResult, self).__init__(*args)
class LinkResult(_Result):
def __init__(self, href, *args):
self.href = href
super(LinkResult, self).__init__(*args)
def get_charset(response, default='utf-8'):
"""Return encoding."""
try:
# Python 3.
return response.info().get_param('charset', default)
except AttributeError:
# Python 2.
content_type = response.headers['content-type']
split_on = 'charset='
if split_on in content_type:
return content_type.split(split_on)[-1]
else:
return default
|
/*jslint nomen: true */
var path = require('path'),
fs = require('fs'),
cp = require('child_process'),
Module = require('module'),
originalLoader = Module._extensions['.js'],
common = require('./common'),
MAIN_FILE = path.resolve(__dirname, '..', 'lib', 'cli.js'),
DEFAULT_CWD = path.resolve(__dirname, 'cli', 'sample-project'),
COVER_ROOT = path.resolve(__dirname, '..'),
EXCLUDES = [ '**/node_modules/**', '**/test/**', '**/yui-load-hook.js'],
COVER_VAR = '$$selfcover$$',
seq = 0,
verbose = false,
OPTS = {};
/*
* Danger, Will Robinson! A lot of small stuff has to fall in place just so
* for self-coverage to work correctly for command line tests.
*
* In no-self-cover mode, this class does very little - which is:
*
* 1. Create a child process to run the supplied istanbul command
* 2. Callback the test case with an object that allows the test case
* to grep on stdout and stderr, inspect exit codes etc.
* 3. This is a "correct" test because we run the commands exactly as they
* would be run by the user.
*
* In self-cover mode, this works slightly differently:
*
* 1. Sets up a bunch of environment variables to keep track of what it was
* asked to do
* 2. Creates a child process forking _itself_. Returns the same object to
* the caller for purposes of grepping stdout, inspecting status codes etc.
* 3. In the child process,
* a. hooks the module loader to set up coverage for our library code
* b. Ensures that the `hook` module is not loaded until all this happens
* so that the hook module sees _our_ module loader hook as the original
* loader. This ensures that our hook will be used to instrument this
* library's code. Note that the hook set up by the `cover` command that
* is executed only instruments the modules of the sample test library.
* c. Calls Module.runMain on the command that it was asked to invoke
* d. Sets up an exit handler to write the coverage information for our
* library calls
* 4. The exit handler is also set up in special ways because in order to
* instrument the `cover` command's exit handler, our exit handler has
* to be added later so as to be able to track coverage for the cover
* commands handler.
*
* Since there is no general purpose way in which this can be correctly
* done, test cases have to indicate which ones expect the exit handler
* to be set up in the cover module and which ones do not. This is the
* reason `setOpts` exists.
*
*/
function setVerbose(flag) {
verbose = flag;
}
function setOpts(userOpts) {
Object.keys(userOpts).forEach(function (k) { OPTS[k] = userOpts[k]; });
}
function resetOpts() {
OPTS = {};
}
function runCommand(command, args, envVars, callback) {
/* jshint maxcomplexity: 8 */
var cmd = 'node',
selfCover = common.isSelfCover(),
env = {},
handle,
out = '',
err = '',
exitCode = 1,
grepper = function (array) {
return function (pat) {
var filtered = array.filter(function (item) {
return item.match(pat);
});
if (filtered.length === 0) {
if (verbose) {
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
console.log('Could not find: ' + pat + ' in:');
console.log(array.join('\n'));
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
}
}
return filtered.length > 0;
};
};
if (selfCover) {
seq += 1;
env.COMMAND_NAME = command || '';
env.COMMAND_ARGS = args.join('\t');
env.COVERAGE_FILE = 'coverage-' + seq + '.json';
env.LAZY_HOOK = OPTS.lazyHook ? '1' : '';
args = [ __filename ];
} else {
if (command) {
args.unshift(command);
}
args.unshift(MAIN_FILE);
}
if (!callback && typeof envVars === 'function') {
callback = envVars;
envVars = {};
}
Object.keys(process.env).forEach(function (key) {
env[key] = process.env[key];
});
Object.keys(envVars).forEach(function (key) {
env[key] = envVars[key];
});
handle = cp.spawn(cmd, args, { env: env, cwd: OPTS.cwd || DEFAULT_CWD });
handle.stdout.setEncoding('utf8');
handle.stderr.setEncoding('utf8');
handle.stdout.on('data', function (data) {
out += data;
if (verbose) {
process.stdout.write(data);
}
});
handle.stderr.on('data', function (data) {
err += data;
if (verbose) {
process.stderr.write(data);
}
});
handle.on('exit', function (code) {
exitCode = code;
setTimeout(function () {
out = out.split(/\r?\n/);
err = err.split(/\r?\n/);
callback({
succeeded: function () { return exitCode === 0; },
exitCode: exitCode,
stdout: function () { return out; },
stderr: function () { return err; },
grepOutput: grepper(out),
grepError: grepper(err)
});
}, 100);
});
}
function customHook(lazyHook, callback) {
var Instrumenter = require('../lib/instrumenter'),
instrumenter = new Instrumenter({ coverageVariable: COVER_VAR }),
transformer = function (file) {
return instrumenter.instrumentSync(fs.readFileSync(file, 'utf8'), file);
},
handler = function () {
process.once('exit', function () {
var file;
if (typeof global[COVER_VAR] !== 'undefined') {
file = path.resolve(common.getCoverageDir(), process.env.COVERAGE_FILE);
fs.writeFileSync(file, JSON.stringify(global[COVER_VAR], undefined, 4), 'utf8');
}
});
};
require('../lib/util/file-matcher').matcherFor({
root : COVER_ROOT,
excludes: EXCLUDES,
includes: [ '**/*.js']
}, function (err, matcher) {
var added = false;
Module._extensions['.js'] = function (module, filename) {
if (matcher(filename)) {
module._compile(transformer(filename), filename);
} else {
originalLoader(module, filename);
}
};
if (!lazyHook) {
handler();
} else {
process.on('newListener', function (event) {
if (event === 'exit') {
if (!added) {
added = true;
process.nextTick(function () {
handler();
});
}
}
});
}
callback();
});
}
module.exports = {
setVerbose: setVerbose,
runCommand: runCommand,
resetOpts: resetOpts,
setOpts: setOpts
};
if (require.main === module) { //we are running ourselves under self-cover
(function () {
var command = process.env.COMMAND_NAME,
args = process.env.COMMAND_ARGS ? process.env.COMMAND_ARGS.split(/\t/) : [],
fullArgs = [];
if (command) { fullArgs.push(command); }
fullArgs.push.apply(fullArgs, args);
customHook(process.env.LAZY_HOOK, function () {
console.error('Running command using CLI object:' + JSON.stringify({ cmd: command, args: args }));
require('../lib/cli').runToCompletion(fullArgs);
});
}());
}
|
import Label, {textLayoutToJSON} from './label';
import Vector from '../utils/vector';
import OBB from '../utils/obb';
const STOPS = [0, 0.33, 0.66, 0.99]; // zoom levels for curved label snapshot data (offsets and angles)
const LINE_EXCEED_STRAIGHT = 1.5; // minimal ratio for straight labels (label length) / (line length)
const LINE_EXCEED_STRAIGHT_NO_CURVE = 1.8; // minimal ratio for straight labels that have no curved option (like Arabic)
const LINE_EXCEED_STAIGHT_LOOSE = 2.3; // 2nd pass minimal ratio for straight labels
const STRAIGHT_ANGLE_TOLERANCE = 0.1; // multiple "almost straight" segments within this angle tolerance can be considered one straight segment (in radians)
const CURVE_MIN_TOTAL_COST = 1.3; // curved line total curvature tolerance (sum in radians)
const CURVE_MIN_AVG_COST = 0.4; // curved line average curvature tolerance (mean)
const CURVE_MAX_ANGLE = 1; // curved line singular curvature tolerance (value in radians)
const ORIENTED_LABEL_OFFSET_FACTOR = 1.2; // multiply offset by this amount to avoid linked label collision
const VERTICAL_ANGLE_TOLERANCE = 0.01; // nearly vertical lines considered vertical within this angle tolerance
let LabelLine = {
// Given a label's bounding box size and size of broken up individual segments
// return a label that fits along the line geometry that is either straight (preferred) or curved (if straight tolerances aren't met)
create : function(segment_sizes, total_size, line, layout){
// The passes done for fitting a label, and provided tolerances for each pass
// First straight is chosen with a low tolerance. Then curved. Then straight with a higher tolerance.
const passes = [
{ type: 'straight', tolerance : (layout.no_curving) ? LINE_EXCEED_STRAIGHT_NO_CURVE : LINE_EXCEED_STRAIGHT },
{ type: 'curved' },
{ type: 'straight', tolerance : LINE_EXCEED_STAIGHT_LOOSE }
];
// loop through passes. first label found wins.
for (let i = 0; i < passes.length; i++){
let check = passes[i];
let label;
if (check.type === 'straight'){
label = new LabelLineStraight(total_size, line, layout, check.tolerance);
}
else if (check.type === 'curved' && !layout.no_curving && line.length > 2){
label = new LabelLineCurved(segment_sizes, line, layout);
}
if (label && !label.throw_away) {
return label;
}
}
return false;
}
};
export default LabelLine;
// Base class for a labels.
export class LabelLineBase {
constructor (layout) {
this.id = Label.nextLabelId();
this.layout = layout;
this.position = [];
this.angle = 0;
this.offset = layout.offset.slice();
this.unit_scale = this.layout.units_per_pixel;
this.obbs = [];
this.aabbs = [];
this.type = ''; // "curved" or "straight" to be set by child class
this.throw_away = false; // boolean that determines if label should be discarded
}
// Minimal representation of label
toJSON () {
return {
id: this.id,
type: this.type,
position: this.position,
size: this.size,
offset: this.offset,
angle: this.angle,
breach: this.breach,
may_repeat_across_tiles: this.may_repeat_across_tiles,
layout: textLayoutToJSON(this.layout)
};
}
// Given a line, find the longest series of segments that maintains a constant orientation in the x-direction.
// This assures us that the line has no orientation flip, so text would not appear upside-down.
// If the line's orientation is reversed, the flip return value will be true, otherwise false
static splitLineByOrientation(line){
let current_line = [line[0]];
let current_length = 0;
let max_length = 0;
let orientation = 0;
let longest_line = current_line;
let flip = false;
for (let i = 1; i < line.length; i++) {
let pt = line[i];
let prev_pt = line[i - 1];
let length = Vector.length(Vector.sub(pt, prev_pt));
if (pt[0] > prev_pt[0]){
// positive orientation
if (orientation === 1){
current_line.push(pt);
current_length += length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = false;
}
}
else {
current_line = [prev_pt, pt];
current_length = length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = false;
}
orientation = 1;
}
}
else if (pt[0] < prev_pt[0]) {
// negative orientation
if (orientation === -1){
current_line.unshift(pt);
current_length += length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = true;
}
}
else {
// prepend points (reverse order)
current_line = [pt, prev_pt];
current_length = length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = true;
}
orientation = -1;
}
}
else {
// vertical line (doesn't change previous orientation)
if (orientation === -1){
current_line.unshift(pt);
}
else {
current_line.push(pt);
orientation = 1;
}
current_length += length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = (orientation === -1);
}
}
}
return [longest_line, flip];
}
// Checks each segment to see if it should be discarded (via collision). If any segment fails this test, they all fail.
discard(bboxes, exclude = null) {
if (this.throw_away) {
return true;
}
for (let i = 0; i < this.obbs.length; i++){
let aabb = this.aabbs[i];
let obb = this.obbs[i];
let obj = { aabb, obb };
let shouldDiscard = Label.prototype.occluded.call(obj, bboxes, exclude);
if (shouldDiscard) {
return true;
}
}
return false;
}
// Checks each segment to see if it is within the tile. If any segment fails this test, they all fail.
inTileBounds() {
for (let i = 0; i < this.aabbs.length; i++) {
let aabb = this.aabbs[i];
let obj = { aabb };
let in_bounds = Label.prototype.inTileBounds.call(obj);
if (!in_bounds) {
return false;
}
}
return true;
}
// Method to calculate oriented bounding box
// "angle" is the angle of the text segment, "angle_offset" is the angle applied to the offset.
// Offset angle is constant for the entire label, while segment angles are not.
static createOBB (position, width, height, angle, angle_offset, offset, upp) {
let p0 = position[0];
let p1 = position[1];
// apply offset, x positive, y pointing down
if (offset && (offset[0] !== 0 || offset[1] !== 0)) {
offset = Vector.rot(offset, angle_offset);
p0 += offset[0] * upp;
p1 -= offset[1] * upp;
}
// the angle of the obb is negative since it's the tile system y axis is pointing down
return new OBB(p0, p1, -angle, width, height);
}
}
// Class for straight labels.
// Extends base LabelLine class.
export class LabelLineStraight extends LabelLineBase {
constructor (size, line, layout, tolerance){
super(layout);
this.type = 'straight';
this.size = size;
this.throw_away = !this.fit(size, line, layout, tolerance);
}
// Determine if the label can fit the geometry within provided tolerance
// A straight label is generally placed at segment midpoints, but can "look ahead" to further segments
// if they are within an angle bound given by STRAIGHT_ANGLE_TOLERANCE and place at the midpoint between non-consecutive segments
fit (size, line, layout, tolerance){
let upp = this.unit_scale;
let flipped; // boolean indicating if orientation of line is changed
// Make new copy of line, with consistent orientation
[line, flipped] = LabelLineBase.splitLineByOrientation(line);
// matches for "left" or "right" labels where the offset angle is dependent on the geometry
if (typeof layout.orientation === 'number'){
this.offset[1] += ORIENTED_LABEL_OFFSET_FACTOR * (size[1] - layout.vertical_buffer);
// if line is flipped, or the orientation is "left" (-1), flip the offset's y-axis
if (flipped){
this.offset[1] *= -1;
}
if (layout.orientation === -1){
this.offset[1] *= -1;
}
}
let line_lengths = getLineLengths(line);
let label_length = size[0] * upp;
// loop through line looking for a placement for the label
for (let i = 0; i < line.length - 1; i++){
let curr = line[i];
let curve_tolerance = 0;
let length = 0;
let ahead_index = i + 1;
let prev_angle;
// look ahead to further line segments within an angle tolerance
while (ahead_index < line.length){
let ahead_curr = line[ahead_index - 1];
let ahead_next = line[ahead_index];
let next_angle = getAngleForSegment(ahead_curr, ahead_next);
if (ahead_index !== i + 1){
curve_tolerance += getAbsAngleDiff(next_angle, prev_angle);
}
// if curve tolerance is exceeded, break out of loop
if (Math.abs(curve_tolerance) > STRAIGHT_ANGLE_TOLERANCE){
break;
}
length += line_lengths[ahead_index - 1];
// check if label fits geometry
if (calcFitness(length, label_length) < tolerance){
let curr_midpt = Vector.mult(Vector.add(curr, ahead_next), 0.5);
// TODO: modify angle if line chosen within curve_angle_tolerance
// Currently line angle is the same as the starting angle, perhaps it should average across segments?
this.angle = -next_angle;
// ensure that all vertical labels point up (not down) by snapping angles close to pi/2 to -pi/2
if (Math.abs(this.angle - Math.PI/2) < VERTICAL_ANGLE_TOLERANCE) {
// flip angle and offset
this.angle = -Math.PI/2;
if (typeof layout.orientation === 'number'){
this.offset[1] *= -1;
}
}
this.position = curr_midpt;
this.updateBBoxes(this.position, size, this.angle, this.angle, this.offset);
return true; // use this placement
}
prev_angle = next_angle;
ahead_index++;
}
}
return false;
}
// Calculate bounding boxes
updateBBoxes(position, size, angle, angle_offset, offset) {
let upp = this.unit_scale;
// reset bounding boxes
this.obbs = [];
this.aabbs = [];
let width = (size[0] + 2 * this.layout.buffer[0]) * upp * Label.epsilon;
let height = (size[1] + 2 * this.layout.buffer[1]) * upp * Label.epsilon;
let obb = LabelLineBase.createOBB(position, width, height, angle, angle_offset, offset, upp);
let aabb = obb.getExtent();
this.obbs.push(obb);
this.aabbs.push(aabb);
if (this.inTileBounds) {
this.breach = !this.inTileBounds();
}
if (this.mayRepeatAcrossTiles) {
this.may_repeat_across_tiles = this.mayRepeatAcrossTiles();
}
}
}
// Class for curved labels
// Extends base LabelLine class to support angles, pre_angles, offsets as arrays for each segment
class LabelLineCurved extends LabelLineBase {
constructor (segment_sizes, line, layout) {
super(layout);
this.type = 'curved';
// extra data for curved labels
this.angles = [];
this.pre_angles = [];
this.offsets = [];
this.num_segments = segment_sizes.length;
this.sizes = segment_sizes;
this.throw_away = !this.fit(this.sizes, line, layout);
}
// Minimal representation of label
toJSON () {
return {
id: this.id,
type: this.type,
obbs: this.obbs.map(o => o.toJSON()),
position: this.position,
breach: this.breach,
may_repeat_across_tiles: this.may_repeat_across_tiles,
layout: textLayoutToJSON(this.layout)
};
}
// Determine if the curved label can fit the geometry.
// No tolerance is provided because the label must fit entirely within the line geometry.
fit (size, line, layout){
let upp = this.unit_scale;
let flipped; // boolean determining if the line orientation is reversed
let height_px = Math.max(...size.map(s => s[1])); // use max segment height
let height = height_px * upp;
// Make new copy of line, with consistent orientation
[line, flipped] = LabelLineBase.splitLineByOrientation(line);
// matches for "left" or "right" labels where the offset angle is dependent on the geometry
if (typeof layout.orientation === 'number'){
this.offset[1] += ORIENTED_LABEL_OFFSET_FACTOR * (height_px - layout.vertical_buffer);
// if line is flipped, or the orientation is "left" (-1), flip the offset's y-axis
if (flipped){
this.offset[1] *= -1;
}
if (layout.orientation === -1){
this.offset[1] *= -1;
}
}
let line_lengths = getLineLengths(line);
let label_lengths = size.map(size => size[0] * upp);
let total_line_length = line_lengths.reduce((prev, next) => prev + next, 0);
let total_label_length = label_lengths.reduce((prev, next) => prev + next, 0);
// if label displacement is longer than the line, no fit can be possible
if (total_label_length > total_line_length){
return false;
}
// need two line segments for a curved label
// NB: single segment lines should still be labeled if possible during straight label placement pass
let start_index = 0, end_index = line.length-1;
if (end_index - start_index < 2){
return false;
}
// all positional offsets of the label are relative to the anchor
let anchor_index = LabelLineCurved.curvaturePlacement(line, total_line_length, line_lengths, total_label_length, start_index, end_index);
let anchor = line[anchor_index];
// if anchor not found, or greater than the end_index, no fit possible
if (anchor_index === -1 || end_index - anchor_index < 2){
return false;
}
// set start position at anchor position
this.position = anchor;
// Loop through labels at each zoom level stop
// TODO: Can be made faster since we are computing every segment for every zoom stop
// We can skip a segment's calculation once a segment's angle equals its fully zoomed angle
for (var i = 0; i < label_lengths.length; i++){
this.offsets[i] = [];
this.angles[i] = [];
this.pre_angles[i] = [];
// loop through stops (z = [0, .33, .66, .99] + base zoom)
for (var j = 0; j < STOPS.length; j++){
let stop = STOPS[j];
// scale the line geometry by the zoom magnification
let [new_line, line_lengths] = LabelLineCurved.scaleLine(stop, line);
anchor = new_line[anchor_index];
// calculate label data relative to anchor position
let {positions, offsets, angles, pre_angles} = LabelLineCurved.placeAtIndex(anchor_index, new_line, line_lengths, label_lengths);
// translate 2D offsets into "polar coordinates"" (1D distances with angles)
let offsets1d = offsets.map(offset => {
return Math.sqrt(offset[0] * offset[0] + offset[1] * offset[1]) / upp;
});
// Calculate everything that is independent of zoom level (angle for offset, bounding boxes, etc)
if (stop === 0){
// use average angle for a global label offset (if offset is specified)
this.angle = 1 / angles.length * angles.reduce((prev, next) => prev + next);
// calculate bounding boxes for collision at zoom level 0
for (let i = 0; i < positions.length; i++){
let position = positions[i];
let pre_angle = pre_angles[i];
let width = label_lengths[i];
let angle_segment = pre_angle + angles[i];
let angle_offset = this.angle;
let obb = LabelLineBase.createOBB(position, width, height, angle_segment, angle_offset, this.offset, upp);
let aabb = obb.getExtent();
this.obbs.push(obb);
this.aabbs.push(aabb);
}
}
// push offsets/angles/pre_angles for each zoom and for each label segment
this.offsets[i].push(offsets1d[i]);
this.angles[i].push(angles[i]);
this.pre_angles[i].push(pre_angles[i]);
}
}
return true;
}
// Find optimal starting segment for placing a curved label along a line within provided tolerances
// This is determined by calculating the curvature at each interior vertex of a line
// then construct a "window" whose breadth is the length of the label. Place this label at each vertex
// and add the curvatures of each vertex within the window. The vertex mimimizing this value is the "best" placement.
// Return -1 is no placement found.
static curvaturePlacement(line, total_line_length, line_lengths, label_length, start_index, end_index){
start_index = start_index || 0;
end_index = end_index || line.length - 1;
var curvatures = []; // array of curvature values per line vertex
// calculate curvature values
for (let i = start_index + 1; i < end_index; i++){
var prev = line[i - 1];
var curr = line[i];
var next = line[i + 1];
var norm_1 = Vector.perp(curr, prev);
var norm_2 = Vector.perp(next, curr);
var curvature = Vector.angleBetween(norm_1, norm_2);
// If curvature at a vertex is greater than the tolerance, remove it from consideration
// by giving it an infinite penalty
if (curvature > CURVE_MAX_ANGLE) {
curvature = Infinity;
}
curvatures.push(curvature);
}
curvatures.push(Infinity); // Infinite penalty for going off end of line
// calculate curvature costs
var total_costs = [];
var avg_costs = [];
var line_index = start_index;
var position = 0;
for (let i = 0; i < start_index; i++){
position += line_lengths[i];
}
// move window along line, starting at first vertex
while (position + label_length < total_line_length){
// define window breadth
var window_start = position;
var window_end = window_start + label_length;
var line_position = window_start;
var ahead_index = line_index;
var cost = 0;
// iterate through points on line intersecting window
while (ahead_index < end_index && line_position + line_lengths[ahead_index] < window_end){
cost += curvatures[ahead_index];
if (cost === Infinity) {
break; // no further progress can be made
}
line_position += line_lengths[ahead_index];
ahead_index++;
}
// if optimal cost, break out
if (cost === 0) {
return line_index;
}
var avg_cost = cost / (ahead_index - line_index);
total_costs.push(cost);
avg_costs.push(avg_cost);
position += line_lengths[line_index];
line_index++;
}
if (total_costs.length === 0) {
return -1;
}
// calculate min cost and avg cost to determine if label can fit within curvatures tolerances
var min_total_cost = Math.min.apply(null, total_costs);
var min_index = total_costs.indexOf(min_total_cost);
var min_avg_cost = avg_costs[min_index];
if (min_total_cost < CURVE_MIN_TOTAL_COST && min_avg_cost < CURVE_MIN_AVG_COST){
// return index with best placement (least curvature)
return total_costs.indexOf(min_total_cost);
}
else {
// if tolerances aren't satisfied, throw away tile
return -1;
}
}
// Scale the line by a scale factor (used for computing the angles and offsets at fractional zoom levels)
// Return the new line positions and their lengths
static scaleLine(scale, line){
var new_line = [line[0]];
var line_lengths = [];
line.forEach((pt, i) => {
if (i === line.length - 1) {
return;
}
var v = Vector.sub(line[i+1], line[i]);
var delta = Vector.mult(v, 1 + scale);
new_line.push(Vector.add(new_line[i], delta));
line_lengths.push(Vector.length(delta));
});
return [new_line, line_lengths];
}
// Place a label at a given line index
static placeAtIndex(anchor_index, line, line_lengths, label_lengths){
let anchor = line[anchor_index];
// Use flat coordinates. Get nearest line vertex index, and offset from the vertex for all labels.
let [indices, relative_offsets] = LabelLineCurved.getIndicesAndOffsets(anchor_index, line_lengths, label_lengths);
// get 2D positions based on "flat" indices and offsets
let positions = LabelLineCurved.getPositionsFromIndicesAndOffsets(line, indices, relative_offsets);
// get 2d offsets, angles and pre_angles relative to anchor
let [offsets, angles, pre_angles] = LabelLineCurved.getAnglesFromIndicesAndOffsets(anchor, indices, line, positions);
return {positions, offsets, angles, pre_angles};
}
// Given label lengths to place along a line broken into several lengths, computer what indices and at which offsets
// the labels will appear on the line. Assume the line is straight, as it is not necessary to consider angles.
//
// Label lengths:
// |-----|----|-----|-----------------|-------------|
//
// Line Lengths;
// |---------|---------|-------------|------------|----------|-------|
//
// Result: indices: [0,0,1,1,3,4]
static getIndicesAndOffsets(line_index, line_lengths, label_lengths){
let num_labels = label_lengths.length;
let indices = [];
let offsets = [];
let label_index = 0;
let label_offset = 0;
let line_offset = 0;
// iterate along line
while (label_index < num_labels){
let label_length = label_lengths[label_index];
// iterate along labels within the line segment
while (label_index < num_labels && label_offset + 0.5 * label_length <= line_offset + line_lengths[line_index]){
let offset = label_offset - line_offset + 0.5 * label_length;
offsets.push(offset);
indices.push(line_index);
label_offset += label_length;
label_index++;
label_length = label_lengths[label_index];
}
line_offset += line_lengths[line_index];
line_index++;
}
return [indices, offsets];
}
// Given indices and 1D offsets on a line, compute their 2D positions
static getPositionsFromIndicesAndOffsets(line, indices, offsets){
let positions = [];
for (let i = 0; i < indices.length; i++){
let index = indices[i];
let offset = offsets[i];
let angle = getAngleForSegment(line[index], line[index + 1]);
let offset2d = Vector.rot([offset, 0], angle);
let position = Vector.add(line[index], offset2d);
positions.push(position);
}
return positions;
}
// Given indices and 1D offsets on a line, compute their angles and pre-angles from a reference anchor point
static getAnglesFromIndicesAndOffsets(anchor, indices, line, positions){
let angles = [];
let pre_angles = [];
let offsets = [];
for (let i = 0; i < positions.length; i++){
let position = positions[i];
let index = indices[i];
let offset = Vector.sub(position, anchor);
let offset_angle = -Vector.angle(offset);
let angle = getTextAngleForSegment(line[index], line[index + 1]);
let pre_angle = angle - offset_angle;
if (i > 0){
let prev_angle = angles[i - 1];
let prev_pre_angle = pre_angles[i - 1];
if (Math.abs(offset_angle - prev_angle) > Math.PI) {
offset_angle += (offset_angle > prev_angle) ? -2 * Math.PI : 2 * Math.PI;
}
if (Math.abs(prev_pre_angle - pre_angle) > Math.PI) {
pre_angle += (pre_angle > prev_pre_angle) ? -2 * Math.PI : 2 * Math.PI;
}
}
angles.push(offset_angle);
pre_angles.push(pre_angle);
offsets.push(offset);
}
return [offsets, angles, pre_angles];
}
}
// Fitness function (label length / line length)
function calcFitness(line_length, label_length) {
return label_length / line_length;
}
function getAngleForSegment(p, q){
let pq = Vector.sub(q,p);
return Vector.angle(pq);
}
function getTextAngleForSegment(pt1, pt2) {
return -getAngleForSegment(pt1, pt2);
}
function getLineLengths(line){
let lengths = [];
for (let i = 0; i < line.length - 1; i++){
let p = line[i];
let q = line[i+1];
let length = Math.hypot(p[0] - q[0], p[1] - q[1]);
lengths.push(length);
}
return lengths;
}
function getAbsAngleDiff(angle1, angle2){
let small, big;
if (angle1 > angle2){
small = angle2;
big = angle1;
}
else {
small = angle1;
big = angle2;
}
while (big - small > Math.PI){
small += 2 * Math.PI;
}
return Math.abs(big - small);
}
|
import os.path
LIST_OF_DEIDS=[
100, 101, 102, 103,
200, 201, 202, 203,
300, 301, 302, 303,
400, 401, 402, 403,
500, 501, 502, 503, 504, 505, 506, 507,
508, 509, 510, 511,
512, 513, 514, 515, 516, 517,
600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617,
700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725,
800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825,
900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925,
1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025
]
|
from selfdrive.car import dbc_dict
from cereal import car
Ecu = car.CarParams.Ecu
# Steer torque limits
class SteerLimitParams:
STEER_MAX = 1500
STEER_DELTA_UP = 10 # 1.5s time to peak torque
STEER_DELTA_DOWN = 25 # always lower than 45 otherwise the Rav4 faults (Prius seems ok with 50)
STEER_ERROR_MAX = 350 # max delta between torque cmd and torque motor
class CAR:
PRIUS = "TOYOTA PRIUS 2017"
RAV4H = "TOYOTA RAV4 HYBRID 2017"
RAV4 = "TOYOTA RAV4 2017"
COROLLA = "TOYOTA COROLLA 2017"
LEXUS_RXH = "LEXUS RX HYBRID 2017"
CHR = "TOYOTA C-HR 2018"
CHRH = "TOYOTA C-HR HYBRID 2018"
CAMRY = "TOYOTA CAMRY 2018"
CAMRYH = "TOYOTA CAMRY HYBRID 2018"
HIGHLANDER = "TOYOTA HIGHLANDER 2017"
HIGHLANDERH = "TOYOTA HIGHLANDER HYBRID 2018"
AVALON = "TOYOTA AVALON 2016"
RAV4_TSS2 = "TOYOTA RAV4 2019"
COROLLA_TSS2 = "TOYOTA COROLLA TSS2 2019"
COROLLAH_TSS2 = "TOYOTA COROLLA HYBRID TSS2 2019"
LEXUS_ES_TSS2 = "LEXUS ES 2019"
LEXUS_ESH_TSS2 = "LEXUS ES 300H 2019"
SIENNA = "TOYOTA SIENNA XLE 2018"
LEXUS_IS = "LEXUS IS300 2018"
LEXUS_CTH = "LEXUS CT 200H 2018"
class ECU:
CAM = Ecu.fwdCamera # camera
DSU = Ecu.dsu # driving support unit
APGS = Ecu.apgs # advanced parking guidance system
# addr: (ecu, cars, bus, 1/freq*100, vl)
STATIC_MSGS = [
(0x128, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.RAV4, CAR.COROLLA, CAR.AVALON), 1, 3, b'\xf4\x01\x90\x83\x00\x37'),
(0x128, ECU.DSU, (CAR.HIGHLANDER, CAR.HIGHLANDERH, CAR.SIENNA, CAR.LEXUS_CTH), 1, 3, b'\x03\x00\x20\x00\x00\x52'),
(0x141, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.RAV4, CAR.COROLLA, CAR.HIGHLANDER, CAR.HIGHLANDERH, CAR.AVALON, CAR.SIENNA, CAR.LEXUS_CTH), 1, 2, b'\x00\x00\x00\x46'),
(0x160, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.RAV4, CAR.COROLLA, CAR.HIGHLANDER, CAR.HIGHLANDERH, CAR.AVALON, CAR.SIENNA, CAR.LEXUS_CTH), 1, 7, b'\x00\x00\x08\x12\x01\x31\x9c\x51'),
(0x161, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.RAV4, CAR.COROLLA, CAR.AVALON), 1, 7, b'\x00\x1e\x00\x00\x00\x80\x07'),
(0X161, ECU.DSU, (CAR.HIGHLANDERH, CAR.HIGHLANDER, CAR.SIENNA, CAR.LEXUS_CTH), 1, 7, b'\x00\x1e\x00\xd4\x00\x00\x5b'),
(0x283, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.RAV4, CAR.COROLLA, CAR.HIGHLANDER, CAR.HIGHLANDERH, CAR.AVALON, CAR.SIENNA, CAR.LEXUS_CTH), 0, 3, b'\x00\x00\x00\x00\x00\x00\x8c'),
(0x2E6, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH), 0, 3, b'\xff\xf8\x00\x08\x7f\xe0\x00\x4e'),
(0x2E7, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH), 0, 3, b'\xa8\x9c\x31\x9c\x00\x00\x00\x02'),
(0x33E, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH), 0, 20, b'\x0f\xff\x26\x40\x00\x1f\x00'),
(0x344, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.RAV4, CAR.COROLLA, CAR.HIGHLANDER, CAR.HIGHLANDERH, CAR.AVALON, CAR.SIENNA, CAR.LEXUS_CTH), 0, 5, b'\x00\x00\x01\x00\x00\x00\x00\x50'),
(0x365, ECU.DSU, (CAR.PRIUS, CAR.LEXUS_RXH, CAR.HIGHLANDERH), 0, 20, b'\x00\x00\x00\x80\x03\x00\x08'),
(0x365, ECU.DSU, (CAR.RAV4, CAR.RAV4H, CAR.COROLLA, CAR.HIGHLANDER, CAR.AVALON, CAR.SIENNA, CAR.LEXUS_CTH), 0, 20, b'\x00\x00\x00\x80\xfc\x00\x08'),
(0x366, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.HIGHLANDERH), 0, 20, b'\x00\x00\x4d\x82\x40\x02\x00'),
(0x366, ECU.DSU, (CAR.RAV4, CAR.COROLLA, CAR.HIGHLANDER, CAR.AVALON, CAR.SIENNA, CAR.LEXUS_CTH), 0, 20, b'\x00\x72\x07\xff\x09\xfe\x00'),
(0x470, ECU.DSU, (CAR.PRIUS, CAR.LEXUS_RXH), 1, 100, b'\x00\x00\x02\x7a'),
(0x470, ECU.DSU, (CAR.HIGHLANDER, CAR.HIGHLANDERH, CAR.RAV4H, CAR.SIENNA, CAR.LEXUS_CTH), 1, 100, b'\x00\x00\x01\x79'),
(0x4CB, ECU.DSU, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.RAV4, CAR.COROLLA, CAR.HIGHLANDERH, CAR.HIGHLANDER, CAR.AVALON, CAR.SIENNA, CAR.LEXUS_CTH), 0, 100, b'\x0c\x00\x00\x00\x00\x00\x00\x00'),
(0x292, ECU.APGS, (CAR.PRIUS), 0, 3, b'\x00\x00\x00\x00\x00\x00\x00\x9e'),
(0x32E, ECU.APGS, (CAR.PRIUS), 0, 20, b'\x00\x00\x00\x00\x00\x00\x00\x00'),
(0x396, ECU.APGS, (CAR.PRIUS), 0, 100, b'\xBD\x00\x00\x00\x60\x0F\x02\x00'),
(0x43A, ECU.APGS, (CAR.PRIUS), 0, 100, b'\x84\x00\x00\x00\x00\x00\x00\x00'),
(0x43B, ECU.APGS, (CAR.PRIUS), 0, 100, b'\x00\x00\x00\x00\x00\x00\x00\x00'),
(0x497, ECU.APGS, (CAR.PRIUS), 0, 100, b'\x00\x00\x00\x00\x00\x00\x00\x00'),
(0x4CC, ECU.APGS, (CAR.PRIUS), 0, 100, b'\x0D\x00\x00\x00\x00\x00\x00\x00'),
]
ECU_FINGERPRINT = {
ECU.CAM: [0x2e4], # steer torque cmd
ECU.DSU: [0x343], # accel cmd
ECU.APGS: [0x835], # angle cmd
}
FINGERPRINTS = {
CAR.RAV4: [{
36: 8, 37: 8, 170: 8, 180: 8, 186: 4, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 512: 6, 513: 6, 547: 8, 548: 8, 552: 4, 562: 4, 608: 8, 610: 5, 643: 7, 705: 8, 725: 2, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 3, 918: 7, 921: 8, 933: 8, 944: 8, 945: 8, 951: 8, 955: 4, 956: 8, 979: 2, 998: 5, 999: 7, 1000: 8, 1001: 8, 1005: 2, 1008: 2, 1014: 8, 1017: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1059: 1, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1227: 8, 1228: 8, 1235: 8, 1237: 8, 1263: 8, 1264: 8, 1279: 8, 1408: 8, 1409: 8, 1410: 8, 1552: 8, 1553: 8, 1554: 8, 1555: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1596: 8, 1597: 8, 1600: 8, 1656: 8, 1664: 8, 1728: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8, 2015: 8, 2024: 8
}],
CAR.RAV4H: [{
36: 8, 37: 8, 170: 8, 180: 8, 186: 4, 296: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 547: 8, 548: 8, 550: 8, 552: 4, 560: 7, 562: 4, 581: 5, 608: 8, 610: 5, 643: 7, 705: 8, 713: 8, 725: 2, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 3, 918: 7, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 3, 955: 8, 956: 8, 979: 2, 998: 5, 999: 7, 1000: 8, 1001: 8, 1005: 2, 1008: 2, 1014: 8, 1017: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1059: 1, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1184: 8, 1185: 8, 1186: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1212: 8, 1227: 8, 1228: 8, 1232: 8, 1235: 8, 1237: 8, 1263: 8, 1264: 8, 1279: 8, 1408: 8, 1409: 8, 1410: 8, 1552: 8, 1553: 8, 1554: 8, 1555: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1596: 8, 1597: 8, 1600: 8, 1656: 8, 1664: 8, 1728: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
# Chinese RAV4
{
36: 8, 37: 8, 170: 8, 180: 8, 186: 4, 355: 5, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 512: 6, 513: 6, 547: 8, 548: 8, 552: 4, 562: 4, 608: 8, 610: 5, 643: 7, 705: 8, 725: 2, 740: 5, 742: 8, 743: 8, 800: 8, 830: 7, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 3, 921: 8, 922: 8, 933: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 979: 2, 998: 5, 999: 7, 1000: 8, 1001: 8, 1008: 2, 1017: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1059: 1, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1207: 8, 1227: 8, 1235: 8, 1263: 8, 1279: 8, 1552: 8, 1553: 8, 1554: 8, 1555: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1596: 8, 1597: 8, 1600: 8, 1664: 8, 1728: 8, 1745: 8, 1779: 8
}],
CAR.PRIUS: [{
# with ipas
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 512: 6, 513: 6, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 614: 8, 643: 7, 658: 8, 713: 8, 740: 5, 742: 8, 743: 8, 800: 8, 810: 2, 814: 8, 824: 2, 829: 2, 830: 7, 835: 8, 836: 8, 845: 5, 863: 8, 869: 7, 870: 7, 871: 2,898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 918: 8, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 974: 8, 975: 5, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1005: 2, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1076: 8, 1077: 8, 1082: 8, 1083: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1175: 8, 1227: 8, 1228: 8, 1235: 8, 1237: 8, 1264: 8, 1279: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1595: 8, 1777: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
#2019 LE
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 614: 8, 643: 7, 658: 8, 713: 8, 740: 5, 742: 8, 743: 8, 800: 8, 810: 2, 814: 8, 829: 2, 830: 7, 835: 8, 836: 8, 863: 8, 865: 8, 869: 7, 870: 7, 871: 2, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 918: 8, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 5, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1076: 8, 1077: 8, 1082: 8, 1083: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1175: 8, 1227: 8, 1228: 8, 1235: 8, 1237: 8, 1279: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1595: 8, 1777: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
#2020 Prius Prime Limited
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 614: 8, 643: 7, 658: 8, 713: 8, 740: 5, 742: 8, 743: 8, 800: 8, 810: 2, 814: 8, 824: 2, 829: 2, 830: 7, 835: 8, 836: 8, 863: 8, 865: 8, 869: 7, 870: 7, 871: 2, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 918: 8, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 974: 8, 975: 5, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1076: 8, 1077: 8, 1082: 8, 1083: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1175: 8, 1227: 8, 1228: 8, 1235: 8, 1237: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1595: 8, 1649: 8, 1777: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8, 2015: 8, 2024: 8, 2026: 8, 2027: 8, 2029: 8, 2030: 8, 2031: 8
}],
#Corolla w/ added Pedal Support (512L and 513L)
CAR.COROLLA: [{
36: 8, 37: 8, 170: 8, 180: 8, 186: 4, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 512: 6, 513: 6, 547: 8, 548: 8, 552: 4, 608: 8, 610: 5, 643: 7, 705: 8, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 2, 921: 8, 933: 8, 944: 8, 945: 8, 951: 8, 955: 4, 956: 8, 979: 2, 992: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1017: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1059: 1, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1196: 8, 1227: 8, 1235: 8, 1279: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1596: 8, 1597: 8, 1600: 8, 1664: 8, 1728: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8, 2016: 8, 2017: 8, 2018: 8, 2019: 8, 2020: 8, 2021: 8, 2022: 8, 2023: 8, 2024: 8
}],
CAR.LEXUS_RXH: [{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 512: 6, 513:6, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 5, 643: 7, 658: 8, 713: 8, 740: 5, 742: 8, 743: 8, 800: 8, 810: 2, 812: 3, 814: 8, 830: 7, 835: 8, 836: 8, 845: 5, 863: 8, 869: 7, 870: 7, 871: 2, 898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 918: 8, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 6, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1005: 2, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1063: 8, 1071: 8, 1077: 8, 1082: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1227: 8, 1228: 8, 1235: 8, 1237: 8, 1264: 8, 1279: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1575: 8, 1595: 8, 1777: 8, 1779: 8, 1808: 8, 1810: 8, 1816: 8, 1818: 8, 1840: 8, 1848: 8, 1904: 8, 1912: 8, 1940: 8, 1941: 8, 1948: 8, 1949: 8, 1952: 8, 1956: 8, 1960: 8, 1964: 8, 1986: 8, 1990: 8, 1994: 8, 1998: 8, 2004: 8, 2012: 8
},
# RX450HL
# TODO: get proper fingerprint in stock mode
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 512: 6, 513: 6, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 5, 643: 7, 658: 8, 713: 8, 740: 5, 742: 8, 743: 8, 800: 8, 810: 2, 812: 3, 814: 8, 830: 7, 835: 8, 836: 8, 863: 8, 865: 8, 869: 7, 870: 7, 898: 8, 900: 6, 902: 6, 905: 8, 918: 8, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 6, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1005: 2, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1056: 8, 1057: 8, 1059: 1, 1063: 8, 1071: 8, 1076: 8, 1077: 8, 1082: 8, 1114: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1227: 8, 1228: 8, 1237: 8, 1264: 8, 1279: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1575: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1777: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
# RX540H 2019 with color hud
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 512: 6, 513: 6, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 5, 643: 7, 658: 8, 713: 8, 740: 5, 742: 8, 743: 8, 800: 8, 810: 2, 812: 3, 814: 8, 818: 8, 819: 8, 820: 8, 821: 8, 822: 8, 830: 7, 835: 8, 836: 8, 845: 5, 863: 8, 865: 8, 869: 7, 870: 7, 871: 2, 898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 918: 8, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 6, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1063: 8, 1071: 8, 1076: 8, 1077: 8, 1082: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1227: 8, 1228: 8, 1235: 8, 1237: 8, 1263: 8, 1264: 8, 1279: 8, 1349: 8, 1350: 8, 1351: 8, 1413: 8, 1414: 8, 1415: 8, 1416: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1575: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1777: 8, 1779: 8, 1808: 8, 1810: 8, 1816: 8, 1818: 8, 1904: 8, 1912: 8, 1952: 8, 1960: 8, 1990: 8, 1998: 8
}],
CAR.CHR: [{
36: 8, 37: 8, 170: 8, 180: 8, 186: 4, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 608: 8, 610: 8, 614: 8, 643: 7, 658: 8, 705: 8, 740: 5, 800: 8, 810: 2, 812: 8, 814: 8, 830: 7, 835: 8, 836: 8, 845: 5, 869: 7, 870: 7, 871: 2, 898: 8, 913: 8, 918: 8, 921: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 1014: 8, 1017: 8, 1020: 8, 1021: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1082: 8, 1083: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1175: 8, 1228: 8, 1235: 8, 1237: 8, 1279: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1595: 8, 1745: 8, 1779: 8
}],
CAR.CHRH: [{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 614: 8, 643: 7, 658: 8, 713: 8, 740: 5, 800: 8, 810: 2, 812: 8, 814: 8, 829: 2, 830: 7, 835: 8, 836: 8, 845: 5, 869: 7, 870: 7, 871: 2, 898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 918: 8, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 5, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1014: 8, 1017: 8, 1020: 8, 1021: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1076: 8, 1077: 8, 1082: 8, 1083: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1175: 8, 1228: 8, 1235: 8, 1237: 8, 1279: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1595: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}],
CAR.CAMRY: [
#XLE and LE
{
36: 8, 37: 8, 119: 6, 170: 8, 180: 8, 186: 4, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 608: 8, 610: 8, 643: 7, 658: 8, 705: 8, 728: 8, 740: 5, 761: 8, 764: 8, 800: 8, 810: 2, 812: 8, 814: 8, 818: 8, 822: 8, 824: 8, 830: 7, 835: 8, 836: 8, 869: 7, 870: 7, 871: 2, 888: 8, 889: 8, 891: 8, 898: 8, 900: 6, 902: 6, 905: 8, 918: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 983: 8, 984: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1011: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1076: 8, 1077: 8, 1082: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1228: 8, 1235: 8, 1237: 8, 1263: 8, 1264: 8, 1279: 8, 1412: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1595: 8, 1745: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1808: 8, 1816: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
#XSE and SE
# TODO: get proper fingerprint in stock mode
{
36: 8, 37: 8, 114: 5, 119: 6, 120: 4, 170: 8, 180: 8, 186: 4, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 608: 8, 610: 8, 643: 7, 658: 8, 705: 8, 728: 8, 740: 5, 761: 8, 764: 8, 800: 8, 810: 2, 812: 8, 814: 8, 818: 8, 822: 8, 824: 8, 830: 7, 835: 8, 836: 8, 869: 7, 870: 7, 888: 8, 889: 8, 891: 8, 898: 8, 900: 6, 902: 6, 905: 8, 918: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 983: 8, 984: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1011: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1056: 8, 1059: 1, 1076: 8, 1077: 8, 1082: 8, 1114: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1228: 8, 1237: 8, 1263: 8, 1264: 8, 1279: 8, 1412: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1595: 8, 1745: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1808: 8, 1816: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}],
CAR.CAMRYH: [
#SE, LE and LE with Blindspot Monitor
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 643: 7, 713: 8, 728: 8, 740: 5, 761: 8, 764: 8, 800: 8, 810: 2, 812: 8, 818: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 889: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 5, 983: 8, 984: 8, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1011: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1076: 8, 1077: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1235: 8, 1237: 8, 1264: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1745: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1808: 8, 1810: 8, 1816: 8, 1818: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
#SL
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 643: 7, 713: 8, 728: 8, 740: 5, 761: 8, 764: 8, 800: 8, 810: 2, 812: 8, 818: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 869: 7, 870: 7, 871: 2, 888: 8, 889: 8, 898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 918: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 5, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1076: 8, 1077: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1228: 8, 1235: 8, 1237: 8, 1264: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1595: 8, 1745: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
#XLE
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 643: 7, 658: 8, 713: 8, 728: 8, 740: 5, 761: 8, 764: 8, 800: 8, 810: 2, 812: 8, 814: 8, 818: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 869: 7, 870: 7, 871: 2, 888: 8, 889: 8, 898: 8, 900: 6, 902: 6, 905: 8, 918: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 5, 983: 8, 984: 8, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1011: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1076: 8, 1077: 8, 1082: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1228: 8, 1235: 8, 1237: 8, 1264: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1595: 8, 1745: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}],
CAR.HIGHLANDER: [{
36: 8, 37: 8, 114: 5, 119: 6, 120: 4, 170: 8, 180: 8, 186: 4, 238: 4, 355: 5, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 545: 5, 550: 8, 552: 4, 608: 8, 610: 5, 643: 7, 705: 8, 725: 2, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 3, 921: 8, 922: 8, 933: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 979: 2, 998: 5, 999: 7, 1000: 8, 1001: 8, 1008: 2, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1059: 1, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1182: 8, 1183: 8, 1189: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1206: 8, 1207: 8, 1212: 8, 1227: 8, 1235: 8, 1237: 8, 1279: 8, 1408: 8, 1409: 8, 1410: 8, 1552: 8, 1553: 8, 1554: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1599: 8, 1656: 8, 1666: 8, 1667: 8, 1728: 8, 1745: 8, 1779: 8, 1872: 8, 1880: 8, 1904: 8, 1912: 8, 1984: 8, 1988: 8, 1992: 8, 1996: 8, 1990: 8, 1998: 8
},
# 2019 Highlander XLE
{
36: 8, 37: 8, 114: 5, 119: 6, 120: 4, 170: 8, 180: 8, 186: 4, 238: 4, 355: 5, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 545: 5, 550: 8, 552: 4, 608: 8, 610: 5, 643: 7, 705: 8, 725: 2, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 3, 921: 8, 922: 8, 933: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 979: 2, 992: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1008: 2, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1059: 1, 1076: 8, 1077: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1182: 8, 1183: 8, 1189: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1206: 8, 1207: 8, 1212: 8, 1227: 8, 1235: 8, 1237: 8, 1279: 8, 1408: 8, 1409: 8, 1410: 8, 1552: 8, 1553: 8, 1554: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1599: 8, 1656: 8, 1728: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
# 2017 Highlander Limited
{
36: 8, 37: 8, 114: 5, 119: 6, 120: 4, 170: 8, 180: 8, 186: 4, 238: 4, 355: 5, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 545: 5, 550: 8, 552: 4, 608: 8, 610: 5, 643: 7, 705: 8, 725: 2, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 3, 918: 7, 921: 8, 922: 8, 933: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 979: 2, 998: 5, 999: 7, 1000: 8, 1001: 8, 1005: 2, 1008: 2, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1059: 1, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1182: 8, 1183: 8, 1189: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1206: 8, 1207: 8, 1212: 8, 1227: 8, 1235: 8, 1237: 8, 1264: 8, 1279: 8, 1408: 8, 1409: 8, 1410: 8, 1552: 8, 1553: 8, 1554: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1599: 8, 1656: 8, 1728: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}],
CAR.HIGHLANDERH: [{
36: 8, 37: 8, 170: 8, 180: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 581: 5, 608: 8, 610: 5, 643: 7, 713: 8, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 3, 918: 7, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 3, 955: 8, 956: 8, 979: 2, 998: 5, 999: 7, 1000: 8, 1001: 8, 1005: 2, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1059: 1, 1112: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1184: 8, 1185: 8, 1186: 8, 1189: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1206: 8, 1212: 8, 1227: 8, 1232: 8, 1235: 8, 1237: 8, 1263: 8, 1264: 8, 1279: 8, 1552: 8, 1553: 8, 1554: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1599: 8, 1656: 8, 1728: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
{
# 2019 Highlander Hybrid Limited Platinum
36: 8, 37: 8, 170: 8, 180: 8, 296: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 581: 5, 608: 8, 610: 5, 643: 7, 713: 8, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 3, 918: 7, 921: 8, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 3, 955: 8, 956: 8, 979: 2, 992: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1076: 8, 1077: 8, 1112: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1184: 8, 1185: 8, 1186: 8, 1189: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1206: 8, 1212: 8, 1227: 8, 1232: 8, 1235: 8, 1237: 8, 1263: 8, 1279: 8, 1552: 8, 1553: 8, 1554: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1599: 8, 1656: 8, 1666: 8, 1667: 8, 1728: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}],
CAR.AVALON: [{
36: 8, 37: 8, 170: 8, 180: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 547: 8, 550: 8, 552: 4, 562: 6, 608: 8, 610: 5, 643: 7, 705: 8, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 905: 8, 911: 1, 916: 2, 921: 8, 933: 6, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 979: 2, 1005: 2, 1014: 8, 1017: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1200: 8, 1201: 8, 1202: 8, 1203: 8, 1206: 8, 1227: 8, 1235: 8, 1237: 8, 1264: 8, 1279: 8, 1552: 8, 1553: 8, 1554: 8, 1555: 8, 1556: 8, 1557: 8, 1558: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1596: 8, 1597: 8, 1664: 8, 1728: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}],
CAR.RAV4_TSS2: [
# LE
{
36: 8, 37: 8, 170: 8, 180: 8, 186: 4, 355: 5, 401: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 565: 8, 608: 8, 610: 8, 643: 7, 705: 8, 728: 8, 740: 5, 742: 8, 743: 8, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 882: 8, 885: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1063: 8, 1076: 8, 1077: 8,1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1235: 8, 1279: 8, 1541: 8, 1552: 8, 1553:8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1745: 8, 1775: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
# XLE, Limited, and AWD
{
36: 8, 37: 8, 170: 8, 180: 8, 186: 4, 401: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 565: 8, 608: 8, 610: 8, 643: 7, 658: 8, 705: 8, 728: 8, 740: 5, 742: 8, 743: 8, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 814: 8, 818: 8, 822: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 882: 8, 885: 8, 889: 8, 891: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 918: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 987: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1063: 8, 1076: 8, 1077: 8, 1082: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1228: 8, 1235: 8, 1237: 8, 1263: 8, 1264: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1696: 8, 1745: 8, 1775: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8, 2015: 8, 2016: 8, 2024: 8
}],
CAR.COROLLA_TSS2: [
# hatch 2019+ and sedan 2020+
{
36: 8, 37: 8, 114: 5, 170: 8, 180: 8, 186: 4, 401: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 608: 8, 610: 8, 643: 7, 705: 8, 728: 8, 740: 5, 742: 8, 743: 8, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1076: 8, 1077: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1235: 8, 1237: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1595: 8, 1649: 8, 1745: 8, 1775: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1808: 8, 1809: 8, 1816: 8, 1817: 8, 1840: 8, 1848: 8, 1904: 8, 1912: 8, 1940: 8, 1941: 8, 1948: 8, 1949: 8, 1952: 8, 1960: 8, 1981: 8, 1986: 8, 1990: 8, 1994: 8, 1998: 8, 2004: 8
}],
CAR.COROLLAH_TSS2: [
# 2019 Taiwan Altis Hybrid
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 401: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 643: 7, 713: 8, 728: 8, 740: 5, 742: 8, 743: 8, 761: 8, 765: 8, 800: 8, 810: 2, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 885: 8, 896: 8, 898: 8, 918: 7, 921: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 5, 987: 8, 993: 8, 1002: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1082: 8, 1112: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1172: 8, 1235: 8, 1237: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1594: 8, 1595: 8, 1745: 8, 1775: 8, 1779: 8
},
# 2019 Chinese Levin Hybrid
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 401: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 643: 7, 713: 8, 728: 8, 740: 5, 742: 8, 743: 8, 761: 8, 765: 8, 800: 8, 810: 2, 812: 8, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 885: 8, 896: 8, 898: 8, 921: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 5, 993: 8, 1002: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1172: 8, 1235: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1594: 8, 1595: 8, 1600: 8, 1649: 8, 1745: 8, 1775: 8, 1779: 8
}
],
CAR.LEXUS_ES_TSS2: [{
36: 8, 37: 8, 114: 5, 119: 6, 120: 4, 170: 8, 180: 8, 186: 4, 401: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 608: 8, 610: 8, 643: 7, 658: 8, 705: 8, 728: 8, 740: 5, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 814: 8, 818: 8, 824: 8, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 882: 8, 885: 8, 889: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 918: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 987: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1076: 8, 1077: 8, 1082: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1228: 8, 1235: 8, 1237: 8, 1264: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1575: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1696: 8, 1775: 8, 1777: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8
}],
CAR.LEXUS_ESH_TSS2: [
{
36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 401: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 643: 7, 658: 8, 713: 8, 728: 8, 740: 5, 742: 8, 743: 8, 744: 8, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 814: 8, 818: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 863: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 882: 8, 885: 8, 889: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 918: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 5, 987: 8, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1076: 8, 1077: 8, 1082: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1228: 8, 1235: 8, 1264: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1575: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1696: 8, 1775: 8, 1777: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}],
CAR.SIENNA: [
{
36: 8, 37: 8, 114: 5, 119: 6, 120: 4, 170: 8, 180: 8, 186: 4, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 545: 5, 548: 8, 550: 8, 552: 4, 562: 4, 608: 8, 610: 5, 643: 7, 705: 8, 725: 2, 740: 5, 764: 8, 800: 8, 824: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 888: 8, 896: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 1, 918: 7, 921: 8, 933: 8, 944: 6, 945: 8, 951: 8, 955: 8, 956: 8, 979: 2, 992: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1008: 2, 1014: 8, 1017: 8, 1041: 8, 1042: 8, 1043: 8, 1056: 8, 1059: 1, 1076: 8, 1077: 8, 1114: 8, 1160: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1182: 8, 1183: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1200: 8, 1201: 8, 1202: 8, 1203: 8, 1212: 8, 1227: 8, 1228: 8, 1235: 8, 1237: 8, 1279: 8, 1552: 8, 1553: 8, 1555: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1656: 8, 1664: 8, 1666: 8, 1667: 8, 1728: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
# XLE AWD 2018
{
36: 8, 37: 8, 114: 5, 119: 6, 120: 4, 170: 8, 180: 8, 186: 4, 238: 4, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 545: 5, 548: 8, 550: 8, 552: 4, 562: 4, 608: 8, 610: 5, 643: 7, 705: 8, 725: 2, 740: 5, 764: 8, 800: 8, 824: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 1, 921: 8, 933: 8, 944: 6, 945: 8, 951: 8, 955: 8, 956: 8, 979: 2, 992: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1008: 2, 1014: 8, 1017: 8, 1041: 8, 1042: 8, 1043: 8, 1056: 8, 1059: 1, 1076: 8, 1077: 8, 1114: 8, 1160: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1182: 8, 1183: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1200: 8, 1201: 8, 1202: 8, 1203: 8, 1212: 8, 1227: 8, 1235: 8, 1237: 8, 1279: 8, 1552: 8, 1553: 8, 1555: 8, 1556: 8, 1557: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1656: 8, 1664: 8, 1666: 8, 1667: 8, 1728: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}],
CAR.LEXUS_IS: [
# IS300 2018
{
36: 8, 37: 8, 114: 5, 119: 6, 120: 4, 170: 8, 180: 8, 186: 4, 238: 4, 400: 6, 426: 6, 452: 8, 464: 8, 466: 8, 467: 5, 544: 4, 550: 8, 552: 4, 608: 8, 610: 5, 643: 7, 705: 8, 740: 5, 800: 8, 836: 8, 845: 5, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 900: 6, 902: 6, 905: 8, 911: 8, 913: 8, 916: 3, 918: 7, 921: 8, 933: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 979: 2, 992: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1005: 2, 1008: 2, 1009: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1059: 1, 1112: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1168: 1, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1182: 8, 1183: 8, 1184: 8, 1185: 8, 1186: 8, 1187: 8, 1189: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1206: 8, 1208: 8, 1212: 8, 1227: 8, 1235: 8, 1237: 8, 1279: 8, 1408: 8, 1409: 8, 1410: 8, 1552: 8, 1553: 8, 1554: 8, 1555: 8, 1556: 8, 1557: 8, 1561: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1575: 8, 1584: 8, 1589: 8, 1590: 8, 1592: 8, 1593: 8, 1595: 8, 1599: 8, 1648: 8, 1666: 8, 1667: 8, 1728: 8, 1745: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
},
# IS300H 2017
{
36: 8, 37: 8, 170: 8, 180: 8, 295: 8, 296: 8, 400: 6, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 581: 5, 608: 8, 610: 5, 643: 7, 713: 8, 740: 5, 800: 8, 836: 8, 845: 5, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 900: 6, 902: 6, 905: 8, 911: 8, 913: 8, 916: 3, 918: 7, 921: 7, 933: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 3, 955: 8, 956: 8, 979: 2, 992: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1009: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1056: 8, 1057: 8, 1059: 1, 1112: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1168: 1, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1184: 8, 1185: 8, 1186: 8, 1187: 8, 1189: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1197: 8, 1198: 8, 1199: 8, 1206: 8, 1208: 8, 1212: 8, 1227: 8, 1232: 8, 1235: 8, 1279: 8, 1408: 8, 1409: 8, 1410: 8, 1552: 8, 1553: 8, 1554: 8, 1555: 8, 1556: 8, 1557: 8, 1561: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1575: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1599: 8, 1728: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}],
CAR.LEXUS_CTH: [{
36: 8, 37: 8, 170: 8, 180: 8, 288: 8, 426: 6, 452: 8, 466: 8, 467: 8, 548: 8, 552: 4, 560: 7, 581: 5, 608: 8, 610: 5, 643: 7, 713: 8, 740: 5, 800: 8, 810: 2, 832: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 897: 8, 900: 6, 902: 6, 905: 8, 911: 8, 916: 1, 921: 8, 933: 8, 944: 6, 945: 8, 950: 8, 951: 8, 953: 3, 955: 4, 956: 8, 979: 2, 992: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1017: 8, 1041: 8, 1042: 8, 1043: 8, 1056: 8, 1057: 8, 1059: 1, 1076: 8, 1077: 8, 1114: 8, 1116: 8, 1160: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1184: 8, 1185: 8, 1186: 8, 1190: 8, 1191: 8, 1192: 8, 1227: 8, 1235: 8, 1279: 8, 1552: 8, 1553: 8, 1554: 8, 1555: 8, 1556: 8, 1557: 8, 1558: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1575: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1664: 8, 1728: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8
}]
}
FW_VERSIONS = {
CAR.COROLLA_TSS2: {
(Ecu.engine, 0x700, None): [b'\x01896630ZG5000\x00\x00\x00\x00'],
(Ecu.eps, 0x7a1, None): [b'\x018965B12350\x00\x00\x00\x00\x00\x00'],
(Ecu.esp, 0x7b0, None): [b'\x01F152602280\x00\x00\x00\x00\x00\x00'],
(Ecu.fwdRadar, 0x750, 0xf): [b'\x018821F3301100\x00\x00\x00\x00'],
(Ecu.fwdCamera, 0x750, 0x6d): [b'\x028646F1201200\x00\x00\x00\x008646G26011A0\x00\x00\x00\x00'],
},
CAR.PRIUS: {
(Ecu.engine, 0x700, None): [b'\x03896634759200\x00\x00\x00\x008966A4703000\x00\x00\x00\x00897CF4701003\x00\x00\x00\x00'],
(Ecu.eps, 0x7a1, None): [b'8965B47023\x00\x00\x00\x00\x00\x00'],
(Ecu.esp, 0x7b0, None): [b'F152647416\x00\x00\x00\x00\x00\x00'],
(Ecu.dsu, 0x791, None): [b'881514703100\x00\x00\x00\x00'],
(Ecu.fwdRadar, 0x750, 0xf): [b'8821F4702100\x00\x00\x00\x00'],
(Ecu.fwdCamera, 0x750, 0x6d): [b'8646F4702100\x00\x00\x00\x00'],
},
CAR.RAV4: {
(Ecu.engine, 0x7e0, None): [b'\x02342Q2100\x00\x00\x00\x00\x00\x00\x00\x0054213000\x00\x00\x00\x00\x00\x00\x00\x00'],
(Ecu.eps, 0x7a1, None): [b'8965B42083\x00\x00\x00\x00\x00\x00'],
(Ecu.esp, 0x7b0, None): [b'F15260R103\x00\x00\x00\x00\x00\x00'],
(Ecu.dsu, 0x791, None): [b'881514201400\x00\x00\x00\x00'],
(Ecu.fwdRadar, 0x750, 0xf): [b'8821F4702100\x00\x00\x00\x00'],
(Ecu.fwdCamera, 0x750, 0x6d): [b'8646F4202100\x00\x00\x00\x00'],
}
}
STEER_THRESHOLD = 100
DBC = {
CAR.RAV4H: dbc_dict('toyota_rav4_hybrid_2017_pt_generated', 'toyota_adas'),
CAR.RAV4: dbc_dict('toyota_rav4_2017_pt_generated', 'toyota_adas'),
CAR.PRIUS: dbc_dict('toyota_prius_2017_pt_generated', 'toyota_adas'),
CAR.COROLLA: dbc_dict('toyota_corolla_2017_pt_generated', 'toyota_adas'),
CAR.LEXUS_RXH: dbc_dict('lexus_rx_hybrid_2017_pt_generated', 'toyota_adas'),
CAR.CHR: dbc_dict('toyota_nodsu_pt_generated', 'toyota_adas'),
CAR.CHRH: dbc_dict('toyota_nodsu_hybrid_pt_generated', 'toyota_adas'),
CAR.CAMRY: dbc_dict('toyota_nodsu_pt_generated', 'toyota_adas'),
CAR.CAMRYH: dbc_dict('toyota_camry_hybrid_2018_pt_generated', 'toyota_adas'),
CAR.HIGHLANDER: dbc_dict('toyota_highlander_2017_pt_generated', 'toyota_adas'),
CAR.HIGHLANDERH: dbc_dict('toyota_highlander_hybrid_2018_pt_generated', 'toyota_adas'),
CAR.AVALON: dbc_dict('toyota_avalon_2017_pt_generated', 'toyota_adas'),
CAR.RAV4_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'),
CAR.COROLLA_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'),
CAR.COROLLAH_TSS2: dbc_dict('toyota_nodsu_hybrid_pt_generated', 'toyota_tss2_adas'),
CAR.LEXUS_ES_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'),
CAR.LEXUS_ESH_TSS2: dbc_dict('toyota_nodsu_hybrid_pt_generated', 'toyota_tss2_adas'),
CAR.SIENNA: dbc_dict('toyota_sienna_xle_2018_pt_generated', 'toyota_adas'),
CAR.LEXUS_IS: dbc_dict('lexus_is_2018_pt_generated', 'toyota_adas'),
CAR.LEXUS_CTH: dbc_dict('lexus_ct200h_2018_pt_generated', 'toyota_adas'),
}
NO_DSU_CAR = [CAR.CHR, CAR.CHRH, CAR.CAMRY, CAR.CAMRYH, CAR.RAV4_TSS2, CAR.COROLLA_TSS2, CAR.COROLLAH_TSS2, CAR.LEXUS_ES_TSS2, CAR.LEXUS_ESH_TSS2]
TSS2_CAR = [CAR.RAV4_TSS2, CAR.COROLLA_TSS2, CAR.COROLLAH_TSS2, CAR.LEXUS_ES_TSS2, CAR.LEXUS_ESH_TSS2]
NO_STOP_TIMER_CAR = [CAR.RAV4H, CAR.HIGHLANDERH, CAR.HIGHLANDER, CAR.RAV4_TSS2, CAR.COROLLA_TSS2, CAR.COROLLAH_TSS2, CAR.LEXUS_ES_TSS2, CAR.LEXUS_ESH_TSS2, CAR.SIENNA] # no resume button press required
|
//
// PluginLogging.h
// libraries/gl/src/gl/
//
// Created by Seth Alves on 2016-9-14.
// Copyright 2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#ifndef hifi_PluginLogging_h
#define hifi_PluginLogging_h
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(plugins)
#endif // hifi_PluginLogging_h
|
# Copyright (c) 2016. Mount Sinai School of Medicine
#
# 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.
from . import data_path, generated_data_path
import vcf
from varcode import load_vcf_fast
from os import path, makedirs
def generate_vcfs(id_to_mutation_count, file_format, template_name):
"""
Generate cropped VCFs from a template, for each sample.
Parameters
----------
id_to_mutation_count : dict
sample ID to number of mutations we want to generate for that sample
Returns
-------
str
Path to the generated VCF directory
"""
for sample_id in id_to_mutation_count.keys():
template_path = data_path(template_name)
vcf_reader = vcf.Reader(filename=template_path)
file_path = generated_data_path(
path.join("vcfs", file_format % sample_id))
file_dir = path.dirname(file_path)
if not path.exists(file_dir):
makedirs(file_dir)
with open(file_path, "w") as f:
vcf_writer = vcf.Writer(f, vcf_reader)
i = 0
num_records_in_template = len(load_vcf_fast(template_path))
num_records_to_generate = id_to_mutation_count[sample_id]
assert num_records_in_template >= num_records_to_generate, (
"Cannot generate more records than exist in the template: %d is less than %d" % (
num_records_in_template, num_records_to_generate))
for record in vcf_reader:
if i < id_to_mutation_count[sample_id]:
vcf_writer.write_record(record)
i += 1
else:
break
return path.dirname(f.name)
|
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helpers for defining Apple bundling rules uniformly."""
load(
"@build_bazel_rules_apple//apple/bundling:product_support.bzl",
"apple_product_type",
)
load(
"@build_bazel_rules_apple//apple/internal/aspects:framework_import_aspect.bzl",
"framework_import_aspect",
)
load(
"@build_bazel_rules_apple//apple/internal/aspects:resource_aspect.bzl",
"apple_resource_aspect",
)
load(
"@build_bazel_rules_apple//apple/internal:rule_support.bzl",
"rule_support",
)
load(
"@build_bazel_rules_apple//apple:providers.bzl",
"AppleBundleInfo",
"AppleBundleVersionInfo",
"IosFrameworkBundleInfo",
"IosImessageExtensionBundleInfo",
"IosStickerPackExtensionBundleInfo",
)
load(
"@build_bazel_rules_swift//swift:swift.bzl",
"swift_usage_aspect",
)
load(
"@bazel_skylib//lib:dicts.bzl",
"dicts",
)
# Private attributes on every rule that provide access to tools and other file dependencies.
_COMMON_PRIVATE_TOOL_ATTRS = {
"_bundletool": attr.label(
cfg = "host",
executable = True,
default = Label("@build_bazel_rules_apple//tools/bundletool"),
),
"_bundletool_experimental": attr.label(
cfg = "host",
executable = True,
default = Label("@build_bazel_rules_apple//tools/bundletool:bundletool_experimental"),
),
"_environment_plist": attr.label(
cfg = "host",
executable = True,
default = Label("@build_bazel_rules_apple//tools/environment_plist"),
),
"_plisttool": attr.label(
cfg = "host",
default = Label("@build_bazel_rules_apple//tools/plisttool"),
executable = True,
),
"_process_and_sign_template": attr.label(
allow_single_file = True,
default = Label("@build_bazel_rules_apple//tools/bundletool:process_and_sign_template"),
),
# TODO(b/117933004): Find out whether realpath is still needed for symlinking, and if not,
# remove this attribute, which is still used by file_actions.symlink.
"_realpath": attr.label(
cfg = "host",
allow_single_file = True,
default = Label("@build_bazel_rules_apple//tools/realpath"),
),
"_xcode_config": attr.label(
default = configuration_field(
name = "xcode_config_label",
fragment = "apple",
),
),
# TODO(b/117932394): Remove uses of this private attribute and migrate them to the _xctoolrunner
# tool instead.
"_xcrunwrapper": attr.label(
cfg = "host",
executable = True,
default = Label("@bazel_tools//tools/objc:xcrunwrapper"),
),
"_xctoolrunner": attr.label(
cfg = "host",
executable = True,
default = Label("@build_bazel_rules_apple//tools/xctoolrunner"),
),
}
_COMMON_BINARY_LINKING_ATTRS = {
"_cc_toolchain": attr.label(
default = configuration_field(
name = "cc_toolchain",
fragment = "cpp",
),
),
"_child_configuration_dummy": attr.label(
cfg = apple_common.multi_arch_split,
default = configuration_field(
name = "cc_toolchain",
fragment = "cpp",
),
),
"_googlemac_proto_compiler": attr.label(
cfg = "host",
default = Label("@bazel_tools//tools/objc:protobuf_compiler_wrapper"),
),
"_googlemac_proto_compiler_support": attr.label(
cfg = "host",
default = Label("@bazel_tools//tools/objc:protobuf_compiler_support"),
),
"_protobuf_well_known_types": attr.label(
cfg = "host",
default = Label("@bazel_tools//tools/objc:protobuf_well_known_types"),
),
"binary_type": attr.string(
default = "executable",
doc = """
This attribute is public as an implementation detail while we migrate the architecture of the rules.
Do not change its value.
""",
),
"bundle_loader": attr.label(
aspects = [apple_common.objc_proto_aspect],
doc = """
This attribute is public as an implementation detail while we migrate the architecture of the rules.
Do not change its value.
""",
),
"deps": attr.label_list(
aspects = [
apple_common.objc_proto_aspect,
apple_resource_aspect,
framework_import_aspect,
swift_usage_aspect,
],
cfg = apple_common.multi_arch_split,
doc = """
A list of dependencies targets that will be linked into this target's binary. Any resources, such as
asset catalogs, that are referenced by those targets will also be transitively included in the final
bundle.
""",
),
"dylibs": attr.label_list(
aspects = [apple_common.objc_proto_aspect],
doc = """
This attribute is public as an implementation detail while we migrate the architecture of the rules.
Do not change its value.
""",
),
"linkopts": attr.string_list(
doc = """
A list of strings representing extra flags that should be passed to the linker.
""",
),
}
def _get_legacy_attributes(rule_descriptor):
"""Returns a dictionary with legacy attributes that should get replaced by rule descriptors."""
# TODO(b/117933005): Remove these attributes once the uses of these are migrated to retrieving
# these configs from the rule descriptors.
return {
"_allowed_families": attr.string_list(default = rule_descriptor.allowed_device_families),
"_needs_pkginfo": attr.bool(default = rule_descriptor.requires_pkginfo),
"_requires_signing_for_device": attr.bool(
default = rule_descriptor.requires_signing_for_device,
),
"_skip_signing": attr.bool(default = rule_descriptor.skip_signing),
"_skip_simulator_signing_allowed": attr.bool(
default = rule_descriptor.skip_simulator_signing_allowed,
),
}
def _get_common_bundling_attributes(rule_descriptor):
"""Returns a list of dictionaries with attributes common to all bundling rules."""
# TODO(kaipi): Review platform specific wording in the documentation before migrating macOS
# rules to use this rule factory.
attrs = [_COMMON_PRIVATE_TOOL_ATTRS]
attrs.append({
"bundle_id": attr.string(
mandatory = True,
doc = "The bundle ID (reverse-DNS path followed by app name) for this target.",
),
"bundle_name": attr.string(
mandatory = False,
doc = """
The desired name of the bundle (without the extension). If this attribute is not set, then the name
of the target will be used instead.
""",
),
"infoplists": attr.label_list(
allow_empty = False,
allow_files = [".plist"],
mandatory = True,
doc = """
A list of .plist files that will be merged to form the Info.plist for this target. At least one file
must be specified. Please see
[Info.plist Handling](https://github.com/bazelbuild/rules_apple/blob/master/doc/common_info.md#infoplist-handling)
for what is supported.
""",
),
# TODO(b/36512239): Rename to "bundle_post_processor".
"ipa_post_processor": attr.label(
allow_files = True,
executable = True,
cfg = "host",
doc = """
A tool that edits this target's archive after it is assembled but before it is signed. The tool is
invoked with a single command-line argument that denotes the path to a directory containing the
unzipped contents of the archive; this target's bundle will be the directory's only contents.
Any changes made by the tool must be made in this directory, and the tool's execution must be
hermetic given these inputs to ensure that the result can be safely cached.
""",
),
"minimum_os_version": attr.string(
mandatory = True,
doc = """
An optional string indicating the minimum OS version supported by the target, represented as a
dotted version number (for example, "9.0"). If this attribute is omitted, then the value specified
by the flag `--ios_minimum_os` will be used instead.
""",
),
"provisioning_profile": attr.label(
allow_single_file = [rule_descriptor.provisioning_profile_extension],
doc = """
The provisioning profile (`{profile_extension}` file) to use when creating the bundle. This value is
optional for simulator builds as the simulator doesn't fully enforce entitlements, but is
required for device builds.
""".format(profile_extension = rule_descriptor.provisioning_profile_extension),
),
"strings": attr.label_list(
allow_files = [".strings"],
doc = """
A list of `.strings` files, often localizable. These files are converted to binary plists (if they
are not already) and placed in the root of the final bundle, unless a file's immediate containing
directory is named `*.lproj`, in which case it will be placed under a directory with the same name
in the bundle.
""",
),
"version": attr.label(
providers = [[AppleBundleVersionInfo]],
doc = """
An `apple_bundle_version` target that represents the version for this target. See
[`apple_bundle_version`](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-general.md?cl=head#apple_bundle_version).
""",
),
})
if len(rule_descriptor.allowed_device_families):
attrs.append({
"families": attr.string_list(
mandatory = True,
allow_empty = False,
doc = """
A list of device families supported by this extension. Valid values are `iphone` and `ipad`; at
least one must be specified.
""",
),
})
if rule_descriptor.app_icon_extension:
attrs.append({
"app_icons": attr.label_list(
allow_files = True,
doc = """
Files that comprise the app icons for the application. Each file must have a containing directory
named `*.{app_icon_parent_extension}/*.{app_icon_extension}` and there may be only one such
`.{app_icon_extension}` directory in the list.""".format(
app_icon_extension = rule_descriptor.app_icon_extension,
app_icon_parent_extension = rule_descriptor.app_icon_parent_extension,
),
),
})
if rule_descriptor.requires_deps:
attrs.append({
"entitlements": attr.label(
allow_single_file = [".entitlements"],
doc = """
The entitlements file required for device builds of this target. If absent, the default entitlements
from the provisioning profile will be used.
The following variables are substituted in the entitlements file: `$(CFBundleIdentifier)` with the
bundle ID of the application and `$(AppIdentifierPrefix)` with the value of the
`ApplicationIdentifierPrefix` key from the target's provisioning profile.
""",
),
})
return attrs
def _get_ios_attrs(rule_descriptor):
"""Returns a list of dictionaries with attributes for the iOS platform."""
attrs = []
# TODO(kaipi): Add support for all valid product types for iOS.
if rule_descriptor.product_type == apple_product_type.messages_sticker_pack_extension:
attrs.append({
"sticker_assets": attr.label_list(
allow_files = True,
doc = """
List of sticker files to bundle. The collection of assets should be under a folder named
`*.*.xcstickers`. The icons go in a `*.stickersiconset` (instead of `*.appiconset`); and the files
for the stickers should all be in Sticker Pack directories, so `*.stickerpack/*.sticker` or
`*.stickerpack/*.stickersequence`.
""",
),
})
elif rule_descriptor.product_type == apple_product_type.messages_application:
attrs.append({
"extension": attr.label(
mandatory = True,
providers = [
[AppleBundleInfo, IosImessageExtensionBundleInfo],
[AppleBundleInfo, IosStickerPackExtensionBundleInfo],
],
doc = """
Single label referencing either an ios_imessage_extension or ios_sticker_pack_extension target.
Required.
""",
),
})
# TODO(kaipi): Once all platforms have framework rules, move this into
# _COMMON_BINARY_LINKING_ATTRS.
if rule_descriptor.requires_deps:
attrs.append({
"frameworks": attr.label_list(
providers = [[AppleBundleInfo, IosFrameworkBundleInfo]],
doc = """
A list of framework targets (see
[`ios_framework`](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-ios.md#ios_framework))
that this target depends on.
""",
),
})
return attrs
def _create_apple_bundling_rule(implementation, platform_type, product_type, doc):
"""Creates an Apple bundling rule."""
rule_attrs = [
{
# TODO(kaipi): Make these attributes private. They are required by the native linking
# API and product_support.
"platform_type": attr.string(default = platform_type),
"product_type": attr.string(default = product_type),
},
]
rule_descriptor = rule_support.rule_descriptor_no_ctx(platform_type, product_type)
rule_attrs.extend(_get_common_bundling_attributes(rule_descriptor))
rule_attrs.append(_get_legacy_attributes(rule_descriptor))
if rule_descriptor.requires_deps:
rule_attrs.append(_COMMON_BINARY_LINKING_ATTRS)
# TODO(kaipi): Add support for all platforms.
if platform_type == "ios":
rule_attrs.extend(_get_ios_attrs(rule_descriptor))
archive_name = "%{name}" + rule_descriptor.archive_extension
return rule(
implementation = implementation,
# TODO(kaipi): Replace dicts.add with a version that errors on duplicate keys.
attrs = dicts.add(*rule_attrs),
doc = doc,
fragments = ["apple", "cpp", "objc"],
# TODO(kaipi): Remove the implicit output and use DefaultInfo instead.
outputs = {"archive": archive_name},
)
rule_factory = struct(
create_apple_bundling_rule = _create_apple_bundling_rule,
)
|
import { __assign } from "tslib";
import * as React from 'react';
import { StyledIconBase } from '../../StyledIconBase';
export var Youtube = React.forwardRef(function (props, ref) {
var attrs = {
"fill": "currentColor",
"xmlns": "http://www.w3.org/2000/svg",
};
return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }),
React.createElement("path", { fill: "none", d: "M0 0h24v24H0z", key: "k0" }),
React.createElement("path", { d: "M21.543 6.498C22 8.28 22 12 22 12s0 3.72-.457 5.502c-.254.985-.997 1.76-1.938 2.022C17.896 20 12 20 12 20s-5.893 0-7.605-.476c-.945-.266-1.687-1.04-1.938-2.022C2 15.72 2 12 2 12s0-3.72.457-5.502c.254-.985.997-1.76 1.938-2.022C6.107 4 12 4 12 4s5.896 0 7.605.476c.945.266 1.687 1.04 1.938 2.022zM10 15.5l6-3.5-6-3.5v7z", key: "k1" })));
});
Youtube.displayName = 'Youtube';
export var YoutubeDimensions = { height: 24, width: 24 };
|
import logging
import time
import asyncpraw
import discord
from discord.ext import tasks, commands
from utils.config import config
log = logging.getLogger(__name__)
class RedditTask(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot_started_at = time.time()
self.cache = []
self.client_id = config.get("reddit", {}).get("client_id")
self.client_secret = config.get("reddit", {}).get("client_secret")
self.user_agent = config.get("reddit", {}).get("user_agent")
self.subreddit = config.get("reddit", {}).get("subreddit")
self.channel = config.get("reddit", {}).get("channel")
if not all([self.client_id, self.client_secret, self.user_agent, self.subreddit, self.channel]):
log.warning("Reddit functionality is disabled due to missing prerequisites")
return
self.reddit = asyncpraw.Reddit(
client_id=self.client_id,
client_secret=self.client_secret,
user_agent=self.user_agent
)
log.info("Starting reddit functionality background task")
self.check_for_posts.start()
def cog_unload(self):
self.check_for_posts.cancel()
@tasks.loop(seconds=5)
async def check_for_posts(self):
""" Posts new reddit submissions to channel specified in config """
# Needed to fix bot crashes when reddit is down during startup.
await self.bot.wait_until_ready()
try:
subreddit = await self.reddit.subreddit(config["reddit"]["subreddit"])
async for submission in subreddit.new(limit=10):
if submission.id in self.cache or submission.created_utc <= self.bot_started_at:
continue
await submission.author.load()
await submission.subreddit.load()
embed = discord.Embed(
title=submission.title[0:252],
url=f"https://reddit.com{submission.permalink}",
description=submission.selftext[0:350], # Cuts off the description.
)
embed.set_author(
name=submission.author.name,
url=f"https://reddit.com/u/{submission.author.name}",
icon_url=submission.author.icon_img
)
embed.set_footer(
text=f"{submission.link_flair_text} posted on /r/{submission.subreddit}",
icon_url=submission.subreddit.community_icon)
# Adds ellipsis if the data is too long to signify cutoff.
if len(submission.title) >= 252:
embed.title = embed.title + "..."
if len(submission.selftext) >= 350:
embed.description = embed.description + "..."
if not isinstance(self.channel, discord.TextChannel):
self.channel = await self.bot.fetch_channel(self.channel)
log.info(f"{submission.title} was posted by /u/{submission.author.name}")
await self.channel.send(embed=embed)
self.cache.append(submission.id)
# Catch all exceptions to avoid crashing when reddit has downtime.
except Exception as e:
log.error(e)
def setup(bot) -> None:
bot.add_cog(RedditTask(bot))
log.info("Task loaded: reddit")
|
var ElapsedTimeBar = {
// default value
barColor: 'rgb(200,0,0)',
pausedBarColor: 'rgba(200,0,0,.6)',
isPaused: false,
isFinished: false,
allottedTime: null,
timeProgressBar: null,
startTime: null,
pauseTime: null,
pauseTimeDuration: 0,
/**
* initialize elements
*/
handleReady() {
var config = Reveal.getConfig();
// activate this plugin if config.allottedTime exists.
if (!config.allottedTime) {
console.warn('Failed to start ElapsedTimeBar plugin. "allottedTime" property is required.');
return;
}
// set configurations
this.barColor = config.barColor || this.barColor;
this.pausedBarColor = config.pausedBarColor || this.pausedBarColor;
// calc barHeight from config.barHeight or page-progress container
var barHeight;
var pageProgressContainer = document.querySelector('.progress');
if (config.progressBarHeight) {
barHeight = parseInt(config.progressBarHeight, 10) + 'px';
// override height of page-progress container
pageProgressContainer && (pageProgressContainer.style.height = barHeight);
} else if (config.progress && pageProgressContainer) {
// get height from page-progress container
barHeight = pageProgressContainer.getBoundingClientRect().height + 'px';
} else {
// default
barHeight = '3px';
}
// create container of time-progress
var timeProgressContainer = document.createElement('div');
timeProgressContainer.classList.add('progress');
Object.entries({
display: 'block',
position: 'fixed',
bottom: config.progress ? barHeight : 0,
width: '100%',
height: barHeight
}).forEach(([k, v]) => {
timeProgressContainer.style[k] = v;
});
document.querySelector('.reveal').appendChild(timeProgressContainer);
// create content of time-progress
this.timeProgressBar = document.createElement('div');
Object.entries({
height: '100%',
willChange: 'width'
}).forEach(([k, v]) => {
this.timeProgressBar.style[k] = v;
});
timeProgressContainer.appendChild(this.timeProgressBar);
// start timer
this.start(config.allottedTime);
},
/**
* update repeatedly using requestAnimationFrame.
*/
loop() {
if (this.isPaused) return;
var now = +new Date();
var elapsedTime = now - this.startTime - this.pauseTimeDuration;
if (elapsedTime > this.allottedTime) {
this.timeProgressBar.style.width = '100%';
this.isFinished = true;
} else {
this.timeProgressBar.style.width = elapsedTime / this.allottedTime * 100 + '%';
requestAnimationFrame(this.loop.bind(this));
}
},
/**
* set color of progress bar
*/
setBarColor() {
if (this.isPaused) {
this.timeProgressBar.style.backgroundColor = this.pausedBarColor;
} else {
this.timeProgressBar.style.backgroundColor = this.barColor;
}
},
/**
* start(reset) timer with new allotted time.
* @param {number} allottedTime
* @param {number} [elapsedTime=0]
*/
start(allottedTime, elapsedTime = 0) {
this.isFinished = false;
this.isPaused = false;
this.allottedTime = allottedTime;
this.startTime = +new Date() - elapsedTime;
this.pauseTimeDuration = 0;
this.setBarColor();
this.loop();
},
reset() {
this.start(this.allottedTime);
},
pause() {
if (this.isPaused) return;
this.isPaused = true;
this.pauseTime = +new Date();
this.setBarColor();
},
resume() {
if (!this.isPaused) return;
// add paused time duration
this.isPaused = false;
this.pauseTimeDuration += new Date() - this.pauseTime;
this.pauseTime = null;
this.setBarColor();
this.loop();
}
};
if (Reveal.isReady()) {
ElapsedTimeBar.handleReady();
} else {
Reveal.addEventListener('ready', () => ElapsedTimeBar.handleReady());
}
|
import axios from "axios";
import axiosWithAuth from "../utils/axiosWithAuth";
export const SIGNUP_START = "SIGNUP_START";
export const SIGNUP_SUCCESS = "SIGNUP_SUCCESS";
export const SIGNUP_FAIL = "SIGNUP_FAIL";
export const LOGIN_START = "LOGIN_START";
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAIL = "LOGIN_FAIL";
export const SEND_MESSAGE_START = "SEND_MESSAGE_START";
export const SEND_MESSAGE_SUCCESS = "SEND_MESSAGE_SUCCESS";
export const SEND_MESSAGE_FAIL = "SEND_MESSAGE_FAIL";
export const postRegistration = newUser => dispatch => {
dispatch({ type: SIGNUP_START });
axios
.post(
"https://empoweredconversations.herokuapp.com/api/auth/register",
newUser
)
.then(res => dispatch({ type: SIGNUP_SUCCESS, payload: res.data }))
.then(res => {
localStorage.setItem("token", res.data.authorization);
})
.catch(err => dispatch({ type: SIGNUP_FAIL, payload: err }));
};
export const userLogin = user => dispatch => {
dispatch({ type: LOGIN_START });
axios
.post("https://empoweredconversations.herokuapp.com/api/auth/login", user)
.then(res => {
// console.log(res);
dispatch({ type: LOGIN_SUCCESS, payload: res.data });
localStorage.setItem("token", res.data.authorization);
localStorage.setItem("user", JSON.stringify(res.data.user));
})
.catch(err => {
dispatch({ type: LOGIN_FAIL, payload: err });
window.alert("Either the email or password you've entered is incorrect");
});
};
export const messageSend = recipient => dispatch => {
dispatch({ type: SEND_MESSAGE_START });
const user = JSON.parse(localStorage.getItem("user"));
console.log(recipient);
axiosWithAuth()
.post(
`https://empoweredconversations.herokuapp.com/api/users/${user.id}/conversations`,
recipient
)
.then(res => {
console.log(res);
dispatch({ type: SEND_MESSAGE_SUCCESS, payload: res.data });
})
.catch(err => {
console.log(err.message);
dispatch({ type: SEND_MESSAGE_FAIL, payload: err });
});
};
|
import Login from './screens/Login';
import Profile from './screens/Profile';
import Loading from './screens/Loading';
import AuthContext from './context/AuthContext';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import React, { useContext } from 'react';
const Tab = createBottomTabNavigator();
export default function Navigator({navigation}) {
const {authToken, isLoading} = useContext(AuthContext);
if(isLoading) {
return <Loading />;
}
return (
<Tab.Navigator>
{authToken != null ?
<>
<Tab.Screen name="My Profile" component={Profile} />
</>
: <Tab.Screen name="Login" component={Login} />
}
</Tab.Navigator>
)
}
|
// @flow
import React, { type Node } from 'react';
type Props = {|
href: string,
children: Node,
className?: string,
'aria-label'?: string,
|};
export default class ExternalLink extends React.Component<Props> {
render(): Node {
return (
<a
className={this.props.className}
aria-label={this.props['aria-label']}
href={this.props.href}
target='_blank'
rel='noopener noreferrer'
>
{this.props.children}
</a>
);
}
}
|
const billingController = require('./controllers/billingController');
const billingValidator = require('./validators/billingValidator');
app.post('/make_user_payment', billingValidator.makeUserPayment, billingController.makeUserPayment);
app.post('/get_user_card', billingValidator.getUserCard, billingController.getUserCard);
app.post('/billing/setupIntent', billingValidator.setupIntent, billingController.setupIntent);
app.post('/billing/addCard', billingValidator.addUserCardV2, billingController.addUserCardV2);
|
# coding=utf-8
# *** WARNING: this file was generated by test. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import errno
from setuptools import setup, find_packages
from setuptools.command.install import install
from subprocess import check_call
class InstallPluginCommand(install):
def run(self):
install.run(self)
try:
check_call(['pulumi', 'plugin', 'install', 'resource', 'xyz', '${PLUGIN_VERSION}'])
except OSError as error:
if error.errno == errno.ENOENT:
print("""
There was an error installing the xyz resource provider plugin.
It looks like `pulumi` is not installed on your system.
Please visit https://pulumi.com/ to install the Pulumi CLI.
You may try manually installing the plugin by running
`pulumi plugin install resource xyz ${PLUGIN_VERSION}`
""")
else:
raise
def readme():
try:
with open('README.md', encoding='utf-8') as f:
return f.read()
except FileNotFoundError:
return "xyz Pulumi Package - Development Version"
setup(name='pulumi_xyz',
version='${VERSION}',
long_description=readme(),
long_description_content_type='text/markdown',
cmdclass={
'install': InstallPluginCommand,
},
packages=find_packages(),
package_data={
'pulumi_xyz': [
'py.typed',
]
},
install_requires=[
'parver>=0.2.1',
'pulumi>=3.0.0,<4.0.0',
'pulumi-aws>=4.0.0,<5.0.0',
'semver>=2.8.1'
],
zip_safe=False)
|
/**
* convertapi
* Convert API lets you effortlessly convert file formats and types.
*
* OpenAPI spec version: v1
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
*
* Swagger Codegen version: 2.4.5
*
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/DocxCellStyle'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./DocxCellStyle'));
} else {
// Browser globals (root is window)
if (!root.CloudmersiveConvertApiClient) {
root.CloudmersiveConvertApiClient = {};
}
root.CloudmersiveConvertApiClient.GetXlsxStylesResponse = factory(root.CloudmersiveConvertApiClient.ApiClient, root.CloudmersiveConvertApiClient.DocxCellStyle);
}
}(this, function(ApiClient, DocxCellStyle) {
'use strict';
/**
* The GetXlsxStylesResponse model module.
* @module model/GetXlsxStylesResponse
* @version 2.1.7
*/
/**
* Constructs a new <code>GetXlsxStylesResponse</code>.
* Result of running a Get-Worksheets command
* @alias module:model/GetXlsxStylesResponse
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>GetXlsxStylesResponse</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/GetXlsxStylesResponse} obj Optional instance to populate.
* @return {module:model/GetXlsxStylesResponse} The populated <code>GetXlsxStylesResponse</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('Successful')) {
obj['Successful'] = ApiClient.convertToType(data['Successful'], 'Boolean');
}
if (data.hasOwnProperty('CellStyles')) {
obj['CellStyles'] = ApiClient.convertToType(data['CellStyles'], [DocxCellStyle]);
}
}
return obj;
}
/**
* True if successful, false otherwise
* @member {Boolean} Successful
*/
exports.prototype['Successful'] = undefined;
/**
* Cell styles
* @member {Array.<module:model/DocxCellStyle>} CellStyles
*/
exports.prototype['CellStyles'] = undefined;
return exports;
}));
|
// Copyright (c) 2019 Gregory Meyer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <common/app.h>
#include <common/argparse.h>
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define COMPRESSION_INPUT_HELP_TEXT \
"Uncompressed file to read from. The current user must have the correct " \
"permissions to read from this file."
#define COMPRESSION_OUTPUT_HELP_TEXT_FORMAT \
"Filename of the compressed file to create. If this file already exists, " \
"it is truncated to length 0 before being written to. Should %s exit with " \
"an error after truncating this file, it will be deleted. The current user " \
"must have write permissions in this file's parent directory and, if the " \
"file already exists, write permissions on this file."
#define DECOMPRESSION_INPUT_HELP_TEXT \
"Compressed file to read from. The current user must have the correct " \
"permissions to read from this file."
#define DECOMPRESSION_OUTPUT_HELP_TEXT_FORMAT \
"Filename of the uncompressed file to create. If this file already exists, " \
"it is truncated to length 0 before being written to. Should %s exit with " \
"an error after truncating this file, it will be deleted. The current user " \
"must have write permissions in this file's parent directory and, if the " \
"file already exists, write permissions on this file."
static int run_transformer_app(int argc, const char *const argv[argc],
const AppParams *params,
const char *input_help_text,
const char *output_help_text_format);
int run_compression_app(int argc, const char *const argv[argc],
const AppParams *params) {
return run_transformer_app(argc, argv, params, COMPRESSION_INPUT_HELP_TEXT,
COMPRESSION_OUTPUT_HELP_TEXT_FORMAT);
}
int run_decompression_app(int argc, const char *const argv[argc],
const AppParams *params) {
return run_transformer_app(argc, argv, params, DECOMPRESSION_INPUT_HELP_TEXT,
DECOMPRESSION_OUTPUT_HELP_TEXT_FORMAT);
}
static int run_transformer_app(int argc, const char *const argv[argc],
const AppParams *params,
const char *input_help_text,
const char *output_help_text_format) {
#ifndef NDEBUG
assert(argc > 0);
assert(argv);
assert(params);
assert(params->executable_name);
assert(params->version);
assert(params->author);
if (params->num_keyword_args > 0) {
assert(params->keyword_args);
for (size_t i = 0; i < params->num_keyword_args; ++i) {
assert(params->keyword_args[i]);
}
}
assert(params->size);
assert(params->run);
assert(input_help_text);
assert(output_help_text_format);
#endif
const int required_buffer_length =
snprintf(NULL, 0, output_help_text_format, params->executable_name);
assert(required_buffer_length >= 0);
const size_t output_help_text_length = (size_t)required_buffer_length;
char *const output_help_text = malloc(output_help_text_length + 1);
const int ret = snprintf(output_help_text, output_help_text_length + 1,
output_help_text_format, params->executable_name);
assert(ret == required_buffer_length);
PassthroughArgumentParser input_filename_parser =
make_passthrough_parser("INPUT_FILE", NULL);
PassthroughArgumentParser output_filename_parser =
make_passthrough_parser("OUTPUT_FILE", NULL);
Arguments arguments = {
.executable_name = params->executable_name,
.version = params->version,
.author = params->author,
.description = params->description,
.positional_args =
(PositionalArgument *[]){
&(PositionalArgument){
.name = "INPUT_FILE",
.help_text = input_help_text,
.parser = &input_filename_parser.argument_parser,
},
&(PositionalArgument){
.name = "OUTPUT_FILE",
.help_text = output_help_text,
.parser = &output_filename_parser.argument_parser,
},
},
.num_positional_args = 2,
.keyword_args = params->keyword_args,
.num_keyword_args = params->num_keyword_args,
};
int return_code = EXIT_SUCCESS;
Error error = parse_arguments(&arguments, argc, argv);
if (error.what) {
print_error(error);
return_code = EXIT_FAILURE;
goto cleanup_help;
}
if (arguments.has_help) {
print_help(&arguments);
goto cleanup_help;
} else if (arguments.has_version) {
print_version(&arguments);
goto cleanup_help;
}
free(output_help_text);
AppIOState io_state = {.input_mapping_first_unused_offset = 0,
.output_mapping_first_unused_offset = 0,
.output_bytes_written = 0};
if ((error = open_and_map_file(input_filename_parser.value,
&io_state.input_file)),
error.what) {
print_error(error);
return EXIT_FAILURE;
}
const size_t output_file_size =
params->size(io_state.input_file.file_size, params->arg);
if ((error = create_and_map_file(output_filename_parser.value,
output_file_size, &io_state.output_file)),
error.what) {
print_error(error);
return_code = EXIT_FAILURE;
goto cleanup_input_only;
}
if (params->init) {
if ((error = params->init(&io_state, params->arg)), error.what) {
print_error(error);
return_code = EXIT_FAILURE;
goto cleanup_files;
}
}
bool finished = false;
while (!finished) {
if ((error = params->run(&io_state, &finished, params->arg)), error.what) {
print_error(error);
return_code = EXIT_FAILURE;
goto cleanup;
}
// not the end of the world if we can't unmap unused pages
if ((error =
unmap_unused_pages(&io_state.input_file,
&io_state.input_mapping_first_unused_offset)),
error.what) {
print_warning(error);
}
if ((error =
unmap_unused_pages(&io_state.output_file,
&io_state.output_mapping_first_unused_offset)),
error.what) {
print_warning(error);
}
if ((error = expand_output_mapping(
&io_state.output_file,
io_state.output_mapping_first_unused_offset)),
error.what) {
print_error(error);
return_code = EXIT_FAILURE;
goto cleanup;
}
}
if (ftruncate(io_state.output_file.fd,
(off_t)io_state.output_bytes_written) == -1) {
print_error(ERRNO_EFORMAT("couldn't resize output file '%s'",
output_filename_parser.value));
return_code = EXIT_FAILURE;
}
cleanup:
if (params->cleanup) {
params->cleanup(&io_state, params->arg);
}
cleanup_files:
if ((error = free_file(io_state.output_file)), error.what) {
print_error(error);
return_code = EXIT_FAILURE;
}
if (return_code != EXIT_SUCCESS) {
if (unlink(output_filename_parser.value) == -1) {
print_error(ERRNO_EFORMAT("couldn't remove file '%s'",
output_filename_parser.value));
// no need to set return_code, it is already != EXIT_SUCCESS
}
}
cleanup_input_only:;
if ((error = free_file(io_state.input_file)), error.what) {
print_error(error);
return EXIT_FAILURE;
}
return return_code;
cleanup_help:
free(output_help_text);
return return_code;
}
|
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { createFunction } from "./createFunction.js";
// Small helper function to factorize code on this page.
/** @internal */
function createRuntimeFunction(method, key, {
docs,
type
}) {
return registry => createFunction(registry, {
meta: {
docs: registry.createType('Vec<Text>', [docs]),
modifier: registry.createType('StorageEntryModifierLatest', 1),
// required
name: registry.createType('Text', method),
toJSON: () => key,
type: registry.createType('StorageEntryTypeLatest', type, 0)
},
method,
prefix: 'Substrate',
section: 'substrate'
}, {
key,
skipHashing: true
});
}
export const substrate = {
changesTrieConfig: createRuntimeFunction('changesTrieConfig', ':changes_trie', {
docs: ' Changes trie configuration is stored under this key.',
type: 'u32'
}),
childStorageKeyPrefix: createRuntimeFunction('childStorageKeyPrefix', ':child_storage:', {
docs: ' Prefix of child storage keys.',
type: 'u32'
}),
code: createRuntimeFunction('code', ':code', {
docs: ' Wasm code of the runtime.',
type: 'Bytes'
}),
extrinsicIndex: createRuntimeFunction('extrinsicIndex', ':extrinsic_index', {
docs: ' Current extrinsic index (u32) is stored under this key.',
type: 'u32'
}),
heapPages: createRuntimeFunction('heapPages', ':heappages', {
docs: ' Number of wasm linear memory pages required for execution of the runtime.',
type: 'u64'
})
};
|
/* istanbul instrument in package npmdoc_stream_combiner */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
switch (local.modeJs) {
// re-init local from window.local
case 'browser':
local = local.global.utility2.objectSetDefault(
local.global.utility2_rollup || local.global.local,
local.global.utility2
);
break;
// re-init local from example.js
case 'node':
local = (local.global.utility2_rollup || require('utility2'))
.requireReadme();
break;
}
// export local
local.global.local = local;
}());
// run shared js-env code - function
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - function
case 'browser':
break;
// run node js-env code - function
case 'node':
break;
}
// run shared js-env code - init-after
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - init-after
case 'browser':
local.testCase_browser_nullCase = local.testCase_browser_nullCase || function (
options,
onError
) {
/*
* this function will test browsers's null-case handling-behavior-behavior
*/
onError(null, options);
};
// run tests
local.nop(local.modeTest &&
document.querySelector('#testRunButton1') &&
document.querySelector('#testRunButton1').click());
break;
// run node js-env code - init-after
/* istanbul ignore next */
case 'node':
local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
options,
onError
) {
/*
* this function will test buildApidoc's default handling-behavior-behavior
*/
options = { modulePathList: module.paths };
local.buildApidoc(options, onError);
};
local.testCase_buildApp_default = local.testCase_buildApp_default || function (
options,
onError
) {
/*
* this function will test buildApp's default handling-behavior-behavior
*/
local.testCase_buildReadme_default(options, local.onErrorThrow);
local.testCase_buildLib_default(options, local.onErrorThrow);
local.testCase_buildTest_default(options, local.onErrorThrow);
local.testCase_buildCustomOrg_default(options, local.onErrorThrow);
options = [];
local.buildApp(options, onError);
};
local.testCase_buildCustomOrg_default = local.testCase_buildCustomOrg_default ||
function (options, onError) {
/*
* this function will test buildCustomOrg's default handling-behavior
*/
options = {};
local.buildCustomOrg(options, onError);
};
local.testCase_buildLib_default = local.testCase_buildLib_default || function (
options,
onError
) {
/*
* this function will test buildLib's default handling-behavior
*/
options = {};
local.buildLib(options, onError);
};
local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
options,
onError
) {
/*
* this function will test buildReadme's default handling-behavior-behavior
*/
options = {};
local.buildReadme(options, onError);
};
local.testCase_buildTest_default = local.testCase_buildTest_default || function (
options,
onError
) {
/*
* this function will test buildTest's default handling-behavior
*/
options = {};
local.buildTest(options, onError);
};
local.testCase_webpage_default = local.testCase_webpage_default || function (
options,
onError
) {
/*
* this function will test webpage's default handling-behavior
*/
options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
local.browserTest(options, onError);
};
// run test-server
local.testRunServer(local);
break;
}
}());
|
from django.contrib.auth.models import AbstractUser
from django.db import models
class Volunteer(AbstractUser):
region = models.CharField(max_length=3, null=True)
def save(self, *args, **kwargs):
super(Volunteer, self).save(*args, **kwargs)
def __str__(self):
return str(self.region)
def __unicode__(self):
return str(self.region)
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013 - 2019, Gorka Zamora-López <galib@Zamora-Lopez.xyz>
#
# Released under the Apache License, Version 2.0 (the "License");
# you may not use this software except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
"""
This script computes the rich-club coefficient of a graph. It also does so for
an ensemble of rewired networks conserving the degree distribution.
Here the different cases for DIRECTED graphs are considered.
"""
from __future__ import division, print_function
__author__ = "Gorka Zamora-Lopez"
__email__ = "galib@zamora-lopez.xyz"
__copyright__ = "Copyright 2013-2019"
__license__ = "Apache License 2.0"
__update__="13/06/2019"
# Standard library imports
import os, os.path
# Third party imports
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from numpy import*
# Personal libraries
from galib import RichClub
import galib.models
from galib.models import RewireNetwork
from galib.tools import SymmetriseMatrix, LoadFromPajek
##################################################################
# 0) READ THE DATA
currdir = os.getcwd()
dataroot = os.path.join(currdir, 'Data/')
net = loadtxt(dataroot + 'Cat53_cortex.txt', dtype=uint8)
N = len(net)
# 1) COMPUTE THE RICH-CLUB OF THE NETWORKS
# 1.1) Empirical network. Three different cases: input, output & average degrees
# Notice that 'net' is weighted but function RichClub ignores the weights.
inphi = RichClub(net, rctype='indegree')
outphi= RichClub(net, rctype='outdegree')
avphi = RichClub(net, rctype='average')
# 1.2) Rich-club in an ensemble of rewired networks for comparison
nrealiz = 100
prewire = 10
inkmax = len(inphi)
rewphi_in = zeros((nrealiz,inkmax), float)
outkmax = len(outphi)
rewphi_out = zeros((nrealiz,outkmax), float)
avkmax = len(avphi)
rewphi_av = zeros((nrealiz,avkmax), float)
for re in range(nrealiz):
# Generate a randomly rewired graph (conserving the in-/out-degrees)
rewnet = RewireNetwork(net, prewire, directed=True)
# Compute the rich club of the rewired network
rewphi_in[re] = RichClub(rewnet, rctype='indegree')
rewphi_out[re] = RichClub(rewnet, rctype='outdegree')
rewphi_av[re] = RichClub(rewnet, rctype='average')
# Find the average rich-club and deviation for each k value
maxrewphi_in = rewphi_in.max(axis=0)
minrewphi_in = rewphi_in.min(axis=0)
meanrewphi_in = rewphi_in.mean(axis=0)
devrewphi_in = rewphi_in.std(axis=0)
maxrewphi_out = rewphi_out.max(axis=0)
minrewphi_out = rewphi_out.min(axis=0)
meanrewphi_out = rewphi_out.mean(axis=0)
devrewphi_out = rewphi_out.std(axis=0)
maxrewphi_av = rewphi_av.max(axis=0)
minrewphi_av = rewphi_av.min(axis=0)
meanrewphi_av = rewphi_av.mean(axis=0)
devrewphi_av = rewphi_av.std(axis=0)
# 2) PLOT THE RESULTS. REQUIRES MATPLOTLIB!!
colorlist = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b']
# 2.1) Rich-club for the INPUT degrees
plt.figure()
plt.title('Rich-club for input connections', fontsize=14)
# Plot the rich-club of the network
klist = arange(inkmax)
plt.plot(klist, inphi, color=colorlist[1], label='Original network')
# Plot the mean rich-club of rewired networks with errorbars
plt.plot(klist,meanrewphi_in, color=colorlist[0], label='Rewired networks')
plt.plot(klist, maxrewphi_in, '--', color=colorlist[0], zorder=0)
plt.plot(klist, minrewphi_in, '--', color=colorlist[0], zorder=0)
# Eye candy
plt.xlabel('(Input) Node degree', fontsize=14)
plt.ylabel('$\phi$-density', fontsize=14)
plt.legend(loc='upper left', fontsize=10)
plt.grid()
# 2.2) Rich-club for the OUTPUT degrees
plt.figure()
plt.title('Rich-club for output connections', fontsize=14)
# Plot the rich-club of the network
klist = arange(inkmax)
plt.plot(klist, outphi, color=colorlist[1], label='Original network')
# Plot the mean rich-club of rewired networks with errorbars
plt.plot(klist,meanrewphi_out, color=colorlist[0], label='Rewired networks')
plt.plot(klist, maxrewphi_out, '--', color=colorlist[0], zorder=0)
plt.plot(klist, minrewphi_out, '--', color=colorlist[0], zorder=0)
# Eye candy
plt.xlabel('(Output) Node degree', fontsize=14)
plt.ylabel('$\phi$-density', fontsize=14)
plt.legend(loc='upper left', fontsize=10)
plt.grid()
# 2.3) Rich-club for the AVERAGE degrees
plt.figure()
plt.title('Rich-club for average connections', fontsize=14)
# Plot the rich-club of the network
klist = arange(avkmax)
plt.plot(klist, avphi, color=colorlist[1], label='Original network')
# Plot the mean rich-club of rewired networks with errorbars
plt.plot(klist,meanrewphi_av, color=colorlist[0], label='Rewired networks')
plt.plot(klist, maxrewphi_av, '--', color=colorlist[0], zorder=0)
plt.plot(klist, minrewphi_av, '--', color=colorlist[0], zorder=0)
# Eye candy
plt.xlabel('(Averaged) Node degree', fontsize=14)
plt.ylabel('$\phi$-density', fontsize=14)
plt.legend(loc='upper left', fontsize=10)
plt.grid()
plt.show()
|
import os
import yaml
from xml.etree.ElementTree import tostring as ElementToString
from .building import Building
from .etree_utils import indent_etree
class Generator:
def __init__(self):
pass
def parse_editor_yaml(self, input_filename):
if not os.path.isfile(input_filename):
raise FileNotFoundError(f'input file {input_filename} not found')
with open(input_filename, 'r') as f:
y = yaml.safe_load(f)
return Building(y)
def generate_sdf(
self,
input_filename,
output_filename,
output_models_dir,
options
):
print('generating {} from {}'.format(output_filename, input_filename))
building = self.parse_editor_yaml(input_filename)
# Remove namespaces in models
for level_name, level in building.levels.items():
for model in level.models:
if "/" in model.model_name:
model.model_name = \
"/".join(model.model_name.split("/")[1:])
if not os.path.exists(output_models_dir):
os.makedirs(output_models_dir)
building.generate_sdf_models(output_models_dir)
# generate a top-level SDF for convenience
sdf = building.generate_sdf_world(options)
indent_etree(sdf)
sdf_str = str(ElementToString(sdf), 'utf-8')
with open(output_filename, 'w') as f:
f.write(sdf_str)
print(f'{len(sdf_str)} bytes written to {output_filename}')
def generate_gazebo_sdf(
self,
input_filename,
output_filename,
output_models_dir,
options
):
self.generate_sdf(
input_filename,
output_filename,
output_models_dir,
options + ['gazebo'])
def generate_ignition_sdf(
self,
input_filename,
output_filename,
output_models_dir,
options
):
self.generate_sdf(
input_filename,
output_filename,
output_models_dir,
options + ['ignition'])
def generate_nav(self, input_filename, output_dir):
building = self.parse_editor_yaml(input_filename)
nav_graphs = building.generate_nav_graphs()
class CustomDumper(yaml.Dumper):
def ignore_aliases(self, _):
return True
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for graph_name, graph_data in nav_graphs.items():
output_filename = os.path.join(output_dir, f'{graph_name}.yaml')
print(f'writing {output_filename}')
with open(output_filename, 'w') as f:
yaml.dump(
graph_data,
f,
default_flow_style=None,
Dumper=CustomDumper)
|
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from .models import Category, Comment, Listing, User, Bid, Watchlist
from .forms import ListingForm
from .utils import get_max_bid, is_watched
def index(request):
context = {
"listings": Listing.objects.all()
}
return render(request, "auctions/index.html", context)
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("auctions:index"))
else:
return render(request, "auctions/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "auctions/login.html")
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("auctions:index"))
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "auctions/register.html", {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "auctions/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("auctions:index"))
else:
return render(request, "auctions/register.html")
@login_required
def create_listing(request, user_id):
# Create new listing as a logged-in User
user = User.objects.get(pk=user_id)
date = timezone.now()
if request.method == "POST":
form = ListingForm(request.POST, request.FILES)
if form.is_valid():
listing = form.save(commit=False)
listing.user = user
form.save()
return HttpResponseRedirect(reverse("auctions:index"))
else:
context = {"form": form}
return render(request, "auctions/create_listing.html", context)
else:
form = ListingForm()
context = {
"form": form,
"user": user,
"date": date,
}
return render(request, "auctions/create_listing.html", context)
def view_listing(request, listing_id):
# View existing listing via its page
listing = Listing.objects.get(pk=listing_id)
watched = is_watched(request, listing_id)
context = {"listing": listing, "watched": watched}
return render(request, "auctions/view_listing.html", context)
@login_required
def close_listing(request, listing_id):
# If auction is done, mark the listing as closed (inactive), declare the winner
listing = Listing.objects.get(pk=listing_id)
bid_list = Bid.objects.all().filter(listing=listing.id)
winner = bid_list.last().user.username
listing.active = False
listing.winner = winner
listing.save()
context = {"listing": listing}
return render(request, "auctions/view_listing.html", context)
@login_required
def bid_add(request, listing_id):
# Add a bid to listing (checks for it to be greater than current max bid)
listing = Listing.objects.get(pk=listing_id)
max_bid = get_max_bid(listing_id)
if request.method == "POST":
bid_price = int(request.POST["bid"])
context = {"listing": listing, "message_error": "Your bid must be higher that the current price."}
if not max_bid:
if bid_price >= int(listing.price):
bid = Bid(user=request.user, size=bid_price, listing=listing)
bid.save()
listing.bid = bid
listing.save()
return HttpResponseRedirect(reverse("auctions:listing", args=(listing.id,)))
else:
return render(request, "auctions/view_listing.html", context)
elif max_bid:
if bid_price > max(int(listing.price), int(max_bid)):
bid = Bid(user=request.user, size=bid_price, listing_id=listing.id)
bid.save()
listing.bid = bid
listing.save()
return HttpResponseRedirect(reverse("auctions:listing", args=(listing.id,)))
else:
return render(request, "auctions/view_listing.html", context)
else:
context = {"listing": listing}
return render(request, "auctions/view_listing.html", context)
@login_required
def watchlist_add(request, listing_id):
# Add currently viewed listing to logged-in User's watchlist
listing = Listing.objects.get(pk=listing_id)
watchlist = Watchlist(user=request.user, listing=listing)
watchlist.save()
watchlist_list = Watchlist.objects.all().filter(user=request.user)
context = {"watchlist": watchlist_list, "listing": listing,}
return HttpResponseRedirect(reverse("auctions:listing", args=(listing.id,)))
@login_required
def watchlist_remove(request, listing_id):
listing = Listing.objects.get(pk=listing_id)
watchlist = Watchlist.objects.all().filter(user=request.user, listing=listing)
watchlist.delete()
watchlist = Watchlist.objects.all().filter(user=request.user, listing=listing)
return HttpResponseRedirect(reverse("auctions:watchlist", args=(request.user.id,)))
@login_required
def watchlist_view(request, user_id):
watchlist = Watchlist.objects.all().filter(user=request.user)
context = {"watchlist": watchlist}
return render(request, "auctions/watchlist.html", context)
@login_required
def comment_add(request, listing_id):
listing = Listing.objects.get(pk=listing_id)
watched = is_watched(request, listing_id)
if request.method == "POST":
text = request.POST["text"]
author = User.objects.get(pk=request.user.id)
comment = Comment(text=text, author=author, listing=listing)
comment.save()
context = {"listing": listing}
return HttpResponseRedirect(reverse("auctions:listing", args=(listing.id,)))
else:
context = {"listing": listing, "watched": watched}
return render(request, "auctions/view_listing.html", context)
def comment_view(request, listing_id):
listing = Listing.objects.get(pk=listing_id)
comments = Comment.objects.all().filter(listing=listing)
context = {"comments": comments}
return HttpResponseRedirect(reverse("auctions:listing", args=(listing.id,)))
def categories(request):
# Show list of existing categories of listings
categories = Category.objects.all()
context = {"categories": categories}
return render(request, "auctions/categories.html", context)
def category_listings(request, cat_id):
# Show all listings in the chosen category
category = Category.objects.get(pk=cat_id)
cat_listings = Listing.objects.all().filter(category=category)
context = {"listings": cat_listings, "category": category}
return render(request, "auctions/category_listings.html", context)
|
/**
* Bio component that queries for data
* with Gatsby's useStaticQuery component
*
* See: https://www.gatsbyjs.com/docs/use-static-query/
*/
import * as React from "react"
import { useStaticQuery, graphql } from "gatsby"
import { StaticImage } from "gatsby-plugin-image"
const Bio = () => {
const data = useStaticQuery(graphql`
query BioQuery {
site {
siteMetadata {
author {
name
summary
}
social {
twitter
github
linkedin
substack
}
}
}
}
`)
const author = data.site.siteMetadata?.author
const social = data.site.siteMetadata?.social
return (
<div className="bio">
<StaticImage
className="bio-avatar"
layout="fixed"
formats={["AUTO", "WEBP", "AVIF"]}
src="../images/prof-pic.png"
width={250}
height={250}
quality={95}
alt="Profile picture"
/>
<h1 className="bio-name">{author?.name}</h1>
<h2 className="bio-summary">{author?.summary}</h2>
<ul className="social-list">
<li className="social-item">
<a className="social-link" href={`https://twitter.com/${social?.twitter || ``}`}>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z" /></svg>
</a>
</li>
<li className="social-item">
<a className="social-link" href={`https://github.com/${social?.github || ``}`}>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" /></svg>
</a>
</li>
<li className="social-item">
<a className="social-link" href={`https://linkedin.com/in/${social?.linkedin || ``}`}>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 0h-14c-2.761 0-5 2.239-5 5v14c0 2.761 2.239 5 5 5h14c2.762 0 5-2.239 5-5v-14c0-2.761-2.238-5-5-5zm-11 19h-3v-11h3v11zm-1.5-12.268c-.966 0-1.75-.79-1.75-1.764s.784-1.764 1.75-1.764 1.75.79 1.75 1.764-.783 1.764-1.75 1.764zm13.5 12.268h-3v-5.604c0-3.368-4-3.113-4 0v5.604h-3v-11h3v1.765c1.396-2.586 7-2.777 7 2.476v6.759z" /></svg>
</a>
</li>
{/* <li className="social-item">
<a className="social-link" href={`https://${social?.substack + '.' || ``}substack.com`}>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M22.539 8.242H1.46V5.406h21.08v2.836zM1.46 10.812V24L12 18.11L22.54 24V10.812H1.46zM22.54 0H1.46v2.836h21.08V0z" fill="black" /></svg>
</a>
</li> */}
</ul>
</div>
)
}
export default Bio
|
# https://gist.github.com/fjl/3a78780d17c755d22df2 # data used here
# https://github.com/ethereum/cpp-ethereum/blob/develop/test/rlpx.cpp#L183
# https://gist.github.com/fjl/6dd7f51f1bf226488e00
from devp2p.rlpxcipher import RLPxSession
from devp2p.crypto import ECCx, privtopub
from quarkchain.rlp.utils import decode_hex
test_values = \
{
"initiator_private_key": "5e173f6ac3c669587538e7727cf19b782a4f2fda07c1eaa662c593e5e85e3051",
"receiver_private_key": "c45f950382d542169ea207959ee0220ec1491755abe405cd7498d6b16adb6df8",
"initiator_ephemeral_private_key": "19c2185f4f40634926ebed3af09070ca9e029f2edd5fae6253074896205f5f6c",
"receiver_ephemeral_private_key": "d25688cf0ab10afa1a0e2dba7853ed5f1e5bf1c631757ed4e103b593ff3f5620",
"auth_plaintext": "884c36f7ae6b406637c1f61b2f57e1d2cab813d24c6559aaf843c3f48962f32f46662c066d39669b7b2e3ba14781477417600e7728399278b1b5d801a519aa570034fdb5419558137e0d44cd13d319afe5629eeccb47fd9dfe55cc6089426e46cc762dd8a0636e07a54b31169eba0c7a20a1ac1ef68596f1f283b5c676bae4064abfcce24799d09f67e392632d3ffdc12e3d6430dcb0ea19c318343ffa7aae74d4cd26fecb93657d1cd9e9eaf4f8be720b56dd1d39f190c4e1c6b7ec66f077bb1100",
"authresp_plaintext": "802b052f8b066640bba94a4fc39d63815c377fced6fcb84d27f791c9921ddf3e9bf0108e298f490812847109cbd778fae393e80323fd643209841a3b7f110397f37ec61d84cea03dcc5e8385db93248584e8af4b4d1c832d8c7453c0089687a700",
"auth_ciphertext": "04a0274c5951e32132e7f088c9bdfdc76c9d91f0dc6078e848f8e3361193dbdc43b94351ea3d89e4ff33ddcefbc80070498824857f499656c4f79bbd97b6c51a514251d69fd1785ef8764bd1d262a883f780964cce6a14ff206daf1206aa073a2d35ce2697ebf3514225bef186631b2fd2316a4b7bcdefec8d75a1025ba2c5404a34e7795e1dd4bc01c6113ece07b0df13b69d3ba654a36e35e69ff9d482d88d2f0228e7d96fe11dccbb465a1831c7d4ad3a026924b182fc2bdfe016a6944312021da5cc459713b13b86a686cf34d6fe6615020e4acf26bf0d5b7579ba813e7723eb95b3cef9942f01a58bd61baee7c9bdd438956b426a4ffe238e61746a8c93d5e10680617c82e48d706ac4953f5e1c4c4f7d013c87d34a06626f498f34576dc017fdd3d581e83cfd26cf125b6d2bda1f1d56",
"authresp_ciphertext": "049934a7b2d7f9af8fd9db941d9da281ac9381b5740e1f64f7092f3588d4f87f5ce55191a6653e5e80c1c5dd538169aa123e70dc6ffc5af1827e546c0e958e42dad355bcc1fcb9cdf2cf47ff524d2ad98cbf275e661bf4cf00960e74b5956b799771334f426df007350b46049adb21a6e78ab1408d5e6ccde6fb5e69f0f4c92bb9c725c02f99fa72b9cdc8dd53cff089e0e73317f61cc5abf6152513cb7d833f09d2851603919bf0fbe44d79a09245c6e8338eb502083dc84b846f2fee1cc310d2cc8b1b9334728f97220bb799376233e113",
"ecdhe_shared_secret": "e3f407f83fc012470c26a93fdff534100f2c6f736439ce0ca90e9914f7d1c381",
"initiator_nonce": "cd26fecb93657d1cd9e9eaf4f8be720b56dd1d39f190c4e1c6b7ec66f077bb11",
"receiver_nonce": "f37ec61d84cea03dcc5e8385db93248584e8af4b4d1c832d8c7453c0089687a7",
"aes_secret": "c0458fa97a5230830e05f4f20b7c755c1d4e54b1ce5cf43260bb191eef4e418d",
"mac_secret": "48c938884d5067a1598272fcddaa4b833cd5e7d92e8228c0ecdfabbe68aef7f1",
"token": "3f9ec2592d1554852b1f54d228f042ed0a9310ea86d038dc2b401ba8cd7fdac4",
"initial_egress_MAC": "09771e93b1a6109e97074cbe2d2b0cf3d3878efafe68f53c41bb60c0ec49097e",
"initial_ingress_MAC": "75823d96e23136c89666ee025fb21a432be906512b3dd4a3049e898adb433847",
"initiator_hello_packet": "6ef23fcf1cec7312df623f9ae701e63b550cdb8517fefd8dd398fc2acd1d935e6e0434a2b96769078477637347b7b01924fff9ff1c06df2f804df3b0402bbb9f87365b3c6856b45e1e2b6470986813c3816a71bff9d69dd297a5dbd935ab578f6e5d7e93e4506a44f307c332d95e8a4b102585fd8ef9fc9e3e055537a5cec2e9",
"receiver_hello_packet": "6ef23fcf1cec7312df623f9ae701e63be36a1cdd1b19179146019984f3625d4a6e0434a2b96769050577657247b7b02bc6c314470eca7e3ef650b98c83e9d7dd4830b3f718ff562349aead2530a8d28a8484604f92e5fced2c6183f304344ab0e7c301a0c05559f4c25db65e36820b4b909a226171a60ac6cb7beea09376d6d8"
}
for k, v in test_values.items():
test_values[k] = decode_hex(v)
keys = ['initiator_private_key',
'receiver_private_key',
'initiator_ephemeral_private_key',
'receiver_ephemeral_private_key',
'initiator_nonce',
'receiver_nonce',
# auth
'auth_plaintext',
'auth_ciphertext',
# auth response
'authresp_plaintext',
'authresp_ciphertext',
# on ack receive
'ecdhe_shared_secret',
'aes_secret',
'mac_secret',
'token',
'initial_egress_MAC',
'initial_ingress_MAC',
# messages
'initiator_hello_packet',
'receiver_hello_packet'
]
assert set(keys) == set(test_values.keys())
# see also
# https://github.com/ethereum/cpp-ethereum/blob/develop/test/rlpx.cpp#L183
def test_ecies_decrypt():
tv = test_values
e = ECCx(raw_privkey=tv['receiver_private_key'])
_dec = e.ecies_decrypt(tv['auth_ciphertext'])
assert len(_dec) == len(tv['auth_plaintext'])
assert _dec == tv['auth_plaintext']
def test_handshake():
tv = test_values
initiator = RLPxSession(ECCx(raw_privkey=tv['initiator_private_key']),
is_initiator=True,
ephemeral_privkey=tv['initiator_ephemeral_private_key'])
initiator_pubkey = initiator.ecc.raw_pubkey
responder = RLPxSession(ECCx(raw_privkey=tv['receiver_private_key']),
ephemeral_privkey=tv['receiver_ephemeral_private_key'])
responder_pubkey = responder.ecc.raw_pubkey
# test encryption
_enc = initiator.encrypt_auth_message(tv['auth_plaintext'], responder_pubkey)
assert len(_enc) == len(tv['auth_ciphertext'])
assert len(tv['auth_ciphertext']) == 113 + len(tv['auth_plaintext']) # len
# test auth_msg plain
auth_msg = initiator.create_auth_message(remote_pubkey=responder_pubkey,
ephemeral_privkey=tv['initiator_ephemeral_private_key'],
nonce=tv['initiator_nonce'])
# test auth_msg plain
assert len(auth_msg) == len(tv['auth_plaintext']) == 194
assert auth_msg[65:] == tv['auth_plaintext'][65:] # starts with non deterministic k
_auth_msg_cipher = initiator.encrypt_auth_message(auth_msg, responder_pubkey)
# test shared
responder.ecc.get_ecdh_key(initiator_pubkey) == \
initiator.ecc.get_ecdh_key(responder_pubkey)
# test decrypt
assert auth_msg == responder.ecc.ecies_decrypt(_auth_msg_cipher)
# check receive
responder_ephemeral_pubkey = privtopub(tv['receiver_ephemeral_private_key'])
auth_msg_cipher = tv['auth_ciphertext']
auth_msg = responder.ecc.ecies_decrypt(auth_msg_cipher)
assert auth_msg[65:] == tv['auth_plaintext'][65:] # starts with non deterministic k
responder.decode_authentication(auth_msg_cipher)
auth_ack_msg = responder.create_auth_ack_message(responder_ephemeral_pubkey, nonce=tv['receiver_nonce'])
assert auth_ack_msg == tv['authresp_plaintext']
auth_ack_msg_cipher = responder.encrypt_auth_ack_message(auth_ack_msg, remote_pubkey=responder.remote_pubkey)
# set auth ack msg cipher (needed later for mac calculation)
responder.auth_ack = tv['authresp_ciphertext']
responder.setup_cipher()
assert responder.ecdhe_shared_secret == tv['ecdhe_shared_secret']
assert len(responder.token) == len(tv['token'])
assert responder.token == tv['token']
assert responder.aes_secret == tv['aes_secret']
assert responder.mac_secret == tv['mac_secret']
assert responder.initiator_nonce == tv['initiator_nonce']
assert responder.responder_nonce == tv['receiver_nonce']
assert responder.auth_init == tv['auth_ciphertext']
assert responder.auth_ack == tv['authresp_ciphertext']
# test values are from initiator perspective?
assert responder.ingress_mac.digest() == tv['initial_egress_MAC']
assert responder.ingress_mac.digest() == tv['initial_egress_MAC']
assert responder.egress_mac.digest() == tv['initial_ingress_MAC']
assert responder.egress_mac.digest() == tv['initial_ingress_MAC']
r = responder.decrypt(tv['initiator_hello_packet'])
# unpack hello packet
import struct
import rlp
import rlp.sedes as sedes
from rlp.codec import consume_item
header = r['header']
frame_length = struct.unpack(b'>I', b'\x00' + header[:3])[0]
header_sedes = sedes.List([sedes.big_endian_int, sedes.big_endian_int])
header_data = rlp.decode(header[3:], strict=False, sedes=header_sedes)
print('header', repr(header_data))
# frame
frame = r['frame']
# normal: rlp(packet-type) [|| rlp(packet-data)] || padding
packet_type, end = consume_item(frame, start=0)
packet_type = rlp.decode(frame, sedes=sedes.big_endian_int, strict=False)
print('packet_type', repr(packet_type))
# decode hello body
_sedes_capabilites_tuple = sedes.List([sedes.binary, sedes.big_endian_int])
structure = [
('version', sedes.big_endian_int),
('client_version_string', sedes.big_endian_int),
('capabilities', sedes.CountableList(_sedes_capabilites_tuple)),
('listen_port', sedes.big_endian_int),
('remote_pubkey', sedes.binary)
]
hello_sedes = sedes.List([x[1] for x in structure])
frame_data = rlp.decode(frame[end:], sedes=hello_sedes)
frame_data = dict((structure[i][0], x) for i, x in enumerate(frame_data))
print('frame', frame_data)
|
/*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
seq_axioms.h
Abstract:
Axiomatize string operations that can be reduced to
more basic operations.
Author:
Nikolaj Bjorner (nbjorner) 2020-4-16
Revision History:
--*/
#pragma once
#include "ast/seq_decl_plugin.h"
#include "ast/arith_decl_plugin.h"
#include "ast/rewriter/th_rewriter.h"
#include "smt/smt_theory.h"
#include "smt/seq_skolem.h"
namespace smt {
class seq_axioms {
theory& th;
th_rewriter& m_rewrite;
ast_manager& m;
arith_util a;
seq_util seq;
seq_skolem m_sk;
bool m_digits_initialized;
literal mk_eq_empty(expr* e, bool phase = true) { return mk_eq_empty2(e, phase); }
context& ctx() { return th.get_context(); }
literal mk_eq(expr* a, expr* b);
literal mk_literal(expr* e);
literal mk_seq_eq(expr* a, expr* b) { SASSERT(seq.is_seq(a) && seq.is_seq(b)); return mk_literal(m_sk.mk_eq(a, b)); }
expr_ref mk_len(expr* s);
expr_ref mk_sub(expr* x, expr* y);
expr_ref mk_concat(expr* e1, expr* e2, expr* e3) { return expr_ref(seq.str.mk_concat(e1, e2, e3), m); }
expr_ref mk_concat(expr* e1, expr* e2) { return expr_ref(seq.str.mk_concat(e1, e2), m); }
expr_ref mk_nth(expr* e, unsigned i) { return expr_ref(seq.str.mk_nth_i(e, a.mk_int(i)), m); }
literal mk_ge_e(expr* x, expr* y) { return mk_literal(a.mk_ge(x, y)); }
literal mk_le_e(expr* x, expr* y) { return mk_literal(a.mk_le(x, y)); }
void add_axiom(literal l1, literal l2 = null_literal, literal l3 = null_literal,
literal l4 = null_literal, literal l5 = null_literal) { add_axiom5(l1, l2, l3, l4, l5); }
void add_tail_axiom(expr* e, expr* s);
void add_drop_last_axiom(expr* e, expr* s);
bool is_drop_last(expr* s, expr* i, expr* l);
bool is_tail(expr* s, expr* i, expr* l);
bool is_extract_prefix0(expr* s, expr* i, expr* l);
bool is_extract_suffix(expr* s, expr* i, expr* l);
void add_extract_prefix_axiom(expr* e, expr* s, expr* l);
void add_extract_suffix_axiom(expr* e, expr* s, expr* i);
void tightest_prefix(expr* s, expr* x);
void ensure_digit_axiom();
public:
seq_axioms(theory& th, th_rewriter& r);
// we rely on client to supply the following functions:
std::function<void(literal l1, literal l2, literal l3, literal l4, literal l5)> add_axiom5;
std::function<literal(expr*,bool)> mk_eq_empty2;
void add_suffix_axiom(expr* n);
void add_prefix_axiom(expr* n);
void add_extract_axiom(expr* n);
void add_indexof_axiom(expr* n);
void add_last_indexof_axiom(expr* n);
void add_replace_axiom(expr* n);
void add_at_axiom(expr* n);
void add_nth_axiom(expr* n);
void add_itos_axiom(expr* n);
void add_stoi_axiom(expr* n);
void add_stoi_axiom(expr* e, unsigned k);
void add_itos_axiom(expr* s, unsigned k);
void add_lt_axiom(expr* n);
void add_le_axiom(expr* n);
void add_is_digit_axiom(expr* n);
void add_str_to_code_axiom(expr* n);
void add_str_from_code_axiom(expr* n);
void add_unit_axiom(expr* n);
void add_length_axiom(expr* n);
void unroll_not_contains(expr* n);
literal is_digit(expr* ch);
literal mk_ge(expr* e, int k) { return mk_ge_e(e, a.mk_int(k)); }
literal mk_le(expr* e, int k) { return mk_le_e(e, a.mk_int(k)); }
literal mk_ge(expr* e, rational const& k) { return mk_ge_e(e, a.mk_int(k)); }
literal mk_le(expr* e, rational const& k) { return mk_le_e(e, a.mk_int(k)); }
expr_ref add_length_limit(expr* s, unsigned k);
};
};
|
/*
Auvitek AU8522 QAM/8VSB demodulator driver
Copyright (C) 2008 Steven Toth <stoth@linuxtv.org>
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/delay.h>
#include "dvb_frontend.h"
#include "au8522.h"
#include "au8522_priv.h"
static int debug;
/* Despite the name "hybrid_tuner", the framework works just as well for
hybrid demodulators as well... */
static LIST_HEAD(hybrid_tuner_instance_list);
static DEFINE_MUTEX(au8522_list_mutex);
#define dprintk(arg...)\
do { if (debug)\
printk(arg);\
} while (0)
/* 16 bit registers, 8 bit values */
int au8522_writereg(struct au8522_state *state, u16 reg, u8 data)
{
int ret;
u8 buf[] = { (reg >> 8) | 0x80, reg & 0xff, data };
struct i2c_msg msg = { .addr = state->config->demod_address,
.flags = 0, .buf = buf, .len = 3 };
ret = i2c_transfer(state->i2c, &msg, 1);
if (ret != 1)
printk("%s: writereg error (reg == 0x%02x, val == 0x%04x, "
"ret == %i)\n", __func__, reg, data, ret);
return (ret != 1) ? -1 : 0;
}
u8 au8522_readreg(struct au8522_state *state, u16 reg)
{
int ret;
u8 b0[] = { (reg >> 8) | 0x40, reg & 0xff };
u8 b1[] = { 0 };
struct i2c_msg msg[] = {
{ .addr = state->config->demod_address, .flags = 0,
.buf = b0, .len = 2 },
{ .addr = state->config->demod_address, .flags = I2C_M_RD,
.buf = b1, .len = 1 } };
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2)
printk(KERN_ERR "%s: readreg error (ret == %i)\n",
__func__, ret);
return b1[0];
}
static int au8522_i2c_gate_ctrl(struct dvb_frontend *fe, int enable)
{
struct au8522_state *state = fe->demodulator_priv;
dprintk("%s(%d)\n", __func__, enable);
if (state->operational_mode == AU8522_ANALOG_MODE) {
/* We're being asked to manage the gate even though we're
not in digital mode. This can occur if we get switched
over to analog mode before the dvb_frontend kernel thread
has completely shutdown */
return 0;
}
if (enable)
return au8522_writereg(state, 0x106, 1);
else
return au8522_writereg(state, 0x106, 0);
}
struct mse2snr_tab {
u16 val;
u16 data;
};
/* VSB SNR lookup table */
static struct mse2snr_tab vsb_mse2snr_tab[] = {
{ 0, 270 },
{ 2, 250 },
{ 3, 240 },
{ 5, 230 },
{ 7, 220 },
{ 9, 210 },
{ 12, 200 },
{ 13, 195 },
{ 15, 190 },
{ 17, 185 },
{ 19, 180 },
{ 21, 175 },
{ 24, 170 },
{ 27, 165 },
{ 31, 160 },
{ 32, 158 },
{ 33, 156 },
{ 36, 152 },
{ 37, 150 },
{ 39, 148 },
{ 40, 146 },
{ 41, 144 },
{ 43, 142 },
{ 44, 140 },
{ 48, 135 },
{ 50, 130 },
{ 43, 142 },
{ 53, 125 },
{ 56, 120 },
{ 256, 115 },
};
/* QAM64 SNR lookup table */
static struct mse2snr_tab qam64_mse2snr_tab[] = {
{ 15, 0 },
{ 16, 290 },
{ 17, 288 },
{ 18, 286 },
{ 19, 284 },
{ 20, 282 },
{ 21, 281 },
{ 22, 279 },
{ 23, 277 },
{ 24, 275 },
{ 25, 273 },
{ 26, 271 },
{ 27, 269 },
{ 28, 268 },
{ 29, 266 },
{ 30, 264 },
{ 31, 262 },
{ 32, 260 },
{ 33, 259 },
{ 34, 258 },
{ 35, 256 },
{ 36, 255 },
{ 37, 254 },
{ 38, 252 },
{ 39, 251 },
{ 40, 250 },
{ 41, 249 },
{ 42, 248 },
{ 43, 246 },
{ 44, 245 },
{ 45, 244 },
{ 46, 242 },
{ 47, 241 },
{ 48, 240 },
{ 50, 239 },
{ 51, 238 },
{ 53, 237 },
{ 54, 236 },
{ 56, 235 },
{ 57, 234 },
{ 59, 233 },
{ 60, 232 },
{ 62, 231 },
{ 63, 230 },
{ 65, 229 },
{ 67, 228 },
{ 68, 227 },
{ 70, 226 },
{ 71, 225 },
{ 73, 224 },
{ 74, 223 },
{ 76, 222 },
{ 78, 221 },
{ 80, 220 },
{ 82, 219 },
{ 85, 218 },
{ 88, 217 },
{ 90, 216 },
{ 92, 215 },
{ 93, 214 },
{ 94, 212 },
{ 95, 211 },
{ 97, 210 },
{ 99, 209 },
{ 101, 208 },
{ 102, 207 },
{ 104, 206 },
{ 107, 205 },
{ 111, 204 },
{ 114, 203 },
{ 118, 202 },
{ 122, 201 },
{ 125, 200 },
{ 128, 199 },
{ 130, 198 },
{ 132, 197 },
{ 256, 190 },
};
/* QAM256 SNR lookup table */
static struct mse2snr_tab qam256_mse2snr_tab[] = {
{ 16, 0 },
{ 17, 400 },
{ 18, 398 },
{ 19, 396 },
{ 20, 394 },
{ 21, 392 },
{ 22, 390 },
{ 23, 388 },
{ 24, 386 },
{ 25, 384 },
{ 26, 382 },
{ 27, 380 },
{ 28, 379 },
{ 29, 378 },
{ 30, 377 },
{ 31, 376 },
{ 32, 375 },
{ 33, 374 },
{ 34, 373 },
{ 35, 372 },
{ 36, 371 },
{ 37, 370 },
{ 38, 362 },
{ 39, 354 },
{ 40, 346 },
{ 41, 338 },
{ 42, 330 },
{ 43, 328 },
{ 44, 326 },
{ 45, 324 },
{ 46, 322 },
{ 47, 320 },
{ 48, 319 },
{ 49, 318 },
{ 50, 317 },
{ 51, 316 },
{ 52, 315 },
{ 53, 314 },
{ 54, 313 },
{ 55, 312 },
{ 56, 311 },
{ 57, 310 },
{ 58, 308 },
{ 59, 306 },
{ 60, 304 },
{ 61, 302 },
{ 62, 300 },
{ 63, 298 },
{ 65, 295 },
{ 68, 294 },
{ 70, 293 },
{ 73, 292 },
{ 76, 291 },
{ 78, 290 },
{ 79, 289 },
{ 81, 288 },
{ 82, 287 },
{ 83, 286 },
{ 84, 285 },
{ 85, 284 },
{ 86, 283 },
{ 88, 282 },
{ 89, 281 },
{ 256, 280 },
};
static int au8522_mse2snr_lookup(struct mse2snr_tab *tab, int sz, int mse,
u16 *snr)
{
int i, ret = -EINVAL;
dprintk("%s()\n", __func__);
for (i = 0; i < sz; i++) {
if (mse < tab[i].val) {
*snr = tab[i].data;
ret = 0;
break;
}
}
dprintk("%s() snr=%d\n", __func__, *snr);
return ret;
}
static int au8522_set_if(struct dvb_frontend *fe, enum au8522_if_freq if_freq)
{
struct au8522_state *state = fe->demodulator_priv;
u8 r0b5, r0b6, r0b7;
char *ifmhz;
switch (if_freq) {
case AU8522_IF_3_25MHZ:
ifmhz = "3.25";
r0b5 = 0x00;
r0b6 = 0x3d;
r0b7 = 0xa0;
break;
case AU8522_IF_4MHZ:
ifmhz = "4.00";
r0b5 = 0x00;
r0b6 = 0x4b;
r0b7 = 0xd9;
break;
case AU8522_IF_6MHZ:
ifmhz = "6.00";
r0b5 = 0xfb;
r0b6 = 0x8e;
r0b7 = 0x39;
break;
default:
dprintk("%s() IF Frequency not supported\n", __func__);
return -EINVAL;
}
dprintk("%s() %s MHz\n", __func__, ifmhz);
au8522_writereg(state, 0x80b5, r0b5);
au8522_writereg(state, 0x80b6, r0b6);
au8522_writereg(state, 0x80b7, r0b7);
return 0;
}
/* VSB Modulation table */
static struct {
u16 reg;
u16 data;
} VSB_mod_tab[] = {
{ 0x8090, 0x84 },
{ 0x4092, 0x11 },
{ 0x2005, 0x00 },
{ 0x8091, 0x80 },
{ 0x80a3, 0x0c },
{ 0x80a4, 0xe8 },
{ 0x8081, 0xc4 },
{ 0x80a5, 0x40 },
{ 0x80a7, 0x40 },
{ 0x80a6, 0x67 },
{ 0x8262, 0x20 },
{ 0x821c, 0x30 },
{ 0x80d8, 0x1a },
{ 0x8227, 0xa0 },
{ 0x8121, 0xff },
{ 0x80a8, 0xf0 },
{ 0x80a9, 0x05 },
{ 0x80aa, 0x77 },
{ 0x80ab, 0xf0 },
{ 0x80ac, 0x05 },
{ 0x80ad, 0x77 },
{ 0x80ae, 0x41 },
{ 0x80af, 0x66 },
{ 0x821b, 0xcc },
{ 0x821d, 0x80 },
{ 0x80a4, 0xe8 },
{ 0x8231, 0x13 },
};
/* QAM64 Modulation table */
static struct {
u16 reg;
u16 data;
} QAM64_mod_tab[] = {
{ 0x00a3, 0x09 },
{ 0x00a4, 0x00 },
{ 0x0081, 0xc4 },
{ 0x00a5, 0x40 },
{ 0x00aa, 0x77 },
{ 0x00ad, 0x77 },
{ 0x00a6, 0x67 },
{ 0x0262, 0x20 },
{ 0x021c, 0x30 },
{ 0x00b8, 0x3e },
{ 0x00b9, 0xf0 },
{ 0x00ba, 0x01 },
{ 0x00bb, 0x18 },
{ 0x00bc, 0x50 },
{ 0x00bd, 0x00 },
{ 0x00be, 0xea },
{ 0x00bf, 0xef },
{ 0x00c0, 0xfc },
{ 0x00c1, 0xbd },
{ 0x00c2, 0x1f },
{ 0x00c3, 0xfc },
{ 0x00c4, 0xdd },
{ 0x00c5, 0xaf },
{ 0x00c6, 0x00 },
{ 0x00c7, 0x38 },
{ 0x00c8, 0x30 },
{ 0x00c9, 0x05 },
{ 0x00ca, 0x4a },
{ 0x00cb, 0xd0 },
{ 0x00cc, 0x01 },
{ 0x00cd, 0xd9 },
{ 0x00ce, 0x6f },
{ 0x00cf, 0xf9 },
{ 0x00d0, 0x70 },
{ 0x00d1, 0xdf },
{ 0x00d2, 0xf7 },
{ 0x00d3, 0xc2 },
{ 0x00d4, 0xdf },
{ 0x00d5, 0x02 },
{ 0x00d6, 0x9a },
{ 0x00d7, 0xd0 },
{ 0x0250, 0x0d },
{ 0x0251, 0xcd },
{ 0x0252, 0xe0 },
{ 0x0253, 0x05 },
{ 0x0254, 0xa7 },
{ 0x0255, 0xff },
{ 0x0256, 0xed },
{ 0x0257, 0x5b },
{ 0x0258, 0xae },
{ 0x0259, 0xe6 },
{ 0x025a, 0x3d },
{ 0x025b, 0x0f },
{ 0x025c, 0x0d },
{ 0x025d, 0xea },
{ 0x025e, 0xf2 },
{ 0x025f, 0x51 },
{ 0x0260, 0xf5 },
{ 0x0261, 0x06 },
{ 0x021a, 0x00 },
{ 0x0546, 0x40 },
{ 0x0210, 0xc7 },
{ 0x0211, 0xaa },
{ 0x0212, 0xab },
{ 0x0213, 0x02 },
{ 0x0502, 0x00 },
{ 0x0121, 0x04 },
{ 0x0122, 0x04 },
{ 0x052e, 0x10 },
{ 0x00a4, 0xca },
{ 0x00a7, 0x40 },
{ 0x0526, 0x01 },
};
/* QAM256 Modulation table */
static struct {
u16 reg;
u16 data;
} QAM256_mod_tab[] = {
{ 0x80a3, 0x09 },
{ 0x80a4, 0x00 },
{ 0x8081, 0xc4 },
{ 0x80a5, 0x40 },
{ 0x80aa, 0x77 },
{ 0x80ad, 0x77 },
{ 0x80a6, 0x67 },
{ 0x8262, 0x20 },
{ 0x821c, 0x30 },
{ 0x80b8, 0x3e },
{ 0x80b9, 0xf0 },
{ 0x80ba, 0x01 },
{ 0x80bb, 0x18 },
{ 0x80bc, 0x50 },
{ 0x80bd, 0x00 },
{ 0x80be, 0xea },
{ 0x80bf, 0xef },
{ 0x80c0, 0xfc },
{ 0x80c1, 0xbd },
{ 0x80c2, 0x1f },
{ 0x80c3, 0xfc },
{ 0x80c4, 0xdd },
{ 0x80c5, 0xaf },
{ 0x80c6, 0x00 },
{ 0x80c7, 0x38 },
{ 0x80c8, 0x30 },
{ 0x80c9, 0x05 },
{ 0x80ca, 0x4a },
{ 0x80cb, 0xd0 },
{ 0x80cc, 0x01 },
{ 0x80cd, 0xd9 },
{ 0x80ce, 0x6f },
{ 0x80cf, 0xf9 },
{ 0x80d0, 0x70 },
{ 0x80d1, 0xdf },
{ 0x80d2, 0xf7 },
{ 0x80d3, 0xc2 },
{ 0x80d4, 0xdf },
{ 0x80d5, 0x02 },
{ 0x80d6, 0x9a },
{ 0x80d7, 0xd0 },
{ 0x8250, 0x0d },
{ 0x8251, 0xcd },
{ 0x8252, 0xe0 },
{ 0x8253, 0x05 },
{ 0x8254, 0xa7 },
{ 0x8255, 0xff },
{ 0x8256, 0xed },
{ 0x8257, 0x5b },
{ 0x8258, 0xae },
{ 0x8259, 0xe6 },
{ 0x825a, 0x3d },
{ 0x825b, 0x0f },
{ 0x825c, 0x0d },
{ 0x825d, 0xea },
{ 0x825e, 0xf2 },
{ 0x825f, 0x51 },
{ 0x8260, 0xf5 },
{ 0x8261, 0x06 },
{ 0x821a, 0x00 },
{ 0x8546, 0x40 },
{ 0x8210, 0x26 },
{ 0x8211, 0xf6 },
{ 0x8212, 0x84 },
{ 0x8213, 0x02 },
{ 0x8502, 0x01 },
{ 0x8121, 0x04 },
{ 0x8122, 0x04 },
{ 0x852e, 0x10 },
{ 0x80a4, 0xca },
{ 0x80a7, 0x40 },
{ 0x8526, 0x01 },
};
static int au8522_enable_modulation(struct dvb_frontend *fe,
fe_modulation_t m)
{
struct au8522_state *state = fe->demodulator_priv;
int i;
dprintk("%s(0x%08x)\n", __func__, m);
switch (m) {
case VSB_8:
dprintk("%s() VSB_8\n", __func__);
for (i = 0; i < ARRAY_SIZE(VSB_mod_tab); i++)
au8522_writereg(state,
VSB_mod_tab[i].reg,
VSB_mod_tab[i].data);
au8522_set_if(fe, state->config->vsb_if);
break;
case QAM_64:
dprintk("%s() QAM 64\n", __func__);
for (i = 0; i < ARRAY_SIZE(QAM64_mod_tab); i++)
au8522_writereg(state,
QAM64_mod_tab[i].reg,
QAM64_mod_tab[i].data);
au8522_set_if(fe, state->config->qam_if);
break;
case QAM_256:
dprintk("%s() QAM 256\n", __func__);
for (i = 0; i < ARRAY_SIZE(QAM256_mod_tab); i++)
au8522_writereg(state,
QAM256_mod_tab[i].reg,
QAM256_mod_tab[i].data);
au8522_set_if(fe, state->config->qam_if);
break;
default:
dprintk("%s() Invalid modulation\n", __func__);
return -EINVAL;
}
state->current_modulation = m;
return 0;
}
/* Talk to the demod, set the FEC, GUARD, QAM settings etc */
static int au8522_set_frontend(struct dvb_frontend *fe,
struct dvb_frontend_parameters *p)
{
struct au8522_state *state = fe->demodulator_priv;
int ret = -EINVAL;
dprintk("%s(frequency=%d)\n", __func__, p->frequency);
if ((state->current_frequency == p->frequency) &&
(state->current_modulation == p->u.vsb.modulation))
return 0;
au8522_enable_modulation(fe, p->u.vsb.modulation);
/* Allow the demod to settle */
msleep(100);
if (fe->ops.tuner_ops.set_params) {
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
ret = fe->ops.tuner_ops.set_params(fe, p);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
}
if (ret < 0)
return ret;
state->current_frequency = p->frequency;
return 0;
}
/* Reset the demod hardware and reset all of the configuration registers
to a default state. */
int au8522_init(struct dvb_frontend *fe)
{
struct au8522_state *state = fe->demodulator_priv;
dprintk("%s()\n", __func__);
state->operational_mode = AU8522_DIGITAL_MODE;
/* Clear out any state associated with the digital side of the
chip, so that when it gets powered back up it won't think
that it is already tuned */
state->current_frequency = 0;
au8522_writereg(state, 0xa4, 1 << 5);
au8522_i2c_gate_ctrl(fe, 1);
return 0;
}
static int au8522_led_gpio_enable(struct au8522_state *state, int onoff)
{
struct au8522_led_config *led_config = state->config->led_cfg;
u8 val;
/* bail out if we cant control an LED */
if (!led_config || !led_config->gpio_output ||
!led_config->gpio_output_enable || !led_config->gpio_output_disable)
return 0;
val = au8522_readreg(state, 0x4000 |
(led_config->gpio_output & ~0xc000));
if (onoff) {
/* enable GPIO output */
val &= ~((led_config->gpio_output_enable >> 8) & 0xff);
val |= (led_config->gpio_output_enable & 0xff);
} else {
/* disable GPIO output */
val &= ~((led_config->gpio_output_disable >> 8) & 0xff);
val |= (led_config->gpio_output_disable & 0xff);
}
return au8522_writereg(state, 0x8000 |
(led_config->gpio_output & ~0xc000), val);
}
/* led = 0 | off
* led = 1 | signal ok
* led = 2 | signal strong
* led < 0 | only light led if leds are currently off
*/
static int au8522_led_ctrl(struct au8522_state *state, int led)
{
struct au8522_led_config *led_config = state->config->led_cfg;
int i, ret = 0;
/* bail out if we cant control an LED */
if (!led_config || !led_config->gpio_leds ||
!led_config->num_led_states || !led_config->led_states)
return 0;
if (led < 0) {
/* if LED is already lit, then leave it as-is */
if (state->led_state)
return 0;
else
led *= -1;
}
/* toggle LED if changing state */
if (state->led_state != led) {
u8 val;
dprintk("%s: %d\n", __func__, led);
au8522_led_gpio_enable(state, 1);
val = au8522_readreg(state, 0x4000 |
(led_config->gpio_leds & ~0xc000));
/* start with all leds off */
for (i = 0; i < led_config->num_led_states; i++)
val &= ~led_config->led_states[i];
/* set selected LED state */
if (led < led_config->num_led_states)
val |= led_config->led_states[led];
else if (led_config->num_led_states)
val |=
led_config->led_states[led_config->num_led_states - 1];
ret = au8522_writereg(state, 0x8000 |
(led_config->gpio_leds & ~0xc000), val);
if (ret < 0)
return ret;
state->led_state = led;
if (led == 0)
au8522_led_gpio_enable(state, 0);
}
return 0;
}
int au8522_sleep(struct dvb_frontend *fe)
{
struct au8522_state *state = fe->demodulator_priv;
dprintk("%s()\n", __func__);
/* Only power down if the digital side is currently using the chip */
if (state->operational_mode == AU8522_ANALOG_MODE) {
/* We're not in one of the expected power modes, which means
that the DVB thread is probably telling us to go to sleep
even though the analog frontend has already started using
the chip. So ignore the request */
return 0;
}
/* turn off led */
au8522_led_ctrl(state, 0);
/* Power down the chip */
au8522_writereg(state, 0xa4, 1 << 5);
state->current_frequency = 0;
return 0;
}
static int au8522_read_status(struct dvb_frontend *fe, fe_status_t *status)
{
struct au8522_state *state = fe->demodulator_priv;
u8 reg;
u32 tuner_status = 0;
*status = 0;
if (state->current_modulation == VSB_8) {
dprintk("%s() Checking VSB_8\n", __func__);
reg = au8522_readreg(state, 0x4088);
if ((reg & 0x03) == 0x03)
*status |= FE_HAS_LOCK | FE_HAS_SYNC | FE_HAS_VITERBI;
} else {
dprintk("%s() Checking QAM\n", __func__);
reg = au8522_readreg(state, 0x4541);
if (reg & 0x80)
*status |= FE_HAS_VITERBI;
if (reg & 0x20)
*status |= FE_HAS_LOCK | FE_HAS_SYNC;
}
switch (state->config->status_mode) {
case AU8522_DEMODLOCKING:
dprintk("%s() DEMODLOCKING\n", __func__);
if (*status & FE_HAS_VITERBI)
*status |= FE_HAS_CARRIER | FE_HAS_SIGNAL;
break;
case AU8522_TUNERLOCKING:
/* Get the tuner status */
dprintk("%s() TUNERLOCKING\n", __func__);
if (fe->ops.tuner_ops.get_status) {
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
fe->ops.tuner_ops.get_status(fe, &tuner_status);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
}
if (tuner_status)
*status |= FE_HAS_CARRIER | FE_HAS_SIGNAL;
break;
}
state->fe_status = *status;
if (*status & FE_HAS_LOCK)
/* turn on LED, if it isn't on already */
au8522_led_ctrl(state, -1);
else
/* turn off LED */
au8522_led_ctrl(state, 0);
dprintk("%s() status 0x%08x\n", __func__, *status);
return 0;
}
static int au8522_led_status(struct au8522_state *state, const u16 *snr)
{
struct au8522_led_config *led_config = state->config->led_cfg;
int led;
u16 strong;
/* bail out if we cant control an LED */
if (!led_config)
return 0;
if (0 == (state->fe_status & FE_HAS_LOCK))
return au8522_led_ctrl(state, 0);
else if (state->current_modulation == QAM_256)
strong = led_config->qam256_strong;
else if (state->current_modulation == QAM_64)
strong = led_config->qam64_strong;
else /* (state->current_modulation == VSB_8) */
strong = led_config->vsb8_strong;
if (*snr >= strong)
led = 2;
else
led = 1;
if ((state->led_state) &&
(((strong < *snr) ? (*snr - strong) : (strong - *snr)) <= 10))
/* snr didn't change enough to bother
* changing the color of the led */
return 0;
return au8522_led_ctrl(state, led);
}
static int au8522_read_snr(struct dvb_frontend *fe, u16 *snr)
{
struct au8522_state *state = fe->demodulator_priv;
int ret = -EINVAL;
dprintk("%s()\n", __func__);
if (state->current_modulation == QAM_256)
ret = au8522_mse2snr_lookup(qam256_mse2snr_tab,
ARRAY_SIZE(qam256_mse2snr_tab),
au8522_readreg(state, 0x4522),
snr);
else if (state->current_modulation == QAM_64)
ret = au8522_mse2snr_lookup(qam64_mse2snr_tab,
ARRAY_SIZE(qam64_mse2snr_tab),
au8522_readreg(state, 0x4522),
snr);
else /* VSB_8 */
ret = au8522_mse2snr_lookup(vsb_mse2snr_tab,
ARRAY_SIZE(vsb_mse2snr_tab),
au8522_readreg(state, 0x4311),
snr);
if (state->config->led_cfg)
au8522_led_status(state, snr);
return ret;
}
static int au8522_read_signal_strength(struct dvb_frontend *fe,
u16 *signal_strength)
{
return au8522_read_snr(fe, signal_strength);
}
static int au8522_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
{
struct au8522_state *state = fe->demodulator_priv;
if (state->current_modulation == VSB_8)
*ucblocks = au8522_readreg(state, 0x4087);
else
*ucblocks = au8522_readreg(state, 0x4543);
return 0;
}
static int au8522_read_ber(struct dvb_frontend *fe, u32 *ber)
{
return au8522_read_ucblocks(fe, ber);
}
static int au8522_get_frontend(struct dvb_frontend *fe,
struct dvb_frontend_parameters *p)
{
struct au8522_state *state = fe->demodulator_priv;
p->frequency = state->current_frequency;
p->u.vsb.modulation = state->current_modulation;
return 0;
}
static int au8522_get_tune_settings(struct dvb_frontend *fe,
struct dvb_frontend_tune_settings *tune)
{
tune->min_delay_ms = 1000;
return 0;
}
static struct dvb_frontend_ops au8522_ops;
int au8522_get_state(struct au8522_state **state, struct i2c_adapter *i2c,
u8 client_address)
{
int ret;
mutex_lock(&au8522_list_mutex);
ret = hybrid_tuner_request_state(struct au8522_state, (*state),
hybrid_tuner_instance_list,
i2c, client_address, "au8522");
mutex_unlock(&au8522_list_mutex);
return ret;
}
void au8522_release_state(struct au8522_state *state)
{
mutex_lock(&au8522_list_mutex);
if (state != NULL)
hybrid_tuner_release_state(state);
mutex_unlock(&au8522_list_mutex);
}
static void au8522_release(struct dvb_frontend *fe)
{
struct au8522_state *state = fe->demodulator_priv;
au8522_release_state(state);
}
struct dvb_frontend *au8522_attach(const struct au8522_config *config,
struct i2c_adapter *i2c)
{
struct au8522_state *state = NULL;
int instance;
/* allocate memory for the internal state */
instance = au8522_get_state(&state, i2c, config->demod_address);
switch (instance) {
case 0:
dprintk("%s state allocation failed\n", __func__);
break;
case 1:
/* new demod instance */
dprintk("%s using new instance\n", __func__);
break;
default:
/* existing demod instance */
dprintk("%s using existing instance\n", __func__);
break;
}
/* setup the state */
state->config = config;
state->i2c = i2c;
state->operational_mode = AU8522_DIGITAL_MODE;
/* create dvb_frontend */
memcpy(&state->frontend.ops, &au8522_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
if (au8522_init(&state->frontend) != 0) {
printk(KERN_ERR "%s: Failed to initialize correctly\n",
__func__);
goto error;
}
/* Note: Leaving the I2C gate open here. */
au8522_i2c_gate_ctrl(&state->frontend, 1);
return &state->frontend;
error:
au8522_release_state(state);
return NULL;
}
EXPORT_SYMBOL(au8522_attach);
static struct dvb_frontend_ops au8522_ops = {
.info = {
.name = "Auvitek AU8522 QAM/8VSB Frontend",
.type = FE_ATSC,
.frequency_min = 54000000,
.frequency_max = 858000000,
.frequency_stepsize = 62500,
.caps = FE_CAN_QAM_64 | FE_CAN_QAM_256 | FE_CAN_8VSB
},
.init = au8522_init,
.sleep = au8522_sleep,
.i2c_gate_ctrl = au8522_i2c_gate_ctrl,
.set_frontend = au8522_set_frontend,
.get_frontend = au8522_get_frontend,
.get_tune_settings = au8522_get_tune_settings,
.read_status = au8522_read_status,
.read_ber = au8522_read_ber,
.read_signal_strength = au8522_read_signal_strength,
.read_snr = au8522_read_snr,
.read_ucblocks = au8522_read_ucblocks,
.release = au8522_release,
};
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Enable verbose debug messages");
MODULE_DESCRIPTION("Auvitek AU8522 QAM-B/ATSC Demodulator driver");
MODULE_AUTHOR("Steven Toth");
MODULE_LICENSE("GPL");
|
# encoding: utf-8
"""
Example RESTful API Server.
"""
import logging
import os
import sys
from flask import Flask
CONFIG_NAME_MAPPER = {
'development': 'config.DevelopmentConfig',
'testing': 'config.TestingConfig',
'production': 'config.ProductionConfig',
'local': 'local_config.LocalConfig',
}
def create_app(flask_config_name=None, **kwargs):
"""
Entry point to the Flask RESTful Server application.
"""
app = Flask(__name__, **kwargs)
env_flask_config_name = os.getenv('FLASK_CONFIG')
if not env_flask_config_name and flask_config_name is None:
flask_config_name = 'local'
elif flask_config_name is None:
flask_config_name = env_flask_config_name
else:
if env_flask_config_name:
assert env_flask_config_name == flask_config_name, (
"FLASK_CONFIG environment variable (\"%s\") and flask_config_name argument "
"(\"%s\") are both set and are not the same." % (
env_flask_config_name,
flask_config_name
)
)
try:
app.config.from_object(CONFIG_NAME_MAPPER[flask_config_name])
except ImportError:
if flask_config_name == 'local':
app.logger.error(
"You have to have `local_config.py` or `local_config/__init__.py` in order to use "
"the default 'local' Flask Config. Alternatively, you may set `FLASK_CONFIG` "
"environment variable to one of the following options: development, production, "
"testing."
)
sys.exit(1)
raise
if app.debug:
logging.getLogger('flask_oauthlib').setLevel(logging.DEBUG)
app.logger.setLevel(logging.DEBUG)
from . import extensions
extensions.init_app(app)
from . import modules
modules.init_app(app)
return app
|
import asyncio
import logging
import sys
from inspect import isawaitable
import pytest
from sanic.exceptions import SanicException
from sanic.response import text
def uvloop_installed():
try:
import uvloop # noqa
return True
except ImportError:
return False
def test_app_loop_running(app):
@app.get("/test")
async def handler(request):
assert isinstance(app.loop, asyncio.AbstractEventLoop)
return text("pass")
request, response = app.test_client.get("/test")
assert response.text == "pass"
@pytest.mark.skipif(
sys.version_info < (3, 7), reason="requires python3.7 or higher"
)
def test_create_asyncio_server(app):
if not uvloop_installed():
loop = asyncio.get_event_loop()
asyncio_srv_coro = app.create_server(return_asyncio_server=True)
assert isawaitable(asyncio_srv_coro)
srv = loop.run_until_complete(asyncio_srv_coro)
assert srv.is_serving() is True
@pytest.mark.skipif(
sys.version_info < (3, 7), reason="requires python3.7 or higher"
)
def test_asyncio_server_start_serving(app):
if not uvloop_installed():
loop = asyncio.get_event_loop()
asyncio_srv_coro = app.create_server(
return_asyncio_server=True,
asyncio_server_kwargs=dict(start_serving=False),
)
srv = loop.run_until_complete(asyncio_srv_coro)
assert srv.is_serving() is False
def test_app_loop_not_running(app):
with pytest.raises(SanicException) as excinfo:
app.loop
assert str(excinfo.value) == (
"Loop can only be retrieved after the app has started "
"running. Not supported with `create_server` function"
)
def test_app_run_raise_type_error(app):
with pytest.raises(TypeError) as excinfo:
app.run(loop="loop")
assert str(excinfo.value) == (
"loop is not a valid argument. To use an existing loop, "
"change to create_server().\nSee more: "
"https://sanic.readthedocs.io/en/latest/sanic/deploying.html"
"#asynchronous-support"
)
def test_app_route_raise_value_error(app):
with pytest.raises(ValueError) as excinfo:
@app.route("/test")
async def handler():
return text("test")
assert (
str(excinfo.value)
== "Required parameter `request` missing in the handler() route?"
)
def test_app_handle_request_handler_is_none(app, monkeypatch):
def mockreturn(*args, **kwargs):
return None, [], {}, ""
# Not sure how to make app.router.get() return None, so use mock here.
monkeypatch.setattr(app.router, "get", mockreturn)
@app.get("/test")
def handler(request):
return text("test")
request, response = app.test_client.get("/test")
assert (
response.text
== "Error: 'None' was returned while requesting a handler from the router"
)
@pytest.mark.parametrize("websocket_enabled", [True, False])
@pytest.mark.parametrize("enable", [True, False])
def test_app_enable_websocket(app, websocket_enabled, enable):
app.websocket_enabled = websocket_enabled
app.enable_websocket(enable=enable)
assert app.websocket_enabled == enable
@app.websocket("/ws")
async def handler(request, ws):
await ws.send("test")
assert app.websocket_enabled == True
def test_handle_request_with_nested_exception(app, monkeypatch):
err_msg = "Mock Exception"
# Not sure how to raise an exception in app.error_handler.response(), use mock here
def mock_error_handler_response(*args, **kwargs):
raise Exception(err_msg)
monkeypatch.setattr(
app.error_handler, "response", mock_error_handler_response
)
@app.get("/")
def handler(request):
raise Exception
request, response = app.test_client.get("/")
assert response.status == 500
assert response.text == "An error occurred while handling an error"
def test_handle_request_with_nested_exception_debug(app, monkeypatch):
err_msg = "Mock Exception"
# Not sure how to raise an exception in app.error_handler.response(), use mock here
def mock_error_handler_response(*args, **kwargs):
raise Exception(err_msg)
monkeypatch.setattr(
app.error_handler, "response", mock_error_handler_response
)
@app.get("/")
def handler(request):
raise Exception
request, response = app.test_client.get("/", debug=True)
assert response.status == 500
assert response.text.startswith(
"Error while handling error: {}\nStack: Traceback (most recent call last):\n".format(
err_msg
)
)
def test_handle_request_with_nested_sanic_exception(app, monkeypatch, caplog):
# Not sure how to raise an exception in app.error_handler.response(), use mock here
def mock_error_handler_response(*args, **kwargs):
raise SanicException("Mock SanicException")
monkeypatch.setattr(
app.error_handler, "response", mock_error_handler_response
)
@app.get("/")
def handler(request):
raise Exception
with caplog.at_level(logging.ERROR):
request, response = app.test_client.get("/")
assert response.status == 500
assert response.text == "Error: Mock SanicException"
assert (
"sanic.root",
logging.ERROR,
"Exception occurred while handling uri: 'http://127.0.0.1:42101/'",
) in caplog.record_tuples
|