file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
main.rs
#![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] mod cmd; use serde::Serialize; #[derive(Serialize)] struct Reply { data: String } fn main() { tauri::AppBuilder::new() .setup(|webview, _source| { let handle = webview.handle(); tauri::event::listen(String::from("js-event"), move |msg| { println!("got js-event with message '{}'", msg); let reply = Reply { data: "something else".to_string(), }; tauri::event::emit( &handle, String::from("rust-event"), serde_json::to_string(&reply).unwrap(), ); }); }) .invoke_handler(|_webview, arg| { use cmd::Cmd::*; match serde_json::from_str(arg) { Err(_) => {} Ok(command) => {
println!("{} {:?}", event, payload); }, PerformRequest { endpoint, body, callback, error } => { // tauri::execute_promise is a helper for APIs that uses the tauri.promisified JS function // so you can easily communicate between JS and Rust with promises tauri::execute_promise( _webview, move || { println!("{} {:?}", endpoint, body); // perform an async operation here // if the returned value is Ok, the promise will be resolved with its value // if the returned value is Err, the promise will be rejected with its value // the value is a string that will be eval'd Ok("{ key: 'response', value: [{ id: 3 }] }".to_string()) }, callback, error ) }, } } } }) .build() .run(); }
match command { LogOperation { event, payload } => {
_published_blueprints_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PublishedBlueprintsOperations: """PublishedBlueprintsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~blueprint_management_client.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None:
async def create( self, resource_scope: str, blueprint_name: str, version_id: str, published_blueprint: Optional["_models.PublishedBlueprint"] = None, **kwargs: Any ) -> "_models.PublishedBlueprint": """Publish a new version of the blueprint definition with the latest artifacts. Published blueprint definitions are immutable. :param resource_scope: The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'). :type resource_scope: str :param blueprint_name: Name of the blueprint definition. :type blueprint_name: str :param version_id: Version of the published blueprint definition. :type version_id: str :param published_blueprint: Published Blueprint to create or update. :type published_blueprint: ~blueprint_management_client.models.PublishedBlueprint :keyword callable cls: A custom type or function that will be passed the direct response :return: PublishedBlueprint, or the result of cls(response) :rtype: ~blueprint_management_client.models.PublishedBlueprint :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublishedBlueprint"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-11-01-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create.metadata['url'] # type: ignore path_format_arguments = { 'resourceScope': self._serialize.url("resource_scope", resource_scope, 'str', skip_quote=True), 'blueprintName': self._serialize.url("blueprint_name", blueprint_name, 'str'), 'versionId': self._serialize.url("version_id", version_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] if published_blueprint is not None: body_content = self._serialize.body(published_blueprint, 'PublishedBlueprint') else: body_content = None body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PublishedBlueprint', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create.metadata = {'url': '/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/versions/{versionId}'} # type: ignore async def get( self, resource_scope: str, blueprint_name: str, version_id: str, **kwargs: Any ) -> "_models.PublishedBlueprint": """Get a published version of a blueprint definition. :param resource_scope: The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'). :type resource_scope: str :param blueprint_name: Name of the blueprint definition. :type blueprint_name: str :param version_id: Version of the published blueprint definition. :type version_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PublishedBlueprint, or the result of cls(response) :rtype: ~blueprint_management_client.models.PublishedBlueprint :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublishedBlueprint"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-11-01-preview" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceScope': self._serialize.url("resource_scope", resource_scope, 'str', skip_quote=True), 'blueprintName': self._serialize.url("blueprint_name", blueprint_name, 'str'), 'versionId': self._serialize.url("version_id", version_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PublishedBlueprint', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/versions/{versionId}'} # type: ignore async def delete( self, resource_scope: str, blueprint_name: str, version_id: str, **kwargs: Any ) -> Optional["_models.PublishedBlueprint"]: """Delete a published version of a blueprint definition. :param resource_scope: The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'). :type resource_scope: str :param blueprint_name: Name of the blueprint definition. :type blueprint_name: str :param version_id: Version of the published blueprint definition. :type version_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PublishedBlueprint, or the result of cls(response) :rtype: ~blueprint_management_client.models.PublishedBlueprint or None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PublishedBlueprint"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-11-01-preview" accept = "application/json" # Construct URL url = self.delete.metadata['url'] # type: ignore path_format_arguments = { 'resourceScope': self._serialize.url("resource_scope", resource_scope, 'str', skip_quote=True), 'blueprintName': self._serialize.url("blueprint_name", blueprint_name, 'str'), 'versionId': self._serialize.url("version_id", version_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('PublishedBlueprint', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete.metadata = {'url': '/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/versions/{versionId}'} # type: ignore def list( self, resource_scope: str, blueprint_name: str, **kwargs: Any ) -> AsyncIterable["_models.PublishedBlueprintList"]: """List published versions of given blueprint definition. :param resource_scope: The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'). :type resource_scope: str :param blueprint_name: Name of the blueprint definition. :type blueprint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PublishedBlueprintList or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~blueprint_management_client.models.PublishedBlueprintList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublishedBlueprintList"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-11-01-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceScope': self._serialize.url("resource_scope", resource_scope, 'str', skip_quote=True), 'blueprintName': self._serialize.url("blueprint_name", blueprint_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('PublishedBlueprintList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/versions'} # type: ignore
self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
wallet_block_store.py
from typing import Dict, Optional, Tuple, List import aiosqlite from src.consensus.sub_block_record import SubBlockRecord from src.types.header_block import HeaderBlock from src.util.ints import uint32, uint64 from src.wallet.block_record import HeaderBlockRecord from src.types.sized_bytes import bytes32 class WalletBlockStore: """ This object handles HeaderBlocks and SubBlocks stored in DB used by wallet. """ db: aiosqlite.Connection @classmethod async def create(cls, connection: aiosqlite.Connection): self = cls() self.db = connection await self.db.execute( "CREATE TABLE IF NOT EXISTS header_blocks(header_hash text PRIMARY KEY, sub_height int, height int," " timestamp int, block blob)" ) await self.db.execute("CREATE INDEX IF NOT EXISTS header_hash on header_blocks(header_hash)") await self.db.execute("CREATE INDEX IF NOT EXISTS timestamp on header_blocks(timestamp)") await self.db.execute("CREATE INDEX IF NOT EXISTS sub_height on header_blocks(sub_height)") await self.db.execute("CREATE INDEX IF NOT EXISTS height on header_blocks(height)") # Sub block records await self.db.execute( "CREATE TABLE IF NOT EXISTS sub_block_records(header_hash " "text PRIMARY KEY, prev_hash text, sub_height bigint, height int, weight bigint, total_iters text," "sub_block blob, is_peak tinyint)" ) # Height index so we can look up in order of height for sync purposes await self.db.execute("CREATE INDEX IF NOT EXISTS sub_block_height on sub_block_records(sub_height)") await self.db.execute("CREATE INDEX IF NOT EXISTS height on sub_block_records(height)") await self.db.execute("CREATE INDEX IF NOT EXISTS hh on sub_block_records(header_hash)") await self.db.execute("CREATE INDEX IF NOT EXISTS peak on sub_block_records(is_peak)") await self.db.commit() await self.db.commit() return self async def
(self): cursor_2 = await self.db.execute("DELETE FROM header_blocks") await cursor_2.close() await self.db.commit() async def rollback_lca_to_block(self, block_index): # TODO pass async def add_block_record(self, block_record: HeaderBlockRecord, sub_block: SubBlockRecord): """ Adds a block record to the database. This block record is assumed to be connected to the chain, but it may or may not be in the LCA path. """ if block_record.header.foliage_block is not None: timestamp = block_record.header.foliage_block.timestamp else: timestamp = uint64(0) cursor = await self.db.execute( "INSERT OR REPLACE INTO header_blocks VALUES(?, ?, ?, ?, ?)", ( block_record.header_hash.hex(), block_record.sub_block_height, sub_block.height, timestamp, bytes(block_record), ), ) await cursor.close() cursor_2 = await self.db.execute( "INSERT OR REPLACE INTO sub_block_records VALUES(?, ?, ?, ?, ?, ?, ?, ?)", ( block_record.header.header_hash.hex(), block_record.header.prev_header_hash.hex(), block_record.header.sub_block_height, block_record.header.height, block_record.header.weight.to_bytes(128 // 8, "big", signed=False).hex(), block_record.header.total_iters.to_bytes(128 // 8, "big", signed=False).hex(), bytes(sub_block), False, ), ) await cursor_2.close() await self.db.commit() async def get_header_block(self, header_hash: bytes32) -> Optional[HeaderBlock]: """Gets a block record from the database, if present""" cursor = await self.db.execute("SELECT * from header_blocks WHERE header_hash=?", (header_hash.hex(),)) row = await cursor.fetchone() await cursor.close() if row is not None: hbr = HeaderBlockRecord.from_bytes(row[4]) return hbr.header else: return None async def get_header_block_at(self, sub_heights: List[uint32]) -> List[HeaderBlock]: if len(sub_heights) == 0: return [] heights_db = tuple(sub_heights) formatted_str = f'SELECT block from header_blocks WHERE sub_height in ({"?," * (len(heights_db) - 1)}?)' cursor = await self.db.execute(formatted_str, heights_db) rows = await cursor.fetchall() await cursor.close() return [HeaderBlock.from_bytes(row[0]) for row in rows] async def get_header_block_record(self, header_hash: bytes32) -> Optional[HeaderBlockRecord]: """Gets a block record from the database, if present""" cursor = await self.db.execute("SELECT * from header_blocks WHERE header_hash=?", (header_hash.hex(),)) row = await cursor.fetchone() await cursor.close() if row is not None: hbr = HeaderBlockRecord.from_bytes(row[4]) return hbr else: return None async def get_sub_block_record(self, header_hash: bytes32) -> Optional[SubBlockRecord]: cursor = await self.db.execute( "SELECT sub_block from sub_block_records WHERE header_hash=?", (header_hash.hex(),), ) row = await cursor.fetchone() await cursor.close() if row is not None: return SubBlockRecord.from_bytes(row[0]) return None async def get_sub_block_records( self, ) -> Tuple[Dict[bytes32, SubBlockRecord], Optional[bytes32]]: """ Returns a dictionary with all sub blocks, as well as the header hash of the peak, if present. """ cursor = await self.db.execute("SELECT * from sub_block_records") rows = await cursor.fetchall() await cursor.close() ret: Dict[bytes32, SubBlockRecord] = {} peak: Optional[bytes32] = None for row in rows: header_hash = bytes.fromhex(row[0]) ret[header_hash] = SubBlockRecord.from_bytes(row[6]) if row[7]: assert peak is None # Sanity check, only one peak peak = header_hash return ret, peak async def set_peak(self, header_hash: bytes32) -> None: cursor_1 = await self.db.execute("UPDATE sub_block_records SET is_peak=0 WHERE is_peak=1") await cursor_1.close() cursor_2 = await self.db.execute( "UPDATE sub_block_records SET is_peak=1 WHERE header_hash=?", (header_hash.hex(),), ) await cursor_2.close() await self.db.commit()
_clear_database
golint_suggestion_test.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package suggestion import ( "go/token" "testing" "github.com/golang/lint" ) func TestLintNamesUnderscore(t *testing.T) { var testcases = []struct { problem lint.Problem expectedSuggestion string }{ { problem: lint.Problem{ Position: token.Position{ Filename: "qux.go", }, Text: "don't use underscores in Go names; func Qux_1 should be Qux1", Link: "http://golang.org/doc/effective_go.html#mixed-caps", Category: "naming", LineText: "func Qux_1() error {", Confidence: 100.00, }, expectedSuggestion: "```suggestion\nfunc Qux1() error {```\n", }, { problem: lint.Problem{ Position: token.Position{ Filename: "qux.go", }, Text: "don't use underscores in Go names; func Qux_Foo_Func should be QuxFooFunc", Link: "http://golang.org/doc/effective_go.html#mixed-caps", Category: "naming", LineText: "func Qux_Foo_Func() error {", Confidence: 100.00, }, expectedSuggestion: "```suggestion\nfunc QuxFooFunc() error {```\n", }, { problem: lint.Problem{ Position: token.Position{ Filename: "qux.go", }, Text: "don't use underscores in Go names; func Qux_Foo_Func should be QuxFooFunc", Link: "http://golang.org/doc/effective_go.html#mixed-caps", Category: "naming", LineText: "func QuxCorrectFunc() error {", Confidence: 100.00, }, expectedSuggestion: "", }, } for _, test := range testcases { suggestion := SuggestCodeChange(test.problem) if suggestion != test.expectedSuggestion { t.Errorf("Excepted code suggestion %s but got %s for LineText %s", test.expectedSuggestion, suggestion, test.problem.LineText) } } } func TestLintNamesAllCaps(t *testing.T) { var testcases = []struct { problem lint.Problem expectedSuggestion string }{ { problem: lint.Problem{ Position: token.Position{ Filename: "qux.go", }, Text: "don't use ALL_CAPS in Go names; use CamelCase", Link: "", Category: "naming", LineText: "func QUX_FUNC() error {", Confidence: 100.00, }, expectedSuggestion: "```suggestion\nfunc QuxFunc() error {```\n", }, { problem: lint.Problem{ Position: token.Position{ Filename: "qux.go", }, Text: "don't use ALL_CAPS in Go names; use CamelCase", Link: "http://golang.org/doc/effective_go.html#mixed-caps", Category: "naming", LineText: "func QUX() error {", Confidence: 100.00, }, expectedSuggestion: "```suggestion\nfunc Qux() error {```\n", }, { problem: lint.Problem{ Position: token.Position{ Filename: "qux.go", }, Text: "don't use ALL_CAPS in Go names; use CamelCase", Link: "http://golang.org/doc/effective_go.html#mixed-caps", Category: "naming", LineText: "func QUX_FOO_FUNC() error {", Confidence: 100.00, }, expectedSuggestion: "```suggestion\nfunc QuxFooFunc() error {```\n", }, { problem: lint.Problem{ Position: token.Position{ Filename: "qux.go", }, Text: "don't use ALL_CAPS in Go names; use CamelCase", Link: "http://golang.org/doc/effective_go.html#mixed-caps", Category: "naming", LineText: "func QUX_FOO_FUNC_1() error {", Confidence: 100.00, }, expectedSuggestion: "```suggestion\nfunc QuxFooFunc1() error {```\n", }, { problem: lint.Problem{ Position: token.Position{ Filename: "qux.go", }, Text: "don't use ALL_CAPS in Go names; use CamelCase", Link: "http://golang.org/doc/effective_go.html#mixed-caps", Category: "naming", LineText: "func QuxCorrectFunc() error {", Confidence: 100.00, }, expectedSuggestion: "", }, { problem: lint.Problem{ Position: token.Position{ Filename: "qux.go", }, Text: "don't use ALL_CAPS in Go names; use CamelCase", Link: "http://golang.org/doc/effective_go.html#mixed-caps", Category: "naming", LineText: "func Qux() error {", Confidence: 100.00, }, expectedSuggestion: "", }, } for _, test := range testcases { suggestion := SuggestCodeChange(test.problem) if suggestion != test.expectedSuggestion
} }
{ t.Errorf("Excepted code suggestion %s but got %s for LineText %s", test.expectedSuggestion, suggestion, test.problem.LineText) }
nvicispr2.rs
#[doc = "Register `NVICISPR2` reader"] pub struct R(crate::R<NVICISPR2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<NVICISPR2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<NVICISPR2_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<NVICISPR2_SPEC>) -> Self { R(reader) } } #[doc = "Register `NVICISPR2` writer"] pub struct W(crate::W<NVICISPR2_SPEC>); impl core::ops::Deref for W { type Target = crate::W<NVICISPR2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<NVICISPR2_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<NVICISPR2_SPEC>) -> Self { W(writer) } } #[doc = "Field `SETPEND` reader - Interrupt set-pending bits"] pub struct SETPEND_R(crate::FieldReader<u32, u32>); impl SETPEND_R { #[inline(always)] pub(crate) fn new(bits: u32) -> Self { SETPEND_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SETPEND_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `SETPEND` writer - Interrupt set-pending bits"] pub struct SETPEND_W<'a> { w: &'a mut W, } impl<'a> SETPEND_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = value; self.w } } impl R { #[doc = "Bits 0:31 - Interrupt set-pending bits"] #[inline(always)] pub fn setpend(&self) -> SETPEND_R { SETPEND_R::new(self.bits) } } impl W { #[doc = "Bits 0:31 - Interrupt set-pending bits"] #[inline(always)] pub fn setpend(&mut self) -> SETPEND_W { SETPEND_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self
} #[doc = "Interrupt Set Pending Register n\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [nvicispr2](index.html) module"] pub struct NVICISPR2_SPEC; impl crate::RegisterSpec for NVICISPR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [nvicispr2::R](R) reader structure"] impl crate::Readable for NVICISPR2_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [nvicispr2::W](W) writer structure"] impl crate::Writable for NVICISPR2_SPEC { type Writer = W; } #[doc = "`reset()` method sets NVICISPR2 to value 0"] impl crate::Resettable for NVICISPR2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
{ self.0.bits(bits); self }
cf.go
package main import ( "io/ioutil" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/cloudformation" "gopkg.in/yaml.v3" ) //CloudformationStack is a class describing the required attributes and methods to manage a cloudformation template. type CloudformationStack struct { TemplatePath string TemplateParameterPath string StackName string AwsSession *session.Session Capabilities *[]string DisableRollback bool Parameters map[string]string Timeout int64 } func MakeCloudformationStack() CloudformationStack { cf := CloudformationStack{ Capabilities: new([]string), Parameters: make(map[string]string), } return cf } //GetTemplateBody returns a reference to a string containing the template body. func (cf *CloudformationStack) GetTemplateBody() *string { templateBody, err := ioutil.ReadFile(cf.TemplatePath) if err != nil
return aws.String(string(templateBody)) } //ValidateTemplate validates a CF template returns false when the validations fails. func (cf *CloudformationStack) ValidateTemplate() (isValid bool, err error) { templateBody, err := ioutil.ReadFile(cf.TemplatePath) if err != nil { printErrorf("Something went wrong when trying to open template body. %v", err) return false, err } _, err = cf.Client().ValidateTemplate(&cloudformation.ValidateTemplateInput{TemplateBody: aws.String(string(templateBody))}) if err != nil { return false, err } return true, err } //Client is a function that returns a cloudformation client object func (cf *CloudformationStack) Client() *cloudformation.CloudFormation { return cloudformation.New(cf.AwsSession) } //Exists a function that tests if the cloudformation exists or not. func (cf *CloudformationStack) Exists() bool { stack, _ := cf.Client().DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(cf.StackName)}) return stack.Stacks != nil } func (cf *CloudformationStack) GetParameters() (map[string]string, error) { params := make(map[string]string) parametersFile, err := ioutil.ReadFile(cf.TemplateParameterPath) if err != nil { printErrorf("Something went wrong when trying to open parameters file. %v", err) return nil, err } err = yaml.Unmarshal(parametersFile, &params) if err != nil { printErrorf("Something went wrong when loading yaml content from paramters file. %v", err) return nil, err } return params, nil } func (cf *CloudformationStack) GenerateParameters() ([]*cloudformation.Parameter, error) { var Parameters []*cloudformation.Parameter parametersMap, err := cf.GetParameters() for key, element := range parametersMap { Parameters = append(Parameters, &cloudformation.Parameter{ParameterKey: aws.String(key), ParameterValue: aws.String(element)}) } return Parameters, err } func (cf *CloudformationStack) getCreateStackInput() (*cloudformation.CreateStackInput, error) { parameters, err := cf.GenerateParameters() stackInput := cloudformation.CreateStackInput{ Capabilities: aws.StringSlice(*cf.Capabilities), DisableRollback: aws.Bool(cf.DisableRollback), Parameters: parameters, StackName: aws.String(cf.StackName), TemplateBody: cf.GetTemplateBody(), TimeoutInMinutes: aws.Int64(cf.Timeout), } return &stackInput, err } func (cf *CloudformationStack) CreateStack() (*cloudformation.CreateStackOutput, error) { stackInput, err := cf.getCreateStackInput() if err != nil { return nil, err } res, err := cf.Client().CreateStack(stackInput) return res, err } func (cf *CloudformationStack) DeleteStack() (*cloudformation.DeleteStackOutput, error) { deleteStackInput := cloudformation.DeleteStackInput{StackName: aws.String(cf.StackName)} res, err := cf.Client().DeleteStack(&deleteStackInput) return res, err } func (cf *CloudformationStack) getUpdateStackInput() (*cloudformation.UpdateStackInput, error) { parameters, err := cf.GenerateParameters() updateStackInput := cloudformation.UpdateStackInput{ Capabilities: aws.StringSlice(*cf.Capabilities), Parameters: parameters, StackName: aws.String(cf.StackName), TemplateBody: cf.GetTemplateBody(), } return &updateStackInput, err } func (cf *CloudformationStack) UpdateStack() (*cloudformation.UpdateStackOutput, error) { updateStackInput, err := cf.getUpdateStackInput() if err != nil { return nil, err } updateStackOutput, err := cf.Client().UpdateStack(updateStackInput) return updateStackOutput, err } func (cf *CloudformationStack) DescribeStack() (*cloudformation.DescribeStacksOutput, error) { describeStacksInput := cloudformation.DescribeStacksInput{StackName: aws.String(cf.StackName)} describeStacksOutpt, err := cf.Client().DescribeStacks(&describeStacksInput) return describeStacksOutpt, err } func (cf *CloudformationStack) GetStatus() (string, error) { describeStacksoutput, err := cf.DescribeStack() return *describeStacksoutput.Stacks[0].StackStatus, err }
{ printErrorf("Something went wrong when trying to open template body. %v", err) return nil }
js-15.js
/* Rambunctious Recitation */ const fs = require("fs"); const input = fs .readFileSync("./input.txt", (_, a) => a) .toString() .split("\r\n") .map((a) => a.split(','))[0].map(a=>a >>>0); /** * Enumerates rules and returns the number at the stopAtTurn turn * @param {[Number]} input Starting Set of Numbers * @param {Number} stopAtTurn Turn on which to stop the iterations * @returns Value when stopped * @description Uses a Naive loop and array based approach with costly lookups. * Works well for small stopAtTurn values. Speaking a number is easy : just add it to the array. The array is a dictionary i:turn number and the spoken number */ const enumerateByRule_bruteforce = ([...input],stopAtTurn) => { const spoken = []; for (i in input) { spoken[i] = { i: 1 + parseInt(i), spoken: input[i] }; } for (let i = input.length; i < stopAtTurn; i++) { lastSpoken = spoken[i - 1].spoken; // Find the number to be actually spoken let actualSpoken = lastSpoken; previouslySpoken = spoken.filter((x) => x.spoken == lastSpoken); if (previouslySpoken.length > 1) { prevInd = previouslySpoken.slice(-2)[0].i; actualSpoken = i - prevInd; } else if (previouslySpoken.length > 0) { actualSpoken = 0; } // speak the number spoken[i] = { i: i + 1, spoken: actualSpoken }; } return spoken.slice(-1)[0].spoken; }; console.time("Part1 - bruteForce algo"); var p1_bf = enumerateByRule_bruteforce(input, 2020); console.timeEnd("Part1 - bruteForce algo"); console.log("Part1 - BF: ", p1_bf); /** * Enumerates rules and returns the number at the stopAtTurn turn * @param {[Number]} input Starting Set of Numbers * @param {Number} stopAtTurn Turn on which to stop the iterations * @returns Value when stopped * @description Uses a hashmap lookup table with keys being the spoken numbers. This should speed up the enumeration for larger stopAtTurn numbers. * The values are a dictionary with last: the last index this number was spoken; beforeLast: index prior to the last index the number was spoken.
*/ const enumerateByRule_hashmap = ([...input], stopAtTurn) => { const spoken = new Map(); for (i in input) { spoken.set(input[i], { last: parseInt(i), beforeLast: null }); } let lastSpoken = input[input.length-1]; for (let turn = input.length; turn < stopAtTurn; turn++) { //Get number Actual spoken let actualSpoken = lastSpoken; let { last, beforeLast } = spoken.get(lastSpoken); if (beforeLast == null) { actualSpoken = 0; } else { actualSpoken = last - beforeLast; } //Speak number if (spoken.has(actualSpoken)) { //actualSpokenNumber was already spoken, update hash map by setting last to current turn and beforeLast to the original last let { last: orig_last } = spoken.get(actualSpoken); spoken.set(actualSpoken, { last: parseInt(turn), beforeLast: orig_last, }); } else { // add actuallySpoken number to the has map with last as current spoken.set(actualSpoken, { last: parseInt(turn), beforeLast: null }); } lastSpoken = actualSpoken; } return lastSpoken; }; // PART 1 console.time("Part1 - hashmap algo"); var p1_hm = enumerateByRule_hashmap(input, 2020); console.timeEnd("Part1 - hashmap algo"); console.log("Part1 hashmap ", p1_hm); // PART 2 console.log("Part2 : ", enumerateByRule_hashmap(input, 30000000));
* The speak part of this method is a little more involved, since "speaking the number" equates to updating the hashmap.
decode.rs
//! Displays a pretty-printed debug view of a state file. use ic_protobuf::state::{ canister_state_bits::v1 as pb_canister, queues::v1 as pb_queues, system_metadata::v1 as pb_metadata, }; use ic_replicated_state::{canister_state::CanisterQueues, SystemMetadata}; use ic_state_layout::{CanisterStateBits, ProtoFileWith, ReadOnly};
pub fn do_decode(path: PathBuf) -> Result<(), String> { let fname = path .file_name() .ok_or_else(|| format!("failed to get file name of path {}", path.display()))? .to_str() .ok_or_else(|| format!("failed to convert path {} to UTF-8 string", path.display()))?; match fname { "system_metadata.pbuf" => { display_proto::<pb_metadata::SystemMetadata, SystemMetadata>(path.clone()) } "queues.pbuf" => display_proto::<pb_queues::CanisterQueues, CanisterQueues>(path.clone()), "subnet_queues.pbuf" => { display_proto::<pb_queues::CanisterQueues, CanisterQueues>(path.clone()) } "canister.pbuf" => { display_proto::<pb_canister::CanisterStateBits, CanisterStateBits>(path.clone()) } _ => Err(format!("don't know how to decode {}", fname)), } } /// Pretty prints the `RustType` persisted at `path`, encoded as `ProtoType`. fn display_proto<ProtoType, RustType>(path: PathBuf) -> Result<(), String> where ProtoType: prost::Message + Default, RustType: TryFrom<ProtoType> + std::fmt::Debug, <RustType as TryFrom<ProtoType>>::Error: std::fmt::Display, { let f: ProtoFileWith<ProtoType, ReadOnly> = path.into(); let pb = f.deserialize().map_err(|e| format!("{:?}", e))?; let t = RustType::try_from(pb).map_err(|e| { format!( "failed to decode rust type {} from protobuf {}: {}", std::any::type_name::<RustType>(), std::any::type_name::<ProtoType>(), e ) })?; println!("{:#?}", t); Ok(()) }
use std::convert::TryFrom; use std::path::PathBuf; /// Decodes the `.pbuf` state file located at `path`.
get_online_users_count.rs
use serde::{Deserialize, Serialize}; #[derive(Serialize, Default, Debug, Clone)] pub struct Request {} #[derive(Deserialize, Debug, Clone)] pub struct Response { pub count: u64, } impl misskey_core::Request for Request { type Response = Response; const ENDPOINT: &'static str = "get-online-users-count"; } #[cfg(test)] mod tests { use super::Request; use crate::test::{ClientExt, TestClient}; #[tokio::test] async fn
() { let client = TestClient::new(); client.test(Request::default()).await; } }
request
channel_pins_update.rs
use crate::id::ChannelId; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] pub struct
{ pub channel_id: ChannelId, pub last_pin_timestamp: Option<String>, }
ChannelPinsUpdate
UserInput.ts
import { Field, InputType } from 'type-graphql';
@InputType() export class UserInput { @Field({ description: 'Google token id' }) public tokenId: string; }
cfg.rs
#[doc = "Reader of register CFG"] pub type R = crate::R<u32, super::CFG>; #[doc = "Writer for register CFG"] pub type W = crate::W<u32, super::CFG>; #[doc = "Register CFG `reset()`'s with value 0"] impl crate::ResetValue for super::CFG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Mode Select\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MODE_A { #[doc = "0: General Purpose"] NONE, #[doc = "1: SDRAM"] SDRAM, #[doc = "2: 8-Bit Host-Bus (HB8)"] HB8, #[doc = "3: 16-Bit Host-Bus (HB16)"] HB16, } impl From<MODE_A> for u8 { #[inline(always)] fn from(variant: MODE_A) -> Self { match variant { MODE_A::NONE => 0, MODE_A::SDRAM => 1, MODE_A::HB8 => 2, MODE_A::HB16 => 3, } } } #[doc = "Reader of field `MODE`"] pub type MODE_R = crate::R<u8, MODE_A>; impl MODE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, MODE_A> { use crate::Variant::*; match self.bits { 0 => Val(MODE_A::NONE), 1 => Val(MODE_A::SDRAM), 2 => Val(MODE_A::HB8), 3 => Val(MODE_A::HB16), i => Res(i), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == MODE_A::NONE } #[doc = "Checks if the value of the field is `SDRAM`"] #[inline(always)] pub fn is_sdram(&self) -> bool { *self == MODE_A::SDRAM } #[doc = "Checks if the value of the field is `HB8`"] #[inline(always)] pub fn is_hb8(&self) -> bool { *self == MODE_A::HB8 } #[doc = "Checks if the value of the field is `HB16`"] #[inline(always)] pub fn is_hb16(&self) -> bool { *self == MODE_A::HB16 } } #[doc = "Write proxy for field `MODE`"] pub struct MODE_W<'a> { w: &'a mut W, } impl<'a> MODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MODE_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "General Purpose"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(MODE_A::NONE) } #[doc = "SDRAM"] #[inline(always)] pub fn sdram(self) -> &'a mut W { self.variant(MODE_A::SDRAM) } #[doc = "8-Bit Host-Bus (HB8)"] #[inline(always)] pub fn hb8(self) -> &'a mut W { self.variant(MODE_A::HB8) } #[doc = "16-Bit Host-Bus (HB16)"] #[inline(always)] pub fn hb16(self) -> &'a mut W
#[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `BLKEN`"] pub type BLKEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BLKEN`"] pub struct BLKEN_W<'a> { w: &'a mut W, } impl<'a> BLKEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `INTDIV`"] pub type INTDIV_R = crate::R<bool, bool>; #[doc = "Write proxy for field `INTDIV`"] pub struct INTDIV_W<'a> { w: &'a mut W, } impl<'a> INTDIV_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } impl R { #[doc = "Bits 0:3 - Mode Select"] #[inline(always)] pub fn mode(&self) -> MODE_R { MODE_R::new((self.bits & 0x0f) as u8) } #[doc = "Bit 4 - Block Enable"] #[inline(always)] pub fn blken(&self) -> BLKEN_R { BLKEN_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 8 - Integer Clock Divider Enable"] #[inline(always)] pub fn intdiv(&self) -> INTDIV_R { INTDIV_R::new(((self.bits >> 8) & 0x01) != 0) } } impl W { #[doc = "Bits 0:3 - Mode Select"] #[inline(always)] pub fn mode(&mut self) -> MODE_W { MODE_W { w: self } } #[doc = "Bit 4 - Block Enable"] #[inline(always)] pub fn blken(&mut self) -> BLKEN_W { BLKEN_W { w: self } } #[doc = "Bit 8 - Integer Clock Divider Enable"] #[inline(always)] pub fn intdiv(&mut self) -> INTDIV_W { INTDIV_W { w: self } } }
{ self.variant(MODE_A::HB16) }
virtualmachinesizes.go
package compute // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // VirtualMachineSizesClient is the compute Client type VirtualMachineSizesClient struct { BaseClient } // NewVirtualMachineSizesClient creates an instance of the VirtualMachineSizesClient client. func NewVirtualMachineSizesClient(subscriptionID string) VirtualMachineSizesClient { return NewVirtualMachineSizesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewVirtualMachineSizesClientWithBaseURI creates an instance of the VirtualMachineSizesClient client using a custom // endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure // stack). func NewVirtualMachineSizesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineSizesClient { return VirtualMachineSizesClient{NewWithBaseURI(baseURI, subscriptionID)} } // List lists all available virtual machine sizes for a subscription in a location. // Parameters: // location - the location upon which virtual-machine-sizes is queried. func (client VirtualMachineSizesClient) List(ctx context.Context, location string) (result VirtualMachineSizeListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineSizesClient.List") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: location, Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("compute.VirtualMachineSizesClient", "List", err.Error()) } req, err := client.ListPreparer(ctx, location) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure sending request") return } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure responding to request") return } return } // ListPreparer prepares the List request. func (client VirtualMachineSizesClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": autorest.Encode("path", location), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/vmSizes", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineSizesClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client))
} // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client VirtualMachineSizesClient) ListResponder(resp *http.Response) (result VirtualMachineSizeListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
index.tsx
import { h, Component, Fragment } from 'preact'; import * as style from './style.css'; import 'add-css:./style.css'; import 'shared/custom-els/loading-spinner'; import { SourceImage } from '../'; import prettyBytes from './pretty-bytes'; import { Arrow, DownloadIcon } from 'client/lazy-app/icons'; interface Props { loading: boolean; source?: SourceImage; imageFile?: File; downloadUrl?: string; flipSide: boolean; typeLabel: string; } interface State { showLoadingState: boolean; } const loadingReactionDelay = 500; export default class Results extends Component<Props, State> { state: State = { showLoadingState: this.props.loading, }; /** The timeout ID between entering the loading state, and changing UI */ private loadingTimeoutId: number = 0; componentDidUpdate(prevProps: Props, prevState: State) { if (prevProps.loading && !this.props.loading) { // Just stopped loading clearTimeout(this.loadingTimeoutId); this.setState({ showLoadingState: false }); } else if (!prevProps.loading && this.props.loading) { // Just started loading this.loadingTimeoutId = self.setTimeout( () => this.setState({ showLoadingState: true }), loadingReactionDelay, ); } } private onDownload = () => { // GA can’t do floats. So we round to ints. We're deliberately rounding to nearest kilobyte to // avoid cases where exact image sizes leak something interesting about the user. const before = Math.round(this.props.source!.file.size / 1024); const after = Math.round(this.props.imageFile!.size / 1024); const change = Math.round((after / before) * 1000); ga('send', 'event', 'compression', 'download', { metric1: before, metric2: after, metric3: change, }); }; render( { source, imageFile, downloadUrl, flipSide, typeLabel }: Props, { showLoadingState }: State, ) { const prettySize = imageFile && prettyBytes(imageFile.size); const isOriginal = !source || !imageFile || source.file === imageFile; let diff; let percent; if (source && imageFile) { diff = imageFile.size / source.file.size; const absolutePercent = Math.round(Math.abs(diff) * 100); percent = diff > 1 ? absolutePercent - 100 : 100 - absolutePercent; } return ( <div class={ (flipSide ? style.resultsRight : style.resultsLeft) + ' ' + (isOriginal ? style.isOriginal : '') } > <div class={style.expandArrow}> <Arrow /> </div> <div class={style.bubble}> <div class={style.bubbleInner}> <div class={style.sizeInfo}> <div class={style.fileSize}> {prettySize ? ( <Fragment> {prettySize.value}{' '} <span class={style.unit}>{prettySize.unit}</span> <span class={style.typeLabel}> {typeLabel}</span> </Fragment> ) : ( '…' )} </div> </div>
viewBox="0 0 1 2" class={style.bigArrow} preserveAspectRatio="none" > <path d="M1 0v2L0 1z" /> </svg> <div class={style.percentOutput}> {diff && diff !== 1 && ( <span class={style.sizeDirection}> {diff < 1 ? '↓' : '↑'} </span> )} <span class={style.sizeValue}>{percent || 0}</span> <span class={style.percentChar}>%</span> </div> </div> </div> </div> <a class={showLoadingState ? style.downloadDisable : style.download} href={downloadUrl} download={imageFile ? imageFile.name : ''} title="Download" onClick={this.onDownload} > <svg class={style.downloadBlobs} viewBox="0 0 89.6 86.9"> <title>Download</title> <path d="M27.3 72c-8-4-15.6-12.3-16.9-21-1.2-8.7 4-17.8 10.5-26s14.4-15.6 24-16 21.2 6 28.6 16.5c7.4 10.5 10.8 25 6.6 34S64.1 71.8 54 73.6c-10.2 2-18.7 2.3-26.7-1.6z" /> <path d="M19.8 24.8c4.3-7.8 13-15 21.8-15.7 8.7-.8 17.5 4.8 25.4 11.8 7.8 6.9 14.8 15.2 14.7 24.9s-7.1 20.7-18 27.6c-10.8 6.8-25.5 9.5-34.2 4.8S18.1 61.6 16.7 51.4c-1.3-10.3-1.3-18.8 3-26.6z" /> </svg> <div class={style.downloadIcon}> <DownloadIcon /> </div> {showLoadingState && <loading-spinner />} </a> </div> ); } }
<div class={style.percentInfo}> <svg
jparc_enge_func_factory.py
#!/usr/bin/env python #-------------------------------------------------------------- # This is a Enge Function Factory specific for the J-PARC. Some # Enge's function parameters are defined by the aperture and length, # and others are defined by the field distribution formula from Trace3D # documentation. #-------------------------------------------------------------- import math import sys import os from overlapping_quad_fields_lib import PMQ_Trace3D_Function from overlapping_quad_fields_lib import EngeFunction from overlapping_quad_fields_lib import SimpleQuadFieldFunc def
(quad): """ It generates the Enge's Function for J-PARC quads. """ name = quad.getName() length_param = quad.getLength() #---- general PMQ function described in Trace3D documentation if(quad.hasParam("radIn") and quad.hasParam("radOut")): radIn = quad.getParam("radIn") radOut = quad.getParam("radOut") cutoff_level = 0.01 if(name == "LI_DTL1:DTQ01"): cutoff_level = 0.02 func = PMQ_Trace3D_Function(length_param,radIn,radOut,cutoff_level) return func #----- general Enge's Function if(quad.hasParam("aperture")): acceptance_diameter_param = quad.getParam("aperture") cutoff_level = 0.01 func = EngeFunction(length_param,acceptance_diameter_param,cutoff_level) return func else: msg = "SNS_EngeFunctionFactory Python function. " msg += os.linesep msg += "Cannot create the EngeFunction for the quad!" msg += os.linesep msg = msg + "quad name = " + quad.getName() msg = msg + os.linesep msg = msg + "It does not have the aperture parameter!" msg = msg + os.linesep orbitFinalize(msg) return None
JPARC_EngeFunctionFactory
expectation.go
package app import ( "fmt" "strings" "github.com/argoproj/gitops-engine/pkg/utils/health" . "github.com/argoproj/gitops-engine/pkg/utils/kube/sync/common" v1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" . "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/test/e2e/fixture" ) type state = string const ( failed = "failed" pending = "pending" succeeded = "succeeded" ) type Expectation func(c *Consequences) (state state, message string) func OperationPhaseIs(expected OperationPhase) Expectation { return func(c *Consequences) (state, string) { operationState := c.app().Status.OperationState actual := OperationRunning if operationState != nil { actual = operationState.Phase } return simple(actual == expected, fmt.Sprintf("operation phase should be %s, is %s", expected, actual)) } } func simple(success bool, message string) (state, string) { if success { return succeeded, message } else { return pending, message } } func SyncStatusIs(expected SyncStatusCode) Expectation { return func(c *Consequences) (state, string) { actual := c.app().Status.Sync.Status return simple(actual == expected, fmt.Sprintf("sync status to be %s, is %s", expected, actual)) } } func Condition(conditionType ApplicationConditionType, conditionMessage string) Expectation { return func(c *Consequences) (state, string) { got := c.app().Status.Conditions message := fmt.Sprintf("condition {%s %s} in %v", conditionType, conditionMessage, got) for _, condition := range got { if conditionType == condition.Type && strings.Contains(condition.Message, conditionMessage) { return succeeded, message } } return pending, message } } func NoConditions() Expectation { return func(c *Consequences) (state, string) { message := "no conditions" if len(c.app().Status.Conditions) == 0 { return succeeded, message } return pending, message } } func HealthIs(expected health.HealthStatusCode) Expectation { return func(c *Consequences) (state, string) { actual := c.app().Status.Health.Status return simple(actual == expected, fmt.Sprintf("health to should %s, is %s", expected, actual)) } } func ResourceSyncStatusIs(kind, resource string, expected SyncStatusCode) Expectation { return func(c *Consequences) (state, string) { actual := c.resource(kind, resource).Status return simple(actual == expected, fmt.Sprintf("resource '%s/%s' sync status should be %s, is %s", kind, resource, expected, actual)) } } func ResourceHealthIs(kind, resource string, expected health.HealthStatusCode) Expectation { return func(c *Consequences) (state, string) { actual := c.resource(kind, resource).Health.Status return simple(actual == expected, fmt.Sprintf("resource '%s/%s' health should be %s, is %s", kind, resource, expected, actual)) } } func ResourceResultNumbering(num int) Expectation { return func(c *Consequences) (state, string) { actualNum := len(c.app().Status.OperationState.SyncResult.Resources) if actualNum < num { return pending, fmt.Sprintf("not enough results yet, want %d, got %d", num, actualNum) } else if actualNum == num { return succeeded, fmt.Sprintf("right number of results, want %d, got %d", num, actualNum) } else { return failed, fmt.Sprintf("too many results, want %d, got %d", num, actualNum) } } } func ResourceResultIs(result ResourceResult) Expectation { return func(c *Consequences) (state, string) { results := c.app().Status.OperationState.SyncResult.Resources for _, res := range results { if *res == result { return succeeded, fmt.Sprintf("found resource result %v", result) } } return pending, fmt.Sprintf("waiting for resource result %v in %v", result, results) } } func DoesNotExist() Expectation { return func(c *Consequences) (state, string) { _, err := c.get() if err != nil { if apierr.IsNotFound(err) { return succeeded, "app does not exist" } return failed, err.Error() } return pending, "app should not exist" } } func
(predicate func(p v1.Pod) bool) Expectation { return func(c *Consequences) (state, string) { pods, err := pods() if err != nil { return failed, err.Error() } for _, pod := range pods.Items { if predicate(pod) { return succeeded, fmt.Sprintf("pod predicate matched pod named '%s'", pod.GetName()) } } return pending, fmt.Sprintf("pod predicate does not match pods") } } func NotPod(predicate func(p v1.Pod) bool) Expectation { return func(c *Consequences) (state, string) { pods, err := pods() if err != nil { return failed, err.Error() } for _, pod := range pods.Items { if predicate(pod) { return pending, fmt.Sprintf("pod predicate matched pod named '%s'", pod.GetName()) } } return succeeded, fmt.Sprintf("pod predicate did not match any pod") } } func pods() (*v1.PodList, error) { fixture.KubeClientset.CoreV1() pods, err := fixture.KubeClientset.CoreV1().Pods(fixture.DeploymentNamespace()).List(metav1.ListOptions{}) return pods, err } func Event(reason string, message string) Expectation { return func(c *Consequences) (state, string) { list, err := fixture.KubeClientset.CoreV1().Events(fixture.ArgoCDNamespace).List(metav1.ListOptions{ FieldSelector: fields.SelectorFromSet(map[string]string{ "involvedObject.name": c.context.name, "involvedObject.namespace": fixture.ArgoCDNamespace, }).String(), }) if err != nil { return failed, err.Error() } for i := range list.Items { event := list.Items[i] if event.Reason == reason && strings.Contains(event.Message, message) { return succeeded, fmt.Sprintf("found event with reason=%s; message=%s", reason, message) } } return failed, fmt.Sprintf("unable to find event with reason=%s; message=%s", reason, message) } } // asserts that the last command was successful func Success(message string) Expectation { return func(c *Consequences) (state, string) { if c.actions.lastError != nil { return failed, "error" } if !strings.Contains(c.actions.lastOutput, message) { return failed, fmt.Sprintf("output did not contain '%s'", message) } return succeeded, fmt.Sprintf("no error and output contained '%s'", message) } } // asserts that the last command was an error with substring match func Error(message, err string) Expectation { return func(c *Consequences) (state, string) { if c.actions.lastError == nil { return failed, "no error" } if !strings.Contains(c.actions.lastOutput, message) { return failed, fmt.Sprintf("output does not contain '%s'", message) } if !strings.Contains(c.actions.lastError.Error(), err) { return failed, fmt.Sprintf("error does not contain '%s'", message) } return succeeded, fmt.Sprintf("error '%s'", message) } }
Pod
PostListing.js
import React, { Component } from 'react' import { Link } from 'gatsby'; import matter from 'gray-matter'; export default class
extends Component { render() { const {post} = this.props; return ( <article> <h3><Link to={post.fields.slug}>{post.frontmatter.title}</Link></h3> <span>{post.frontmatter.date}</span> <p>{post.excerpt}</p> </article> ) } }
PostListing
rollup-tree.js
'use strict'; const broccoliRollUp = require('broccoli-rollup'); const Merge = require('broccoli-merge-trees'); const babel = require('@rollup/plugin-babel')['default']; const stew = require('broccoli-stew'); const path = require('path'); const replace = require('broccoli-string-replace'); const relative = require('require-relative'); const Funnel = require('broccoli-funnel'); const UnwatchedDir = require('broccoli-source').UnwatchedDir; const resolve = require('resolve'); const es5Prefix = 'let _outputModule = (function() { let exports = {}; let module = { exports: exports };'; const es5Postfix = 'return module.exports; })(); exports["default"] = _outputModule'; function classifyDependencies(modules) { const namespacedDependencies = []; const nonNamespacedDependencies = []; for (let i = 0; i < modules.length; i++) { const moduleName = modules[i]; let namespaced = true; let rollupEntry; let name; if (typeof moduleName === 'string') { name = moduleName; } else { name = moduleName.name; namespaced = moduleName.namespaced; rollupEntry = moduleName.rollupEntry; } const result = { // for scoped package, we will import '@<scoped>/<package>.js' instead of '<package>.js' fileName: (name.startsWith('@') ? name : name.split('/').pop()) + '.js', moduleName: name, rollupEntry: rollupEntry }; if (namespaced) { namespacedDependencies.push(result); } else { nonNamespacedDependencies.push(result); } } return { namespacedDependencies, nonNamespacedDependencies } } function
() { let current = this; let app; // Keep iterating upward until we don't have a grandparent. // Has to do this grandparent check because at some point we hit the project. do { app = current.app || app; } while (current.parent.parent && (current = current.parent)); let isTopLevelAddon = false; for (let i = 0; i < this.project.addons.length; i++) { const addon = this.project.addons[i]; isTopLevelAddon = isTopLevelAddon || addon.name === this.name; } // If this addon isn't included directly by the app, all bets are off // If the addon is included directly in the app, only import dependencies // if this instance is the top level instance return !isTopLevelAddon || !this.parent.parent; } function _findEntry(pkg, rollupEntry) { let esNext = true; let main = rollupEntry || pkg['jsnext:main'] || pkg['module']; if (!main) { main = pkg.main || 'index.js'; esNext = false; } return { main, esNext }; } function rollup(runtimeDependencies, transpile, addonRoot) { transpile = !!transpile; const trees = runtimeDependencies.map(function(dep) { const packagePath = resolve.sync(path.join(dep.moduleName , 'package.json'), { basedir: addonRoot }); const pkg = relative(packagePath); // If rollupEntry is explicitly specified, treat as es module const { main, esNext } = _findEntry(pkg, dep.rollupEntry); const babelrcPath = path.dirname(main) + '/.babelrc'; // Hacky way of getting the npm dependency folder const depFolder = new UnwatchedDir(path.dirname(packagePath)); const depFolderClean = new Funnel(depFolder, { exclude: ['node_modules', '.git'] }); // Add the babelrc file const babelRc = new Funnel(new UnwatchedDir(__dirname + '/../'), { include: ['rollup.babelrc'], getDestinationPath: function(relativePath) { if (relativePath === 'rollup.babelrc') { return babelrcPath; } return relativePath; } }); let preset = path.dirname(relative.resolve('@babel/preset-env/package.json', __dirname + '/../')); // Windows path adjustment if (process.platform === 'win32') { preset = preset.replace(/\\/g, '\\\\'); } // Add an absolute path to the es2015 preset. Needed since host app // won't have the preset const mappedBabelRc = replace(babelRc, { files: [ babelrcPath ], pattern: { match: /es2015/g, replacement: preset } }); let target; if (esNext) { const amd = transpile ? { id: dep.moduleName } : null; target = new broccoliRollUp(new Merge([ depFolderClean, mappedBabelRc ], { annotation: '[ember-rollup] Merge in BabelRC file' }), { rollup: { input: main, output: { file: dep.fileName, format: transpile ? 'amd' : 'es', name: dep.moduleName, amd }, plugins: [ babel() ] } }); } else { // If not ES6, bail out const wrapped = stew.map(depFolder, '*.js', function(content) { return [es5Prefix, content, es5Postfix].join(''); }); target = new Funnel(wrapped, { include: ['**/*.js'], getDestinationPath: function(relativePath) { if (relativePath === main) { return dep.fileName; } return relativePath; } }); } const moduleDir = path.dirname(dep.moduleName); if (moduleDir === '.' || moduleDir.startsWith('@')) { return target; } else { return new Funnel(target, { destDir: moduleDir }); } }); const runtimeNpmTree = new Merge(trees.filter(Boolean), { annotation: '[ember-rollup] Merge runtime module trees' }); return runtimeNpmTree; } function rollupAllTheThings(root, runtimeDependencies, superFunc, transpile, superAnnotation) { if (shouldAddRuntimeDependencies.call(this)) { const annotation = `[ember-rollup] Merge runtime dependency tree and ${superAnnotation || ' unknown treeFor hook'}`; const runtimeNpmTree = rollup(runtimeDependencies, transpile, this.root); return superFunc.call(this, new Merge([runtimeNpmTree, root].filter(Boolean), { annotation })); } else { return superFunc.call(this, root); } } module.exports = { rollup, classifyDependencies, rollupAllTheThings, _findEntry }
shouldAddRuntimeDependencies
__init__.py
__all__ = ["get_fl", "disp", "select"]
convert.rs
use js_sys::{Array, ArrayBuffer, Object, Promise, Reflect, SyntaxError, Uint8Array}; use wasm_bindgen::{closure::Closure, prelude::*, JsCast}; use rustpython_compiler::error::{CompileError, CompileErrorType}; use rustpython_parser::error::ParseErrorType; use rustpython_vm::byteslike::PyBytesLike; use rustpython_vm::exceptions::PyBaseExceptionRef; use rustpython_vm::function::PyFuncArgs; use rustpython_vm::obj::objtype; use rustpython_vm::pyobject::{ItemProtocol, PyObjectRef, PyResult, PyValue, TryFromObject}; use rustpython_vm::VirtualMachine; use rustpython_vm::{exceptions, py_serde}; use crate::browser_module; use crate::vm_class::{stored_vm_from_wasm, WASMVirtualMachine}; #[wasm_bindgen(inline_js = r" export class PyError extends Error { constructor(info) { const msg = info.args[0]; if (typeof msg === 'string') super(msg); else super(); this.info = info; } get name() { return this.info.exc_type; } get traceback() { return this.info.traceback; } toString() { return this.info.rendered; } } ")] extern "C" { pub type PyError; #[wasm_bindgen(constructor)] fn new(info: JsValue) -> PyError; } pub fn py_err_to_js_err(vm: &VirtualMachine, py_err: &PyBaseExceptionRef) -> JsValue
pub fn js_py_typeerror(vm: &VirtualMachine, js_err: JsValue) -> PyBaseExceptionRef { let msg = js_err.unchecked_into::<js_sys::Error>().to_string(); vm.new_type_error(msg.into()) } pub fn js_err_to_py_err(vm: &VirtualMachine, js_err: &JsValue) -> PyBaseExceptionRef { match js_err.dyn_ref::<js_sys::Error>() { Some(err) => { let exc_type = match String::from(err.name()).as_str() { "TypeError" => &vm.ctx.exceptions.type_error, "ReferenceError" => &vm.ctx.exceptions.name_error, "SyntaxError" => &vm.ctx.exceptions.syntax_error, _ => &vm.ctx.exceptions.exception_type, } .clone(); vm.new_exception_msg(exc_type, err.message().into()) } None => vm.new_exception_msg( vm.ctx.exceptions.exception_type.clone(), format!("{:?}", js_err), ), } } pub fn py_to_js(vm: &VirtualMachine, py_obj: PyObjectRef) -> JsValue { if let Some(ref wasm_id) = vm.wasm_id { if objtype::isinstance(&py_obj, &vm.ctx.types.function_type) { let wasm_vm = WASMVirtualMachine { id: wasm_id.clone(), }; let weak_py_obj = wasm_vm.push_held_rc(py_obj).unwrap(); let closure = move |args: Option<Array>, kwargs: Option<Object>| -> Result<JsValue, JsValue> { let py_obj = match wasm_vm.assert_valid() { Ok(_) => weak_py_obj .upgrade() .expect("weak_py_obj to be valid if VM is valid"), Err(err) => { return Err(err); } }; let vm = &stored_vm_from_wasm(&wasm_vm).vm; let mut py_func_args = PyFuncArgs::default(); if let Some(ref args) = args { for arg in args.values() { py_func_args.args.push(js_to_py(vm, arg?)); } } if let Some(ref kwargs) = kwargs { for pair in object_entries(kwargs) { let (key, val) = pair?; py_func_args .kwargs .insert(js_sys::JsString::from(key).into(), js_to_py(vm, val)); } } let result = vm.invoke(&py_obj, py_func_args); pyresult_to_jsresult(vm, result) }; let closure = Closure::wrap(Box::new(closure) as Box<dyn FnMut(Option<Array>, Option<Object>) -> Result<JsValue, JsValue>>); let func = closure.as_ref().clone(); // stores pretty much nothing, it's fine to leak this because if it gets dropped // the error message is worse closure.forget(); return func; } } // the browser module might not be injected if vm.try_class("browser", "Promise").is_ok() { if let Some(py_prom) = py_obj.payload::<browser_module::PyPromise>() { return py_prom.value().into(); } } if let Ok(bytes) = PyBytesLike::try_from_object(vm, py_obj.clone()) { bytes.with_ref(|bytes| unsafe { // `Uint8Array::view` is an `unsafe fn` because it provides // a direct view into the WASM linear memory; if you were to allocate // something with Rust that view would probably become invalid. It's safe // because we then copy the array using `Uint8Array::slice`. let view = Uint8Array::view(bytes); view.slice(0, bytes.len() as u32).into() }) } else { py_serde::serialize(vm, &py_obj, &serde_wasm_bindgen::Serializer::new()) .unwrap_or(JsValue::UNDEFINED) } } pub fn object_entries(obj: &Object) -> impl Iterator<Item = Result<(JsValue, JsValue), JsValue>> { Object::entries(obj).values().into_iter().map(|pair| { pair.map(|pair| { let key = Reflect::get(&pair, &"0".into()).unwrap(); let val = Reflect::get(&pair, &"1".into()).unwrap(); (key, val) }) }) } pub fn pyresult_to_jsresult(vm: &VirtualMachine, result: PyResult) -> Result<JsValue, JsValue> { result .map(|value| py_to_js(vm, value)) .map_err(|err| py_err_to_js_err(vm, &err)) } pub fn js_to_py(vm: &VirtualMachine, js_val: JsValue) -> PyObjectRef { if js_val.is_object() { if let Some(promise) = js_val.dyn_ref::<Promise>() { // the browser module might not be injected if vm.try_class("browser", "Promise").is_ok() { return browser_module::PyPromise::new(promise.clone()) .into_ref(vm) .into_object(); } } if Array::is_array(&js_val) { let js_arr: Array = js_val.into(); let elems = js_arr .values() .into_iter() .map(|val| js_to_py(vm, val.expect("Iteration over array failed"))) .collect(); vm.ctx.new_list(elems) } else if ArrayBuffer::is_view(&js_val) || js_val.is_instance_of::<ArrayBuffer>() { // unchecked_ref because if it's not an ArrayByffer it could either be a TypedArray // or a DataView, but they all have a `buffer` property let u8_array = js_sys::Uint8Array::new( &js_val .dyn_ref::<ArrayBuffer>() .cloned() .unwrap_or_else(|| js_val.unchecked_ref::<Uint8Array>().buffer()), ); let mut vec = vec![0; u8_array.length() as usize]; u8_array.copy_to(&mut vec); vm.ctx.new_bytes(vec) } else { let dict = vm.ctx.new_dict(); for pair in object_entries(&Object::from(js_val)) { let (key, val) = pair.expect("iteration over object to not fail"); let py_val = js_to_py(vm, val); dict.set_item( String::from(js_sys::JsString::from(key)).as_str(), py_val, vm, ) .unwrap(); } dict.into_object() } } else if js_val.is_function() { let func = js_sys::Function::from(js_val); vm.ctx .new_method(move |vm: &VirtualMachine, args: PyFuncArgs| -> PyResult { let this = Object::new(); for (k, v) in args.kwargs { Reflect::set(&this, &k.into(), &py_to_js(vm, v)) .expect("property to be settable"); } let js_args = Array::new(); for v in args.args { js_args.push(&py_to_js(vm, v)); } func.apply(&this, &js_args) .map(|val| js_to_py(vm, val)) .map_err(|err| js_err_to_py_err(vm, &err)) }) } else if let Some(err) = js_val.dyn_ref::<js_sys::Error>() { js_err_to_py_err(vm, err).into_object() } else if js_val.is_undefined() { // Because `JSON.stringify(undefined)` returns undefined vm.get_none() } else { py_serde::deserialize(vm, serde_wasm_bindgen::Deserializer::from(js_val)) .unwrap_or_else(|_| vm.get_none()) } } pub fn syntax_err(err: CompileError) -> SyntaxError { let js_err = SyntaxError::new(&format!("Error parsing Python code: {}", err)); let _ = Reflect::set(&js_err, &"row".into(), &(err.location.row() as u32).into()); let _ = Reflect::set( &js_err, &"col".into(), &(err.location.column() as u32).into(), ); let can_continue = match &err.error { CompileErrorType::Parse(ParseErrorType::EOF) => true, _ => false, }; let _ = Reflect::set(&js_err, &"canContinue".into(), &can_continue.into()); js_err } pub trait PyResultExt<T> { fn to_js(self, vm: &VirtualMachine) -> Result<T, JsValue>; } impl<T> PyResultExt<T> for PyResult<T> { fn to_js(self, vm: &VirtualMachine) -> Result<T, JsValue> { self.map_err(|err| py_err_to_js_err(vm, &err)) } }
{ let res = serde_wasm_bindgen::to_value(&exceptions::SerializeException::new(vm, py_err)); match res { Ok(err_info) => PyError::new(err_info).into(), Err(e) => e.into(), } }
main.py
''' Main functionality of ``image_slicer``. ''' import os import time import optparse from math import sqrt, ceil, floor from PIL import Image from helpers import get_basename class Tile(object): """Represents a single tile.""" def __init__(self, image, number, position, coords, filename=None): self.image = image self.number = number self.position = position self.coords = coords self.filename = filename @property def row(self): return self.position[0] @property def column(self): return self.position[1] @property def basename(self): """Strip path and extension. Return base filename.""" return get_basename(self.filename) def generate_filename(self, directory=os.getcwd(), prefix='tile', format='png', path=True): """Construct and return a filename for this tile.""" filename = prefix + '_{col:02d}_{row:02d}.{ext}'.format( col=self.column, row=self.row, ext=format) if not path: return filename return os.path.join(directory, filename) def save(self, filename=None, format='png'):
def __repr__(self): """Show tile number, and if saved to disk, filename.""" if self.filename: return '<Tile #{} - {}>'.format(self.number, os.path.basename(self.filename)) return '<Tile #{}>'.format(self.number) def calc_columns_rows(n): """ Calculate the number of columns and rows required to divide an image into ``n`` parts. Return a tuple of integers in the format (num_columns, num_rows) """ num_columns = int(ceil(sqrt(n))) num_rows = int(ceil(n / float(num_columns))) return (num_columns, num_rows) # return (5, 7) def get_combined_size(tiles): """Calculate combined size of tiles.""" # TODO: Refactor calculating layout to avoid repetition. columns, rows = calc_columns_rows(len(tiles)) tile_size = tiles[0].image.size return (tile_size[0] * columns, tile_size[1] * rows) def join(tiles): """ @param ``tiles`` - Tuple of ``Image`` instances. @return ``Image`` instance. """ im = Image.new('RGB', get_combined_size(tiles), None) columns, rows = calc_columns_rows(len(tiles)) for tile in tiles: im.paste(tile.image, tile.coords) return im def validate_image(image, number_tiles): """Basic sanity checks prior to performing a split.""" TILE_LIMIT = 99 * 99 try: number_tiles = int(number_tiles) except: raise ValueError('number_tiles could not be cast to integer.') if number_tiles > TILE_LIMIT or number_tiles < 2: raise ValueError('Number of tiles must be between 2 and {} (you \ asked for {}).'.format(TILE_LIMIT, number_tiles)) def save_tiles(tiles, prefix='', directory=os.getcwd(), format='png'): """ Write image files to disk. Create specified folder(s) if they don't exist. Return list of :class:`Tile` instance. Args: tiles (list): List, tuple or set of :class:`Tile` objects to save. prefix (str): Filename prefix of saved tiles. Kwargs: directory (str): Directory to save tiles. Created if non-existant. Returns: Tuple of :class:`Tile` instances. """ # Causes problems in CLI script. # if not os.path.exists(directory): # os.makedirs(directory) for tile in tiles: tile.save(filename=tile.generate_filename(prefix=prefix, directory=directory, format=format)) return tuple(tiles) def _do_slice(filename, output, **kwargs): """ Split an image into a specified number of tiles. Args: filename (str): The filename of the image to split. number_tiles (int): The number of tiles required. Kwargs: save (bool): Whether or not to save tiles to disk. Returns: Tuple of :class:`Tile` instances. """ im = Image.open(filename) # validate_image(im, number_tiles) im_w, im_h = im.size # columns, rows = calc_columns_rows(number_tiles) columns = int(kwargs.get('columns', 5)) rows = int(kwargs.get('rows', 7)) number_tiles = (columns * rows) - 1 extras = (columns * rows) - number_tiles tile_w, tile_h = int(floor(im_w / columns)), int(floor(im_h / rows)) tiles = [] number = 1 for pos_y in range(0, im_h - rows, tile_h): # -rows for rounding error. for pos_x in range(0, im_w - columns, tile_w): # as above. area = (pos_x, pos_y, pos_x + tile_w, pos_y + tile_h) image = im.crop(area) position = (int(floor(pos_x / tile_w)) + 1, int(floor(pos_y / tile_h)) + 1) coords = (pos_x, pos_y) tile = Tile(image, number, position, coords) tiles.append(tile) number += 1 if not kwargs['dry_run']: save_tiles(tiles, prefix=get_basename(filename), directory=output) return tuple(tiles) def main(path, **kwargs): if os.path.isdir(path): fnames = [os.path.join(path, f) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and f.endswith(".jpg")] output = os.path.join(os.path.abspath(path), 'output') else: fnames = [path] output = os.path.join(os.path.dirname(os.path.abspath(path)), 'output') if not os.path.exists(output): os.makedirs(output) for filename in fnames: tiles = _do_slice(filename, output, **kwargs) print "In %s: saved %d tiles for file %s" % (output, len(tiles), filename) if __name__ == '__main__': parser = optparse.OptionParser(usage="usage: python %prog [OPTIONS] filename") parser.add_option("-c", "--columns", action="store", dest="columns", help="Number of columns") parser.add_option("-r", "--rows", action="store", dest="rows", default=0, help="Number of rows") parser.add_option('-d', "--dry", action='store_true', dest='dry_run', default=False, help='Dry run (do not actually perform anything, only report).') opts, args = parser.parse_args() start_time = time.time() try: main(args[0], **vars(opts)) except IndexError: print "You must specify source filename!" exit() print "Done, took %d seconds" % int(time.time() - start_time)
if not filename: filename = self.generate_filename(format=format) self.image.save(filename, format) self.filename = filename
module$node_modules$$ethersproject$abi$lib$coders$address.js
shadow$provide.module$node_modules$$ethersproject$abi$lib$coders$address=function(global,require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d$jscomp$0,b$jscomp$0){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)b.hasOwnProperty(p)&&(d[p]=b[p])};return extendStatics(d$jscomp$0,b$jscomp$0)};return function(d,b){function __(){this.constructor=d}extendStatics(d,b);d.prototype= null===b?Object.create(b):(__.prototype=b.prototype,new __)}}();Object.defineProperty(exports,"__esModule",{value:!0});var address_1=require("module$node_modules$$ethersproject$address$lib$index"),bytes_1=require("module$node_modules$$ethersproject$bytes$lib$index");global=function(_super){function AddressCoder(localName){return _super.call(this,"address","address",localName,!1)||this}__extends(AddressCoder,_super);AddressCoder.prototype.encode=function(writer,value){try{address_1.getAddress(value)}catch(error){this._throwError(error.message,
value)}return writer.writeValue(value)};AddressCoder.prototype.decode=function(reader){return address_1.getAddress(bytes_1.hexZeroPad(reader.readValue().toHexString(),20))};return AddressCoder}(require("module$node_modules$$ethersproject$abi$lib$coders$abstract_coder").Coder);exports.AddressCoder=global} //# sourceMappingURL=module$node_modules$$ethersproject$abi$lib$coders$address.js.map
_value.py
import _plotly_utils.basevalidators class ValueValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="value", parent_name="scatterpolar.marker.colorbar.tickformatstop", **kwargs ): super(ValueValidator, self).__init__(
plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), **kwargs )
ActivityLogCard.tsx
import { Card } from '@material-ui/core'; import dayjs from 'dayjs'; // interfaces import CardContent from '@material-ui/core/CardContent'; import { createStyles, makeStyles } from '@material-ui/styles'; import { Theme } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import clsx from 'clsx'; import { ActivityLogCardProps } from './interfaces';
createStyles({ root: { margin: 4, }, details: { display: 'flex', flexDirection: 'row', }, content: { flex: '1 0 auto', flexDirection: 'column', width: '100%', paddingBottom: '10px !important', paddingTop: 10, paddingLeft: 10, paddingRight: 10, }, mainCard: { [theme.breakpoints.down('sm')]: { paddingTop: '0 !important', }, }, info: { color: '#0e5827', backgroundColor: '#e6f4ea', }, error: { color: '#821721', backgroundColor: 'rgba(210, 43, 53, 0.12)', }, }), ); const ActivityLogCard = ({ log, date, type, }: ActivityLogCardProps): JSX.Element => { const classes = useStyles(); return ( <Card variant="outlined" className={clsx( classes.root, type === 'info' ? classes.info : classes.error, )} > <CardContent className={classes.content}> <Typography variant="body2" data-testid="header"> {log} </Typography> <Typography variant="caption" style={{ fontWeight: 600 }} data-testid="details" > {`${dayjs(date).format('HH:mm:ss')}`} </Typography> </CardContent> </Card> ); }; export default ActivityLogCard;
const useStyles = makeStyles((theme: Theme) =>
buffer.rs
use crate::memory::find_memory_type_index; use crate::vk_engine::VulkanEngine; use ash::util::Align; use ash::vk::{Buffer, BufferCopy, DeviceMemory}; use ash::{vk, Device}; use std::ffi::c_void; use std::marker::PhantomData; use std::mem::align_of; use tracing::{event, Level}; /// Typed Vulkan buffer. pub struct VulkanBuffer<T> { pub buffer: Buffer, pub memory_flags: vk::MemoryPropertyFlags, pub device_size: u64, pub length: u64, phantom: PhantomData<T>, } impl<T> VulkanBuffer<T> { /// Copy data from one Vulkan buffer to another. Requires correct usage flags. pub unsafe fn copy( &mut self, vk_engine: &VulkanEngine, command_buffer: vk::CommandBuffer, dst: &mut Self, src_offset: u64, dst_offset: u64, length: u64, ) -> Result<(), ()> where T: Copy, { if self.length < length || dst.length < length { Err(()) } else { vk_engine.device.cmd_copy_buffer( command_buffer, self.buffer, dst.buffer, &[BufferCopy::builder() .src_offset(src_offset) .dst_offset(dst_offset) .size(length * std::mem::size_of::<T>() as u64) .build()], ); Ok(()) } } /// Creates a new `VulkanBuffer`. pub unsafe fn new( vk_engine: &VulkanEngine, length: u64, usage: vk::BufferUsageFlags, sharing_mode: vk::SharingMode, memory_property_flags: vk::MemoryPropertyFlags, ) -> Self { let size = length * std::mem::size_of::<T>() as u64; let buffer_info = vk::BufferCreateInfo { size, usage, sharing_mode, ..Default::default() }; let buffer = vk_engine.device.create_buffer(&buffer_info, None).unwrap(); Self { buffer, device_size: size, length, memory_flags: memory_property_flags, phantom: PhantomData::default(), } } /// Get the memory requirements for `self`. pub unsafe fn get_memory_requirements(&self, device: &Device) -> vk::MemoryRequirements { device.get_buffer_memory_requirements(self.buffer) } /// Bind memory to the Vulkan buffer held by `self`. pub unsafe fn bind_memory( &mut self, engine: &VulkanEngine, buffer_memory: DeviceMemory, offset: vk::DeviceSize, ) { engine .device .bind_buffer_memory(self.buffer, buffer_memory, offset) .expect("Binding memory buffer failed"); } /// Frees the buffer resource held by `self`. pub unsafe fn destroy(&mut self, device: &Device) { device.destroy_buffer(self.buffer, None); } } /// A Vulkan buffer with a dedicated memory allocation. pub struct VulkanBufferWithDedicatedAllocation<T> { pub buffer: VulkanBuffer<T>, pub memory: DeviceMemory, } impl<T> VulkanBufferWithDedicatedAllocation<T> { /// Allocates a new buffer. pub unsafe fn allocate( vk_engine: &VulkanEngine, length: u64, usage: vk::BufferUsageFlags, sharing_mode: vk::SharingMode, memory_property_flags: vk::MemoryPropertyFlags, ) -> Self { let mut buffer = VulkanBuffer::new( vk_engine, length, usage, sharing_mode, memory_property_flags, ); let mem_req = buffer.get_memory_requirements(&vk_engine.device); let memory_type_index = find_memory_type_index( &mem_req, &vk_engine.device_memory_properties, memory_property_flags, ); event!( Level::DEBUG, "Selected memory type index for buffer: {}", memory_type_index ); let memory = vk_engine.allocate_memory(mem_req, memory_type_index); buffer.bind_memory(&vk_engine, memory, 0); Self { memory, buffer } } /// Frees the buffer and memory resources held by `self`. pub unsafe fn destroy(&mut self, device: &Device) { device.free_memory(self.memory, None); device.destroy_buffer(self.buffer.buffer, None); } } /// A wrapper for a staging buffer. Holds a `VulkanBuffer<T>` and a pointer to the mapped memory. pub struct
<T: Copy> { pub buffer: VulkanBuffer<T>, pub buffer_ptr: *mut c_void, } impl<T: Copy> StagingBuffer<T> { /// Write the data to the staging buffer. pub unsafe fn write(&mut self, data: &[T]) { let mut slice = Align::new( self.buffer_ptr, align_of::<T>() as vk::DeviceSize, (data.len() * std::mem::size_of::<T>()) as _, ); slice.copy_from_slice(data); } /// Frees the buffer resource held by `self`. pub unsafe fn destroy(&mut self, device: &Device) { self.buffer.destroy(device); } /// Creates a new `StagingBuffer<T>`. Maps the buffer memory for writing; it is never unmapped. pub unsafe fn new( vk_engine: &VulkanEngine, buffer: VulkanBuffer<T>, memory: DeviceMemory, offset: vk::DeviceSize, ) -> Self { let buffer_ptr = vk_engine .device .map_memory( memory, offset, buffer.device_size, vk::MemoryMapFlags::empty(), ) .unwrap(); Self { buffer, buffer_ptr } } } /// A staging buffer with a dedicated allocation. pub struct StagingBufferWithDedicatedAllocation<T: Copy> { pub buffer: StagingBuffer<T>, pub memory: DeviceMemory, } impl<T: Copy> StagingBufferWithDedicatedAllocation<T> { /// Frees the buffer and memory resources held by `self`. pub unsafe fn destroy(&mut self, device: &Device) { device.free_memory(self.memory, None); device.destroy_buffer(self.buffer.buffer.buffer, None); } /// Allocates a new staging buffer. pub unsafe fn allocate( vk_engine: &VulkanEngine, length: u64, usage: vk::BufferUsageFlags, sharing_mode: vk::SharingMode, memory_property_flags: vk::MemoryPropertyFlags, ) -> Self { let dedicated_allocated_buffer = VulkanBufferWithDedicatedAllocation::allocate( vk_engine, length, usage, sharing_mode, memory_property_flags, ); Self { memory: dedicated_allocated_buffer.memory, buffer: StagingBuffer::new( vk_engine, dedicated_allocated_buffer.buffer, dedicated_allocated_buffer.memory, 0, ), } } }
StagingBuffer
tls_file_database.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use crate::TlsDatabase; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use std::ptr; glib::wrapper! { pub struct TlsFileDatabase(Interface<ffi::GTlsFileDatabase, ffi::GTlsFileDatabaseInterface>) @requires TlsDatabase; match fn { type_ => || ffi::g_tls_file_database_get_type(), } } impl TlsFileDatabase { #[doc(alias = "g_tls_file_database_new")] pub fn new<P: AsRef<std::path::Path>>(anchors: P) -> Result<TlsFileDatabase, glib::Error> { unsafe { let mut error = ptr::null_mut(); let ret = ffi::g_tls_file_database_new(anchors.as_ref().to_glib_none().0, &mut error); if error.is_null() { Ok(from_glib_full(ret)) } else { Err(from_glib_full(error)) } } } } pub const NONE_TLS_FILE_DATABASE: Option<&TlsFileDatabase> = None; pub trait TlsFileDatabaseExt: 'static { #[doc(alias = "get_property_anchors")] fn anchors(&self) -> Option<glib::GString>; #[doc(alias = "set_property_anchors")] fn set_anchors(&self, anchors: Option<&str>); fn connect_property_anchors_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<TlsFileDatabase>> TlsFileDatabaseExt for O { fn anchors(&self) -> Option<glib::GString> { unsafe { let mut value = glib::Value::from_type(<glib::GString as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property( self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"anchors\0".as_ptr() as *const _, value.to_glib_none_mut().0, ); value .get() .expect("Return Value for property `anchors` getter") } } fn set_anchors(&self, anchors: Option<&str>) { unsafe { glib::gobject_ffi::g_object_set_property( self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"anchors\0".as_ptr() as *const _, glib::Value::from(anchors).to_glib_none().0, ); } } fn connect_property_anchors_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_anchors_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::GTlsFileDatabase, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<TlsFileDatabase>, { let f: &F = &*(f as *const F); f(&TlsFileDatabase::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::anchors\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_anchors_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } } impl fmt::Display for TlsFileDatabase { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("TlsFileDatabase") } }
fmt
AddExpensePage.test.js
import React from 'react'; import { shallow } from 'enzyme'; import { AddExpensePage } from '../../components/AddExpensePage'; import expenses from '../fixtures/expenses'; let addExpense, history, wrapper; beforeEach(() => { addExpense = jest.fn(); history = { push: jest.fn() }; wrapper = shallow(<AddExpensePage addExpense={addExpense} history={history} />); }); test('should render AddExpensePage correctly', () => {
// In order to trigger onSubmit, we must find the form within the wrapper // Then execute the prop obtained with the prop funciton. wrapper.find('ExpenseForm').prop('onSubmit')(expenses[1]) expect(history.push).toHaveBeenLastCalledWith('/'); expect(addExpense).toHaveBeenLastCalledWith(expenses[1]); });
expect(wrapper).toMatchSnapshot(); }); test('should handle onSubmit', () => {
dao_user_sql.go
package user import ( "github.com/btnguyen2k/henge" "github.com/btnguyen2k/prom" )
// Available since template-v0.2.0 func NewUserDaoSql(sqlc *prom.SqlConnect, tableName string, txModeOnWrite bool) UserDao { dao := &BaseUserDaoImpl{} dao.UniversalDao = henge.NewUniversalDaoSql( sqlc, tableName, txModeOnWrite, map[string]string{UserColMaskUid: UserFieldMaskId}) return dao }
// NewUserDaoSql is helper method to create SQL-implementation of UserDao //
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import colorful.fields import django.contrib.gis.db.models.fields from django.conf import settings import webmap.utils class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Layer', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(default='', help_text='Name of the layer', max_length=255, verbose_name='name')), ('slug', models.SlugField(unique=True, verbose_name='name in URL')), ('desc', models.TextField(help_text='Layer description.', null=True, verbose_name='description', blank=True)), ('order', models.IntegerField(default=0, verbose_name='order')), ('remark', models.TextField(help_text='Internal information about layer.', null=True, verbose_name='internal remark', blank=True)), ('enabled', models.BooleanField(default=True, help_text='True = the layer is enabled on map load', verbose_name='Enabled by defalut')), ], options={ 'ordering': ['order'], 'verbose_name': 'layer', 'verbose_name_plural': 'layers', }, bases=(models.Model,), ), migrations.CreateModel( name='BaseLayer', fields=[ ('layer_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='webmap.Layer', on_delete=models.CASCADE)), ('url', models.URLField(help_text='Base layer tiles url. e.g. ', null=True, verbose_name='URL', blank=True)), ], options={ 'verbose_name': 'base layer', 'verbose_name_plural': 'base layers', }, bases=('webmap.layer',), ), migrations.CreateModel( name='Legend', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=255, verbose_name='name')), ('slug', models.SlugField(unique=True, verbose_name='name in URL')), ('desc', models.TextField(null=True, verbose_name='description', blank=True)), ('image', models.ImageField(upload_to='ikony', storage=webmap.utils.SlugifyFileSystemStorage(), verbose_name='image')), ], options={ 'verbose_name': 'legend item', 'verbose_name_plural': 'legend items', }, bases=(models.Model,), ), migrations.CreateModel( name='License', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(help_text='License name', max_length=255, verbose_name='name')), ('desc', models.TextField(help_text='License description.', null=True, verbose_name='description', blank=True)), ], options={ 'verbose_name': 'license', 'verbose_name_plural': 'licenses', }, bases=(models.Model,), ), migrations.CreateModel( name='Marker', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(help_text='Name of the marker.', unique=True, max_length=255, verbose_name='name')), ('slug', models.SlugField(unique=True, null=True, verbose_name='name in URL')), ('desc', models.TextField(help_text='Detailed marker descrption.', null=True, verbose_name='description', blank=True)), ('remark', models.TextField(help_text='Internal information about layer.', null=True, verbose_name='internal remark', blank=True)), ('default_icon', models.ImageField(storage=webmap.utils.SlugifyFileSystemStorage(), upload_to='icons', null=True, verbose_name='default icon', blank=True)), ('menu_icon', models.ImageField(storage=webmap.utils.SlugifyFileSystemStorage(), upload_to='icons/marker/menu', null=True, verbose_name='menu icon', blank=True)), ('minzoom', models.PositiveIntegerField(default=1, help_text='Minimal zoom in which the POIs of this marker will be shown on the map.', verbose_name='Minimal zoom')), ('maxzoom', models.PositiveIntegerField(default=10, help_text='Maximal zoom in which the POIs of this marker will be shown on the map.', verbose_name='Maximal zoom')), ('line_width', models.FloatField(default=2, verbose_name='line width')), ('line_color', colorful.fields.RGBColorField(default='#ffc90e', verbose_name='line color')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), ('last_modification', models.DateTimeField(auto_now=True, verbose_name='last modification at')), ], options={ 'ordering': ['-layer__order', 'name'], 'verbose_name': 'marker', 'verbose_name_plural': 'markers', 'permissions': [('can_only_view', 'Can only view')], }, bases=(models.Model,), ), migrations.CreateModel( name='OverlayLayer', fields=[ ('layer_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='webmap.Layer', on_delete=models.CASCADE)), ], options={ 'verbose_name': 'overlay layer', 'verbose_name_plural': 'overlay layers', }, bases=('webmap.layer',), ), migrations.CreateModel( name='Photo', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(help_text='Photo name', max_length=255, verbose_name='name', blank=True)), ('desc', models.TextField(help_text='Photo description.', null=True, verbose_name='description', blank=True)), ('order', models.IntegerField(default=0, verbose_name='order')), ('photographer', models.CharField(help_text='Full name of the author of the photography', max_length=255, verbose_name='Photography author', blank=True)), ('photo', models.ImageField(help_text='Upload photo in full resolution.', upload_to='photo', storage=webmap.utils.SlugifyFileSystemStorage(), verbose_name='photo')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at', null=True)), ('last_modification', models.DateTimeField(auto_now=True, verbose_name='last modification at', null=True)), ('author', models.ForeignKey(related_name='photo_create', verbose_name='author', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ('license', models.ForeignKey(verbose_name='license', to='webmap.License', on_delete=models.CASCADE)), ], options={ 'ordering': ['order'], 'verbose_name': 'photo', 'verbose_name_plural': 'photographies', 'permissions': [('can_view_photo_list', 'Can view photo list')], }, bases=(models.Model,), ), migrations.CreateModel( name='Poi', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(help_text='Exact place name', max_length=255, verbose_name='name')), ('importance', models.SmallIntegerField(default=0, help_text='Minimal zoom modificator (use 20+ to show always).<br/>', verbose_name='importance')), ('geom', django.contrib.gis.db.models.fields.GeometryField(help_text='Add point: Select pencil with plus sign icon and place your point to the map.<br/>\n Add line: Select line icon and by clicking to map draw the line. Finish drawing with double click.<br/>\n Add area: Select area icon and by clicking to mapy draw the area. Finish drawing with double click.<br/>\n Object edition: Select the first icon and then select object in map. Draw points in map to move them, use points in the middle of sections to add new edges.', srid=4326, verbose_name='place geometry')), ('desc', models.TextField(help_text='Text that will be shown after selecting POI.', null=True, verbose_name='description', blank=True)), ('desc_extra', models.TextField(help_text='Text that extends the description.', null=True, verbose_name='detailed description', blank=True)), ('url', models.URLField(help_text='Link to the web page of the place.', null=True, verbose_name='URL', blank=True)), ('address', models.CharField(help_text='Poi address (street, house number)', max_length=255, null=True, verbose_name='adress', blank=True)), ('remark', models.TextField(help_text='Internal information about POI.', null=True, verbose_name='Internal remark', blank=True)), ('properties_cache', models.CharField(max_length=255, null=True, blank=True)), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), ('last_modification', models.DateTimeField(auto_now=True, verbose_name='last modification at')), ('author', models.ForeignKey(related_name='poi_create', verbose_name='author', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ('marker', models.ForeignKey(related_name='pois', verbose_name='marker', to='webmap.Marker', help_text='Select icon, that will be shown in map', on_delete=models.CASCADE)), ], options={ 'verbose_name': 'place', 'verbose_name_plural': 'places', 'permissions': [('can_only_own_data_only', 'Can only edit his own data'), ('can_edit_advanced_fields', 'Can edit importance status')], }, bases=(models.Model,), ), migrations.CreateModel( name='Property', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(help_text='Status name', max_length=255, verbose_name='name')), ('as_filter', models.BooleanField(default=False, help_text='Show as a filter in right map menu?', verbose_name='as filter?')), ('order', models.IntegerField(default=0, verbose_name='order')), ('slug', models.SlugField(unique=True, verbose_name='Name in URL')), ('desc', models.TextField(help_text='Property description.', null=True, verbose_name='description', blank=True)), ('remark', models.TextField(help_text='Internal information about the property.', null=True, verbose_name='Internal remark', blank=True)), ('default_icon', models.ImageField(storage=webmap.utils.SlugifyFileSystemStorage(), upload_to='icons', null=True, verbose_name='default icon', blank=True)), ], options={ 'ordering': ['order'], 'verbose_name': 'property', 'verbose_name_plural': 'properties', }, bases=(models.Model,), ), migrations.CreateModel( name='Sector', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=255, verbose_name='name')), ('slug', models.SlugField(unique=True, verbose_name='name in URL')), ('geom', django.contrib.gis.db.models.fields.PolygonField(help_text='Sector area', srid=4326, verbose_name='area')), ], options={ 'verbose_name': 'sector', 'verbose_name_plural': 'sectors', }, bases=(models.Model,), ), migrations.CreateModel( name='Status', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(help_text='Status name', unique=True, max_length=255, verbose_name='name')), ('desc', models.TextField(help_text='Status description.', null=True, verbose_name='description', blank=True)), ('show', models.BooleanField(default=False, help_text='Show to map user', verbose_name='show')), ('show_to_mapper', models.BooleanField(default=False, help_text='Show to mapper', verbose_name='show to mapper')), ], options={ 'verbose_name': 'status', 'verbose_name_plural': 'statuses', }, bases=(models.Model,), ), migrations.AddField( model_name='property', name='status', field=models.ForeignKey(verbose_name='status', to='webmap.Status', on_delete=models.CASCADE), preserve_default=True, ), migrations.AddField( model_name='poi', name='properties', field=models.ManyToManyField(help_text='POI properties', to='webmap.Property', null=True, verbose_name='properties', blank=True), preserve_default=True, ), migrations.AddField( model_name='poi', name='status', field=models.ForeignKey(default=0, verbose_name='status', to='webmap.Status', help_text='POI status, determinse if it will be shown in map', on_delete=models.CASCADE), preserve_default=True, ), migrations.AddField( model_name='poi', name='updated_by', field=models.ForeignKey(related_name='poi_update', verbose_name='last updated by', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE), preserve_default=True, ), migrations.AddField( model_name='photo', name='poi', field=models.ForeignKey(related_name='photos', verbose_name='poi', to='webmap.Poi', on_delete=models.CASCADE), preserve_default=True, ), migrations.AddField( model_name='photo', name='updated_by', field=models.ForeignKey(related_name='photo_update', verbose_name='last updated by', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE), preserve_default=True, ), migrations.AddField( model_name='marker', name='layer', field=models.ForeignKey(verbose_name='layer', to='webmap.Layer', on_delete=models.CASCADE), preserve_default=True, ), migrations.AddField( model_name='marker', name='status', field=models.ForeignKey(verbose_name='status', to='webmap.Status', on_delete=models.CASCADE), preserve_default=True, ), migrations.AddField( model_name='layer', name='status', field=models.ForeignKey(verbose_name='status', to='webmap.Status', on_delete=models.CASCADE), preserve_default=True, ), ]
formize.rules.js
export function isRequired(report, schema, json) { // eslint-disable-line import/prefer-default-export const originalPath = report.path; if (Array.isArray(schema.required)) { schema.required.forEach(prop => { const hasValue = json[prop]; if (!hasValue) { report.path = [prop]; // eslint-disable-line no-param-reassign report.addCustomError('IS_REQUIRED', 'Field is required', [prop], null, schema.description); } }); }
report.path = originalPath; // eslint-disable-line no-param-reassign }
fake.go
package mocks import ( "testing" pgapis "github.com/operator-backing-service-samples/postgresql-operator/pkg/apis" pgv1alpha1 "github.com/operator-backing-service-samples/postgresql-operator/pkg/apis/postgresql/v1alpha1" olmv1alpha1 "github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1alpha1" "github.com/stretchr/testify/require" appsv1 "k8s.io/api/apps/v1" apiextensionv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" fakedynamic "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/kubernetes/scheme" ocav1 "github.com/openshift/api/apps/v1" knativev1 "knative.dev/serving/pkg/apis/serving/v1" v1alpha1 "github.com/redhat-developer/service-binding-operator/pkg/apis/apps/v1alpha1" ) // Fake defines all the elements to fake a kubernetes api client. type Fake struct { t *testing.T // testing instance ns string // namespace S *runtime.Scheme // runtime client scheme objs []runtime.Object // all fake objects } // AddMockedServiceBindingRequest add mocked object from ServiceBindingRequestMock. func (f *Fake) AddMockedServiceBindingRequest( name string, backingServiceNamespace *string, backingServiceResourceRef string, applicationResourceRef string, applicationGVR schema.GroupVersionResource, matchLabels map[string]string, ) *v1alpha1.ServiceBindingRequest { f.S.AddKnownTypes(v1alpha1.SchemeGroupVersion, &v1alpha1.ServiceBindingRequest{}) sbr := ServiceBindingRequestMock(f.ns, name, backingServiceNamespace, backingServiceResourceRef, applicationResourceRef, applicationGVR, matchLabels) f.objs = append(f.objs, sbr) return sbr } // AddMockedServiceBindingRequestWithUnannotated add mocked object from ServiceBindingRequestMock with DetectBindingResources. func (f *Fake) AddMockedServiceBindingRequestWithUnannotated( name string, backingServiceResourceRef string, applicationResourceRef string, applicationGVR schema.GroupVersionResource, matchLabels map[string]string, ) *v1alpha1.ServiceBindingRequest { f.S.AddKnownTypes(v1alpha1.SchemeGroupVersion, &v1alpha1.ServiceBindingRequest{}) sbr := ServiceBindingRequestMock(f.ns, name, nil, backingServiceResourceRef, applicationResourceRef, applicationGVR, matchLabels) f.objs = append(f.objs, sbr) return sbr } // AddMockedUnstructuredServiceBindingRequestWithoutApplication creates a mock ServiceBindingRequest object func (f *Fake) AddMockedUnstructuredServiceBindingRequestWithoutApplication( name string, backingServiceResourceRef string, ) *unstructured.Unstructured { f.S.AddKnownTypes(v1alpha1.SchemeGroupVersion, &v1alpha1.ServiceBindingRequest{}) var emptyGVR = schema.GroupVersionResource{} sbr, err := UnstructuredServiceBindingRequestMock(f.ns, name, backingServiceResourceRef, "", emptyGVR, nil) require.NoError(f.t, err) f.objs = append(f.objs, sbr) return sbr } // AddMockedUnstructuredServiceBindingRequest creates a mock ServiceBindingRequest object func (f *Fake) AddMockedUnstructuredServiceBindingRequest( name string, backingServiceResourceRef string, applicationResourceRef string, applicationGVR schema.GroupVersionResource, matchLabels map[string]string, ) *unstructured.Unstructured { f.S.AddKnownTypes(v1alpha1.SchemeGroupVersion, &v1alpha1.ServiceBindingRequest{}) sbr, err := UnstructuredServiceBindingRequestMock(f.ns, name, backingServiceResourceRef, applicationResourceRef, applicationGVR, matchLabels) require.NoError(f.t, err) f.objs = append(f.objs, sbr) return sbr } // AddMockedUnstructuredCSV add mocked unstructured CSV. func (f *Fake) AddMockedUnstructuredCSV(name string) { require.NoError(f.t, olmv1alpha1.AddToScheme(f.S)) csv, err := UnstructuredClusterServiceVersionMock(f.ns, name) require.NoError(f.t, err) f.S.AddKnownTypes(olmv1alpha1.SchemeGroupVersion, &olmv1alpha1.ClusterServiceVersion{}) f.objs = append(f.objs, csv) } // AddMockedCSVList add mocked object from ClusterServiceVersionListMock. func (f *Fake) AddMockedCSVList(name string) { require.NoError(f.t, olmv1alpha1.AddToScheme(f.S)) f.S.AddKnownTypes(olmv1alpha1.SchemeGroupVersion, &olmv1alpha1.ClusterServiceVersion{}) f.objs = append(f.objs, ClusterServiceVersionListMock(f.ns, name)) } // AddMockedCSVWithVolumeMountList add mocked object from ClusterServiceVersionListVolumeMountMock. func (f *Fake) AddMockedCSVWithVolumeMountList(name string) { require.NoError(f.t, olmv1alpha1.AddToScheme(f.S)) f.S.AddKnownTypes(olmv1alpha1.SchemeGroupVersion, &olmv1alpha1.ClusterServiceVersion{}) f.objs = append(f.objs, ClusterServiceVersionListVolumeMountMock(f.ns, name)) } // AddMockedUnstructuredCSVWithVolumeMount same than AddMockedCSVWithVolumeMountList but using // unstructured object. func (f *Fake) AddMockedUnstructuredCSVWithVolumeMount(name string) { require.NoError(f.t, olmv1alpha1.AddToScheme(f.S)) csv, err := UnstructuredClusterServiceVersionVolumeMountMock(f.ns, name) require.NoError(f.t, err) f.S.AddKnownTypes(olmv1alpha1.SchemeGroupVersion, &olmv1alpha1.ClusterServiceVersion{}) f.objs = append(f.objs, csv) } // AddMockedDatabaseCR add mocked object from DatabaseCRMock. func (f *Fake) AddMockedDatabaseCR(ref string, namespace string) runtime.Object { require.NoError(f.t, pgapis.AddToScheme(f.S)) f.S.AddKnownTypes(pgv1alpha1.SchemeGroupVersion, &pgv1alpha1.Database{}) mock := DatabaseCRMock(namespace, ref) f.objs = append(f.objs, mock) return mock } func (f *Fake) AddMockedUnstructuredDatabaseCR(ref string) { require.NoError(f.t, pgapis.AddToScheme(f.S)) d, err := UnstructuredDatabaseCRMock(f.ns, ref) require.NoError(f.t, err) f.objs = append(f.objs, d) } // AddMockedUnstructuredDeploymentConfig adds mocked object from UnstructuredDeploymentConfigMock. func (f *Fake) AddMockedUnstructuredDeploymentConfig(name string, matchLabels map[string]string) { require.Nil(f.t, ocav1.AddToScheme(f.S)) d, err := UnstructuredDeploymentConfigMock(f.ns, name, matchLabels) require.Nil(f.t, err) f.S.AddKnownTypes(ocav1.SchemeGroupVersion, &ocav1.DeploymentConfig{}) f.objs = append(f.objs, d) } // AddMockedUnstructuredDeployment add mocked object from UnstructuredDeploymentMock. func (f *Fake) AddMockedUnstructuredDeployment(name string, matchLabels map[string]string) *unstructured.Unstructured { require.NoError(f.t, appsv1.AddToScheme(f.S)) d, err := UnstructuredDeploymentMock(f.ns, name, matchLabels) require.NoError(f.t, err) f.S.AddKnownTypes(appsv1.SchemeGroupVersion, &appsv1.Deployment{}) f.objs = append(f.objs, d) return d } // AddMockedUnstructuredKnativeService add mocked object from UnstructuredKnativeService. func (f *Fake) AddMockedUnstructuredKnativeService(name string, matchLabels map[string]string) { require.NoError(f.t, knativev1.AddToScheme(f.S)) d, err := UnstructuredKnativeServiceMock(f.ns, name, matchLabels) require.NoError(f.t, err) f.S.AddKnownTypes(knativev1.SchemeGroupVersion, &knativev1.Service{}) f.objs = append(f.objs, d) } func (f *Fake) AddMockedUnstructuredDatabaseCRD() *unstructured.Unstructured { require.NoError(f.t, apiextensionv1beta1.AddToScheme(f.S)) c, err := UnstructuredDatabaseCRDMock(f.ns) require.NoError(f.t, err) f.S.AddKnownTypes(apiextensionv1beta1.SchemeGroupVersion, &apiextensionv1beta1.CustomResourceDefinition{}) f.objs = append(f.objs, c) return c } func (f *Fake) AddMockedUnstructuredPostgresDatabaseCR(ref string) *unstructured.Unstructured { d, err := UnstructuredPostgresDatabaseCRMock(f.ns, ref) require.NoError(f.t, err) f.objs = append(f.objs, d) return d } // AddMockedUnstructuredSecret add mocked object from SecretMock. func (f *Fake) AddMockedUnstructuredSecret(name string) *unstructured.Unstructured { s, err := UnstructuredSecretMock(f.ns, name) require.NoError(f.t, err) f.objs = append(f.objs, s) return s } // AddMockedUnstructuredSecret add mocked object from SecretMock. This secret is created with a resourceVersion func (f *Fake) AddMockedUnstructuredSecretRV(name string) *unstructured.Unstructured { s, err := UnstructuredSecretMockRV(f.ns, name) require.NoError(f.t, err) f.objs = append(f.objs, s) return s } // AddNamespacedMockedSecret add mocked object from SecretMock in a namespace // which isn't necessarily same as that of the ServiceBindingRequest namespace. func (f *Fake) AddNamespacedMockedSecret(name string, namespace string, data map[string][]byte) { f.objs = append(f.objs, SecretMock(namespace, name, data)) } // AddMockedUnstructuredConfigMap add mocked object from ConfigMapMock. func (f *Fake) AddMockedUnstructuredConfigMap(name string) { mock := ConfigMapMock(f.ns, name) uObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(mock) require.NoError(f.t, err) f.objs = append(f.objs, &unstructured.Unstructured{Object: uObj}) } func (f *Fake) AddMockResource(resource runtime.Object) { f.objs = append(f.objs, resource) } // FakeDynClient returns fake dynamic api client. func (f *Fake) FakeDynClient() *fakedynamic.FakeDynamicClient { return fakedynamic.NewSimpleDynamicClient(f.S, f.objs...) } // NewFake instantiate Fake type. func
(t *testing.T, ns string) *Fake { return &Fake{t: t, ns: ns, S: scheme.Scheme} }
NewFake
node_info_test.go
package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/ed25519" tmnet "github.com/tendermint/tendermint/libs/net" "github.com/tendermint/tendermint/version" ) const testCh = 0x01 func TestNodeInfoValidate(t *testing.T) { // empty fails ni := NodeInfo{} assert.Error(t, ni.Validate()) channels := make([]byte, maxNumChannels) for i := 0; i < maxNumChannels; i++ { channels[i] = byte(i) } dupChannels := make([]byte, 5) copy(dupChannels, channels[:5]) dupChannels = append(dupChannels, testCh) nonASCII := "¢§µ" emptyTab := "\t" emptySpace := " " testCases := []struct { testName string malleateNodeInfo func(*NodeInfo) expectErr bool }{ { "Too Many Channels", func(ni *NodeInfo) { ni.Channels = append(channels, byte(maxNumChannels)) }, true, }, {"Duplicate Channel", func(ni *NodeInfo) { ni.Channels = dupChannels }, true}, {"Good Channels", func(ni *NodeInfo) { ni.Channels = ni.Channels[:5] }, false}, {"Invalid NetAddress", func(ni *NodeInfo) { ni.ListenAddr = "not-an-address" }, true}, {"Good NetAddress", func(ni *NodeInfo) { ni.ListenAddr = "0.0.0.0:26656" }, false}, {"Non-ASCII Version", func(ni *NodeInfo) { ni.Version = nonASCII }, true}, {"Empty tab Version", func(ni *NodeInfo) { ni.Version = emptyTab }, true}, {"Empty space Version", func(ni *NodeInfo) { ni.Version = emptySpace }, true}, {"Empty Version", func(ni *NodeInfo) { ni.Version = "" }, false}, {"Non-ASCII Moniker", func(ni *NodeInfo) { ni.Moniker = nonASCII }, true}, {"Empty tab Moniker", func(ni *NodeInfo) { ni.Moniker = emptyTab }, true}, {"Empty space Moniker", func(ni *NodeInfo) { ni.Moniker = emptySpace }, true}, {"Empty Moniker", func(ni *NodeInfo) { ni.Moniker = "" }, true}, {"Good Moniker", func(ni *NodeInfo) { ni.Moniker = "hey its me" }, false}, {"Non-ASCII TxIndex", func(ni *NodeInfo) { ni.Other.TxIndex = nonASCII }, true}, {"Empty tab TxIndex", func(ni *NodeInfo) { ni.Other.TxIndex = emptyTab }, true}, {"Empty space TxIndex", func(ni *NodeInfo) { ni.Other.TxIndex = emptySpace }, true}, {"Empty TxIndex", func(ni *NodeInfo) { ni.Other.TxIndex = "" }, false}, {"Off TxIndex", func(ni *NodeInfo) { ni.Other.TxIndex = "off" }, false}, {"Non-ASCII RPCAddress", func(ni *NodeInfo) { ni.Other.RPCAddress = nonASCII }, true}, {"Empty tab RPCAddress", func(ni *NodeInfo) { ni.Other.RPCAddress = emptyTab }, true}, {"Empty space RPCAddress", func(ni *NodeInfo) { ni.Other.RPCAddress = emptySpace }, true}, {"Empty RPCAddress", func(ni *NodeInfo) { ni.Other.RPCAddress = "" }, false}, {"Good RPCAddress", func(ni *NodeInfo) { ni.Other.RPCAddress = "0.0.0.0:26657" }, false}, } nodeKeyID := testNodeID() name := "testing" // test case passes ni = testNodeInfo(t, nodeKeyID, name) ni.Channels = channels assert.NoError(t, ni.Validate()) for _, tc := range testCases { t.Run(tc.testName, func(t *testing.T) { ni := testNodeInfo(t, nodeKeyID, name) ni.Channels = channels tc.malleateNodeInfo(&ni) err := ni.Validate() if tc.expectErr { assert.Error(t, err, tc.testName) } else { assert.NoError(t, err, tc.testName) } }) } } func testNodeID() NodeID { return NodeIDFromPubKey(ed25519.GenPrivKey().PubKey()) } func testNodeInfo(t *testing.T, id NodeID, name string) NodeInfo { return testNodeInfoWithNetwork(t, id, name, "testing") } func testNodeInfoWithNetwork(t *testing.T, id NodeID, name, network string) NodeInfo { t.Helper() return NodeInfo{
App: 0, }, NodeID: id, ListenAddr: fmt.Sprintf("127.0.0.1:%d", getFreePort(t)), Network: network, Version: "1.2.3-rc0-deadbeef", Channels: []byte{testCh}, Moniker: name, Other: NodeInfoOther{ TxIndex: "on", RPCAddress: fmt.Sprintf("127.0.0.1:%d", getFreePort(t)), }, } } func getFreePort(t *testing.T) int { t.Helper() port, err := tmnet.GetFreePort() require.NoError(t, err) return port } func TestNodeInfoCompatible(t *testing.T) { nodeKey1ID := testNodeID() nodeKey2ID := testNodeID() name := "testing" var newTestChannel byte = 0x2 // test NodeInfo is compatible ni1 := testNodeInfo(t, nodeKey1ID, name) ni2 := testNodeInfo(t, nodeKey2ID, name) assert.NoError(t, ni1.CompatibleWith(ni2)) // add another channel; still compatible ni2.Channels = []byte{newTestChannel, testCh} assert.NoError(t, ni1.CompatibleWith(ni2)) testCases := []struct { testName string malleateNodeInfo func(*NodeInfo) }{ {"Wrong block version", func(ni *NodeInfo) { ni.ProtocolVersion.Block++ }}, {"Wrong network", func(ni *NodeInfo) { ni.Network += "-wrong" }}, {"No common channels", func(ni *NodeInfo) { ni.Channels = []byte{newTestChannel} }}, } for _, tc := range testCases { ni := testNodeInfo(t, nodeKey2ID, name) tc.malleateNodeInfo(&ni) assert.Error(t, ni1.CompatibleWith(ni)) } } func TestNodeInfoAddChannel(t *testing.T) { nodeInfo := testNodeInfo(t, testNodeID(), "testing") nodeInfo.Channels = []byte{} require.Empty(t, nodeInfo.Channels) nodeInfo.AddChannel(2) require.Contains(t, nodeInfo.Channels, byte(0x02)) // adding the same channel again shouldn't be a problem nodeInfo.AddChannel(2) require.Contains(t, nodeInfo.Channels, byte(0x02)) } func TestParseAddressString(t *testing.T) { testCases := []struct { name string addr string expected string correct bool }{ {"no node id and no protocol", "127.0.0.1:8080", "", false}, {"no node id w/ tcp input", "tcp://127.0.0.1:8080", "", false}, {"no node id w/ udp input", "udp://127.0.0.1:8080", "", false}, { "no protocol", "[email protected]:8080", "[email protected]:8080", true, }, { "tcp input", "tcp://[email protected]:8080", "[email protected]:8080", true, }, { "udp input", "udp://[email protected]:8080", "[email protected]:8080", true, }, {"malformed tcp input", "tcp//[email protected]:8080", "", false}, {"malformed udp input", "udp//[email protected]:8080", "", false}, // {"127.0.0:8080", false}, {"invalid host", "notahost", "", false}, {"invalid port", "127.0.0.1:notapath", "", false}, {"invalid host w/ port", "notahost:8080", "", false}, {"just a port", "8082", "", false}, {"non-existent port", "127.0.0:8080000", "", false}, {"too short nodeId", "[email protected]:8080", "", false}, {"too short, not hex nodeId", "[email protected]:8080", "", false}, {"not hex nodeId", "[email protected]:8080", "", false}, {"too short nodeId w/tcp", "tcp://[email protected]:8080", "", false}, {"too short notHex nodeId w/tcp", "tcp://[email protected]:8080", "", false}, {"notHex nodeId w/tcp", "tcp://[email protected]:8080", "", false}, { "correct nodeId w/tcp", "tcp://[email protected]:8080", "[email protected]:8080", true, }, {"no node id", "tcp://@127.0.0.1:8080", "", false}, {"no node id or IP", "tcp://@", "", false}, {"tcp no host, w/ port", "tcp://:26656", "", false}, {"empty", "", "", false}, {"node id delimiter 1", "@", "", false}, {"node id delimiter 2", " @", "", false}, {"node id delimiter 3", " @ ", "", false}, } for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { na, err := ParseAddressString(tc.addr) if tc.correct { require.NoError(t, err, tc.addr) assert.Contains(t, tc.expected, na.IP.String()) assert.Contains(t, tc.expected, fmt.Sprint(na.Port)) } else { assert.Error(t, err, "%v", tc.addr) } }) } }
ProtocolVersion: ProtocolVersion{ P2P: version.P2PProtocol, Block: version.BlockProtocol,
test_wordTemplate.py
from unittest import TestCase, skip import os from docxtpl import DocxTemplate class
(TestCase): def setUp(self): self.APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory self.FIXTURE_DIR = os.path.join(os.path.dirname(self.APP_DIR), 'fixtures') self.FORM_DIR = os.path.join(self.APP_DIR, 'static', 'formlib') def test_render1(self): doc = DocxTemplate(os.path.join( self.FIXTURE_DIR, 'test_docx.docx')) context = {'claimant_full_name':"Mary Smith", 'claimant_ssn': '111-22-1234'} doc.render(context) doc.save(os.path.join(self.FIXTURE_DIR, 'generated_doc.docx')) def test_render2(self): doc = DocxTemplate(os.path.join( self.FIXTURE_DIR,'do-letter-form.docx')) context = {'claimant_full_name':"Mary Smith", 'claimant_ssn': '111-22-1234'} doc.render(context) doc.save(os.path.join(self.FIXTURE_DIR, 'generated_doc2.docx'))
TestDocxTemplate
roi_box_predictors.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from maskrcnn_benchmark.modeling import registry from torch import nn @registry.ROI_BOX_PREDICTOR.register("FastRCNNPredictor") class FastRCNNPredictor(nn.Module): def __init__(self, config, in_channels): super(FastRCNNPredictor, self).__init__() assert in_channels is not None num_inputs = in_channels num_classes = config.MODEL.ROI_BOX_HEAD.NUM_CLASSES if config.FEW_SHOT.SECOND_STAGE_METHOD == 'rn': num_classes = 2 self.avgpool = nn.AdaptiveAvgPool2d(1) self.cls_score = nn.Linear(num_inputs, num_classes) num_bbox_reg_classes = 2 if config.MODEL.CLS_AGNOSTIC_BBOX_REG else num_classes self.bbox_pred = nn.Linear(num_inputs, num_bbox_reg_classes * 4) nn.init.normal_(self.cls_score.weight, mean=0, std=0.01) nn.init.constant_(self.cls_score.bias, 0) nn.init.normal_(self.bbox_pred.weight, mean=0, std=0.001) nn.init.constant_(self.bbox_pred.bias, 0) def forward(self, x): x = self.avgpool(x) x = x.view(x.size(0), -1) cls_logit = self.cls_score(x) bbox_pred = self.bbox_pred(x) return cls_logit, bbox_pred @registry.ROI_BOX_PREDICTOR.register("FPNPredictor") class FPNPredictor(nn.Module): def __init__(self, cfg, in_channels): super(FPNPredictor, self).__init__() num_classes = cfg.MODEL.ROI_BOX_HEAD.NUM_CLASSES num_bbox_reg_classes = 2 if cfg.FEW_SHOT.SECOND_STAGE_METHOD == 'rn' and cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS == 'focal_loss': num_classes = 1 elif cfg.FEW_SHOT.SECOND_STAGE_METHOD == 'rn' and cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS != 'focal_loss': num_classes= 2 elif cfg.FEW_SHOT.SECOND_STAGE_METHOD == 'concat' and \ cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS == 'focal_loss' and \ not cfg.FEW_SHOT.NEG_SUPPORT.TURN_ON: num_classes = 1 elif cfg.FEW_SHOT.SECOND_STAGE_METHOD == 'concat' and \ cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS == 'focal_loss' and \ cfg.FEW_SHOT.NEG_SUPPORT.TURN_ON: num_classes = 2 elif cfg.FEW_SHOT.SECOND_STAGE_METHOD == 'concat' and \ cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS == 'ce_loss' and \ not cfg.FEW_SHOT.NEG_SUPPORT.TURN_ON: num_classes = 2 elif cfg.FEW_SHOT.SECOND_STAGE_METHOD == 'concat' and \ cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS == 'ce_loss' and \ cfg.FEW_SHOT.NEG_SUPPORT.TURN_ON: num_classes = 2 # originally 3, but 2 in new version neg support elif cfg.FEW_SHOT.SECOND_STAGE_METHOD == 'concat' and \ cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS =='cxe_loss' and cfg.FEW_SHOT.SOFT_LABELING: num_classes = 2 elif cfg.FEW_SHOT.SECOND_STAGE_METHOD == 'concat' and \ cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS in ['mse_loss','l1_loss']: num_classes = 1 else: raise Exception('setting not compatible {} {} {}'.format( cfg.FEW_SHOT.SECOND_STAGE_METHOD, cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS, cfg.FEW_SHOT.NEG_SUPPORT.TURN_ON )) if cfg.FEW_SHOT.SECOND_STAGE_CLS_LOSS in ['focal_loss', 'mse_loss', 'l1_loss']: num_bbox_reg_classes = num_classes+1 else: num_bbox_reg_classes = num_classes representation_size = in_channels self.cls_score = nn.Linear(representation_size, num_classes) # num_bbox_reg_classes = 2 #if cfg.MODEL.CLS_AGNOSTIC_BBOX_REG else num_classes self.bbox_pred = nn.Linear(representation_size, num_bbox_reg_classes * 4) nn.init.normal_(self.cls_score.weight, std=0.01) nn.init.normal_(self.bbox_pred.weight, std=0.001) for l in [self.cls_score, self.bbox_pred]: nn.init.constant_(l.bias, 0) def forward(self, x): if x.ndimension() == 4: assert list(x.shape[2:]) == [1, 1] x = x.view(x.size(0), -1) scores = self.cls_score(x) bbox_deltas = self.bbox_pred(x) return scores, bbox_deltas def make_roi_box_predictor(cfg, in_channels):
func = registry.ROI_BOX_PREDICTOR[cfg.MODEL.ROI_BOX_HEAD.PREDICTOR] return func(cfg, in_channels)
model_employer_verification.go
/* * The Plaid API * * The Plaid REST API. Please see https://plaid.com/docs/api for more details. * * API version: 2020-09-14_1.54.0 */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package plaid import ( "encoding/json" ) // EmployerVerification An object containing employer data. type EmployerVerification struct { // Name of employer. Name NullableString `json:"name,omitempty"` AdditionalProperties map[string]interface{} } type _EmployerVerification EmployerVerification // NewEmployerVerification instantiates a new EmployerVerification object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewEmployerVerification() *EmployerVerification { this := EmployerVerification{} return &this } // NewEmployerVerificationWithDefaults instantiates a new EmployerVerification object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewEmployerVerificationWithDefaults() *EmployerVerification { this := EmployerVerification{} return &this } // GetName returns the Name field value if set, zero value otherwise (both if not set or set to explicit null). func (o *EmployerVerification) GetName() string { if o == nil || o.Name.Get() == nil { var ret string return ret } return *o.Name.Get() } // GetNameOk returns a tuple with the Name field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *EmployerVerification) GetNameOk() (*string, bool) { if o == nil { return nil, false } return o.Name.Get(), o.Name.IsSet() } // HasName returns a boolean if a field has been set. func (o *EmployerVerification) HasName() bool { if o != nil && o.Name.IsSet() { return true } return false } // SetName gets a reference to the given NullableString and assigns it to the Name field. func (o *EmployerVerification) SetName(v string) { o.Name.Set(&v) } // SetNameNil sets the value for Name to be an explicit nil func (o *EmployerVerification) SetNameNil() { o.Name.Set(nil) } // UnsetName ensures that no value is present for Name, not even an explicit nil func (o *EmployerVerification) UnsetName() { o.Name.Unset() } func (o EmployerVerification) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Name.IsSet() { toSerialize["name"] = o.Name.Get() } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *EmployerVerification) UnmarshalJSON(bytes []byte) (err error) { varEmployerVerification := _EmployerVerification{} if err = json.Unmarshal(bytes, &varEmployerVerification); err == nil { *o = EmployerVerification(varEmployerVerification) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } return err } type NullableEmployerVerification struct { value *EmployerVerification isSet bool } func (v NullableEmployerVerification) Get() *EmployerVerification { return v.value } func (v *NullableEmployerVerification) Set(val *EmployerVerification) { v.value = val v.isSet = true } func (v NullableEmployerVerification) IsSet() bool { return v.isSet } func (v *NullableEmployerVerification) Unset() { v.value = nil v.isSet = false } func NewNullableEmployerVerification(val *EmployerVerification) *NullableEmployerVerification
func (v NullableEmployerVerification) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableEmployerVerification) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
{ return &NullableEmployerVerification{value: val, isSet: true} }
jquery.min.js
/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ /*For Carousel Begin*/ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function
(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); /*For Carousel End*/ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){ return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});
st
random-wrapper.service.ts
/* imports from node_modules */ import { Injectable } from '@angular/core'; /* imports from app */ import { RandomService } from '@monographia/random.service'; import { XXhashService } from '@monographia/xxhash.service'; @Injectable({ providedIn: 'root' }) export class
{ constructor(private randomService: RandomService, private xxhashService: XXhashService){ } public async random(min: number = 0, max: number = 1, seed?: string): Promise<number> { if(seed == null){ seed = new Date().toString(); } const hwx: string = await this.xxhashService.h64(seed + ' w/x ' + seed.split('').reverse().join('-')); const hyz: string = await this.xxhashService.h64(seed + ' y/z ' + seed.split('').reverse().join(' ')); return(this.randomService.sfc32(min, max, parseInt(hwx.substring(0, 8), 16), parseInt(hwx.substring(8, 16), 16), parseInt(hyz.substring(0, 8), 16), parseInt(hyz.substring(8, 16), 16))); } }
RandomWrapperService
verifier.rs
use math::fft::{EvaluationDomain, Evaluations as EvaluationsOnDomain}; use math::PrimeField; use rand::RngCore; use crate::r1cs::SynthesisError; use crate::ToString; use crate::marlin::ahp::arithmetic::BivariatePoly; use crate::marlin::ahp::constraint_systems::ProverConstraintSystem; use crate::marlin::ahp::indexer::IndexInfo; use crate::marlin::ahp::{Error, AHP}; use crate::marlin::pc::{Evaluations, QuerySet}; pub struct VerifierState<F: PrimeField> { pub domain_h: EvaluationDomain<F>, pub domain_k: EvaluationDomain<F>, pub eta_a: Option<F>, pub eta_b: Option<F>, pub eta_c: Option<F>, pub alpha: Option<F>, pub beta: Option<F>, pub gamma: Option<F>, } #[derive(Copy, Clone)] pub struct VerifierFirstMsg<F: PrimeField> { pub alpha: F, pub eta_a: F, pub eta_b: F, pub eta_c: F, } #[derive(Copy, Clone)] pub struct VerifierSecondMsg<F: PrimeField> { pub beta: F, } impl<F: PrimeField> AHP<F> { pub fn verifier_first_round<R: RngCore>( index_info: IndexInfo, rng: &mut R, ) -> Result<(VerifierState<F>, VerifierFirstMsg<F>), Error> { if index_info.num_constraints != index_info.num_variables { return Err(Error::NonSquareMatrix); } let domain_h = EvaluationDomain::new(index_info.num_constraints) .ok_or(SynthesisError::PolynomialDegreeTooLarge)?; let domain_k = EvaluationDomain::new(index_info.num_non_zeros) .ok_or(SynthesisError::PolynomialDegreeTooLarge)?; let msg = VerifierFirstMsg { alpha: Self::sample_element_outside_domain(&domain_h, rng), eta_a: F::rand(rng), eta_b: F::rand(rng), eta_c: F::rand(rng), }; let state = VerifierState { domain_h, domain_k, eta_a: Some(msg.eta_a), eta_b: Some(msg.eta_b), eta_c: Some(msg.eta_c), alpha: Some(msg.alpha), beta: None, gamma: None, }; Ok((state, msg)) } pub fn verifier_second_round<R: RngCore>( mut state: VerifierState<F>, rng: &mut R, ) -> Result<(VerifierState<F>, VerifierSecondMsg<F>), Error> { let beta = Self::sample_element_outside_domain(&state.domain_h, rng); let msg = VerifierSecondMsg { beta }; state.beta = Some(beta); Ok((state, msg)) } pub fn
<R: RngCore>( mut state: VerifierState<F>, rng: &mut R, ) -> Result<VerifierState<F>, Error> { state.gamma = Some(F::rand(rng)); Ok(state) } pub fn verifier_query_set(state: &VerifierState<F>) -> QuerySet<F> { let beta = state.beta.unwrap(); let gamma = state.gamma.unwrap(); let mut query_set = QuerySet::new(); query_set.insert(("w".into(), beta)); query_set.insert(("z_a".into(), beta)); query_set.insert(("z_b".into(), beta)); query_set.insert(("mask".into(), beta)); query_set.insert(("t".into(), beta)); query_set.insert(("g_1".into(), beta)); query_set.insert(("h_1".into(), beta)); query_set.insert(("g_2".into(), gamma)); query_set.insert(("h_2".into(), gamma)); query_set.insert(("a_row".into(), gamma)); query_set.insert(("a_col".into(), gamma)); query_set.insert(("a_val".into(), gamma)); query_set.insert(("a_row_col".into(), gamma)); query_set.insert(("b_row".into(), gamma)); query_set.insert(("b_col".into(), gamma)); query_set.insert(("b_val".into(), gamma)); query_set.insert(("b_row_col".into(), gamma)); query_set.insert(("c_row".into(), gamma)); query_set.insert(("c_col".into(), gamma)); query_set.insert(("c_val".into(), gamma)); query_set.insert(("c_row_col".into(), gamma)); query_set } fn sample_element_outside_domain<R: RngCore>(domain: &EvaluationDomain<F>, rng: &mut R) -> F { let mut t = F::rand(rng); while domain.evaluate_vanishing_polynomial(t) == F::zero() { t = F::rand(rng); } t } pub fn verifier_equality_check( public_input: &[F], evaluations: &Evaluations<F>, state: &VerifierState<F>, ) -> Result<bool, Error> { let alpha = state.alpha.unwrap(); let eta_a = state.eta_a.unwrap(); let eta_b = state.eta_b.unwrap(); let eta_c = state.eta_c.unwrap(); let beta = state.beta.unwrap(); let gamma = state.gamma.unwrap(); let domain_h = state.domain_h; let v_h_at_alpha = domain_h.evaluate_vanishing_polynomial(alpha); let v_h_at_beta = domain_h.evaluate_vanishing_polynomial(beta); let r_alpha_at_beta = domain_h.bivariate_eval(alpha, beta); let formatted_input = ProverConstraintSystem::format_public_input(public_input); let domain_x = EvaluationDomain::<F>::new(formatted_input.len()) .ok_or(SynthesisError::PolynomialDegreeTooLarge)?; let v_x_at_beta = domain_x.evaluate_vanishing_polynomial(beta); let x_poly = &EvaluationsOnDomain::from_vec_and_domain(formatted_input, domain_x).interpolate(); let x_at_beta = x_poly.evaluate(beta); // outer sumcheck let mask_at_beta = Self::get_eval(&evaluations, "mask", beta)?; let z_a_at_beta = Self::get_eval(&evaluations, "z_a", beta)?; let z_b_at_beta = Self::get_eval(&evaluations, "z_b", beta)?; let w_at_beta = Self::get_eval(&evaluations, "w", beta)?; let t_at_beta = Self::get_eval(&evaluations, "t", beta)?; let h_1_at_beta = Self::get_eval(&evaluations, "h_1", beta)?; let g_1_at_beta = Self::get_eval(&evaluations, "g_1", beta)?; let lhs = mask_at_beta + r_alpha_at_beta * (eta_a * z_a_at_beta + eta_b * z_b_at_beta + eta_c * z_a_at_beta * z_b_at_beta) - t_at_beta * (v_x_at_beta * w_at_beta + x_at_beta); let rhs = h_1_at_beta * v_h_at_beta + beta * g_1_at_beta; if lhs != rhs { return Ok(false); } // inner sumcheck let domain_k = state.domain_k; let v_k_at_gamma = domain_k.evaluate_vanishing_polynomial(gamma); let k_size = domain_k.size_as_field_element; let h_2_at_gamma = Self::get_eval(&evaluations, "h_2", gamma)?; let g_2_at_gamma = Self::get_eval(&evaluations, "g_2", gamma)?; let alpha_beta = alpha * beta; let a_val_at_gamma = Self::get_eval(&evaluations, "a_val", gamma)?; let a_row_at_gamma = Self::get_eval(&evaluations, "a_row", gamma)?; let a_col_at_gamma = Self::get_eval(&evaluations, "a_col", gamma)?; let a_row_col_at_gamma = Self::get_eval(&evaluations, "a_row_col", gamma)?; let a_denom_at_gamma = alpha_beta - alpha * a_row_at_gamma - beta * a_col_at_gamma + a_row_col_at_gamma; let b_val_at_gamma = Self::get_eval(&evaluations, "b_val", gamma)?; let b_row_at_gamma = Self::get_eval(&evaluations, "b_row", gamma)?; let b_col_at_gamma = Self::get_eval(&evaluations, "b_col", gamma)?; let b_row_col_at_gamma = Self::get_eval(&evaluations, "b_row_col", gamma)?; let b_denom_at_gamma = alpha_beta - alpha * b_row_at_gamma - beta * b_col_at_gamma + b_row_col_at_gamma; let c_val_at_gamma = Self::get_eval(&evaluations, "c_val", gamma)?; let c_row_at_gamma = Self::get_eval(&evaluations, "c_row", gamma)?; let c_col_at_gamma = Self::get_eval(&evaluations, "c_col", gamma)?; let c_row_col_at_gamma = Self::get_eval(&evaluations, "c_row_col", gamma)?; let c_denom_at_gamma = alpha_beta - alpha * c_row_at_gamma - beta * c_col_at_gamma + c_row_col_at_gamma; let mut a_at_gamma = eta_a * a_val_at_gamma * b_denom_at_gamma * c_denom_at_gamma + eta_b * b_val_at_gamma * c_denom_at_gamma * a_denom_at_gamma + eta_c * c_val_at_gamma * a_denom_at_gamma * b_denom_at_gamma; a_at_gamma *= v_h_at_alpha * v_h_at_beta; let b_at_gamma = a_denom_at_gamma * b_denom_at_gamma * c_denom_at_gamma; let lhs = h_2_at_gamma * v_k_at_gamma; let rhs = a_at_gamma - b_at_gamma * (gamma * g_2_at_gamma + t_at_beta / k_size); Ok(lhs == rhs) } fn get_eval(evals: &Evaluations<F>, label: &str, point: F) -> Result<F, Error> { let key = (label.to_string(), point); evals .get(&key) .map(|v| *v) .ok_or(Error::MissingEval(label.to_string())) } }
verifier_third_round
sys.rs
use { std::{ fmt, mem, }, }; pub use { fe_caps::*, fe_type::*, fe_sec_voltage::*, fe_sec_tone_mode::*, fe_sec_mini_cmd::*, fe_status::*, fe_spectral_inversion::*, fe_code_rate::*, fe_modulation::*, fe_transmit_mode::*, fe_guard_interval::*, fe_hierarchy::*, fe_interleaving::*, fe_pilot::*, fe_rolloff::*, fe_delivery_system::*, fecap_scale_params::*, dtv_property_cmd::*, }; /// Frontend capabilities mod fe_caps { /// There's something wrong at the frontend, and it can't report its capabilities pub const FE_IS_STUPID: u32 = 0; /// Can auto-detect frequency spectral band inversion pub const FE_CAN_INVERSION_AUTO: u32 = 0x1; /// Supports FEC 1/2 pub const FE_CAN_FEC_1_2: u32 = 0x2; /// Supports FEC 2/3 pub const FE_CAN_FEC_2_3: u32 = 0x4; /// Supports FEC 3/4 pub const FE_CAN_FEC_3_4: u32 = 0x8; /// Supports FEC 4/5 pub const FE_CAN_FEC_4_5: u32 = 0x10; /// Supports FEC 5/6 pub const FE_CAN_FEC_5_6: u32 = 0x20; /// Supports FEC 6/7 pub const FE_CAN_FEC_6_7: u32 = 0x40; /// Supports FEC 7/8 pub const FE_CAN_FEC_7_8: u32 = 0x80; /// Supports FEC 8/9 pub const FE_CAN_FEC_8_9: u32 = 0x100; /// Can auto-detect FEC pub const FE_CAN_FEC_AUTO: u32 = 0x200; /// Supports QPSK modulation pub const FE_CAN_QPSK: u32 = 0x400; /// Supports 16-QAM modulation pub const FE_CAN_QAM_16: u32 = 0x800; /// Supports 32-QAM modulation pub const FE_CAN_QAM_32: u32 = 0x1000; /// Supports 64-QAM modulation pub const FE_CAN_QAM_64: u32 = 0x2000; /// Supports 128-QAM modulation pub const FE_CAN_QAM_128: u32 = 0x4000; /// Supports 256-QAM modulation pub const FE_CAN_QAM_256: u32 = 0x8000; /// Can auto-detect QAM modulation pub const FE_CAN_QAM_AUTO: u32 = 0x10000; /// Can auto-detect transmission mode pub const FE_CAN_TRANSMISSION_MODE_AUTO: u32 = 0x20000; /// Can auto-detect bandwidth pub const FE_CAN_BANDWIDTH_AUTO: u32 = 0x40000; /// Can auto-detect guard interval pub const FE_CAN_GUARD_INTERVAL_AUTO: u32 = 0x80000; /// Can auto-detect hierarchy pub const FE_CAN_HIERARCHY_AUTO: u32 = 0x100000; /// Supports 8-VSB modulation pub const FE_CAN_8VSB: u32 = 0x200000; /// Supports 16-VSB modulation pub const FE_CAN_16VSB: u32 = 0x400000; /// Unused pub const FE_HAS_EXTENDED_CAPS: u32 = 0x800000; /// Supports multistream filtering pub const FE_CAN_MULTISTREAM: u32 = 0x4000000; /// Supports "turbo FEC" modulation pub const FE_CAN_TURBO_FEC: u32 = 0x8000000; /// Supports "2nd generation" modulation, e. g. DVB-S2, DVB-T2, DVB-C2 pub const FE_CAN_2G_MODULATION: u32 = 0x10000000; /// Unused pub const FE_NEEDS_BENDING: u32 = 0x20000000; /// Can recover from a cable unplug automatically pub const FE_CAN_RECOVER: u32 = 0x40000000; /// Can stop spurious TS data output pub const FE_CAN_MUTE_TS: u32 = 0x80000000; } /// DEPRECATED: Should be kept just due to backward compatibility mod fe_type { pub const FE_QPSK: u32 = 0; pub const FE_QAM: u32 = 1; pub const FE_OFDM: u32 = 2; pub const FE_ATSC: u32 = 3; } /// Frontend properties and capabilities /// The frequencies are specified in Hz for Terrestrial and Cable systems. /// The frequencies are specified in kHz for Satellite systems. #[repr(C)] #[derive(Debug)] pub struct FeInfo { /// Name of the frontend pub name: [std::os::raw::c_char; 128], /// DEPRECATED: frontend delivery system pub fe_type: u32, /// Minimal frequency supported by the frontend pub frequency_min: u32, /// Maximal frequency supported by the frontend pub frequency_max: u32, /// All frequencies are multiple of this value pub frequency_stepsize: u32, /// Frequency tolerance pub frequency_tolerance: u32, /// Minimal symbol rate, in bauds (for Cable/Satellite systems) pub symbol_rate_min: u32, /// Maximal symbol rate, in bauds (for Cable/Satellite systems) pub symbol_rate_max: u32, /// Maximal symbol rate tolerance, in ppm (for Cable/Satellite systems) pub symbol_rate_tolerance: u32, /// DEPRECATED pub notifier_delay: u32, /// Capabilities supported by the frontend pub caps: u32, } impl Default for FeInfo { #[inline] fn default() -> Self { unsafe { mem::zeroed::<Self>() } } } impl FeInfo { #[inline] pub fn as_mut_ptr(&mut self) -> *mut FeInfo { self as *mut _ } } /// DiSEqC master command /// Check out the DiSEqC bus spec available on http://www.eutelsat.org/ for /// the possible messages that can be used. #[repr(C)] #[derive(Debug)] pub struct DiseqcMasterCmd { /// DiSEqC message to be sent. It contains a 3 bytes header with: /// framing + address + command, and an optional argument /// of up to 3 bytes of data. pub msg: [u8; 6], /// Length of the DiSEqC message. Valid values are 3 to 6. pub len: u8, } impl Default for DiseqcMasterCmd { #[inline] fn default() -> Self { unsafe { mem::zeroed::<Self>() } } } /// DiSEqC received data #[repr(C)] #[derive(Debug)] pub struct DiseqcSlaveReply { /// DiSEqC message buffer to store a message received via DiSEqC. /// It contains one byte header with: framing and /// an optional argument of up to 3 bytes of data. pub msg: [u8; 4], /// Length of the DiSEqC message. Valid values are 0 to 4, /// where 0 means no message. pub len: u8, /// Return from ioctl after timeout ms with errorcode when /// no message was received. pub timeout: u32, } impl Default for DiseqcSlaveReply { #[inline] fn default() -> Self { unsafe { mem::zeroed::<Self>() } } } /// DC Voltage used to feed the LNBf mod fe_sec_voltage { /// Output 13V to the LNB. Vertical linear. Right circular. pub const SEC_VOLTAGE_13: u32 = 0; /// Output 18V to the LNB. Horizontal linear. Left circular. pub const SEC_VOLTAGE_18: u32 = 1; /// Don't feed the LNB with a DC voltage pub const SEC_VOLTAGE_OFF: u32 = 2; } mod fe_sec_tone_mode { /// Sends a 22kHz tone burst to the antenna pub const SEC_TONE_ON: u32 = 0; /// Don't send a 22kHz tone to the antenna (except if the FE_DISEQC_* ioctl are called) pub const SEC_TONE_OFF: u32 = 1; } /// Type of mini burst to be sent mod fe_sec_mini_cmd { /// Sends a mini-DiSEqC 22kHz '0' Tone Burst to select satellite-A pub const SEC_MINI_A: u32 = 0; /// Sends a mini-DiSEqC 22kHz '1' Data Burst to select satellite-B pub const SEC_MINI_B: u32 = 1; } /// Enumerates the possible frontend status mod fe_status { /// The frontend doesn't have any kind of lock. That's the initial frontend status pub const FE_NONE: u32 = 0x00; /// Has found something above the noise level pub const FE_HAS_SIGNAL: u32 = 0x01; /// Has found a signal pub const FE_HAS_CARRIER: u32 = 0x02; /// FEC inner coding (Viterbi, LDPC or other inner code) is stable. pub const FE_HAS_VITERBI: u32 = 0x04; /// Synchronization bytes was found pub const FE_HAS_SYNC: u32 = 0x08; /// Digital TV were locked and everything is working pub const FE_HAS_LOCK: u32 = 0x10; /// Fo lock within the last about 2 seconds pub const FE_TIMEDOUT: u32 = 0x20; /// Frontend was reinitialized, application is recommended /// to reset DiSEqC, tone and parameters pub const FE_REINIT: u32 = 0x40; } /// Spectral band inversion mod fe_spectral_inversion { pub const INVERSION_OFF: u32 = 0; pub const INVERSION_ON: u32 = 1; pub const INVERSION_AUTO: u32 = 2; } mod fe_code_rate { pub const FEC_NONE: u32 = 0; pub const FEC_1_2: u32 = 1; pub const FEC_2_3: u32 = 2; pub const FEC_3_4: u32 = 3; pub const FEC_4_5: u32 = 4; pub const FEC_5_6: u32 = 5; pub const FEC_6_7: u32 = 6; pub const FEC_7_8: u32 = 7; pub const FEC_8_9: u32 = 8; pub const FEC_AUTO: u32 = 9; pub const FEC_3_5: u32 = 10; pub const FEC_9_10: u32 = 11; pub const FEC_2_5: u32 = 12; pub const FEC_1_4: u32 = 13; pub const FEC_1_3: u32 = 14; } /// Type of modulation/constellation mod fe_modulation { pub const QPSK: u32 = 0; pub const QAM_16: u32 = 1; pub const QAM_32: u32 = 2; pub const QAM_64: u32 = 3; pub const QAM_128: u32 = 4; pub const QAM_256: u32 = 5; pub const QAM_AUTO: u32 = 6; pub const VSB_8: u32 = 7; pub const VSB_16: u32 = 8; pub const PSK_8: u32 = 9; pub const APSK_16: u32 = 10; pub const APSK_32: u32 = 11; pub const DQPSK: u32 = 12; pub const QAM_4_NR: u32 = 13; pub const APSK_64: u32 = 14; pub const APSK_128: u32 = 15; pub const APSK_256: u32 = 16; } mod fe_transmit_mode { pub const TRANSMISSION_MODE_2K: u32 = 0; pub const TRANSMISSION_MODE_8K: u32 = 1; pub const TRANSMISSION_MODE_AUTO: u32 = 2; pub const TRANSMISSION_MODE_4K: u32 = 3; pub const TRANSMISSION_MODE_1K: u32 = 4; pub const TRANSMISSION_MODE_16K: u32 = 5; pub const TRANSMISSION_MODE_32K: u32 = 6; pub const TRANSMISSION_MODE_C1: u32 = 7; pub const TRANSMISSION_MODE_C3780: u32 = 8; } mod fe_guard_interval { pub const GUARD_INTERVAL_1_32: u32 = 0; pub const GUARD_INTERVAL_1_16: u32 = 1; pub const GUARD_INTERVAL_1_8: u32 = 2; pub const GUARD_INTERVAL_1_4: u32 = 3; pub const GUARD_INTERVAL_AUTO: u32 = 4; pub const GUARD_INTERVAL_1_128: u32 = 5; pub const GUARD_INTERVAL_19_128: u32 = 6; pub const GUARD_INTERVAL_19_256: u32 = 7; pub const GUARD_INTERVAL_PN420: u32 = 8; pub const GUARD_INTERVAL_PN595: u32 = 9; pub const GUARD_INTERVAL_PN945: u32 = 10; } mod fe_hierarchy { pub const HIERARCHY_NONE: u32 = 0; pub const HIERARCHY_1: u32 = 1; pub const HIERARCHY_2: u32 = 2; pub const HIERARCHY_4: u32 = 3; pub const HIERARCHY_AUTO: u32 = 4; } mod fe_interleaving { pub const INTERLEAVING_NONE: u32 = 0; pub const INTERLEAVING_AUTO: u32 = 1; pub const INTERLEAVING_240: u32 = 2; pub const INTERLEAVING_720: u32 = 3; } mod fe_pilot { pub const PILOT_ON: u32 = 0; pub const PILOT_OFF: u32 = 1; pub const PILOT_AUTO: u32 = 2; } mod fe_rolloff { pub const ROLLOFF_35: u32 = 0; pub const ROLLOFF_20: u32 = 1; pub const ROLLOFF_25: u32 = 2; pub const ROLLOFF_AUTO: u32 = 3; pub const ROLLOFF_15: u32 = 4; pub const ROLLOFF_10: u32 = 5; pub const ROLLOFF_5: u32 = 6; } mod fe_delivery_system { use std::fmt; pub const SYS_UNDEFINED: u32 = 0; pub const SYS_DVBC_ANNEX_A: u32 = 1; pub const SYS_DVBC_ANNEX_B: u32 = 2; pub const SYS_DVBT: u32 = 3; pub const SYS_DSS: u32 = 4; pub const SYS_DVBS: u32 = 5; pub const SYS_DVBS2: u32 = 6; pub const SYS_DVBH: u32 = 7; pub const SYS_ISDBT: u32 = 8; pub const SYS_ISDBS: u32 = 9; pub const SYS_ISDBC: u32 = 10; pub const SYS_ATSC: u32 = 11; pub const SYS_ATSCMH: u32 = 12; pub const SYS_DTMB: u32 = 13; pub const SYS_CMMB: u32 = 14; pub const SYS_DAB: u32 = 15; pub const SYS_DVBT2: u32 = 16; pub const SYS_TURBO: u32 = 17; pub const SYS_DVBC_ANNEX_C: u32 = 18; pub const SYS_DVBC2: u32 = 19; pub struct DeliverySystemDisplay(pub u32); impl fmt::Display for DeliverySystemDisplay { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let v = match self.0 { SYS_UNDEFINED => "none", SYS_DVBC_ANNEX_A => "dvb-c", SYS_DVBC_ANNEX_B => "dvb-c/b", SYS_DVBT => "dvb-t", SYS_DSS => "dss", SYS_DVBS => "dvb-s", SYS_DVBS2 => "dvb-s2", SYS_DVBH => "dvb-h", SYS_ISDBT => "isdb-t", SYS_ISDBS => "isdb-s", SYS_ISDBC => "isdb-c", SYS_ATSC => "atsc", SYS_ATSCMH => "atsc-m/h", SYS_DTMB => "dtmb", SYS_CMMB => "cmmb", SYS_DAB => "dab", SYS_DVBT2 => "dvb-t2", SYS_TURBO => "dvb-s/turbo", SYS_DVBC_ANNEX_C => "dvb-c/c", SYS_DVBC2 => "dvb-c2", _ => "unknown", }; write!(f, "{}", v) } } } /// scale types for the quality parameters mod fecap_scale_params { /// That QoS measure is not available. That could indicate /// a temporary or a permanent condition. pub const FE_SCALE_NOT_AVAILABLE: u8 = 0; /// The scale is measured in 0.001 dB steps, typically used on signal measures. pub const FE_SCALE_DECIBEL: u8 = 1; /// The scale is a relative percentual measure, /// ranging from 0 (0%) to 0xffff (100%). pub const FE_SCALE_RELATIVE: u8 = 2; /// The scale counts the occurrence of an event, like /// bit error, block error, lapsed time. pub const FE_SCALE_COUNTER: u8 = 3; } /// Used for reading a DTV status property #[repr(C, packed)] #[derive(Copy, Clone)] pub struct DtvStats { pub scale: u8, // fecap_scale_params pub value: i64, } impl fmt::Debug for DtvStats { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut s = f.debug_struct("DtvStats"); const FIELD_SCALE: &str = "scale"; const FIELD_VALUE: &str = "value"; match self.scale { FE_SCALE_NOT_AVAILABLE => { s.field(FIELD_SCALE, &"FE_SCALE_NOT_AVAILABLE"); s.field(FIELD_VALUE, &"not available"); } FE_SCALE_DECIBEL => { s.field(FIELD_SCALE, &"FE_SCALE_DECIBEL"); s.field(FIELD_VALUE, &{(self.value as f64) / 1000.0}); } FE_SCALE_RELATIVE => { s.field(FIELD_SCALE, &"FE_SCALE_RELATIVE"); s.field(FIELD_VALUE, &{self.value as u64}); } FE_SCALE_COUNTER => { s.field(FIELD_SCALE, &"FE_SCALE_COUNTER"); s.field(FIELD_VALUE, &{self.value as u64}); } _ => { s.field(FIELD_SCALE, &{self.scale}); s.field(FIELD_VALUE, &"invalid scale format"); } }; s.finish() } } pub const MAX_DTV_STATS: usize = 4; /// Store Digital TV frontend statistics #[repr(C, packed)] #[derive(Copy, Clone)] pub struct DtvFrontendStats { pub len: u8, pub stat: [DtvStats; MAX_DTV_STATS], } impl fmt::Debug for DtvFrontendStats { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { let len = ::std::cmp::min(self.len as usize, self.stat.len()); f.debug_list().entries(self.stat[0 .. len].iter()).finish() } } #[repr(C)] #[derive(Copy, Clone)] pub struct DtvPropertyBuffer { pub data: [u8; 32], pub len: u32, __reserved_1: [u32; 3], __reserved_2: *mut std::ffi::c_void, } #[repr(C)] pub union DtvPropertyData { pub data: u32, pub st: DtvFrontendStats, pub buffer: DtvPropertyBuffer, __align: [u8; 56], } /// DVBv5 property Commands mod dtv_property_cmd { pub const DTV_UNDEFINED: u32 = 0; pub const DTV_TUNE: u32 = 1; pub const DTV_CLEAR: u32 = 2; pub const DTV_FREQUENCY: u32 = 3; pub const DTV_MODULATION: u32 = 4; pub const DTV_BANDWIDTH_HZ: u32 = 5; pub const DTV_INVERSION: u32 = 6; pub const DTV_DISEQC_MASTER: u32 = 7; pub const DTV_SYMBOL_RATE: u32 = 8; pub const DTV_INNER_FEC: u32 = 9; pub const DTV_VOLTAGE: u32 = 10; pub const DTV_TONE: u32 = 11; pub const DTV_PILOT: u32 = 12; pub const DTV_ROLLOFF: u32 = 13; pub const DTV_DISEQC_SLAVE_REPLY: u32 = 14; /* Basic enumeration set for querying unlimited capabilities */ pub const DTV_FE_CAPABILITY_COUNT: u32 = 15; pub const DTV_FE_CAPABILITY: u32 = 16; pub const DTV_DELIVERY_SYSTEM: u32 = 17; /* ISDB-T and ISDB-Tsb */ pub const DTV_ISDBT_PARTIAL_RECEPTION: u32 = 18; pub const DTV_ISDBT_SOUND_BROADCASTING: u32 = 19; pub const DTV_ISDBT_SB_SUBCHANNEL_ID: u32 = 20; pub const DTV_ISDBT_SB_SEGMENT_IDX: u32 = 21; pub const DTV_ISDBT_SB_SEGMENT_COUNT: u32 = 22; pub const DTV_ISDBT_LAYERA_FEC: u32 = 23; pub const DTV_ISDBT_LAYERA_MODULATION: u32 = 24; pub const DTV_ISDBT_LAYERA_SEGMENT_COUNT: u32 = 25; pub const DTV_ISDBT_LAYERA_TIME_INTERLEAVING: u32 = 26; pub const DTV_ISDBT_LAYERB_FEC: u32 = 27; pub const DTV_ISDBT_LAYERB_MODULATION: u32 = 28; pub const DTV_ISDBT_LAYERB_SEGMENT_COUNT: u32 = 29; pub const DTV_ISDBT_LAYERB_TIME_INTERLEAVING: u32 = 30; pub const DTV_ISDBT_LAYERC_FEC: u32 = 31; pub const DTV_ISDBT_LAYERC_MODULATION: u32 = 32; pub const DTV_ISDBT_LAYERC_SEGMENT_COUNT: u32 = 33; pub const DTV_ISDBT_LAYERC_TIME_INTERLEAVING: u32 = 34; pub const DTV_API_VERSION: u32 = 35; /* DVB-T/T2 */ pub const DTV_CODE_RATE_HP: u32 = 36; pub const DTV_CODE_RATE_LP: u32 = 37; pub const DTV_GUARD_INTERVAL: u32 = 38; pub const DTV_TRANSMISSION_MODE: u32 = 39; pub const DTV_HIERARCHY: u32 = 40; pub const DTV_ISDBT_LAYER_ENABLED: u32 = 41; pub const DTV_STREAM_ID: u32 = 42; pub const DTV_DVBT2_PLP_ID_LEGACY: u32 = 43; pub const DTV_ENUM_DELSYS: u32 = 44; /* ATSC-MH */ pub const DTV_ATSCMH_FIC_VER: u32 = 45; pub const DTV_ATSCMH_PARADE_ID: u32 = 46; pub const DTV_ATSCMH_NOG: u32 = 47; pub const DTV_ATSCMH_TNOG: u32 = 48; pub const DTV_ATSCMH_SGN: u32 = 49; pub const DTV_ATSCMH_PRC: u32 = 50; pub const DTV_ATSCMH_RS_FRAME_MODE: u32 = 51; pub const DTV_ATSCMH_RS_FRAME_ENSEMBLE: u32 = 52; pub const DTV_ATSCMH_RS_CODE_MODE_PRI: u32 = 53; pub const DTV_ATSCMH_RS_CODE_MODE_SEC: u32 = 54; pub const DTV_ATSCMH_SCCC_BLOCK_MODE: u32 = 55; pub const DTV_ATSCMH_SCCC_CODE_MODE_A: u32 = 56; pub const DTV_ATSCMH_SCCC_CODE_MODE_B: u32 = 57; pub const DTV_ATSCMH_SCCC_CODE_MODE_C: u32 = 58; pub const DTV_ATSCMH_SCCC_CODE_MODE_D: u32 = 59; pub const DTV_INTERLEAVING: u32 = 60; pub const DTV_LNA: u32 = 61; /* Quality parameters */ pub const DTV_STAT_SIGNAL_STRENGTH: u32 = 62; pub const DTV_STAT_CNR: u32 = 63; pub const DTV_STAT_PRE_ERROR_BIT_COUNT: u32 = 64; pub const DTV_STAT_PRE_TOTAL_BIT_COUNT: u32 = 65; pub const DTV_STAT_POST_ERROR_BIT_COUNT: u32 = 66; pub const DTV_STAT_POST_TOTAL_BIT_COUNT: u32 = 67; pub const DTV_STAT_ERROR_BLOCK_COUNT: u32 = 68; pub const DTV_STAT_TOTAL_BLOCK_COUNT: u32 = 69; /* Physical layer scrambling */ pub const DTV_SCRAMBLING_SEQUENCE_INDEX: u32 = 70; pub const DTV_INPUT: u32 = 71; } /// Store one of frontend command and its value #[repr(C, packed)] pub struct DtvProperty { pub cmd: u32, __reserved_1: [u32; 3], pub u: DtvPropertyData, pub result: i32, } impl fmt::Debug for DtvProperty { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut s = f.debug_struct("DtvProperty"); const FIELD_CMD: &str = "cmd"; const FIELD_DATA: &str = "data"; const FIELD_STATS: &str = "stats"; match self.cmd { DTV_FREQUENCY => { s.field(FIELD_CMD, &"DTV_FREQUENCY"); s.field(FIELD_DATA, unsafe { &self.u.data }); } DTV_MODULATION => { s.field(FIELD_CMD, &"DTV_MODULATION"); s.field(FIELD_DATA, unsafe { &self.u.data }); } DTV_BANDWIDTH_HZ => { s.field(FIELD_CMD, &"DTV_BANDWIDTH_HZ"); s.field(FIELD_DATA, unsafe { &self.u.data }); } DTV_INVERSION => { s.field(FIELD_CMD, &"DTV_INVERSION"); s.field(FIELD_DATA, unsafe { &self.u.data }); } DTV_SYMBOL_RATE => { s.field(FIELD_CMD, &"DTV_SYMBOL_RATE"); s.field(FIELD_DATA, unsafe { &self.u.data }); } DTV_INNER_FEC => { s.field(FIELD_CMD, &"DTV_INNER_FEC"); s.field(FIELD_DATA, unsafe { &self.u.data }); } DTV_PILOT => { s.field(FIELD_CMD, &"DTV_PILOT"); s.field(FIELD_DATA, unsafe { &self.u.data }); } DTV_ROLLOFF => { s.field(FIELD_CMD, &"DTV_ROLLOFF"); s.field(FIELD_DATA, unsafe { &self.u.data }); } DTV_DELIVERY_SYSTEM => { s.field(FIELD_CMD, &"DTV_DELIVERY_SYSTEM"); s.field(FIELD_DATA, unsafe { &self.u.data }); } DTV_API_VERSION => { s.field(FIELD_CMD, &"DTV_API_VERSION"); s.field(FIELD_DATA, unsafe { &self.u.data }); } /* Quality parameters */ DTV_STAT_SIGNAL_STRENGTH => { s.field(FIELD_CMD, &"DTV_STAT_SIGNAL_STRENGTH"); s.field(FIELD_STATS, unsafe { &self.u.st }); } DTV_STAT_CNR => { s.field(FIELD_CMD, &"DTV_STAT_CNR"); s.field(FIELD_STATS, unsafe { &self.u.st }); } DTV_STAT_PRE_ERROR_BIT_COUNT => { s.field(FIELD_CMD, &"DTV_STAT_PRE_ERROR_BIT_COUNT"); s.field(FIELD_STATS, unsafe { &self.u.st }); } DTV_STAT_PRE_TOTAL_BIT_COUNT => { s.field(FIELD_CMD, &"DTV_STAT_PRE_TOTAL_BIT_COUNT"); s.field(FIELD_STATS, unsafe { &self.u.st }); } DTV_STAT_POST_ERROR_BIT_COUNT => { s.field(FIELD_CMD, &"DTV_STAT_POST_ERROR_BIT_COUNT"); s.field(FIELD_STATS, unsafe { &self.u.st }); } DTV_STAT_POST_TOTAL_BIT_COUNT => { s.field(FIELD_CMD, &"DTV_STAT_POST_TOTAL_BIT_COUNT"); s.field(FIELD_STATS, unsafe { &self.u.st }); } DTV_STAT_ERROR_BLOCK_COUNT => { s.field(FIELD_CMD, &"DTV_STAT_ERROR_BLOCK_COUNT"); s.field(FIELD_STATS, unsafe { &self.u.st }); } DTV_STAT_TOTAL_BLOCK_COUNT => { s.field(FIELD_CMD, &"DTV_STAT_TOTAL_BLOCK_COUNT"); s.field(FIELD_STATS, unsafe { &self.u.st }); } // TODO: more values _ => {} } s.field("result", &{ self.result }); s.finish() } } impl DtvProperty { #[inline] pub fn new(cmd: u32, data: u32) -> Self { Self { cmd, __reserved_1: [0, 0, 0], u: DtvPropertyData { data }, result: 0, } } } pub const DTV_MAX_COMMAND: u32 = DTV_INPUT; /// num of properties cannot exceed DTV_IOCTL_MAX_MSGS per ioctl pub const DTV_IOCTL_MAX_MSGS: usize = 64; #[repr(C)] #[derive(Debug)] pub struct FeParameters { /// (absolute) frequency in Hz for DVB-C/DVB-T/ATSC /// intermediate frequency in kHz for DVB-S pub frequency: u32, pub inversion: u32, /// unimplemented frontend parameters data __reserved_1: [u8; 28], } pub const FE_MAX_EVENT: usize = 8; #[repr(C)] #[derive(Debug)] pub struct FeEvent { pub status: u32, pub parameters: FeParameters, } impl Default for FeEvent { #[inline] fn default() -> Self { unsafe { mem::zeroed::<Self>() } } } impl FeEvent { #[inline] pub fn as_mut_ptr(&mut self) -> *mut FeEvent { self as *mut _ } }
fmt
queueFromStacks.ts
// The video for this file: // https://youtu.be/f2FZbeb2hvo export interface Stack<T> { push(item: T): void; pop(): T; readonly length: number; } class
<T> { private in: Stack<T>; private out: Stack<T>; constructor() { this.in = []; this.out = []; } public enqueue(item: T): void { this.in.push(item); } public dequeue(): T{ this._moveToOutStackIfEmpty(); return this.out.pop(); } private _moveToOutStackIfEmpty(): void { if (this.out.length > 0){ return; } while(this.in.length > 0){ this.out.push(this.in.pop()); } } } const queue = new StackQueue<number>(); queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); queue.enqueue(4); queue.enqueue(5); queue.enqueue(6); console.log(queue.dequeue()); console.log(queue.dequeue()); console.log(queue.dequeue()); console.log(queue.dequeue()); console.log(queue.dequeue()); console.log(queue.dequeue());
StackQueue
hole_inliner.rs
use crate::{ analysis::GraphAnalysis, errors::Error, ir::traversal::{Action, Named, VisResult, Visitor}, ir::{self, LibrarySignatures}, passes::TopDownCompileControl, structure, }; use ir::RRC; use std::{collections::HashMap, rc::Rc}; #[derive(Default)] /// Removes all groups and inlines reads and writes from holes. /// /// After running this pass, there are no groups left in the `wires` section /// of the program. /// All remaining wires are continuous assignments which can be transformed /// into wires in a hardware description language. pub struct HoleInliner; impl Named for HoleInliner { fn name() -> &'static str { "hole-inliner" } fn description() -> &'static str { "inlines holes" } } type Store = HashMap<(ir::Id, ir::Id), (RRC<ir::Port>, ir::Guard)>; /// Finds the 'fixed_point' of a map from Hole names to guards under the /// inlining operation. The map contains entries like: /// ``` /// A[go] -> some_thing & B[go] & !A[done] /// B[go] -> C[go] /// C[go] -> go /// ... /// ```
/// We want to transform this so that the guard expression for every /// hole does not itself contain holes. /// /// We compute the fixed point using a worklist algorithm. /// Variables: /// - `guard(x)`: refers to the guard of the hole `x` /// - `worklist`: a queue that contains fully inlined guards that have not yet been inlined into other guards /// /// Algorithm: /// - `worklist` is initialized to be all the holes that contain no holes in their guards. /// - while there are things in `worklist`: /// - pop a hole, `H`, from `worklist` /// - for every hole, `a` that reads from `H` /// - replace all instances of `H` in `guard(a)` with `guard(H)` /// - if no holes in `guard(a)`, add to `worklist` fn fixed_point(graph: &GraphAnalysis, map: &mut Store) { // keeps track of next holes we can inline let mut worklist = Vec::new(); // helper to check if a guard has holes let has_holes = |guard: &ir::Guard| { guard .all_ports() .iter() .map(|p| p.borrow().is_hole()) .any(|e| e) }; // initialize the worklist to have guards that have no holes for (key, (_, guard)) in map.iter() { if !has_holes(guard) { worklist.push(key.clone()) } } while !worklist.is_empty() { let hole_key = worklist.pop().unwrap_or_else(|| unreachable!()); let (hole, new_guard) = map[&hole_key].clone(); // for every read from the hole for read in graph .reads_from(&hole.borrow()) .filter(|p| p.borrow().is_hole()) { // inline `hole_key` into `read` let key = read.borrow().canonical(); map.entry(read.borrow().canonical()) .and_modify(|(_, guard)| { guard.for_each(&mut |port| { if port.borrow().canonical() == hole_key { Some(new_guard.clone()) } else { None } }) }); // if done with this guard, add it to the worklist if !has_holes(&map[&key].1) { worklist.push(key) } } } } impl Visitor for HoleInliner { fn start( &mut self, comp: &mut ir::Component, sigs: &LibrarySignatures, _comps: &[ir::Component], ) -> VisResult { // get the only group in the enable let top_level = match &*comp.control.borrow() { ir::Control::Empty(_) => return Ok(Action::Stop), ir::Control::Enable(en) => Rc::clone(&en.group), _ => return Err(Error::malformed_control(format!( "{}: Control shoudl be a single enable. Try running `{}` before inlining.", Self::name(), TopDownCompileControl::name())) ) }; let this_comp = Rc::clone(&comp.signature); let mut builder = ir::Builder::new(comp, sigs); // add top_level[go] = this.go let mut asgns = vec![ builder.build_assignment( top_level.borrow().get("go"), this_comp.borrow().get_with_attr("go"), ir::Guard::True, ), builder.build_assignment( this_comp.borrow().get_with_attr("done"), top_level.borrow().get("done"), ir::Guard::True, ), ]; builder.component.continuous_assignments.append(&mut asgns); // construct analysis graph and find sub-graph of all edges that include a hole let analysis = GraphAnalysis::from(&*builder.component); let subgraph = analysis .edge_induced_subgraph(|src, dst| src.is_hole() || dst.is_hole()); // if subgraph has cycles, error out if subgraph.has_cycles() { // XXX use topo sort to find where the cycle is return Err(Error::malformed_structure( "Cyclic hole definition.".to_string(), )); } // map of holes to their guard expressions let mut map: Store = HashMap::new(); let mut assignments = vec![]; for group in builder.component.groups.iter() { // remove all assignments from group, taking ownership let mut group = group.borrow_mut(); assignments.append(&mut group.assignments.drain(..).collect()); } // add the continuous assignment edges assignments.append( &mut builder.component.continuous_assignments.drain(..).collect(), ); for asgn in &mut assignments { // if assignment writes into a hole, save it let dst = asgn.dst.borrow(); if dst.is_hole() { map.entry(dst.canonical()) .and_modify(|(_, val)| { // XXX: seems like unncessary clone *val = val.clone().or(asgn .guard .clone() .and(ir::Guard::port(Rc::clone(&asgn.src)))); }) .or_insert(( Rc::clone(&asgn.dst), asgn.guard .clone() .and(ir::Guard::port(Rc::clone(&asgn.src))), )); } } // find fixed point of map fixed_point(&subgraph, &mut map); // remove edges that write to a hole assignments.retain(|asgn| !asgn.dst.borrow().is_hole()); // move direct reads from holes into the guard so they can be inlined // e.g. s.in = G[go]; => s.in G[go] ? 1'b1; structure!( builder; let signal_on = constant(1, 1); ); assignments.iter_mut().for_each(|mut asgn| { if asgn.src.borrow().is_hole() { let and_guard = ir::Guard::port(Rc::clone(&asgn.src)); *asgn.guard &= and_guard; asgn.src = signal_on.borrow().get("out"); } }); // replace reads from a hole with the value in the map for asgn in &mut assignments { asgn.guard.for_each(&mut |port| { if port.borrow().is_hole() { Some(map[&port.borrow().canonical()].1.clone()) } else { None } }) } comp.continuous_assignments = assignments; // remove all groups comp.groups.clear(); // remove group from control Ok(Action::Change(ir::Control::empty())) } }
runtime.rs
use sailar_get::loader::{Identifier, Symbol}; use sailar_vm::interpreter; mod setup; macro_rules! basic_module_str { ($name: ident, $contents: expr) => {{ use sailar::format::FormatVersion; &format!( ".module {{ .name \"{}\"; }};\n.format {{ .major {}; .minor {}; }};\n{}", stringify!($name), FormatVersion::minimum_supported_version().major, FormatVersion::minimum_supported_version().minor, $contents ) }}; } #[test] fn returns_exit_code() { setup::initialize_from_str( include_str!(r"../../sailas/samples/return.txtmdl"), |_, _| (), |_, runtime| assert_eq!(0, runtime.invoke_entry_point(&[], None).unwrap()), ); } #[test] fn successful_function_symbol_lookup() { setup::initialize_from_str( basic_module_str!( SymbolTest, r#" .code @code { .entry $BLOCK; .block $BLOCK () { ret; }; }; .function @Helper () returns () export { .name "unused"; .body defined @code; }; "# ), |_, _| (), |_, runtime| { assert!(runtime .program() .lookup_function(Symbol::Owned(Identifier::try_from("Helper").unwrap())) .is_some()) }, ); } #[test] fn call_stack_overflow() { setup::initialize_from_str( basic_module_str!( StackOverflowTest, r#" .code @code { .entry $BLOCK; .block $BLOCK () { call @exploder; ret; }; }; .function @exploder () returns () export { .name "boom"; .body defined @code; }; .entry @exploder; "# ), |_, _| (), |_, runtime| match runtime.invoke_entry_point(&[], None) { Err(sailar_vm::runtime::Error::InterpreterError(error)) => match error.kind() { interpreter::ErrorKind::CallStackOverflow(capacity) => { assert_eq!(error.stack_trace().len(), capacity.get()) } error => panic!("unexpected error kind {:?}", error), }, result => panic!("unexpected result {:?}", result), }, ); } #[test] fn breakpoints_are_set_during_pause()
#[test] fn conditional_branching_is_correct() { setup::initialize_from_str( basic_module_str!( IfTest, r#" .code @code { .entry $BLOCK; .block $BLOCK (%i_input) { br.if %i_input then $RET_GOOD else $RET_BAD; }; .block $RET_GOOD () { %t_result = const.i s32 61453; ret %t_result; }; .block $RET_BAD () { %t_result = const.i s32 2989; ret %t_result; }; }; .function @test (s32) returns (s32) export { .name "test"; .body defined @code; }; "# ), |_, _| (), |_, runtime| { let test_function = runtime .program() .lookup_function(Symbol::Owned(Identifier::try_from("test").unwrap())) .unwrap(); let mut arguments = [interpreter::Register::from(5i32)]; assert_eq!( vec![interpreter::Register::from(0xF00Di32)], runtime.invoke(test_function, &arguments, None).unwrap() ); arguments[0] = interpreter::Register::from(0i32); assert_eq!( vec![interpreter::Register::from(0xBADi32)], runtime.invoke(test_function, &arguments, None).unwrap() ); }, ); } #[test] fn switch_is_correct() { setup::initialize_from_str( basic_module_str!( SwitchTest, r#" .code @code { .entry $BLOCK; .block $BLOCK (%i_input) { switch s32 %i_input default $BRANCH_DEFAULT or 1 $BRANCH_ONE or 3 $BRANCH_THREE; }; .block $BRANCH_ONE () { %t_result = const.i s32 100; ret %t_result; }; .block $BRANCH_THREE () { %t_result = const.i s32 333; ret %t_result; }; .block $BRANCH_DEFAULT () { %t_result = const.i s32 0; ret %t_result; }; }; .function @test (s32) returns (s32) export { .name "test"; .body defined @code; }; "# ), |_, _| (), |_, runtime| { let test_function = runtime .program() .lookup_function(Symbol::Owned(Identifier::try_from("test").unwrap())) .unwrap(); let mut arguments = [interpreter::Register::from(1i32)]; assert_eq!( vec![interpreter::Register::from(100i32)], runtime.invoke(test_function, &arguments, None).unwrap() ); arguments[0] = interpreter::Register::from(3i32); assert_eq!( vec![interpreter::Register::from(333i32)], runtime.invoke(test_function, &arguments, None).unwrap() ); arguments[0] = interpreter::Register::from(4i32); assert_eq!( vec![interpreter::Register::from(0i32)], runtime.invoke(test_function, &arguments, None).unwrap() ); }, ); } #[test] fn integer_conversions_are_correct() { setup::initialize_from_str( basic_module_str!( IntegerConversions, r#" .code @code { .entry $BLOCK; .block $BLOCK (%i_input) { %s8 = conv.i %i_input to s8; %u8 = conv.i %i_input to u8; %s16 = conv.i %i_input to s16; %u16 = conv.i %i_input to u16; %u32 = conv.i %i_input to u32; %s64 = conv.i %i_input to s64; %u64 = conv.i %i_input to u64; ret %s8, %u8, %s16, %u16, %u32, %s64, %u64; }; }; .function @convert_int (s32) returns (s8, u8, s16, u16, u32, s64, u64) export { .name "convert_int"; .body defined @code; }; "# ), |_, _| (), |_, runtime| { let test_function = runtime .program() .lookup_function(Symbol::Owned(Identifier::try_from("convert_int").unwrap())) .unwrap(); assert_eq!( vec![ interpreter::Register::from(-1i8), interpreter::Register::from(u8::MAX), interpreter::Register::from(-1i16), interpreter::Register::from(u16::MAX), interpreter::Register::from(u32::MAX), interpreter::Register::from(-1i64), interpreter::Register::from(u64::MAX), ], runtime .invoke(test_function, &[interpreter::Register::from(-1i32)], None) .unwrap() ); }, ); } #[test] fn integer_comparisons_are_correct() { setup::initialize_from_str( basic_module_str!( IntegerComparisons, r#" .code @code { .entry $BLOCK; .block $BLOCK (%i_input) { %t_y = const.i s32 8; %t_eq = cmp %i_input eq %t_y; %t_ne = cmp %i_input ne %t_y; %t_lt = cmp %i_input lt %t_y; %t_gt = cmp %i_input gt %t_y; %t_le = cmp %i_input le %t_y; %t_ge = cmp %i_input ge %t_y; ret %t_eq, %t_ne, %t_lt, %t_gt, %t_le, %t_ge; }; }; .function @test (s32) returns (u8, u8, u8, u8, u8, u8) export { .name "test"; .body defined @code; }; "# ), |_, _| (), |_, runtime| { let test_function = runtime .program() .lookup_function(Symbol::Owned(Identifier::try_from("test").unwrap())) .unwrap(); macro_rules! assert_call_results { ($input: expr, $outputs: expr) => { assert_eq!( { let values: &[u8] = &$outputs; values .iter() .copied() .map(interpreter::Register::from) .collect::<Vec<_>>() }, runtime .invoke(test_function, &[i32::into($input)], None) .unwrap() ); }; } assert_call_results!(-1, [0, 1, 1, 0, 1, 0,]); assert_call_results!(8, [1, 0, 0, 0, 1, 1,]); assert_call_results!(0x80, [0, 1, 0, 1, 0, 1,]); }, ); }
{ #[derive(Default)] struct CollectedData { value_1: Option<i32>, value_2: Option<i32>, } setup::initialize_from_str( basic_module_str!( BreakpointTest, r#" .code @code { .entry $BLOCK; .block $BLOCK () { %t_ignored = const.i s32 5; %t_exit = const.i s32 42; ret %t_exit; }; }; .function @test () returns (s32) { .name "ThisIsAVeryLongTestOfThingsToSeeIfTheyWillFitAndAllThatYouKnow"; .body defined @code; }; .entry @test; "# ), |program, _| { let program_name = program.header.0.identifier.clone(); let returned_data = std::rc::Rc::new(std::cell::RefCell::new(CollectedData::default())); let mut pause_count = 0u8; let data = returned_data.clone(); let debugger = move |interpreter: &mut interpreter::Interpreter| { use interpreter::debugger; let call_stack = interpreter.call_stack(); let trace = call_stack.stack_trace(); let reply = match pause_count { 0 => { call_stack .breakpoints_mut() .insert(debugger::Breakpoint::new_owned( debugger::BlockIndex::entry(), 1, program_name.clone(), sailar::format::Identifier::try_from("test").unwrap(), )); debugger::Reply::Continue } 1 => { call_stack .breakpoints_mut() .insert(debugger::Breakpoint::with_symbol( debugger::BlockIndex::entry(), 2, trace[0].function().clone(), )); data.borrow_mut().value_1 = Some(i32::try_from(&trace[0].temporary_registers()[0]).unwrap()); debugger::Reply::Continue } 2.. => { data.borrow_mut().value_2 = Some(i32::try_from(&trace[0].temporary_registers()[1]).unwrap()); debugger::Reply::Detach } }; pause_count += 1; reply }; (returned_data, debugger) }, |(data, debugger), runtime| { assert_eq!(42, runtime.invoke_entry_point(&[], Some(debugger)).unwrap()); assert_eq!(Some(5), data.borrow().value_1); assert_eq!(Some(42), data.borrow().value_2); }, ); }
crypto.rs
use crate::core_arch::arm::{uint32x4_t, uint8x16_t}; #[allow(improper_ctypes)] extern "C" { #[link_name = "llvm.aarch64.crypto.aese"] fn vaeseq_u8_(data: uint8x16_t, key: uint8x16_t) -> uint8x16_t; #[link_name = "llvm.aarch64.crypto.aesd"] fn vaesdq_u8_(data: uint8x16_t, key: uint8x16_t) -> uint8x16_t; #[link_name = "llvm.aarch64.crypto.aesmc"] fn vaesmcq_u8_(data: uint8x16_t) -> uint8x16_t; #[link_name = "llvm.aarch64.crypto.aesimc"] fn vaesimcq_u8_(data: uint8x16_t) -> uint8x16_t; #[link_name = "llvm.aarch64.crypto.sha1h"] fn vsha1h_u32_(hash_e: u32) -> u32; #[link_name = "llvm.aarch64.crypto.sha1su0"] fn vsha1su0q_u32_(w0_3: uint32x4_t, w4_7: uint32x4_t, w8_11: uint32x4_t) -> uint32x4_t; #[link_name = "llvm.aarch64.crypto.sha1su1"] fn vsha1su1q_u32_(tw0_3: uint32x4_t, w12_15: uint32x4_t) -> uint32x4_t; #[link_name = "llvm.aarch64.crypto.sha1c"] fn vsha1cq_u32_(hash_abcd: uint32x4_t, hash_e: u32, wk: uint32x4_t) -> uint32x4_t; #[link_name = "llvm.aarch64.crypto.sha1p"] fn vsha1pq_u32_(hash_abcd: uint32x4_t, hash_e: u32, wk: uint32x4_t) -> uint32x4_t; #[link_name = "llvm.aarch64.crypto.sha1m"] fn vsha1mq_u32_(hash_abcd: uint32x4_t, hash_e: u32, wk: uint32x4_t) -> uint32x4_t; #[link_name = "llvm.aarch64.crypto.sha256h"] fn vsha256hq_u32_(hash_abcd: uint32x4_t, hash_efgh: uint32x4_t, wk: uint32x4_t) -> uint32x4_t; #[link_name = "llvm.aarch64.crypto.sha256h2"] fn vsha256h2q_u32_(hash_efgh: uint32x4_t, hash_abcd: uint32x4_t, wk: uint32x4_t) -> uint32x4_t; #[link_name = "llvm.aarch64.crypto.sha256su0"] fn vsha256su0q_u32_(w0_3: uint32x4_t, w4_7: uint32x4_t) -> uint32x4_t; #[link_name = "llvm.aarch64.crypto.sha256su1"] fn vsha256su1q_u32_(tw0_3: uint32x4_t, w8_11: uint32x4_t, w12_15: uint32x4_t) -> uint32x4_t; } #[cfg(test)] use stdsimd_test::assert_instr; /// AES single round encryption. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(aese))] pub unsafe fn vaeseq_u8(data: uint8x16_t, key: uint8x16_t) -> uint8x16_t { vaeseq_u8_(data, key) } /// AES single round decryption. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(aesd))] pub unsafe fn vaesdq_u8(data: uint8x16_t, key: uint8x16_t) -> uint8x16_t { vaesdq_u8_(data, key) } /// AES mix columns. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(aesmc))] pub unsafe fn vaesmcq_u8(data: uint8x16_t) -> uint8x16_t
/// AES inverse mix columns. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(aesimc))] pub unsafe fn vaesimcq_u8(data: uint8x16_t) -> uint8x16_t { vaesimcq_u8_(data) } /// SHA1 fixed rotate. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha1h))] pub unsafe fn vsha1h_u32(hash_e: u32) -> u32 { vsha1h_u32_(hash_e) } /// SHA1 hash update accelerator, choose. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha1c))] pub unsafe fn vsha1cq_u32(hash_abcd: uint32x4_t, hash_e: u32, wk: uint32x4_t) -> uint32x4_t { vsha1cq_u32_(hash_abcd, hash_e, wk) } /// SHA1 hash update accelerator, majority. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha1m))] pub unsafe fn vsha1mq_u32(hash_abcd: uint32x4_t, hash_e: u32, wk: uint32x4_t) -> uint32x4_t { vsha1mq_u32_(hash_abcd, hash_e, wk) } /// SHA1 hash update accelerator, parity. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha1p))] pub unsafe fn vsha1pq_u32(hash_abcd: uint32x4_t, hash_e: u32, wk: uint32x4_t) -> uint32x4_t { vsha1pq_u32_(hash_abcd, hash_e, wk) } /// SHA1 schedule update accelerator, first part. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha1su0))] pub unsafe fn vsha1su0q_u32(w0_3: uint32x4_t, w4_7: uint32x4_t, w8_11: uint32x4_t) -> uint32x4_t { vsha1su0q_u32_(w0_3, w4_7, w8_11) } /// SHA1 schedule update accelerator, second part. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha1su1))] pub unsafe fn vsha1su1q_u32(tw0_3: uint32x4_t, w12_15: uint32x4_t) -> uint32x4_t { vsha1su1q_u32_(tw0_3, w12_15) } /// SHA256 hash update accelerator. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha256h))] pub unsafe fn vsha256hq_u32( hash_abcd: uint32x4_t, hash_efgh: uint32x4_t, wk: uint32x4_t, ) -> uint32x4_t { vsha256hq_u32_(hash_abcd, hash_efgh, wk) } /// SHA256 hash update accelerator, upper part. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha256h2))] pub unsafe fn vsha256h2q_u32( hash_efgh: uint32x4_t, hash_abcd: uint32x4_t, wk: uint32x4_t, ) -> uint32x4_t { vsha256h2q_u32_(hash_efgh, hash_abcd, wk) } /// SHA256 schedule update accelerator, first part. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha256su0))] pub unsafe fn vsha256su0q_u32(w0_3: uint32x4_t, w4_7: uint32x4_t) -> uint32x4_t { vsha256su0q_u32_(w0_3, w4_7) } /// SHA256 schedule update accelerator, second part. #[inline] #[target_feature(enable = "crypto")] #[cfg_attr(test, assert_instr(sha256su1))] pub unsafe fn vsha256su1q_u32( tw0_3: uint32x4_t, w8_11: uint32x4_t, w12_15: uint32x4_t, ) -> uint32x4_t { vsha256su1q_u32_(tw0_3, w8_11, w12_15) } #[cfg(test)] mod tests { use crate::core_arch::{aarch64::*, simd::*}; use std::mem; use stdsimd_test::simd_test; #[simd_test(enable = "crypto")] unsafe fn test_vaeseq_u8() { let data = ::mem::transmute(u8x16::new(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8)); let key = ::mem::transmute(u8x16::new(0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7)); let r: u8x16 = ::mem::transmute(vaeseq_u8(data, key)); assert_eq!( r, u8x16::new( 124, 123, 124, 118, 124, 123, 124, 197, 124, 123, 124, 118, 124, 123, 124, 197 ) ); } #[simd_test(enable = "crypto")] unsafe fn test_vaesdq_u8() { let data = ::mem::transmute(u8x16::new(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8)); let key = ::mem::transmute(u8x16::new(0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7)); let r: u8x16 = ::mem::transmute(vaesdq_u8(data, key)); assert_eq!( r, u8x16::new(9, 213, 9, 251, 9, 213, 9, 56, 9, 213, 9, 251, 9, 213, 9, 56) ); } #[simd_test(enable = "crypto")] unsafe fn test_vaesmcq_u8() { let data = ::mem::transmute(u8x16::new(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8)); let r: u8x16 = ::mem::transmute(vaesmcq_u8(data)); assert_eq!( r, u8x16::new(3, 4, 9, 10, 15, 8, 21, 30, 3, 4, 9, 10, 15, 8, 21, 30) ); } #[simd_test(enable = "crypto")] unsafe fn test_vaesimcq_u8() { let data = ::mem::transmute(u8x16::new(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8)); let r: u8x16 = ::mem::transmute(vaesimcq_u8(data)); assert_eq!( r, u8x16::new(43, 60, 33, 50, 103, 80, 125, 70, 43, 60, 33, 50, 103, 80, 125, 70) ); } #[simd_test(enable = "crypto")] unsafe fn test_vsha1h_u32() { assert_eq!(vsha1h_u32(0x1234), 0x048d); assert_eq!(vsha1h_u32(0x5678), 0x159e); } #[simd_test(enable = "crypto")] unsafe fn test_vsha1su0q_u32() { let r: u32x4 = ::mem::transmute(vsha1su0q_u32( ::mem::transmute(u32x4::new(0x1234_u32, 0x5678_u32, 0x9abc_u32, 0xdef0_u32)), ::mem::transmute(u32x4::new(0x1234_u32, 0x5678_u32, 0x9abc_u32, 0xdef0_u32)), ::mem::transmute(u32x4::new(0x1234_u32, 0x5678_u32, 0x9abc_u32, 0xdef0_u32)), )); assert_eq!(r, u32x4::new(0x9abc, 0xdef0, 0x1234, 0x5678)); } #[simd_test(enable = "crypto")] unsafe fn test_vsha1su1q_u32() { let r: u32x4 = ::mem::transmute(vsha1su1q_u32( ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), )); assert_eq!( r, u32x4::new(0x00008898, 0x00019988, 0x00008898, 0x0000acd0) ); } #[simd_test(enable = "crypto")] unsafe fn test_vsha1cq_u32() { let r: u32x4 = ::mem::transmute(vsha1cq_u32( ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), 0x1234, ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), )); assert_eq!( r, u32x4::new(0x8a32cbd8, 0x0c518a96, 0x0018a081, 0x0000c168) ); } #[simd_test(enable = "crypto")] unsafe fn test_vsha1pq_u32() { let r: u32x4 = ::mem::transmute(vsha1pq_u32( ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), 0x1234, ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), )); assert_eq!( r, u32x4::new(0x469f0ba3, 0x0a326147, 0x80145d7f, 0x00009f47) ); } #[simd_test(enable = "crypto")] unsafe fn test_vsha1mq_u32() { let r: u32x4 = ::mem::transmute(vsha1mq_u32( ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), 0x1234, ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), )); assert_eq!( r, u32x4::new(0xaa39693b, 0x0d51bf84, 0x001aa109, 0x0000d278) ); } #[simd_test(enable = "crypto")] unsafe fn test_vsha256hq_u32() { let r: u32x4 = ::mem::transmute(vsha256hq_u32( ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), )); assert_eq!( r, u32x4::new(0x05e9aaa8, 0xec5f4c02, 0x20a1ea61, 0x28738cef) ); } #[simd_test(enable = "crypto")] unsafe fn test_vsha256h2q_u32() { let r: u32x4 = ::mem::transmute(vsha256h2q_u32( ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), )); assert_eq!( r, u32x4::new(0x3745362e, 0x2fb51d00, 0xbd4c529b, 0x968b8516) ); } #[simd_test(enable = "crypto")] unsafe fn test_vsha256su0q_u32() { let r: u32x4 = ::mem::transmute(vsha256su0q_u32( ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), )); assert_eq!( r, u32x4::new(0xe59e1c97, 0x5eaf68da, 0xd7bcb51f, 0x6c8de152) ); } #[simd_test(enable = "crypto")] unsafe fn test_vsha256su1q_u32() { let r: u32x4 = ::mem::transmute(vsha256su1q_u32( ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), ::mem::transmute(u32x4::new(0x1234, 0x5678, 0x9abc, 0xdef0)), )); assert_eq!( r, u32x4::new(0x5e09e8d2, 0x74a6f16b, 0xc966606b, 0xa686ee9f) ); } }
{ vaesmcq_u8_(data) }
currencies.go
package main import ( "context" "fmt" "github.com/mikejoh/coinbase-go" "github.com/spf13/cobra" ) // currenciesCmd represents the subcommand for `cb currencies` var currenciesCmd = &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error { client := coinbase.NewClient(coinbase.NewConfig()) ctx := context.Background() c, err := client.Currencies(ctx) if err != nil { return err } if rootOpts.json { json, err := PrettyPrint(c) if err != nil { return err } fmt.Printf("%s \n", json) return nil } fmt.Println(c.String()) return nil }, } func init() { rootCmd.AddCommand(currenciesCmd) }
Use: "currencies", Short: "Lists the supported currencies.", SilenceUsage: true, SilenceErrors: true,
pod.rs
use super::{ super::akri::API_NAMESPACE, OwnershipInfo, ERROR_CONFLICT, ERROR_NOT_FOUND, NODE_SELECTOR_OP_IN, OBJECT_NAME_FIELD, RESOURCE_REQUIREMENTS_KEY, }; use either::Either; use k8s_openapi::api::core::v1::{ Affinity, NodeAffinity, NodeSelector, NodeSelectorRequirement, NodeSelectorTerm, Pod, PodSpec, ResourceRequirements, }; use k8s_openapi::apimachinery::pkg::api::resource::Quantity; use k8s_openapi::apimachinery::pkg::apis::meta::v1::{ObjectMeta, OwnerReference}; use kube::{ api::{Api, DeleteParams, ListParams, ObjectList, PostParams}, client::Client, }; use log::{error, info, trace}; use std::collections::BTreeMap; pub const APP_LABEL_ID: &str = "app"; pub const CONTROLLER_LABEL_ID: &str = "controller"; pub const AKRI_CONFIGURATION_LABEL_NAME: &str = "akri.sh/configuration"; pub const AKRI_INSTANCE_LABEL_NAME: &str = "akri.sh/instance"; pub const AKRI_TARGET_NODE_LABEL_NAME: &str = "akri.sh/target-node"; /// Get Kubernetes Pods with a given label or field selector /// /// Example: /// /// ```no_run /// use akri_shared::k8s::pod; /// use kube::client::Client; /// use kube::config; /// /// # #[tokio::main] /// # async fn main() { /// let label_selector = Some("environment=production,app=nginx".to_string()); /// let api_client = Client::try_default().await.unwrap(); /// for pod in pod::find_pods_with_selector(label_selector, None, api_client).await.unwrap() { /// println!("found pod: {}", pod.metadata.name.unwrap()) /// } /// # } /// ``` /// /// ```no_run /// use akri_shared::k8s::pod; /// use kube::client::Client; /// use kube::config; /// /// # #[tokio::main] /// # async fn main() { /// let field_selector = Some("spec.nodeName=node-a".to_string()); /// let api_client = Client::try_default().await.unwrap(); /// for pod in pod::find_pods_with_selector(None, field_selector, api_client).await.unwrap() { /// println!("found pod: {}", pod.metadata.name.unwrap()) /// } /// # } /// ``` pub async fn find_pods_with_selector( label_selector: Option<String>, field_selector: Option<String>, kube_client: Client, ) -> Result<ObjectList<Pod>, anyhow::Error> { trace!( "find_pods_with_selector with label_selector={:?} field_selector={:?}", &label_selector, &field_selector ); let pods: Api<Pod> = Api::all(kube_client); let pod_list_params = ListParams { label_selector, field_selector, ..Default::default() }; trace!("find_pods_with_selector PRE pods.list(...).await?"); let result = pods.list(&pod_list_params).await; trace!("find_pods_with_selector return"); Ok(result?) } /// Create name for Kubernetes Pod. /// /// Example: /// /// ```no_run /// use akri_shared::k8s::pod; /// /// let svc_name = pod::create_broker_app_name( /// "capability_config", /// Some("node-a"), /// true, /// "pod"); /// ``` pub fn create_broker_app_name( instance_name: &str, node_to_run_broker_on: Option<&str>, capability_is_shared: bool, app_name_suffix: &str, ) -> String { let normalized_instance_name = instance_name.replace('.', "-"); if capability_is_shared { // If the device capability is shared, the instance name will not contain any // node-specific content. To ensure uniqueness of the Pod/Job we are creating, // prepend the node name here. match node_to_run_broker_on { Some(n) => format!("{}-{}-{}", n, normalized_instance_name, app_name_suffix), None => format!("{}-{}", normalized_instance_name, app_name_suffix), } } else
} type ResourceQuantityType = BTreeMap<String, Quantity>; /// Create Kubernetes Pod based on Device Capabililty Instance & Config. /// /// Example: /// /// ```no_run /// use akri_shared::k8s::{ /// OwnershipInfo, /// OwnershipType, /// pod /// }; /// use kube::client::Client; /// use kube::config; /// use k8s_openapi::api::core::v1::PodSpec; /// /// # #[tokio::main] /// # async fn main() { /// let api_client = Client::try_default().await.unwrap(); /// let svc = pod::create_new_pod_from_spec( /// "pod_namespace", /// "capability_instance", /// "capability_config", /// OwnershipInfo::new( /// OwnershipType::Instance, /// "capability_instance".to_string(), /// "instance_uid".to_string() /// ), /// "akri.sh/capability_name", /// "node-a", /// true, /// &PodSpec::default()).unwrap(); /// # } /// ``` #[allow(clippy::too_many_arguments)] pub fn create_new_pod_from_spec( pod_namespace: &str, instance_name: &str, configuration_name: &str, ownership: OwnershipInfo, resource_limit_name: &str, node_to_run_pod_on: &str, capability_is_shared: bool, pod_spec: &PodSpec, ) -> anyhow::Result<Pod> { trace!("create_new_pod_from_spec enter"); let app_name = create_broker_app_name( instance_name, Some(node_to_run_pod_on), capability_is_shared, "pod", ); let mut labels: BTreeMap<String, String> = BTreeMap::new(); labels.insert(APP_LABEL_ID.to_string(), app_name.clone()); labels.insert(CONTROLLER_LABEL_ID.to_string(), API_NAMESPACE.to_string()); labels.insert( AKRI_CONFIGURATION_LABEL_NAME.to_string(), configuration_name.to_string(), ); labels.insert( AKRI_INSTANCE_LABEL_NAME.to_string(), instance_name.to_string(), ); labels.insert( AKRI_TARGET_NODE_LABEL_NAME.to_string(), node_to_run_pod_on.to_string(), ); let owner_references: Vec<OwnerReference> = vec![OwnerReference { api_version: ownership.get_api_version(), kind: ownership.get_kind(), controller: ownership.get_controller(), block_owner_deletion: ownership.get_block_owner_deletion(), name: ownership.get_name(), uid: ownership.get_uid(), }]; let mut modified_pod_spec = pod_spec.clone(); modify_pod_spec( &mut modified_pod_spec, resource_limit_name, Some(node_to_run_pod_on), ); let result = Pod { spec: Some(modified_pod_spec), metadata: ObjectMeta { name: Some(app_name), namespace: Some(pod_namespace.to_string()), labels: Some(labels), owner_references: Some(owner_references), ..Default::default() }, ..Default::default() }; trace!("create_new_pod_from_spec return"); Ok(result) } pub fn modify_pod_spec( pod_spec: &mut PodSpec, resource_limit_name: &str, node_to_run_pod_on: Option<&str>, ) { let insert_akri_resources = |map: &mut ResourceQuantityType| { if map.contains_key(RESOURCE_REQUIREMENTS_KEY) { let placeholder_value = map.get(RESOURCE_REQUIREMENTS_KEY).unwrap().clone(); map.insert(resource_limit_name.to_string(), placeholder_value); map.remove(RESOURCE_REQUIREMENTS_KEY); } }; for container in &mut pod_spec.containers { if let Some(resources) = container.resources.as_ref() { container.resources = Some(ResourceRequirements { limits: { match resources.limits.clone() { Some(mut map) => { insert_akri_resources(&mut map); Some(map) } None => None, } }, requests: { match resources.requests.clone() { Some(mut map) => { insert_akri_resources(&mut map); Some(map) } None => None, } }, }); }; } if let Some(node_name) = node_to_run_pod_on { // Ensure that the modified PodSpec has the required Affinity settings pod_spec .affinity .get_or_insert(Affinity::default()) .node_affinity .get_or_insert(NodeAffinity { ..Default::default() }) .required_during_scheduling_ignored_during_execution .get_or_insert(NodeSelector { node_selector_terms: vec![], }) .node_selector_terms .push(NodeSelectorTerm { match_fields: Some(vec![NodeSelectorRequirement { key: OBJECT_NAME_FIELD.to_string(), operator: NODE_SELECTOR_OP_IN.to_string(), // need to find if there is an equivalent to: v1.NODE_SELECTOR_OP_IN, values: Some(vec![node_name.to_string()]), }]), ..Default::default() }); } } #[cfg(test)] mod broker_podspec_tests { use super::super::super::akri::API_VERSION; use super::super::OwnershipType; use super::*; use env_logger; use k8s_openapi::api::core::v1::Container; #[test] fn test_create_broker_app_name() { let _ = env_logger::builder().is_test(true).try_init(); assert_eq!( "node-instance-name-suffix", create_broker_app_name("instance.name", Some("node"), true, "suffix") ); assert_eq!( "instance-name-suffix", create_broker_app_name("instance.name", Some("node"), false, "suffix") ); assert_eq!( "node-instance-name-suffix", create_broker_app_name("instance-name", Some("node"), true, "suffix") ); assert_eq!( "instance-name-suffix", create_broker_app_name("instance-name", Some("node"), false, "suffix") ); assert_eq!( "node-1-0-0-1-suffix", create_broker_app_name("1-0-0-1", Some("node"), true, "suffix") ); assert_eq!( "1-0-0-1-suffix", create_broker_app_name("1-0-0-1", Some("node"), false, "suffix") ); } #[test] fn test_create_broker_app_name_job() { let _ = env_logger::builder().is_test(true).try_init(); assert_eq!( "node-instance-name-1-job", create_broker_app_name("instance.name", Some("node"), true, "1-job") ); } #[test] fn test_pod_spec_creation() { let image = "image".to_string(); let mut placeholder_limits: ResourceQuantityType = BTreeMap::new(); placeholder_limits.insert(RESOURCE_REQUIREMENTS_KEY.to_string(), Default::default()); placeholder_limits.insert("do-not-change-this".to_string(), Default::default()); let placeholder_requests = placeholder_limits.clone(); do_pod_spec_creation_test( vec![image.clone()], vec![Container { image: Some(image), resources: Some(ResourceRequirements { limits: Some(placeholder_limits), requests: Some(placeholder_requests), }), ..Default::default() }], ); } #[test] fn test_pod_spec_creation_with_multiple_containers() { let mut placeholder_limits1: ResourceQuantityType = BTreeMap::new(); placeholder_limits1.insert(RESOURCE_REQUIREMENTS_KEY.to_string(), Default::default()); placeholder_limits1.insert("do-not-change-this".to_string(), Default::default()); let placeholder_requests1 = placeholder_limits1.clone(); let mut placeholder_limits2: ResourceQuantityType = BTreeMap::new(); placeholder_limits2.insert(RESOURCE_REQUIREMENTS_KEY.to_string(), Default::default()); placeholder_limits2.insert("do-not-change-this".to_string(), Default::default()); let placeholder_requests2 = placeholder_limits2.clone(); do_pod_spec_creation_test( vec!["image1".to_string(), "image2".to_string()], vec![ Container { image: Some("image1".to_string()), resources: Some(ResourceRequirements { limits: Some(placeholder_limits1), requests: Some(placeholder_requests1), }), ..Default::default() }, Container { image: Some("image2".to_string()), resources: Some(ResourceRequirements { limits: Some(placeholder_limits2), requests: Some(placeholder_requests2), }), ..Default::default() }, ], ); } fn do_pod_spec_creation_test(image_names: Vec<String>, container_specs: Vec<Container>) { let _ = env_logger::builder().is_test(true).try_init(); let num_containers = image_names.len(); let pod_spec = PodSpec { containers: container_specs, affinity: Some(Affinity { node_affinity: Some(NodeAffinity { required_during_scheduling_ignored_during_execution: Some(NodeSelector { node_selector_terms: vec![NodeSelectorTerm { match_fields: Some(vec![NodeSelectorRequirement { key: "do-not-change-this".to_string(), operator: NODE_SELECTOR_OP_IN.to_string(), // need to find if there is an equivalent to: v1.NODE_SELECTOR_OP_IN, values: Some(vec!["existing-node-affinity".to_string()]), }]), ..Default::default() }], //..Default::default() }), ..Default::default() }), ..Default::default() }), ..Default::default() }; let pod_namespace = "pod_namespace".to_string(); let instance_name = "instance_name".to_string(); let instance_uid = "instance_uid".to_string(); let configuration_name = "configuration_name".to_string(); let resource_limit_name = "resource_limit_name".to_string(); let node_to_run_pod_on = "node_to_run_pod_on".to_string(); for capability_is_shared in &[true, false] { let pod = create_new_pod_from_spec( &pod_namespace, &instance_name, &configuration_name, OwnershipInfo::new( OwnershipType::Instance, instance_name.clone(), instance_uid.clone(), ), &resource_limit_name, &node_to_run_pod_on, *capability_is_shared, &pod_spec, ) .unwrap(); let app_name = create_broker_app_name( &instance_name, Some(&node_to_run_pod_on), *capability_is_shared, "pod", ); // Validate the metadata name/namesapce assert_eq!(&app_name, &pod.metadata.clone().name.unwrap()); assert_eq!(&pod_namespace, &pod.metadata.clone().namespace.unwrap()); // Validate the labels added assert_eq!( &&app_name, &pod.metadata .clone() .labels .unwrap() .get(APP_LABEL_ID) .unwrap() ); assert_eq!( &&API_NAMESPACE.to_string(), &pod.metadata .clone() .labels .unwrap() .get(CONTROLLER_LABEL_ID) .unwrap() ); assert_eq!( &&configuration_name, &pod.metadata .clone() .labels .unwrap() .get(AKRI_CONFIGURATION_LABEL_NAME) .unwrap() ); assert_eq!( &&instance_name, &pod.metadata .clone() .labels .unwrap() .get(AKRI_INSTANCE_LABEL_NAME) .unwrap() ); assert_eq!( &&node_to_run_pod_on, &pod.metadata .clone() .labels .unwrap() .get(AKRI_TARGET_NODE_LABEL_NAME) .unwrap() ); // Validate ownerReference assert_eq!( instance_name, pod.metadata .clone() .owner_references .unwrap() .get(0) .unwrap() .name ); assert_eq!( instance_uid, pod.metadata .clone() .owner_references .unwrap() .get(0) .unwrap() .uid ); assert_eq!( "Instance", &pod.metadata .clone() .owner_references .unwrap() .get(0) .unwrap() .kind ); assert_eq!( &format!("{}/{}", API_NAMESPACE, API_VERSION), &pod.metadata .clone() .owner_references .unwrap() .get(0) .unwrap() .api_version ); assert!(pod .metadata .clone() .owner_references .unwrap() .get(0) .unwrap() .controller .unwrap()); assert!(pod .metadata .clone() .owner_references .unwrap() .get(0) .unwrap() .block_owner_deletion .unwrap()); // Validate existing and new affinity exist assert_eq!( &2, &pod.spec .clone() .unwrap() .affinity .unwrap() .node_affinity .unwrap() .required_during_scheduling_ignored_during_execution .unwrap() .node_selector_terms .len() ); // Validate existing affinity unchanged assert_eq!( "do-not-change-this", &pod.spec .clone() .unwrap() .affinity .unwrap() .node_affinity .unwrap() .required_during_scheduling_ignored_during_execution .unwrap() .node_selector_terms .get(0) .unwrap() .match_fields .as_ref() .unwrap() .get(0) .unwrap() .key ); assert_eq!( "In", &pod.spec .clone() .unwrap() .affinity .unwrap() .node_affinity .unwrap() .required_during_scheduling_ignored_during_execution .unwrap() .node_selector_terms .get(0) .unwrap() .match_fields .as_ref() .unwrap() .get(0) .unwrap() .operator ); assert_eq!( &&vec!["existing-node-affinity".to_string()], &pod.spec .clone() .unwrap() .affinity .unwrap() .node_affinity .unwrap() .required_during_scheduling_ignored_during_execution .unwrap() .node_selector_terms .get(0) .unwrap() .match_fields .as_ref() .unwrap() .get(0) .unwrap() .values .as_ref() .unwrap() ); // Validate the affinity added assert_eq!( "metadata.name", &pod.spec .clone() .unwrap() .affinity .unwrap() .node_affinity .unwrap() .required_during_scheduling_ignored_during_execution .unwrap() .node_selector_terms .get(1) .unwrap() .match_fields .as_ref() .unwrap() .get(0) .unwrap() .key ); assert_eq!( "In", &pod.spec .clone() .unwrap() .affinity .unwrap() .node_affinity .unwrap() .required_during_scheduling_ignored_during_execution .unwrap() .node_selector_terms .get(1) .unwrap() .match_fields .as_ref() .unwrap() .get(0) .unwrap() .operator ); assert_eq!( &&vec![node_to_run_pod_on.clone()], &pod.spec .clone() .unwrap() .affinity .unwrap() .node_affinity .unwrap() .required_during_scheduling_ignored_during_execution .unwrap() .node_selector_terms .get(1) .unwrap() .match_fields .as_ref() .unwrap() .get(0) .unwrap() .values .as_ref() .unwrap() ); // Validate image name remanes unchanged for i in 0..num_containers { assert_eq!( &image_names.get(i).unwrap(), &pod.spec .clone() .unwrap() .containers .get(i) .unwrap() .image .as_ref() .unwrap() ); // Validate existing limits/requires unchanged assert_eq!( &true, &pod.spec .clone() .unwrap() .containers .get(i) .unwrap() .resources .as_ref() .unwrap() .limits .as_ref() .unwrap() .contains_key("do-not-change-this") ); assert_eq!( &true, &pod.spec .clone() .unwrap() .containers .get(i) .unwrap() .resources .as_ref() .unwrap() .requests .as_ref() .unwrap() .contains_key("do-not-change-this") ); // Validate the limits/requires added assert_eq!( &false, &pod.spec .clone() .unwrap() .containers .get(i) .unwrap() .resources .as_ref() .unwrap() .limits .as_ref() .unwrap() .contains_key(RESOURCE_REQUIREMENTS_KEY) ); assert_eq!( &false, &pod.spec .clone() .unwrap() .containers .get(i) .unwrap() .resources .as_ref() .unwrap() .requests .as_ref() .unwrap() .contains_key(RESOURCE_REQUIREMENTS_KEY) ); assert_eq!( &true, &pod.spec .clone() .unwrap() .containers .get(i) .unwrap() .resources .as_ref() .unwrap() .limits .as_ref() .unwrap() .contains_key(&resource_limit_name.clone()) ); assert_eq!( &true, &pod.spec .clone() .unwrap() .containers .get(i) .unwrap() .resources .as_ref() .unwrap() .requests .as_ref() .unwrap() .contains_key(&resource_limit_name.clone()) ); } } } } /// Create Kubernetes Pod /// /// Example: /// /// ```no_run /// use akri_shared::k8s::pod; /// use kube::client::Client; /// use kube::config; /// use k8s_openapi::api::core::v1::Pod; /// /// # #[tokio::main] /// # async fn main() { /// let api_client = Client::try_default().await.unwrap(); /// pod::create_pod(&Pod::default(), "pod_namespace", api_client).await.unwrap(); /// # } /// ``` pub async fn create_pod( pod_to_create: &Pod, namespace: &str, kube_client: Client, ) -> Result<(), anyhow::Error> { trace!("create_pod enter"); let pods: Api<Pod> = Api::namespaced(kube_client, namespace); info!("create_pod pods.create(...).await?:"); match pods.create(&PostParams::default(), pod_to_create).await { Ok(created_pod) => { info!( "create_pod pods.create return: {:?}", created_pod.metadata.name ); Ok(()) } Err(kube::Error::Api(ae)) => { if ae.code == ERROR_CONFLICT { trace!("create_pod - pod already exists"); Ok(()) } else { error!( "create_pod pods.create [{:?}] returned kube error: {:?}", serde_json::to_string(&pod_to_create), ae ); Err(anyhow::anyhow!(ae)) } } Err(e) => { error!( "create_pod pods.create [{:?}] error: {:?}", serde_json::to_string(&pod_to_create), e ); Err(anyhow::anyhow!(e)) } } } /// Remove Kubernetes Pod /// /// Example: /// /// ```no_run /// use akri_shared::k8s::pod; /// use kube::client::Client; /// use kube::config; /// /// # #[tokio::main] /// # async fn main() { /// let api_client = Client::try_default().await.unwrap(); /// pod::remove_pod("pod_to_remove", "pod_namespace", api_client).await.unwrap(); /// # } /// ``` pub async fn remove_pod( pod_to_remove: &str, namespace: &str, kube_client: Client, ) -> Result<(), anyhow::Error> { trace!("remove_pod enter"); let pods: Api<Pod> = Api::namespaced(kube_client, namespace); info!("remove_pod pods.delete(...).await?:"); match pods.delete(pod_to_remove, &DeleteParams::default()).await { Ok(deleted_pod) => match deleted_pod { Either::Left(spec) => { info!("remove_pod pods.delete return: {:?}", &spec.metadata.name); Ok(()) } Either::Right(status) => { info!("remove_pod pods.delete return: {:?}", &status.status); Ok(()) } }, Err(kube::Error::Api(ae)) => { if ae.code == ERROR_NOT_FOUND { trace!("remove_pod - pod already removed"); Ok(()) } else { error!( "remove_pod pods.delete [{:?}] returned kube error: {:?}", &pod_to_remove, ae ); Err(anyhow::anyhow!(ae)) } } Err(e) => { error!( "remove_pod pods.delete [{:?}] error: {:?}", &pod_to_remove, e ); Err(anyhow::anyhow!(e)) } } }
{ // If the device capability is NOT shared, the instance name will contain // node-specific content, which guarntees uniqueness. format!("{}-{}", normalized_instance_name, app_name_suffix) }
uui-checkbox.element.ts
import { UUIHorizontalShakeAnimationValue, UUIHorizontalShakeKeyframes, } from '@umbraco-ui/uui-base/lib/animations'; import { defineElement } from '@umbraco-ui/uui-base/lib/registration'; import { UUIBooleanInputElement } from '@umbraco-ui/uui-boolean-input/lib'; import { iconCheck } from '@umbraco-ui/uui-icon-registry-essential/lib/svgs'; import { css, html } from 'lit'; /** * Umbraco checkbox, toggles between checked and uncheck * @element uui-checkbox * @fires UUIBooleanInputEvent#change - fires when the element is begin checked by a user action * @cssprop --uui-checkbox-size - To set the size of the checkbox. * @extends UUIBooleanInputElement */ @defineElement('uui-checkbox') export class UUICheckboxElement extends UUIBooleanInputElement { /** * This is a static class field indicating that the element is can be used inside a native form and participate in its events. It may require a polyfill, check support here https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/attachInternals. Read more about form controls here https://web.dev/more-capable-form-controls/ * @type {boolean} */ static readonly formAssociated = true; static styles = [ ...UUIBooleanInputElement.styles, UUIHorizontalShakeKeyframes, css` :host { --uui-checkbox-size: 18px; } #ticker { position: relative; grid-area: 'input'; display: flex; align-items: center; justify-content: center; box-sizing: border-box; width: var(--uui-checkbox-size); height: var(--uui-checkbox-size); border-radius: var( --uui-checkbox-border-radius, var(--uui-border-radius) ); color: var(--uui-toggle-color, var(--uui-interface-chosen-contrast)); background-color: var( --uui-toggle-background-color, var(--uui-interface-surface) ); border: 1px solid var(--uui-checkbox-border-color, var(--uui-interface-border)); font-size: calc(var(--uui-checkbox-size) * 0.7); } label:hover input:not([disabled]) + #ticker { border-color: var( --uui-checkbox-border-color-hover, var(--uui-interface-border-hover) ); background-color: var( --uui-checkbox-background-color-hover, var(--uui-interface-surface-hover) ); } label:focus #ticker { border-color: var( --uui-checkbox-border-color-focus, var(--uui-interface-border-focus) ); background-color: var( --uui-checkbox-background-color-focus, var(--uui-interface-surface-alt-focus) ); } input:checked + #ticker { border-color: var(--uui-interface-chosen); } label:hover input:checked:not([disabled]) + #ticker { border-color: var(--uui-interface-chosen-hover); } label:focus input:checked + #ticker { border-color: var(--uui-interface-chosen-focus); } #icon-check { position: absolute; vertical-align: middle; width: 1em; height: 1em; line-height: 0; transition: fill 120ms, opacity 120ms; fill: var(--uui-interface-chosen-contrast); opacity: 0; } #ticker::before { content: ''; position: absolute; top: 0; left: 0; bottom: 0; right: 0; border-radius: calc( var(--uui-checkbox-border-radius, var(--uui-border-radius)) * 0.5 ); background-color: var(--uui-interface-chosen); transition: transform 120ms ease, opacity 120ms, background-color 120ms; transform: scale(0); opacity: 0; } label:hover input:checked:not([disabled]) + #ticker::before { background-color: var(--uui-interface-chosen-hover); } input:checked + #ticker::before { transform: scale(1); opacity: 1; } input:checked + #ticker #icon-check { opacity: 1; } label:focus input:checked + #ticker { background-color: var(--uui-interface-chosen-focus); } input:focus + #ticker { outline: calc(2px * var(--uui-show-focus-outline, 1)) solid var(--uui-interface-outline); } :host(:not([disabled])) label:active input:checked + #ticker::before { /** Stretch when mouse down */ transform: scale(0.9); }
:host(:not([pristine]):invalid) #ticker, :host(:not([pristine]):invalid) label:hover #ticker, :host(:not([pristine]):invalid) label:hover input:checked:not([disabled]) + #ticker, :host(:not([pristine]):invalid) label:focus input:checked + #ticker, /* polyfill support */ :host(:not([pristine])[internals-invalid]) #ticker, :host(:not([pristine])[internals-invalid]) label:hover #ticker, :host(:not([pristine])[internals-invalid]) label:hover input:checked:not([disabled]) + #ticker, :host(:not([pristine])[internals-invalid]) label:focus input:checked + #ticker { border: 1px solid var(--uui-look-danger-border); } :host([disabled]) #ticker { background-color: var(--uui-interface-surface-disabled); } :host([disabled]) input:checked + #ticker { background-color: var(--uui-interface-chosen-disabled); } :host([disabled]) #ticker:after { background-color: var(--uui-interface-surface-disabled); } :host([disabled]) #ticker #icon-check { fill: var(--uui-interface-contrast-disabled); } :host([disabled]) label:active #ticker { animation: ${UUIHorizontalShakeAnimationValue}; } :host([disabled]) input:checked + #ticker #icon-check { fill: var(--uui-interface-chosen-contrast-disabled); } `, ]; renderCheckbox() { return html` <div id="ticker"> <div id="icon-check">${iconCheck}</div> </div> `; } } declare global { interface HTMLElementTagNameMap { 'uui-checkbox': UUICheckboxElement; } }
cancel.rs
//! This module contains the functions //! for cancelling binary sessions. use std::mem; use std::net::{Shutdown, TcpStream}; /// Cancels a session. Always succeeds. If the partner calls `recv` or `close` after cancellation, /// those calls fail. /// /// # Example /// /// ``` /// use mpstthree::binary::cancel::cancel; /// use mpstthree::binary::struct_trait::end::End; /// use mpstthree::binary::struct_trait::session::Session; /// use mpstthree::meshedchannels::MeshedChannels; /// use mpstthree::role::a::RoleA; /// use mpstthree::role::end::RoleEnd; /// /// let (s, _s_dual) = MeshedChannels::<End, End, RoleEnd, RoleA<RoleEnd>>::new(); /// cancel(s); /// ``` pub fn cancel<T>(s: T) { mem::drop(s); } /// Cancels a session. Always succeeds. If the partner calls `recv` or `close` after cancellation, /// those calls fail. Used for tcp transport. /// /// Drops the session *s* and shutdowns the `TcpStream` *stream* /// /// # Example /// /// ``` /// use mpstthree::binary::cancel::cancel_tcp; /// use mpstthree::binary::struct_trait::end::End; /// use mpstthree::binary::struct_trait::session::Session; /// use mpstthree::meshedchannels::MeshedChannels; /// use mpstthree::role::a::RoleA; /// use mpstthree::role::end::RoleEnd; /// use std::net::{TcpListener, TcpStream}; /// /// let _listener = TcpListener::bind("0.0.0.0:3333").unwrap(); /// let (s, _s_dual) = MeshedChannels::<End, End, RoleEnd, RoleA<RoleEnd>>::new(); /// let stream = TcpStream::connect("localhost:3333").unwrap(); /// cancel_tcp(s, stream); /// ``` pub fn cancel_tcp<T>(s: T, stream: TcpStream)
{ mem::drop(s); stream.shutdown(Shutdown::Both).unwrap(); mem::drop(stream); }
seq2seq.py
from typing import Optional from pydantic import BaseModel
vocab_size: int context_length: int has_eos: Optional[bool] = False keys = ["content", "target"]
class Seq2SeqFormat(BaseModel):
reduction.py
""" A library written in CUDA Python for generating reduction kernels """ from numba.np.numpy_support import from_dtype _WARPSIZE = 32 _NUMWARPS = 4 def _gpu_reduce_factory(fn, nbtype): from numba import cuda reduce_op = cuda.jit(device=True)(fn) inner_sm_size = _WARPSIZE + 1 # plus one to avoid SM collision max_blocksize = _NUMWARPS * _WARPSIZE @cuda.jit(device=True) def inner_warp_reduction(sm_partials, init): """ Compute reduction within a single warp """ tid = cuda.threadIdx.x warpid = tid // _WARPSIZE laneid = tid % _WARPSIZE sm_this = sm_partials[warpid, :] sm_this[laneid] = init cuda.syncwarp() width = _WARPSIZE // 2 while width: if laneid < width: old = sm_this[laneid] sm_this[laneid] = reduce_op(old, sm_this[laneid + width]) cuda.syncwarp() width //= 2 @cuda.jit(device=True) def device_reduce_full_block(arr, partials, sm_partials): """ Partially reduce `arr` into `partials` using `sm_partials` as working space. The algorithm goes like: array chunks of 128: | 0 | 128 | 256 | 384 | 512 | block-0: | x | | | x | | block-1: | | x | | | x | block-2: | | | x | | | The array is divided into chunks of 128 (size of a threadblock). The threadblocks consumes the chunks in roundrobin scheduling. First, a threadblock loads a chunk into temp memory. Then, all subsequent chunks are combined into the temp memory. Once all chunks are processed. Inner-block reduction is performed on the temp memory. So that, there will just be one scalar result per block. The result from each block is stored to `partials` at the dedicated slot. """ tid = cuda.threadIdx.x blkid = cuda.blockIdx.x blksz = cuda.blockDim.x gridsz = cuda.gridDim.x # block strided loop to compute the reduction start = tid + blksz * blkid stop = arr.size step = blksz * gridsz # load first value tmp = arr[start] # loop over all values in block-stride for i in range(start + step, stop, step): tmp = reduce_op(tmp, arr[i]) cuda.syncthreads() # inner-warp reduction inner_warp_reduction(sm_partials, tmp) cuda.syncthreads() # at this point, only the first slot for each warp in tsm_partials # is valid. # finish up block reduction # warning: this is assuming 4 warps. # assert numwarps == 4 if tid < 2: sm_partials[tid, 0] = reduce_op(sm_partials[tid, 0], sm_partials[tid + 2, 0]) cuda.syncwarp() if tid == 0: partials[blkid] = reduce_op(sm_partials[0, 0], sm_partials[1, 0]) @cuda.jit(device=True) def device_reduce_partial_block(arr, partials, sm_partials): """ This computes reduction on `arr`. This device function must be used by 1 threadblock only. The blocksize must match `arr.size` and must not be greater than 128. """ tid = cuda.threadIdx.x blkid = cuda.blockIdx.x blksz = cuda.blockDim.x warpid = tid // _WARPSIZE laneid = tid % _WARPSIZE size = arr.size # load first value tid = cuda.threadIdx.x value = arr[tid] sm_partials[warpid, laneid] = value cuda.syncthreads() if (warpid + 1) * _WARPSIZE < size: # fully populated warps inner_warp_reduction(sm_partials, value) else: # partially populated warps # NOTE: this uses a very inefficient sequential algorithm if laneid == 0: sm_this = sm_partials[warpid, :] base = warpid * _WARPSIZE for i in range(1, size - base): sm_this[0] = reduce_op(sm_this[0], sm_this[i]) cuda.syncthreads() # finish up if tid == 0: num_active_warps = (blksz + _WARPSIZE - 1) // _WARPSIZE result = sm_partials[0, 0] for i in range(1, num_active_warps): result = reduce_op(result, sm_partials[i, 0]) partials[blkid] = result def gpu_reduce_block_strided(arr, partials, init, use_init): """ Perform reductions on *arr* and writing out partial reduction result into *partials*. The length of *partials* is determined by the number of threadblocks. The initial value is set with *init*. Launch config: Blocksize must be multiple of warpsize and it is limited to 4 warps. """ tid = cuda.threadIdx.x sm_partials = cuda.shared.array((_NUMWARPS, inner_sm_size), dtype=nbtype) if cuda.blockDim.x == max_blocksize: device_reduce_full_block(arr, partials, sm_partials) else: device_reduce_partial_block(arr, partials, sm_partials) # deal with the initializer if use_init and tid == 0 and cuda.blockIdx.x == 0: partials[0] = reduce_op(partials[0], init) return cuda.jit(gpu_reduce_block_strided) class Reduce(object): """Create a reduction object that reduces values using a given binary function. The binary function is compiled once and cached inside this object. Keeping this object alive will prevent re-compilation. """ _cache = {} def __init__(self, functor): """ :param functor: A function implementing a binary operation for reduction. It will be compiled as a CUDA device function using ``cuda.jit(device=True)``. """ self._functor = functor def _compile(self, dtype): key = self._functor, dtype if key in self._cache: kernel = self._cache[key] else: kernel = _gpu_reduce_factory(self._functor, from_dtype(dtype)) self._cache[key] = kernel return kernel def __call__(self, arr, size=None, res=None, init=0, stream=0): """Performs a full reduction. :param arr: A host or device array. :param size: Optional integer specifying the number of elements in ``arr`` to reduce. If this parameter is not specified, the entire array is reduced. :param res: Optional device array into which to write the reduction result to. The result is written into the first element of this array. If this parameter is specified, then no communication of the reduction output takes place from the device to the host. :param init: Optional initial value for the reduction, the type of which must match ``arr.dtype``. :param stream: Optional CUDA stream in which to perform the reduction. If no stream is specified, the default stream of 0 is used. :return: If ``res`` is specified, ``None`` is returned. Otherwise, the result of the reduction is returned. """ from numba import cuda # ensure 1d array if arr.ndim != 1: raise TypeError("only support 1D array") # adjust array size if size is not None: arr = arr[:size] init = arr.dtype.type(init) # ensure the right type # return `init` if `arr` is empty if arr.size < 1: return init kernel = self._compile(arr.dtype) # Perform the reduction on the GPU blocksize = _NUMWARPS * _WARPSIZE size_full = (arr.size // blocksize) * blocksize size_partial = arr.size - size_full full_blockct = min(size_full // blocksize, _WARPSIZE * 2) # allocate size of partials array partials_size = full_blockct if size_partial: partials_size += 1 partials = cuda.device_array(shape=partials_size, dtype=arr.dtype) if size_full: # kernel for the fully populated threadblocks kernel[full_blockct, blocksize, stream](arr[:size_full], partials[:full_blockct], init, True) if size_partial: # kernel for partially populated threadblocks kernel[1, size_partial, stream](arr[size_full:], partials[full_blockct:], init, not full_blockct) if partials.size > 1: # finish up kernel[1, partials_size, stream](partials, partials, init, False) # handle return value if res is not None: res[:1].copy_to_device(partials[:1], stream=stream) return else:
return partials[0]
constructioncamerapkloader_gen.go
// Code generated by github.com/vektah/dataloaden, DO NOT EDIT. package model import ( "sync" "time" ) // ConstructionCameraPkLoaderConfig captures the config to create a new ConstructionCameraPkLoader type ConstructionCameraPkLoaderConfig struct { // Fetch is a method that provides the data for the loader Fetch func(keys []string) ([]*ConstructionCamera, []error) // Wait is how long wait before sending a batch Wait time.Duration // MaxBatch will limit the maximum number of keys to send in one batch, 0 = not limit MaxBatch int } // NewConstructionCameraPkLoader creates a new ConstructionCameraPkLoader given a fetch, wait, and maxBatch func NewConstructionCameraPkLoader(config ConstructionCameraPkLoaderConfig) *ConstructionCameraPkLoader { return &ConstructionCameraPkLoader{ fetch: config.Fetch, wait: config.Wait, maxBatch: config.MaxBatch, } } // ConstructionCameraPkLoader batches and caches requests type ConstructionCameraPkLoader struct { // this method provides the data for the loader fetch func(keys []string) ([]*ConstructionCamera, []error) // how long to done before sending a batch wait time.Duration // this will limit the maximum number of keys to send in one batch, 0 = no limit maxBatch int // INTERNAL // lazily created cache cache map[string]*ConstructionCamera // the current batch. keys will continue to be collected until timeout is hit, // then everything will be sent to the fetch method and out to the listeners batch *constructionCameraPkLoaderBatch // mutex to prevent races mu sync.Mutex } type constructionCameraPkLoaderBatch struct { keys []string data []*ConstructionCamera error []error closing bool done chan struct{} } // Load a ConstructionCamera by key, batching and caching will be applied automatically func (l *ConstructionCameraPkLoader) Load(key string) (*ConstructionCamera, error) { return l.LoadThunk(key)() } // LoadThunk returns a function that when called will block waiting for a ConstructionCamera. // This method should be used if you want one goroutine to make requests to many // different data loaders without blocking until the thunk is called. func (l *ConstructionCameraPkLoader) LoadThunk(key string) func() (*ConstructionCamera, error) { l.mu.Lock() if it, ok := l.cache[key]; ok { l.mu.Unlock() return func() (*ConstructionCamera, error) { return it, nil } } if l.batch == nil { l.batch = &constructionCameraPkLoaderBatch{done: make(chan struct{})} } batch := l.batch pos := batch.keyIndex(l, key) l.mu.Unlock() return func() (*ConstructionCamera, error) { <-batch.done var data *ConstructionCamera if pos < len(batch.data) { data = batch.data[pos] } var err error // its convenient to be able to return a single error for everything if len(batch.error) == 1 { err = batch.error[0] } else if batch.error != nil { err = batch.error[pos] } if err == nil { l.mu.Lock() l.unsafeSet(key, data) l.mu.Unlock() } return data, err } } // LoadAll fetches many keys at once. It will be broken into appropriate sized // sub batches depending on how the loader is configured func (l *ConstructionCameraPkLoader) LoadAll(keys []string) ([]*ConstructionCamera, []error) { results := make([]func() (*ConstructionCamera, error), len(keys)) for i, key := range keys { results[i] = l.LoadThunk(key) } constructionCameras := make([]*ConstructionCamera, len(keys)) errors := make([]error, len(keys)) for i, thunk := range results { constructionCameras[i], errors[i] = thunk() } return constructionCameras, errors } // LoadAllThunk returns a function that when called will block waiting for a ConstructionCameras. // This method should be used if you want one goroutine to make requests to many // different data loaders without blocking until the thunk is called. func (l *ConstructionCameraPkLoader) LoadAllThunk(keys []string) func() ([]*ConstructionCamera, []error) { results := make([]func() (*ConstructionCamera, error), len(keys)) for i, key := range keys { results[i] = l.LoadThunk(key) } return func() ([]*ConstructionCamera, []error) { constructionCameras := make([]*ConstructionCamera, len(keys)) errors := make([]error, len(keys)) for i, thunk := range results { constructionCameras[i], errors[i] = thunk() } return constructionCameras, errors } } // Prime the cache with the provided key and value. If the key already exists, no change is made // and false is returned. // (To forcefully prime the cache, clear the key first with loader.clear(key).prime(key, value).) func (l *ConstructionCameraPkLoader) Prime(key string, value *ConstructionCamera) bool { l.mu.Lock() var found bool if _, found = l.cache[key]; !found { // make a copy when writing to the cache, its easy to pass a pointer in from a loop var // and end up with the whole cache pointing to the same value. cpy := *value l.unsafeSet(key, &cpy) } l.mu.Unlock() return !found } // Clear the value at key from the cache, if it exists func (l *ConstructionCameraPkLoader) Clear(key string) { l.mu.Lock() delete(l.cache, key) l.mu.Unlock() } func (l *ConstructionCameraPkLoader) unsafeSet(key string, value *ConstructionCamera) { if l.cache == nil { l.cache = map[string]*ConstructionCamera{} } l.cache[key] = value } // keyIndex will return the location of the key in the batch, if its not found // it will add the key to the batch func (b *constructionCameraPkLoaderBatch) keyIndex(l *ConstructionCameraPkLoader, key string) int { for i, existingKey := range b.keys { if key == existingKey { return i } } pos := len(b.keys) b.keys = append(b.keys, key) if pos == 0 { go b.startTimer(l) } if l.maxBatch != 0 && pos >= l.maxBatch-1 { if !b.closing { b.closing = true l.batch = nil go b.end(l) } } return pos } func (b *constructionCameraPkLoaderBatch) startTimer(l *ConstructionCameraPkLoader) { time.Sleep(l.wait) l.mu.Lock() // we must have hit a batch limit and are already finalizing this batch if b.closing { l.mu.Unlock()
l.mu.Unlock() b.end(l) } func (b *constructionCameraPkLoaderBatch) end(l *ConstructionCameraPkLoader) { b.data, b.error = l.fetch(b.keys) close(b.done) }
return } l.batch = nil
analytics.component.ts
import { Component, OnInit } from '@angular/core'; import { NbThemeService, NbColorHelper } from '@nebular/theme'; @Component({ selector: 'analytics', templateUrl: './analytics.component.html', styleUrls: ['./analytics.component.scss'] }) export class
implements OnInit { // pie data. tokenStatePie: any; orderStatPie: any; totalInvestedPie: any; pieOptions: any; barOptions: any; themeSubscription: any; temperature = 24; temperatureOff = false; temperatureMode = 'cool'; humidity = 87; humidityOff = false; humidityMode = 'heat'; constructor(private theme: NbThemeService) { this.themeSubscription = this.theme.getJsTheme().subscribe(config => { const colors: any = config.variables; const chartjs: any = config.variables.chartjs; this.tokenStatePie = { labels: ['Purchased', 'Reserved', 'Total Volume'], datasets: [{ data: [300, 100, 500], backgroundColor: [colors.primaryLight, colors.infoLight, colors.successLight], }], }; this.orderStatPie = { labels: ['New Orders', 'Pending Orders', 'Successful Orders'], datasets: [{ data: [80, 20, 800], backgroundColor: [colors.primaryLight, colors.infoLight, colors.successLight], }], }; this.totalInvestedPie = { labels: ['BTC', 'BCH', 'LTC', 'DASH', 'ETH', 'ETC', 'XMR', 'ZEC', 'NEO', 'XRP', 'DOGE', 'WAVES', 'STRAT'], datasets: [{ data: [65, 59, 80, 81, 56, 55, 40, 12, 42, 13, 64, 62, 34], label: 'Total Invested', backgroundColor: NbColorHelper.hexToRgbA(colors.primaryLight, 0.8), }], }; this.generateBarOptions(chartjs); this.generateBarOptions(chartjs); }); } ngOnInit() { } onSelect(event) { console.log(event); } generatePieOptions(chartjs) { this.pieOptions = { maintainAspectRatio: false, responsive: true, scales: { xAxes: [ { display: false, }, ], yAxes: [ { display: false, }, ], }, legend: { labels: { fontColor: chartjs.textColor, }, }, }; } generateBarOptions(chartjs) { this.barOptions = { maintainAspectRatio: false, responsive: true, legend: { labels: { fontColor: chartjs.textColor, }, }, scales: { xAxes: [ { gridLines: { display: false, color: chartjs.axisLineColor, }, ticks: { fontColor: chartjs.textColor, }, }, ], yAxes: [ { gridLines: { display: true, color: chartjs.axisLineColor, }, ticks: { fontColor: chartjs.textColor, }, }, ], }, }; } }
AnalyticsComponent
api_op_PutConfigurationAggregator.go
// Code generated by smithy-go-codegen DO NOT EDIT. package configservice import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/configservice/types" smithy "github.com/awslabs/smithy-go" "github.com/awslabs/smithy-go/middleware" smithyhttp "github.com/awslabs/smithy-go/transport/http" ) // Creates and updates the configuration aggregator with the selected source // accounts and regions. The source account can be individual account(s) or an // organization. AWS Config should be enabled in source accounts and regions you // want to aggregate. If your source type is an organization, you must be signed in // to the master account and all features must be enabled in your organization. AWS // Config calls EnableAwsServiceAccess API to enable integration between AWS Config // and AWS Organizations. func (c *Client) PutConfigurationAggregator(ctx context.Context, params *PutConfigurationAggregatorInput, optFns ...func(*Options)) (*PutConfigurationAggregatorOutput, error) { stack := middleware.NewStack("PutConfigurationAggregator", smithyhttp.NewStackRequest) options := c.options.Copy() for _, fn := range optFns { fn(&options) } addawsAwsjson11_serdeOpPutConfigurationAggregatorMiddlewares(stack) awsmiddleware.AddRequestInvocationIDMiddleware(stack) smithyhttp.AddContentLengthMiddleware(stack) addResolveEndpointMiddleware(stack, options) v4.AddComputePayloadSHA256Middleware(stack) addRetryMiddlewares(stack, options) addHTTPSignerV4Middleware(stack, options) awsmiddleware.AddAttemptClockSkewMiddleware(stack) addClientUserAgent(stack) smithyhttp.AddErrorCloseResponseBodyMiddleware(stack) smithyhttp.AddCloseResponseBodyMiddleware(stack) addOpPutConfigurationAggregatorValidationMiddleware(stack) stack.Initialize.Add(newServiceMetadataMiddleware_opPutConfigurationAggregator(options.Region), middleware.Before) addRequestIDRetrieverMiddleware(stack) addResponseErrorMiddleware(stack) for _, fn := range options.APIOptions { if err := fn(stack); err != nil { return nil, err } } handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) result, metadata, err := handler.Handle(ctx, params) if err != nil { return nil, &smithy.OperationError{ ServiceID: ServiceID, OperationName: "PutConfigurationAggregator", Err: err, } } out := result.(*PutConfigurationAggregatorOutput) out.ResultMetadata = metadata return out, nil } type PutConfigurationAggregatorInput struct { // The name of the configuration aggregator. // // This member is required. ConfigurationAggregatorName *string // A list of AccountAggregationSource object. </p> AccountAggregationSources []*types.AccountAggregationSource // An OrganizationAggregationSource object. OrganizationAggregationSource *types.OrganizationAggregationSource // An array of tag object. Tags []*types.Tag } type PutConfigurationAggregatorOutput struct { // Returns a ConfigurationAggregator object. ConfigurationAggregator *types.ConfigurationAggregator // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func addawsAwsjson11_serdeOpPutConfigurationAggregatorMiddlewares(stack *middleware.Stack) { stack.Serialize.Add(&awsAwsjson11_serializeOpPutConfigurationAggregator{}, middleware.After) stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutConfigurationAggregator{}, middleware.After) } func
(region string) awsmiddleware.RegisterServiceMetadata { return awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "config", OperationName: "PutConfigurationAggregator", } }
newServiceMetadataMiddleware_opPutConfigurationAggregator
lib_http_client.go
/* Copyright 2020 Cortex Labs, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cluster import ( "bytes" "crypto/tls" "fmt" "io" "io/ioutil" "mime/multipart" "net/http" "time" "github.com/cortexlabs/cortex/pkg/consts" "github.com/cortexlabs/cortex/pkg/lib/archive" "github.com/cortexlabs/cortex/pkg/lib/errors" "github.com/cortexlabs/cortex/pkg/lib/files" "github.com/cortexlabs/cortex/pkg/lib/json" "github.com/cortexlabs/cortex/pkg/operator/schema" ) type OperatorClient struct { *http.Client } type OperatorConfig struct { Telemetry bool ClientID string EnvName string OperatorEndpoint string AWSAccessKeyID string AWSSecretAccessKey string } func (oc OperatorConfig) AuthHeader() string { return fmt.Sprintf("CortexAWS %s|%s", oc.AWSAccessKeyID, oc.AWSSecretAccessKey) } func HTTPGet(operatorConfig OperatorConfig, endpoint string, qParams ...map[string]string) ([]byte, error) { req, err := operatorRequest(operatorConfig, "GET", endpoint, nil, qParams...) if err != nil { return nil, err } return makeOperatorRequest(operatorConfig, req) } func HTTPPostObjAsJSON(operatorConfig OperatorConfig, endpoint string, requestData interface{}, qParams ...map[string]string) ([]byte, error) { jsonRequestData, err := json.Marshal(requestData) if err != nil { return nil, err } return HTTPPostJSON(operatorConfig, endpoint, jsonRequestData, qParams...) } func HTTPPostJSON(operatorConfig OperatorConfig, endpoint string, jsonRequestData []byte, qParams ...map[string]string) ([]byte, error) { payload := bytes.NewBuffer(jsonRequestData) req, err := operatorRequest(operatorConfig, http.MethodPost, endpoint, payload, qParams...) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") return makeOperatorRequest(operatorConfig, req) } func HTTPPostNoBody(operatorConfig OperatorConfig, endpoint string, qParams ...map[string]string) ([]byte, error) { req, err := operatorRequest(operatorConfig, http.MethodPost, endpoint, nil, qParams...) if err != nil { return nil, err } return makeOperatorRequest(operatorConfig, req) } func HTTPDelete(operatorConfig OperatorConfig, endpoint string, qParams ...map[string]string) ([]byte, error) { req, err := operatorRequest(operatorConfig, http.MethodDelete, endpoint, nil, qParams...) if err != nil { return nil, err } return makeOperatorRequest(operatorConfig, req) } type HTTPUploadInput struct { FilePaths map[string]string Bytes map[string][]byte } func HTTPUpload(operatorConfig OperatorConfig, endpoint string, input *HTTPUploadInput, qParams ...map[string]string) ([]byte, error) { body := new(bytes.Buffer) writer := multipart.NewWriter(body) for fileName, filePath := range input.FilePaths { file, err := files.Open(filePath) if err != nil { return nil, err } defer file.Close() if err := addFileToMultipart(fileName, writer, file); err != nil { return nil, err } } for fileName, fileBytes := range input.Bytes { if err := addFileToMultipart(fileName, writer, bytes.NewReader(fileBytes)); err != nil { return nil, err } } if err := writer.Close(); err != nil { return nil, errors.Wrap(err, _errStrCantMakeRequest) } req, err := operatorRequest(operatorConfig, http.MethodPost, endpoint, body, qParams...) if err != nil { return nil, err } req.Header.Set("Content-Type", writer.FormDataContentType()) return makeOperatorRequest(operatorConfig, req) } func addFileToMultipart(fileName string, writer *multipart.Writer, reader io.Reader) error { part, err := writer.CreateFormFile(fileName, fileName) if err != nil { return errors.Wrap(err, _errStrCantMakeRequest) } if _, err = io.Copy(part, reader); err != nil { return errors.Wrap(err, _errStrCantMakeRequest) } return nil } func HTTPUploadZip(operatorConfig OperatorConfig, endpoint string, zipInput *archive.Input, fileName string, qParams ...map[string]string) ([]byte, error) { zipBytes, _, err := archive.ZipToMem(zipInput) if err != nil { return nil, errors.Wrap(err, "failed to zip configuration file") } uploadInput := &HTTPUploadInput{ Bytes: map[string][]byte{ fileName: zipBytes, }, } return HTTPUpload(operatorConfig, endpoint, uploadInput, qParams...) } func operatorRequest(operatorConfig OperatorConfig, method string, endpoint string, body io.Reader, qParams ...map[string]string) (*http.Request, error)
func makeOperatorRequest(operatorConfig OperatorConfig, request *http.Request) ([]byte, error) { if operatorConfig.Telemetry { values := request.URL.Query() values.Set("clientID", operatorConfig.ClientID) request.URL.RawQuery = values.Encode() } request.Header.Set("Authorization", operatorConfig.AuthHeader()) request.Header.Set("CortexAPIVersion", consts.CortexVersion) timeout := 600 * time.Second if request.URL.Path == "/info" { timeout = 10 * time.Second } client := &http.Client{ Timeout: timeout, Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, } response, err := client.Do(request) if err != nil { if operatorConfig.EnvName == "" { return nil, errors.Wrap(err, "failed to connect to operator", operatorConfig.OperatorEndpoint) } return nil, ErrorFailedToConnectOperator(err, operatorConfig.EnvName, operatorConfig.OperatorEndpoint) } defer response.Body.Close() if response.StatusCode != 200 { bodyBytes, err := ioutil.ReadAll(response.Body) if err != nil { return nil, errors.Wrap(err, _errStrRead) } var output schema.ErrorResponse err = json.Unmarshal(bodyBytes, &output) if err != nil || output.Message == "" { return nil, ErrorOperatorResponseUnknown(string(bodyBytes), response.StatusCode) } return nil, errors.WithStack(&errors.Error{ Kind: output.Kind, Message: output.Message, NoTelemetry: true, }) } bodyBytes, err := ioutil.ReadAll(response.Body) if err != nil { return nil, errors.Wrap(err, _errStrRead) } return bodyBytes, nil }
{ req, err := http.NewRequest(method, operatorConfig.OperatorEndpoint+endpoint, body) if err != nil { return nil, errors.Wrap(err, _errStrCantMakeRequest) } values := req.URL.Query() for _, paramMap := range qParams { for key, value := range paramMap { values.Set(key, value) } } req.URL.RawQuery = values.Encode() return req, nil }
window.py
"""Window object represented in layout.""" from bui.layout.attr import Attr from bui.layout.component import Component class Window(Component):
""" Window tag, to encompass widget tags. The window tag is the only one that is truly mandatory in your [layout](../overview.md). It is used to describe both a window and dialog. It will contain all your widgets (graphical elements). ``` <window> ... </window> ``` ## Attributes | Name | Required | Description | Example | | ------------ | -------- | ------------------------ | ----------- | | `rows` | No | The number of rows in | `<window | | | | the window grid. | rows=10>` | | | | Default is `6`. | | | `cols` | No | The number of columns | `<window | | | | in the window grid. | cols=5>` | | | | Default is `6`. | | | `title` | Yes | The window or dialog | `<window | | | | title. This attribute | title="User | | | | is mandatory. | Config">` | You cannot set a window or dialog without a proper title. Doing so would impair accessibility for screen readers. If these tools can read anything at all on your window, it's the title bar, so be sure it's not empty. > `title` is a translatable attribute. If internationalization is set, it should contain the `ytranslate` path to the title and will be translated in the proper language as needed. The `rows` and `cols` attributes are used to set the window grid. You can think of them as the height (in rows) and width (in columns) of the grid. Changing this value won't make the window any bigger, but it will give you more control on how to place the widget in the window itself. On the other hand, having a large grid can make designing not so easy. It all depends on your needs. > Note: you don't have to set the same number of rows and columns. This is just the default value. You can set different values with no trap: ``` <window cols=1 rows=8> ``` This will set a window with only one column, but 8 rows. If you place a widget in `x=0 y=0`, it will take all the window's width. Again, this doesn't change the window size in any way, just the way widgets are placed on it. You can picture the window to always be a square but sliced in different portions (squares or rectangles, more or less big depending on the height and width you set in the window tag). ## Data A window is a specific graphical element since it only contains other elements and has no meaning by itself. Therefore, you cannot send it data, it wouldn't make much sense. Instead, you should send data to the window's graphical elements themselves. However, some window attributes can be changed on the fly. | Attribute | Meaning and type | Example | | -------------- | ---------------- | --------------------------- | | `title` | The title (str) | `self.title = "New title"` | These attributes can be accessed and set using the standard Python syntax for attributes. Behind the scenes, these attributes are cached, handled by an extended `property()`, but you don't really need to worry about how it works. Suffice it to say that: class Example(Windows): def on_press_a(self): self.title = "You pressed A." ... will update the window title when the user presses the 'a' key on her keyboard. ## Controls The window tag is tied to the [Window](../../widget/Window.md) or [Dialog](../../widget/Dialog.md) class. Therefore, when you write controls on either of these classes, you often want to catch controls on indidivual graphical elements in the window. There are a few exceptions however: | Control | Method | Description | | --------------------------------- | ---------- | ---------------- | | [close](../../control/close.md) | `on_close` | The window is | | | | about to be | | | | closed, but | | | | isn't closed | | | | yet. | | [focus](../../control/focus.md) | `on_focus` | The window is | | | | focused or lose | | | | focus. This | | | | usually happens | | | | for a top window | | | | when the user | | | | switches the | | | | current app. | | [init](../../control/init.md) | `on_init` | The window is | | | | ready to be | | | | displayed, but | | | | is not displayed | | | | just yet. | | [press](../../control/press.md) | `on_press` | The user presses | | | | on a key from her| | | | keyboard. This | | | | control can have | | | | sub-controls. | | [release](../../ | `on_release` | The user | | control/release.md) | | relases a key on | | | | her keyboard. | | | | This control can | | | | have sub- | | | | controls. | | [type](../../control/type.md) | `on_type` | The user types | | | | a character | | | | using her | | | | keyboard. This | | | | control can have | | | | sub-controls. | Notice that we don't specify the window identifier. It would make no sense here. Therefore, to use these events, you should just add a method in the window class with the control name and no identifier: class MainWindow(Window): def on_focus(self): print(f"Am I focused? {'yes' if self.focused else 'no'}") """ tag_name = "window" attrs = ( Attr("title", help="The window title"), Attr("width", help="The window width", type=int, default=6), Attr("height", help="The window height", type=int, default=6), ) def __init__(self, layout, parent, title, width=0, height=0): super().__init__(layout, parent) self.title = title self.width = width self.height = height
mockResponses.ts
export class
{ public static customerWithParameterlessAction = JSON.parse( ` { "class": [ "Customer" ], "title": "A Customer", "properties": { "FullName": "Grace Miranda", "Age": 84, "Address": "6th Avenue 489 Busan", "IsFavorite": false }, "entities": [], "actions": [ { "name": "CustomerMove", "title": "A Customer moved to a new location.", "method": "POST", "href": "http://localhost:5000/Customers/1/Moves", "type": "application/json", "fields": [ { "name": "NewAddress", "type": "application/json", "class": [ "http://localhost:5000/Customers/NewAddressType" ] } ] }, { "name": "MarkAsFavoriteAction", "title": "Marks a Customer as a favorite buyer.", "method": "POST", "href": "http://localhost:5000/Customers/MyFavoriteCustomers", "type": "application/json" } ], "links": [ { "rel": [ "Self" ], "href": "http://localhost:5000/Customers/1" } ] }`); public static mockSchemaResponse = JSON.parse( `{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "title": "CustomerQuery", "additionalProperties": false, "properties": { "Pagination": { "oneOf": [ { "$ref": "#/definitions/Pagination" }, { "type": "null" } ] }, "SortBy": { "oneOf": [ { "$ref": "#/definitions/SortParameterOfCustomerSortProperties" }, { "type": "null" } ] }, "Filter": { "oneOf": [ { "$ref": "#/definitions/CustomerFilter" }, { "type": "null" } ] } }, "definitions": { "Pagination": { "type": "object", "additionalProperties": false, "properties": { "PageSize": { "type": "integer" }, "PageOffset": { "type": "integer" } } }, "SortParameterOfCustomerSortProperties": { "type": "object", "additionalProperties": false, "properties": { "PropertyName": { "oneOf": [ { "$ref": "#/definitions/CustomerSortProperties" }, { "type": "null" } ] }, "SortType": { "oneOf": [ { "$ref": "#/definitions/SortTypes" } ] } } }, "CustomerSortProperties": { "type": "integer", "x-enumNames": [ "Age", "Name" ], "enum": [ 0, 1 ], "description": "" }, "SortTypes": { "type": "integer", "x-enumNames": [ "None", "Ascending", "Descending" ], "enum": [ 0, 1, 2 ], "description": "" }, "CustomerFilter": { "type": "object", "additionalProperties": false, "properties": { "MinAge": { "type": [ "integer", "null" ] } } } } }`); }
MockResponses
roles.rs
use edgeql_parser::helpers::{quote_string, quote_name}; use crate::commands::Options; use crate::client::Connection; use crate::options::{RoleParams}; use crate::print; fn process_params(options: &RoleParams) -> Result<Vec<String>, anyhow::Error> { let mut result = Vec::new(); if options.password || options.password_from_stdin { let password = if options.password_from_stdin { rpassword::read_password()? } else { loop { let password = rpassword::read_password_from_tty( Some(&format!("New password for '{}': ", options.role.escape_default())))?; let confirm = rpassword::read_password_from_tty( Some(&format!("Confirm password for '{}': ", options.role.escape_default())))?; if password != confirm { eprintln!("Password don't match"); } else { break password; } } }; result.push(format!("SET password := {}", quote_string(&password))); } Ok(result) } pub async fn create_superuser(cli: &mut Connection, _options: &Options, role: &RoleParams) -> Result<(), anyhow::Error>
pub async fn alter(cli: &mut Connection, _options: &Options, role: &RoleParams) -> Result<(), anyhow::Error> { let params = process_params(role)?; if params.is_empty() { return Err(anyhow::anyhow!("Please specify attribute to alter")); } else { print::completion(&cli.execute( &format!(r###" ALTER ROLE {name} {{ {params} }}"###, name=quote_name(&role.role), params=params.join(";\n")) ).await?); } Ok(()) } pub async fn drop(cli: &mut Connection, _options: &Options, name: &str) -> Result<(), anyhow::Error> { print::completion(&cli.execute( &format!("DROP ROLE {}", quote_name(name)) ).await?); Ok(()) }
{ let params = process_params(role)?; if params.is_empty() { print::completion(&cli.execute( &format!("CREATE SUPERUSER ROLE {}", quote_name(&role.role)) ).await?); } else { print::completion(&cli.execute( &format!(r###" CREATE SUPERUSER ROLE {name} {{ {params} }}"###, name=quote_name(&role.role), params=params.join(";\n")) ).await?); } Ok(()) }
version.go
package policy import "github.com/Azure/azure-sdk-for-go/version" // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // UserAgent returns the UserAgent string to use when sending http.Requests. func
() string { return "Azure-SDK-For-Go/" + Version() + " policy/2016-12-01" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { return version.Number }
UserAgent
TrashCan.ts
import KahootManager from "./KahootManager"; // Very unelegant solution. // Needed tho since not implemented properly in the deprecated package and for safety reasons
export default class TrashCan { private static _collectingTimeout: number = config.autoCollectingTimeout; public static async autoCollect( visitorId: string, client: any ): Promise<NodeJS.Timeout> { try { return setTimeout( () => KahootManager.removeClient(visitorId, client), this._collectingTimeout ); } catch (err) { console.log(err); } } }
import config from "../config";
obscure.go
package obscure import ( "fmt" "github.com/ncw/rclone/cmd" "github.com/ncw/rclone/fs" "github.com/spf13/cobra" ) func init()
var commandDefintion = &cobra.Command{ Use: "obscure password", Short: `Obscure password for use in the rclone.conf`, Run: func(command *cobra.Command, args []string) { cmd.CheckArgs(1, 1, command, args) cmd.Run(false, false, command, func() error { obscure := fs.MustObscure(args[0]) fmt.Println(obscure) return nil }) }, }
{ cmd.Root.AddCommand(commandDefintion) }
postprocessor.rs
use std::io::{self, Read, Write}; use std::ffi::OsStr; use std::u64; use ahash::AHashSet as HashSet; use string_interner::Symbol; use nwind::{ DebugInfoIndex }; use common::speedy::{ Writable, }; use common::event::{ Event, AllocBody }; use common::lz4_stream::{ Lz4Writer }; use crate::loader::Loader; use crate::reader::parse_events; pub fn postprocess< F, G, D, I >( ifp: F, ofp: G, debug_symbols: I ) -> Result< (), io::Error > where F: Read + Send + 'static, G: Write, D: AsRef< OsStr >, I: IntoIterator< Item = D >
{ let mut ofp = Lz4Writer::new( ofp ); let (header, event_stream) = parse_events( ifp )?; let mut debug_info_index = DebugInfoIndex::new(); for path in debug_symbols { debug_info_index.add( path.as_ref() ); } let mut loader = Loader::new( header.clone(), debug_info_index ); Event::Header( header ).write_to_stream( &mut ofp )?; let mut frames = Vec::new(); let mut frames_to_write = Vec::new(); let mut emitted_strings = HashSet::new(); let mut expected_backtrace_id = 0; let mut expected_frame_id = 0; for event in event_stream { let mut event = event?; let mut process = false; let mut is_backtrace = false; let mut write = true; match event { Event::Backtrace { .. } | Event::Backtrace32 { .. } => { is_backtrace = true; write = false; }, Event::PartialBacktrace { .. } | Event::PartialBacktrace32 { .. } => { is_backtrace = true; write = false; }, Event::Alloc { allocation: AllocBody { ref mut backtrace, .. }, .. } | Event::AllocEx { allocation: AllocBody { ref mut backtrace, .. }, .. } | Event::Realloc { allocation: AllocBody { ref mut backtrace, .. }, .. } | Event::ReallocEx { allocation: AllocBody { ref mut backtrace, .. }, .. } | Event::Free { ref mut backtrace, .. } | Event::FreeEx { ref mut backtrace, .. } | Event::MemoryMap { ref mut backtrace, .. } | Event::MemoryUnmap { ref mut backtrace, .. } | Event::Mallopt { ref mut backtrace, .. } | Event::GroupStatistics { ref mut backtrace, .. } => { if let Some( target_backtrace ) = loader.lookup_backtrace( *backtrace ) { *backtrace = target_backtrace.raw() as _; } else { *backtrace = u64::MAX; } }, Event::File { ref mut contents, .. } if contents.starts_with( b"\x7FELF" ) => { process = true; write = false; }, Event::File { .. } => { process = true; }, Event::Header { .. } => {}, Event::MemoryDump { .. } => {}, Event::Marker { .. } => {}, Event::Environ { .. } => {}, Event::WallClock { .. } => {}, Event::String { .. } => {}, Event::DecodedFrame { .. } => {}, Event::DecodedBacktrace { .. } => {} } if write { event.write_to_stream( &mut ofp )?; } if is_backtrace { frames.clear(); frames_to_write.clear(); let backtrace_id = loader.process_backtrace_event( event, |frame_id, is_new| { frames.push( frame_id as u32 ); if is_new { frames_to_write.push( frame_id ); } }); if backtrace_id.is_none() { assert!( frames.is_empty() ); assert!( frames_to_write.is_empty() ); } for frame_id in frames_to_write.drain( .. ) { let frame = loader.get_frame( frame_id ).clone(); macro_rules! intern { ($value:expr) => { if let Some( id ) = $value { let raw_id = id.to_usize() as u32; if !emitted_strings.contains( &id ) { emitted_strings.insert( id ); let string = loader.interner().resolve( id ).unwrap(); Event::String { id: raw_id, string: string.into() }.write_to_stream( &mut ofp )?; } raw_id } else { 0xFFFFFFFF } } } let library = intern!( frame.library() ); let raw_function = intern!( frame.raw_function() ); let function = intern!( frame.function() ); let source = intern!( frame.source() ); assert_eq!( frame_id, expected_frame_id ); expected_frame_id += 1; Event::DecodedFrame { address: frame.address().raw(), library, raw_function, function, source, line: frame.line().unwrap_or( 0xFFFFFFFF ), column: frame.column().unwrap_or( 0xFFFFFFFF ), is_inline: frame.is_inline() }.write_to_stream( &mut ofp )?; } if let Some( backtrace_id ) = backtrace_id { assert_eq!( backtrace_id.raw(), expected_backtrace_id ); expected_backtrace_id += 1; Event::DecodedBacktrace { frames: (&frames).into() }.write_to_stream( &mut ofp )?; } } else if process { loader.process( event ); } } Ok(()) }
theme.ts
const theme = { color: { black: '#000000', white: '#ffffff',
text: '#2f3f42' }, font: { futura: 'Futura-Medium, Futura' } } export default theme
primary: '#2ecc71',
builder.go
package vulnerabilityreport import ( "fmt" "strings" "github.com/aquasecurity/starboard/pkg/apis/aquasecurity/v1alpha1" "github.com/aquasecurity/starboard/pkg/kube" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" ) type Builder interface { Owner(owner metav1.Object) Builder Container(name string) Builder PodSpecHash(hash string) Builder Result(result v1alpha1.VulnerabilityScanResult) Builder Get() (v1alpha1.VulnerabilityReport, error) } func NewBuilder(scheme *runtime.Scheme) Builder { return &builder{ scheme: scheme, } } type builder struct { scheme *runtime.Scheme owner metav1.Object container string hash string result v1alpha1.VulnerabilityScanResult } func (b *builder) Owner(owner metav1.Object) Builder { b.owner = owner return b } func (b *builder) Container(name string) Builder { b.container = name return b } func (b *builder) PodSpecHash(hash string) Builder { b.hash = hash return b } func (b *builder) Result(result v1alpha1.VulnerabilityScanResult) Builder { b.result = result return b } func (b *builder) reportName() (string, error) { kind, err := kube.KindForObject(b.owner, b.scheme) if err != nil { return "", err } return fmt.Sprintf("%s-%s-%s", strings.ToLower(kind), b.owner.GetName(), b.container), nil } func (b *builder) Get() (v1alpha1.VulnerabilityReport, error) { kind, err := kube.KindForObject(b.owner, b.scheme) if err != nil { return v1alpha1.VulnerabilityReport{}, err } labels := map[string]string{ kube.LabelResourceKind: kind, kube.LabelResourceName: b.owner.GetName(), kube.LabelResourceNamespace: b.owner.GetNamespace(),
if b.hash != "" { labels[kube.LabelPodSpecHash] = b.hash } reportName, err := b.reportName() if err != nil { return v1alpha1.VulnerabilityReport{}, err } report := v1alpha1.VulnerabilityReport{ ObjectMeta: metav1.ObjectMeta{ Name: reportName, Namespace: b.owner.GetNamespace(), Labels: labels, }, Report: b.result, } err = controllerutil.SetOwnerReference(b.owner, &report, b.scheme) if err != nil { return v1alpha1.VulnerabilityReport{}, err } return report, nil }
kube.LabelContainerName: b.container, }
pkg.go
package testutils import ( "fmt" "go/build" "io/ioutil" "log" "os" "path" "strings" "github.com/securego/gosec" "golang.org/x/tools/go/packages" ) type buildObj struct { pkg *build.Package config *packages.Config pkgs []*packages.Package } // TestPackage is a mock package for testing purposes type TestPackage struct { Path string Files map[string]string ondisk bool build *buildObj } // NewTestPackage will create a new and empty package. Must call Close() to cleanup // auxiliary files func NewTestPackage() *TestPackage { workingDir, err := ioutil.TempDir("", "gosecs_test") if err != nil { return nil } return &TestPackage{ Path: workingDir, Files: make(map[string]string), ondisk: false, build: nil, } } // AddFile inserts the filename and contents into the package contents func (p *TestPackage) AddFile(filename, content string) { p.Files[path.Join(p.Path, filename)] = content } func (p *TestPackage) write() error { if p.ondisk { return nil } for filename, content := range p.Files { if e := ioutil.WriteFile(filename, []byte(content), 0644); e != nil { return e } } p.ondisk = true return nil } // Build ensures all files are persisted to disk and built func (p *TestPackage) Build() error { if p.build != nil { return nil } if err := p.write(); err != nil { return err } basePackage, err := build.Default.ImportDir(p.Path, build.ImportComment) if err != nil { return err } var packageFiles []string for _, filename := range basePackage.GoFiles { packageFiles = append(packageFiles, path.Join(p.Path, filename)) } conf := &packages.Config{ Mode: gosec.LoadMode, Tests: false, } pkgs, err := packages.Load(conf, packageFiles...) if err != nil { return err } p.build = &buildObj{ pkg: basePackage, config: conf, pkgs: pkgs, } return nil } // CreateContext builds a context out of supplied package context func (p *TestPackage) CreateContext(filename string) *gosec.Context { if err := p.Build(); err != nil { log.Fatal(err) return nil } for _, pkg := range p.build.pkgs { for _, file := range pkg.Syntax { pkgFile := pkg.Fset.File(file.Pos()).Name() strip := fmt.Sprintf("%s%c", p.Path, os.PathSeparator) pkgFile = strings.TrimPrefix(pkgFile, strip) if pkgFile == filename { ctx := &gosec.Context{ FileSet: pkg.Fset,
Pkg: pkg.Types, Imports: gosec.NewImportTracker(), PassedValues: make(map[string]interface{}), } ctx.Imports.TrackPackages(ctx.Pkg.Imports()...) return ctx } } } return nil } // Close will delete the package and all files in that directory func (p *TestPackage) Close() { if p.ondisk { err := os.RemoveAll(p.Path) if err != nil { log.Fatal(err) } } } // Pkgs returns the current built packages func (p *TestPackage) Pkgs() []*packages.Package { if p.build != nil { return p.build.pkgs } return []*packages.Package{} }
Root: file, Config: gosec.NewConfig(), Info: pkg.TypesInfo,
fields.go
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. 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. // Code generated by beats/dev-tools/cmd/asset/asset.go - DO NOT EDIT. package include import ( "github.com/elastic/beats/v7/libbeat/asset" ) func init() { if err := asset.SetFields("auditbeat", "fields.yml", asset.BeatFieldsPri, AssetFieldsYml); err != nil { panic(err) } } // AssetFieldsYml returns asset data. // This is the base64 encoded gzipped contents of fields.yml. func AssetFieldsYml() string
{ return "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" }
MedianImageFilterFunctionalDocumentationTest.py
#========================================================================== # # Copyright NumFOCUS # # 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.txt # # Unless required by applicable law or agreed to in writing, software
# See the License for the specific language governing permissions and # limitations under the License. # #==========================================================================*/ # # Example on the use of the MedianImageFilter # import itk # Test that docstring in snake_case function is replaced by # docstring from corresponding object. # Not the default docstring. assert "Procedural interface for" not in itk.median_image_filter.__doc__ # But the actual filter docstring. assert "Applies a median filter to an image" in itk.median_image_filter.__doc__
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
extract.rs
//! Request extractors use std::{ convert::Infallible, future::Future, pin::Pin, task::{Context, Poll}, }; use actix_http::{Method, Uri}; use actix_utils::future::{ok, Ready}; use futures_core::ready; use pin_project_lite::pin_project; use crate::{dev::Payload, Error, HttpRequest}; /// A type that implements [`FromRequest`] is called an **extractor** and can extract data from /// the request. Some types that implement this trait are: [`Json`], [`Header`], and [`Path`]. /// /// # Configuration /// An extractor can be customized by injecting the corresponding configuration with one of: /// /// - [`App::app_data()`][crate::App::app_data] /// - [`Scope::app_data()`][crate::Scope::app_data] /// - [`Resource::app_data()`][crate::Resource::app_data] /// /// Here are some built-in extractors and their corresponding configuration. /// Please refer to the respective documentation for details. /// /// | Extractor | Configuration | /// |-------------|-------------------| /// | [`Header`] | _None_ | /// | [`Path`] | [`PathConfig`] | /// | [`Json`] | [`JsonConfig`] | /// | [`Form`] | [`FormConfig`] | /// | [`Query`] | [`QueryConfig`] | /// | [`Bytes`] | [`PayloadConfig`] | /// | [`String`] | [`PayloadConfig`] | /// | [`Payload`] | [`PayloadConfig`] | /// /// # Implementing An Extractor /// To reduce duplicate code in handlers where extracting certain parts of a request has a common /// structure, you can implement `FromRequest` for your own types. /// /// Note that the request payload can only be consumed by one extractor. /// /// [`Header`]: crate::web::Header /// [`Json`]: crate::web::Json /// [`JsonConfig`]: crate::web::JsonConfig /// [`Form`]: crate::web::Form /// [`FormConfig`]: crate::web::FormConfig /// [`Path`]: crate::web::Path /// [`PathConfig`]: crate::web::PathConfig /// [`Query`]: crate::web::Query /// [`QueryConfig`]: crate::web::QueryConfig /// [`Payload`]: crate::web::Payload /// [`PayloadConfig`]: crate::web::PayloadConfig /// [`String`]: FromRequest#impl-FromRequest-for-String /// [`Bytes`]: crate::web::Bytes#impl-FromRequest /// [`Either`]: crate::web::Either #[doc(alias = "extract", alias = "extractor")] pub trait FromRequest: Sized { /// The associated error which can be returned. type Error: Into<Error>; /// Future that resolves to a Self. type Future: Future<Output = Result<Self, Self::Error>>; /// Create a Self from request parts asynchronously. fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future; /// Create a Self from request head asynchronously. /// /// This method is short for `T::from_request(req, &mut Payload::None)`. fn extract(req: &HttpRequest) -> Self::Future { Self::from_request(req, &mut Payload::None) } } /// Optionally extract a field from the request /// /// If the FromRequest for T fails, return None rather than returning an error response /// /// # Examples /// ``` /// use actix_web::{web, dev, App, Error, HttpRequest, FromRequest}; /// use actix_web::error::ErrorBadRequest; /// use futures_util::future::{ok, err, Ready}; /// use serde::Deserialize; /// use rand; /// /// #[derive(Debug, Deserialize)] /// struct Thing { /// name: String /// } /// /// impl FromRequest for Thing { /// type Error = Error; /// type Future = Ready<Result<Self, Self::Error>>; /// /// fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { /// if rand::random() { /// ok(Thing { name: "thingy".into() }) /// } else { /// err(ErrorBadRequest("no luck")) /// } /// /// } /// } /// /// /// extract `Thing` from request /// async fn index(supplied_thing: Option<Thing>) -> String { /// match supplied_thing { /// // Puns not intended /// Some(thing) => format!("Got something: {:?}", thing), /// None => format!("No thing!") /// } /// } /// /// fn main() { /// let app = App::new().service( /// web::resource("/users/:first").route( /// web::post().to(index)) /// ); /// } /// ``` impl<T: 'static> FromRequest for Option<T> where T: FromRequest, T::Future: 'static, { type Error = Error; type Future = FromRequestOptFuture<T::Future>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { FromRequestOptFuture { fut: T::from_request(req, payload), } } } pin_project! { pub struct FromRequestOptFuture<Fut> { #[pin] fut: Fut, } } impl<Fut, T, E> Future for FromRequestOptFuture<Fut> where Fut: Future<Output = Result<T, E>>, E: Into<Error>, { type Output = Result<Option<T>, Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); let res = ready!(this.fut.poll(cx)); match res { Ok(t) => Poll::Ready(Ok(Some(t))), Err(e) => { log::debug!("Error for Option<T> extractor: {}", e.into()); Poll::Ready(Ok(None)) } } } } /// Optionally extract a field from the request or extract the Error if unsuccessful /// /// If the `FromRequest` for T fails, inject Err into handler rather than returning an error response /// /// # Examples /// ``` /// use actix_web::{web, dev, App, Result, Error, HttpRequest, FromRequest}; /// use actix_web::error::ErrorBadRequest; /// use futures_util::future::{ok, err, Ready}; /// use serde::Deserialize; /// use rand; /// /// #[derive(Debug, Deserialize)] /// struct Thing { /// name: String /// } /// /// impl FromRequest for Thing { /// type Error = Error; /// type Future = Ready<Result<Thing, Error>>; /// /// fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { /// if rand::random() { /// ok(Thing { name: "thingy".into() }) /// } else { /// err(ErrorBadRequest("no luck")) /// } /// } /// } /// /// /// extract `Thing` from request /// async fn index(supplied_thing: Result<Thing>) -> String { /// match supplied_thing { /// Ok(thing) => format!("Got thing: {:?}", thing), /// Err(e) => format!("Error extracting thing: {}", e) /// } /// } /// /// fn main() { /// let app = App::new().service( /// web::resource("/users/:first").route(web::post().to(index)) /// ); /// } /// ``` impl<T> FromRequest for Result<T, T::Error> where T: FromRequest + 'static, T::Error: 'static, T::Future: 'static, { type Error = Error; type Future = FromRequestResFuture<T::Future>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { FromRequestResFuture { fut: T::from_request(req, payload), } } } pin_project! { pub struct FromRequestResFuture<Fut> { #[pin] fut: Fut, } } impl<Fut, T, E> Future for FromRequestResFuture<Fut> where Fut: Future<Output = Result<T, E>>, { type Output = Result<Result<T, E>, Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); let res = ready!(this.fut.poll(cx)); Poll::Ready(Ok(res)) } } /// Extract the request's URI. /// /// # Examples /// ``` /// use actix_web::{http::Uri, web, App, Responder}; /// /// async fn handler(uri: Uri) -> impl Responder { /// format!("Requested path: {}", uri.path()) /// } /// /// let app = App::new().default_service(web::to(handler)); /// ``` impl FromRequest for Uri { type Error = Infallible; type Future = Ready<Result<Self, Self::Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { ok(req.uri().clone()) } } /// Extract the request's method. /// /// # Examples /// ``` /// use actix_web::{http::Method, web, App, Responder}; /// /// async fn handler(method: Method) -> impl Responder { /// format!("Request method: {}", method) /// } /// /// let app = App::new().default_service(web::to(handler)); /// ``` impl FromRequest for Method { type Error = Infallible; type Future = Ready<Result<Self, Self::Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { ok(req.method().clone()) } } #[doc(hidden)] impl FromRequest for () { type Error = Infallible; type Future = Ready<Result<Self, Self::Error>>; fn from_request(_: &HttpRequest, _: &mut Payload) -> Self::Future { ok(()) } } #[doc(hidden)] #[allow(non_snake_case)] mod tuple_from_req { use super::*; macro_rules! tuple_from_req { ($fut: ident; $($T: ident),*) => { /// FromRequest implementation for tuple #[allow(unused_parens)] impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+) { type Error = Error; type Future = $fut<$($T),+>; fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { $fut { $( $T: ExtractFuture::Future { fut: $T::from_request(req, payload) }, )+ } } } pin_project! { pub struct $fut<$($T: FromRequest),+> { $( #[pin] $T: ExtractFuture<$T::Future, $T>, )+ } } impl<$($T: FromRequest),+> Future for $fut<$($T),+> { type Output = Result<($($T,)+), Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = self.project(); let mut ready = true; $( match this.$T.as_mut().project() { ExtractProj::Future { fut } => match fut.poll(cx) { Poll::Ready(Ok(output)) => { let _ = this.$T.as_mut().project_replace(ExtractFuture::Done { output }); }, Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())), Poll::Pending => ready = false, }, ExtractProj::Done { .. } => {}, ExtractProj::Empty => unreachable!("FromRequest polled after finished"), } )+ if ready { Poll::Ready(Ok( ($( match this.$T.project_replace(ExtractFuture::Empty) { ExtractReplaceProj::Done { output } => output, _ => unreachable!("FromRequest polled after finished"), }, )+) )) } else { Poll::Pending } } } }; } pin_project! { #[project = ExtractProj] #[project_replace = ExtractReplaceProj] enum ExtractFuture<Fut, Res> { Future { #[pin] fut: Fut }, Done { output: Res, }, Empty } } tuple_from_req! { TupleFromRequest1; A } tuple_from_req! { TupleFromRequest2; A, B } tuple_from_req! { TupleFromRequest3; A, B, C } tuple_from_req! { TupleFromRequest4; A, B, C, D } tuple_from_req! { TupleFromRequest5; A, B, C, D, E } tuple_from_req! { TupleFromRequest6; A, B, C, D, E, F } tuple_from_req! { TupleFromRequest7; A, B, C, D, E, F, G } tuple_from_req! { TupleFromRequest8; A, B, C, D, E, F, G, H } tuple_from_req! { TupleFromRequest9; A, B, C, D, E, F, G, H, I } tuple_from_req! { TupleFromRequest10; A, B, C, D, E, F, G, H, I, J } } #[cfg(test)] mod tests { use actix_http::header; use bytes::Bytes; use serde::Deserialize; use super::*; use crate::test::TestRequest; use crate::types::{Form, FormConfig}; #[derive(Deserialize, Debug, PartialEq)] struct Info { hello: String, } #[actix_rt::test] async fn test_option() { let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .data(FormConfig::default().limit(4096)) .to_http_parts(); let r = Option::<Form<Info>>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(r, None); let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, "9")) .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); let r = Option::<Form<Info>>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!( r, Some(Form(Info { hello: "world".into() })) ); let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, "9")) .set_payload(Bytes::from_static(b"bye=world")) .to_http_parts(); let r = Option::<Form<Info>>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(r, None); } #[actix_rt::test] async fn test_result() { let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, "11")) .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl) .await .unwrap() .unwrap(); assert_eq!( r, Form(Info { hello: "world".into() }) ); let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, 9)) .set_payload(Bytes::from_static(b"bye=world")) .to_http_parts(); let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl) .await .unwrap(); assert!(r.is_err()); } #[actix_rt::test] async fn
() { let req = TestRequest::default().uri("/foo/bar").to_http_request(); let uri = Uri::extract(&req).await.unwrap(); assert_eq!(uri.path(), "/foo/bar"); } #[actix_rt::test] async fn test_method() { let req = TestRequest::default().method(Method::GET).to_http_request(); let method = Method::extract(&req).await.unwrap(); assert_eq!(method, Method::GET); } #[actix_rt::test] async fn test_concurrent() { let (req, mut pl) = TestRequest::default() .uri("/foo/bar") .method(Method::GET) .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, "11")) .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); let (method, uri, form) = <(Method, Uri, Form<Info>)>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(method, Method::GET); assert_eq!(uri.path(), "/foo/bar"); assert_eq!( form, Form(Info { hello: "world".into() }) ); } }
test_uri
post.mutation.ts
import { MutationCreatePostArgs, MutationResolvers, Navigation, NavigationType, PostStatusOptions, PostTypes, RequireFields, } from "@/__generated__/__types__"; import { slugify, getImageDimensions, setImageWidthAndHeightInHtml, getReadingTimeFromHtml, } from "./helpers"; import logger from "@/shared/logger"; import { ResolverContext } from "../context"; import { Prisma } from "@prisma/client"; import { mapPostToGraphql } from "./mapper"; import Cheerio from "cheerio"; import { getLastPartFromPath, textToSlug } from "@/utils/slug"; export const createPost = async ( args: RequireFields<MutationCreatePostArgs, never>, { session, prisma }: ResolverContext, ) => { if (!args.data || !session?.user.id) { return { __typename: "PostError", message: "Session not found", }; } const author = await prisma.author.findFirst({ where: { id: session.user.id }, }); if (!author) { return { __typename: "PostError", message: "Author not found", }; } let slug = args.data.slug; try { const newPost = await prisma.post.create({ data: { title: args.data.title, cover_image: args.data.cover_image?.src, cover_image_width: args.data.cover_image?.width, cover_image_height: args.data.cover_image?.height, html: args.data.html || "", author: { connect: { id: author.id }, }, type: args.data.type || PostTypes.Post, status: args.data.status, }, }); const newSlug = await getOrCreateSlug( prisma.post, newPost.id, slug, args.data.title, ); await prisma.post.update({ data: { slug: newSlug }, where: { id: newPost.id }, }); newPost.slug = newSlug; if (newPost) { return { ...mapPostToGraphql(newPost), title: args.data.title || "Untitled", }; } } catch (e) {} return { __typename: "PostError", message: "Unable to create post", }; }; const Mutation: MutationResolvers<ResolverContext> = { //@ts-ignore async createPost(_parent, args, context) { return await createPost(args, context); }, async updatePost(_parent, args, { session, prisma }, _info) { if (!session?.user.id) { return { __typename: "PostError", message: "Authentication failed", }; } try { if (!args.data) { return { __typename: "PostError", message: "No arguments to create a post", }; } const existingPost = await prisma.post.findFirst({ where: { id: args.data.id }, }); if (!existingPost) { return { __typename: "PostError", message: "Current post not found to update", }; } const newPostArgs: Prisma.PostUpdateArgs = { data: {}, where: { id: args.data.id, }, }; if (args.data.title) { newPostArgs.data.title = args.data.title; } if (args.data.excerpt) { newPostArgs.data.excerpt = args.data.excerpt; } if (args.data.status) { newPostArgs.data.status = args.data.status; } if (args.data.featured) { newPostArgs.data.featured = args.data.featured; } if (args.data.cover_image) { const img = await getCoverImageAttrs(args.data.cover_image); newPostArgs.data.cover_image = img.cover_image; newPostArgs.data.cover_image_width = img.cover_image_width; newPostArgs.data.cover_image_height = img.cover_image_height; } if (args.data.slug) { newPostArgs.data.slug = await slugify( prisma.post, textToSlug(args.data.slug), existingPost.author_id, ); } if (args.data.title && existingPost.slug.includes("untitled")) { newPostArgs.data.slug = await slugify( prisma.post, textToSlug(args.data.title), existingPost.author_id, ); } if (args.data.html) { newPostArgs.data.html = await formatHtml(args.data.html); newPostArgs.data.reading_time = getReadingTimeFromHtml( newPostArgs.data.html, ); } if (args.data.html_draft) { newPostArgs.data.html_draft = await formatHtml(args.data.html_draft); } if (args.data.status === PostStatusOptions.Published) { newPostArgs.data.html = existingPost.html_draft || ""; newPostArgs.data.publishedAt = new Date(); } if (args.data.status === PostStatusOptions.Draft) { newPostArgs.data.html_draft = existingPost.html || ""; } newPostArgs.data.updatedAt = new Date(); if (args.data.tags) { newPostArgs.data.tags = { set: [], connectOrCreate: args.data.tags.map(({ name, slug }) => { return { create: { name, slug }, where: { name }, }; }), }; } const updatedPost = await prisma.post.update(newPostArgs); // update content if (updatedPost) { await updateMenuOnTitleChange({ Author: prisma.author, authorId: session.user.id, isPage: updatedPost.type === PostTypes.Page, prevOriginalName: existingPost.title, originalName: updatedPost.title, slug: updatedPost.slug, }); } if (!updatedPost) { return { __typename: "PostError", message: "Updated post not found", }; } return { ...mapPostToGraphql(updatedPost), }; } catch (e) { console.log(e); return { __typename: "PostError", message: e.message, }; } }, }; interface UpdateMenuProps { Author: Prisma.AuthorDelegate<false>; authorId: number; isPage: boolean; slug: string; originalName?: string; prevOriginalName: string; } async function updateMenuOnTitleChange(props: UpdateMenuProps) { const { Author, isPage, prevOriginalName, originalName, authorId, slug } = props; if (isPage) { const author = await Author.findFirst({ where: { id: authorId }, include: { setting: true }, }); if (!author) return false; const jsonMenu = JSON.parse(author.setting?.menu || "[]") as Navigation[]; const updatedMenu = jsonMenu.map((item) => { if ( item.type === NavigationType.Page && item.original_name === prevOriginalName ) { if (originalName) item.original_name = originalName; item.slug = slug; } return item; }); await Author.update({ data: { setting: { update: { menu: JSON.stringify(updatedMenu), }, }, }, where: { id: authorId }, }); } } async function
( postModel: Prisma.PostDelegate<false>, id: number, newSlug?: string, newTitle?: string, ) { const existingPost = await postModel.findFirst({ where: { id } }); if (!existingPost) return ""; // slug already exist for this post, but user updated the slug if (existingPost?.slug && newSlug) { newSlug = getLastPartFromPath(newSlug); newSlug = await slugify( postModel, textToSlug(newSlug), existingPost.author_id, ); return newSlug; } // slug does not exist for existing post or contains default untitled slug. // If new title was entered, create a new slug if ( newTitle && (existingPost?.slug.startsWith("untitled") || !existingPost?.slug) ) { newSlug = await slugify( postModel, textToSlug(newTitle), existingPost.author_id, ); return newSlug; } if (!existingPost.title && !newTitle && !newSlug) { newSlug = await slugify(postModel, "untitled", existingPost.author_id); return newSlug; } if (!newSlug) return existingPost?.slug; return textToSlug(newSlug); } async function getCoverImageAttrs(cover_image): Promise<{ cover_image: string; cover_image_width: number; cover_image_height: number; }> { if (!cover_image) return { cover_image: "", cover_image_width: 0, cover_image_height: 0 }; const { width, height } = cover_image; let src = cover_image.src?.replace(process.env.ROOT_URL || "", ""); const data = { cover_image: src, cover_image_width: width, cover_image_height: height, }; if (width && height && src) { return data; } if (!src) return data; try { const imageSize = await getImageDimensions(src); data.cover_image_width = imageSize.width; data.cover_image_height = imageSize.height; } catch (e) { logger.error(`Failed to retrieve width and height of image - ${src}`); } return data; } async function formatHtml(html: string) { const $ = Cheerio.load(html, { xmlMode: true, decodeEntities: false, normalizeWhitespace: false, }); // remove all tooltips which are used for grammar checking $("[data-tippy-root]").remove(); $("[data-mce-bogus='all']").remove(); $("head").remove(); $(".mark").each(function () { // remove all decorations caused by grammar $(this).replaceWith($(this).text()); }); html = $.html(); const _html = await setImageWidthAndHeightInHtml(html); if (_html) { html = _html; } return html; } export default { Mutation };
getOrCreateSlug
key_slot_storage.rs
// Copyright 2021 Contributors to the Parsec project. // SPDX-License-Identifier: Apache-2.0 use crate::providers::cryptoauthlib::key_slot::{AteccKeySlot, KeySlotStatus}; use log::warn; use parsec_interface::operations::psa_key_attributes::Attributes; use parsec_interface::requests::{Opcode, ResponseStatus}; use std::sync::RwLock; #[derive(Debug)] pub struct KeySlotStorage { storage: RwLock<[AteccKeySlot; rust_cryptoauthlib::ATCA_ATECC_SLOTS_COUNT as usize]>, } impl KeySlotStorage { pub fn new() -> KeySlotStorage { KeySlotStorage { storage: RwLock::new( [AteccKeySlot::default(); rust_cryptoauthlib::ATCA_ATECC_SLOTS_COUNT as usize], ), } } /// Validate KeyInfo data store entry against hardware. /// Mark slot busy when all checks pass. /// Expected to be called from Provider::new() only. pub fn key_validate_and_mark_busy( &self, key_id: u8, key_attr: &Attributes, ) -> Result<Option<String>, String> { let mut key_slots = self.storage.write().unwrap(); // Get CryptoAuthLibProvider mapping of key triple to key info and check // (1) if the key info matches ATECC configuration - drop key triple if not // (2) if there are no two key triples mapping to a single ATECC slot - warning only ATM // check (1) match key_slots[key_id as usize].key_attr_vs_config(key_id, key_attr, None) { Ok(_) => (), Err(err) => { let error = std::format!("ATECC slot configuration mismatch: {}", err); return Err(error); } }; // check(2) match key_slots[key_id as usize].reference_check_and_set() { Ok(_) => (), Err(slot) => { let warning = std::format!("Superfluous reference(s) to ATECC slot {:?}", slot); return Ok(Some(warning)); } }; // Slot 'key_id' validated - trying to mark it busy match key_slots[key_id as usize].set_slot_status(KeySlotStatus::Busy) { Ok(()) => Ok(None), Err(err) => { let error = std::format!("Unable to set hardware slot status: {}", err); Err(error) } } } /// Lock protected per slot hardware configuration setter pub fn set_hw_config(&self, hw_config: &[rust_cryptoauthlib::AtcaSlot]) -> Result<(), String> { // RwLock protection let mut key_slots = self.storage.write().unwrap(); for slot in hw_config.iter().cloned() { if slot.is_valid() { key_slots[slot.id as usize] = AteccKeySlot { ref_count: 0u8, status: { match slot.is_locked { true => KeySlotStatus::Locked, _ => KeySlotStatus::Free, } }, config: slot.config, }; } } Ok(()) } /// Lock protected set slot status wrapper pub fn set_slot_status( &self, slot_id: usize, status: KeySlotStatus, ) -> Result<(), ResponseStatus> { let mut key_slots = self.storage.write().unwrap(); key_slots[slot_id].set_slot_status(status) } /// Iterate through key_slots and find a free one with configuration matching attributes. /// If found, the slot is marked Busy. pub fn find_suitable_slot( &self, key_attr: &Attributes, op: Option<Opcode>, ) -> Result<u8, ResponseStatus>
}
{ let mut key_slots = self.storage.write().unwrap(); for slot in 0..rust_cryptoauthlib::ATCA_ATECC_SLOTS_COUNT { if !key_slots[slot as usize].is_free() { continue; } match key_slots[slot as usize].key_attr_vs_config(slot, key_attr, op) { Ok(_) => { match key_slots[slot as usize].set_slot_status(KeySlotStatus::Busy) { Ok(()) => return Ok(slot), Err(err) => { warn!( "find_suitable_slot() - slot {} cannot be marked as busy", slot ); return Err(err); } }; } Err(_) => continue, } } Err(ResponseStatus::PsaErrorInsufficientStorage) }
RollingUpgradeFormContainer.js
// Copyright (c) YugaByte, Inc. import { formValueSelector, reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import { RollingUpgradeForm } from '../../../common/forms'; import { closeDialog } from '../../../../actions/modal'; import { rollingUpgrade, rollingUpgradeResponse, closeUniverseDialog, resetRollingUpgrade, fetchUniverseTasks, fetchUniverseTasksResponse, fetchUniverseMetadata, fetchUniverseInfo, fetchUniverseInfoResponse } from '../../../../actions/universe'; import { fetchUniversesPendingTasks, fetchUniversesPendingTasksSuccess, fetchUniversesPendingTasksFailure } from '../../../../actions/tasks'; import { isDefinedNotNull, isNonEmptyObject } from '../../../../utils/ObjectUtils'; import { getPrimaryCluster } from '../../../../utils/UniverseUtils'; import { TASK_LONG_TIMEOUT } from '../../../tasks/constants'; const FORM_NAME = 'RollingUpgradeForm'; const mapDispatchToProps = (dispatch) => { return { /** * Dispatch Rolling Upgrade/ Gflag restart to endpoint and handle response. * @param values form data payload * @param universeUUID UUID of the current Universe * @param reset function that sets the value of the form to pristine state */ submitRollingUpgradeForm: (values, universeUUID, reset) => { dispatch(rollingUpgrade(values, universeUUID)).then((response) => { if (!response.error) { dispatch(closeDialog()); dispatch(closeUniverseDialog()); } dispatch(rollingUpgradeResponse(response.payload)); // Reset the Rolling upgrade form fields to pristine state, // component may be called multiple times within the context of Universe Detail. reset(); }); }, fetchUniverseTasks: (uuid) => { dispatch(fetchUniverseTasks(uuid)).then((response) => { dispatch(fetchUniverseTasksResponse(response.payload)); }); }, getAllUniversePendingTasks: () => { dispatch(fetchUniversesPendingTasks()).then((response) => { if (!response.error) { dispatch(fetchUniversesPendingTasksSuccess(response.payload)); } else { dispatch(fetchUniversesPendingTasksFailure(response.payload)); } }); }, resetRollingUpgrade: () => { dispatch(resetRollingUpgrade()); }, fetchUniverseMetadata: () => { dispatch(fetchUniverseMetadata()); }, fetchCurrentUniverse: (universeUUID) => { dispatch(fetchUniverseInfo(universeUUID)).then((response) => { dispatch(fetchUniverseInfoResponse(response.payload)); }); } }; }; function
(state, ownProps) { const { universe: { currentUniverse } } = state; const initalGFlagValues = {}; if (isNonEmptyObject(currentUniverse) && isNonEmptyObject(currentUniverse.data.universeDetails)) { const primaryCluster = getPrimaryCluster(currentUniverse.data.universeDetails.clusters); if (isDefinedNotNull(primaryCluster)) { const masterGFlags = primaryCluster.userIntent.masterGFlags; const tserverGFlags = primaryCluster.userIntent.tserverGFlags; if (isNonEmptyObject(masterGFlags)) { initalGFlagValues.masterGFlags = Object.keys(masterGFlags).map(function (gFlagKey) { return { name: gFlagKey, value: masterGFlags[gFlagKey] }; }); } if (isNonEmptyObject(tserverGFlags)) { initalGFlagValues.tserverGFlags = Object.keys(tserverGFlags).map(function (gFlagKey) { return { name: gFlagKey, value: tserverGFlags[gFlagKey] }; }); } } } initalGFlagValues.ybSoftwareVersion = state.customer.softwareVersions[0]; initalGFlagValues.timeDelay = TASK_LONG_TIMEOUT / 1000; initalGFlagValues.upgradeOption = 'Rolling'; initalGFlagValues.rollingUpgrade = true; const selector = formValueSelector(FORM_NAME); const upgradeOption = selector(state, 'upgradeOption'); return { modal: state.modal, universe: state.universe, softwareVersions: state.customer.softwareVersions, initialValues: initalGFlagValues, upgradeOption }; } const rollingUpgradeForm = reduxForm({ form: FORM_NAME }); export default connect(mapStateToProps, mapDispatchToProps)(rollingUpgradeForm(RollingUpgradeForm));
mapStateToProps
GetKudoCountOverview.go
package features import ( "fmt" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" "github.com/olekukonko/tablewriter" "gorm.io/gorm" "log" "niverobot/model" "sort" "strconv" "strings" ) type GetKudoCountOverview struct { kudoCounts model.KudoCounts } func NewGetKudoCountOverview(kudoCountService model.KudoCounts) GetKudoCountOverview { return GetKudoCountOverview{kudoCounts: kudoCountService} } func (g GetKudoCountOverview) Execute(update tgbotapi.Update, db *gorm.DB, bot *tgbotapi.BotAPI, history model.MessageHistory) { kudoCounts, err := g.kudoCounts.GetKudoCountPerChat(update.Message.Chat.ID, db) kudoCounts = orderByKudoSum(kudoCounts) table := fmt.Sprintf("%s", renderTableAsString(kudoCounts)) msg := tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("<pre>%s</pre>", table)) msg.ParseMode = "html" if err != nil { msg = tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("Kudo error: %s", err)) } _, err = bot.Send(msg) if err != nil { log.Panicf("error sending message %s", err) } } func (g GetKudoCountOverview) Trigger(update tgbotapi.Update) bool { return strings.EqualFold(update.Message.Text, ".kudos") } func
(kudoCounts []model.KudoCount) []model.KudoCount { sort.Slice(kudoCounts, func(i, j int) bool { return (kudoCounts[i].Plus - kudoCounts[i].Minus) > (kudoCounts[j].Plus - kudoCounts[j].Minus) }) return kudoCounts } func renderTableAsString(kudoCount []model.KudoCount) string { tableString := &strings.Builder{} table := tablewriter.NewWriter(tableString) table.SetHeader([]string{"Name", "Plus", "Min"}) table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) table.SetCenterSeparator("|") for _, kudo := range kudoCount { if len(kudo.User.FirstName.String) > 5{ table.Append([]string{kudo.User.FirstName.String[:5], strconv.Itoa(kudo.Plus), strconv.Itoa(kudo.Minus)}) }else{ table.Append([]string{kudo.User.FirstName.String, strconv.Itoa(kudo.Plus), strconv.Itoa(kudo.Minus)}) } } table.Render() return tableString.String() }
orderByKudoSum
iterator.rs
use crate::prelude::*; use crate::utils::Xob; use std::iter::FromIterator; macro_rules! from_iterator { ($native:ty, $variant:ident) => { impl FromIterator<Option<$native>> for Series { fn from_iter<I: IntoIterator<Item = Option<$native>>>(iter: I) -> Self { let ca = iter.into_iter().collect(); Series::$variant(ca) } } impl FromIterator<$native> for Series { fn from_iter<I: IntoIterator<Item = $native>>(iter: I) -> Self { let ca: Xob<ChunkedArray<_>> = iter.into_iter().collect(); Series::$variant(ca.into_inner()) } } impl<'a> FromIterator<&'a $native> for Series { fn from_iter<I: IntoIterator<Item = &'a $native>>(iter: I) -> Self { let ca = iter.into_iter().map(|v| Some(*v)).collect(); Series::$variant(ca) } } }; } from_iterator!(u8, UInt8); from_iterator!(u16, UInt16); from_iterator!(u32, UInt32); from_iterator!(u64, UInt64); from_iterator!(i8, Int8); from_iterator!(i16, Int16); from_iterator!(i32, Int32); from_iterator!(i64, Int64); from_iterator!(f32, Float32); from_iterator!(f64, Float64); from_iterator!(bool, Bool); impl<'a> FromIterator<&'a str> for Series { fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self { let ca = iter.into_iter().collect(); Series::Utf8(ca) } } impl<'a> FromIterator<&'a Series> for Series { fn from_iter<I: IntoIterator<Item = &'a Series>>(iter: I) -> Self { let ca = iter.into_iter().collect(); Series::List(ca) } } impl FromIterator<Series> for Series { fn from_iter<I: IntoIterator<Item = Series>>(iter: I) -> Self { let ca = iter.into_iter().collect(); Series::List(ca) } } impl FromIterator<Option<Series>> for Series { fn from_iter<I: IntoIterator<Item = Option<Series>>>(iter: I) -> Self { let ca = iter.into_iter().collect();
} } #[cfg(test)] mod test { use crate::prelude::*; #[test] fn test_iter() { let a = Series::new("age", [23, 71, 9].as_ref()); let _b = a .i32() .unwrap() .into_iter() .map(|opt_v| opt_v.map(|v| v * 2)); } }
Series::List(ca)
__init__.py
from __future__ import absolute_import, unicode_literals from ..util import Wheel from ....util.path import Path BUNDLE_FOLDER = Path(__file__).absolute().parent BUNDLE_SUPPORT = { "3.10": { "pip": "pip-21.3.1-py3-none-any.whl", "setuptools": "setuptools-58.3.0-py3-none-any.whl", "wheel": "wheel-0.37.0-py2.py3-none-any.whl", }, "3.9": { "pip": "pip-21.3.1-py3-none-any.whl", "setuptools": "setuptools-58.3.0-py3-none-any.whl", "wheel": "wheel-0.37.0-py2.py3-none-any.whl", }, "3.8": { "pip": "pip-21.3.1-py3-none-any.whl", "setuptools": "setuptools-58.3.0-py3-none-any.whl", "wheel": "wheel-0.37.0-py2.py3-none-any.whl", }, "3.7": { "pip": "pip-21.3.1-py3-none-any.whl", "setuptools": "setuptools-58.3.0-py3-none-any.whl", "wheel": "wheel-0.37.0-py2.py3-none-any.whl", }, "3.6": { "pip": "pip-21.3.1-py3-none-any.whl", "setuptools": "setuptools-58.3.0-py3-none-any.whl", "wheel": "wheel-0.37.0-py2.py3-none-any.whl", }, "3.5": { "pip": "pip-20.3.4-py2.py3-none-any.whl", "setuptools": "setuptools-50.3.2-py3-none-any.whl", "wheel": "wheel-0.37.0-py2.py3-none-any.whl", }, "2.7": { "pip": "pip-20.3.4-py2.py3-none-any.whl", "setuptools": "setuptools-44.1.1-py2.py3-none-any.whl", "wheel": "wheel-0.37.0-py2.py3-none-any.whl", }, } MAX = "3.10" def get_embed_wheel(distribution, for_py_version):
__all__ = ( "get_embed_wheel", "BUNDLE_SUPPORT", "MAX", "BUNDLE_FOLDER", )
path = BUNDLE_FOLDER / (BUNDLE_SUPPORT.get(for_py_version, {}) or BUNDLE_SUPPORT[MAX]).get(distribution) return Wheel.from_path(path)
get_user_documents_handler.go
package api import ( "net/http" "github.com/alphagov/paas-accounts/database" "github.com/labstack/echo" ) func
(db *database.DB) echo.HandlerFunc { return func(c echo.Context) error { allDocuments, err := db.GetDocumentsForUserUUID(c.Param("uuid")) if err != nil { return InternalServerError{err} } onlyUnagreed := c.QueryParam("agreed") == "false" userDocuments := []database.UserDocument{} for _, doc := range allDocuments { if onlyUnagreed && doc.AgreementDate != nil { continue } userDocuments = append(userDocuments, doc) } return c.JSON(http.StatusOK, userDocuments) } }
GetUserDocumentsHandler
mod.rs
// ignore-tidy-filelength //! MIR datatypes and passes. See the [rustc guide] for more info. //! //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html use crate::hir::def::{CtorKind, Namespace}; use crate::hir::def_id::DefId; use crate::hir::{self, InlineAsm as HirInlineAsm}; use crate::mir::interpret::{ConstValue, PanicInfo, Scalar}; use crate::mir::visit::MirVisitable; use crate::ty::adjustment::PointerCast; use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor}; use crate::ty::layout::VariantIdx; use crate::ty::print::{FmtPrinter, Printer}; use crate::ty::subst::{Subst, SubstsRef}; use crate::ty::{ self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex, }; use polonius_engine::Atom; use rustc_index::bit_set::BitMatrix; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::graph::dominators::{dominators, Dominators}; use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors}; use rustc_index::vec::{Idx, IndexVec}; use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::MappedReadGuard; use rustc_macros::HashStable; use rustc_serialize::{Encodable, Decodable}; use smallvec::SmallVec; use std::borrow::Cow; use std::fmt::{self, Debug, Display, Formatter, Write}; use std::ops::{Index, IndexMut}; use std::slice; use std::vec::IntoIter; use std::{iter, mem, option, u32}; use syntax::ast::Name; use syntax::symbol::Symbol; use syntax_pos::{Span, DUMMY_SP}; pub use crate::mir::interpret::AssertMessage; mod cache; pub mod interpret; pub mod mono; pub mod tcx; pub mod traversal; pub mod visit; /// Types for locals type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>; pub trait HasLocalDecls<'tcx> { fn local_decls(&self) -> &LocalDecls<'tcx>; } impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> { fn local_decls(&self) -> &LocalDecls<'tcx> { self } } impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> { fn local_decls(&self) -> &LocalDecls<'tcx> { &self.local_decls } } /// The various "big phases" that MIR goes through. /// /// Warning: ordering of variants is significant. #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum MirPhase { Build = 0, Const = 1, Validated = 2, Optimized = 3, } impl MirPhase { /// Gets the index of the current MirPhase within the set of all `MirPhase`s. pub fn phase_index(&self) -> usize { *self as usize } } /// The lowered representation of a single function. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Body<'tcx> { /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock` /// that indexes into this vector. basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>, /// Records how far through the "desugaring and optimization" process this particular /// MIR has traversed. This is particularly useful when inlining, since in that context /// we instantiate the promoted constants and add them to our promoted vector -- but those /// promoted items have already been optimized, whereas ours have not. This field allows /// us to see the difference and forego optimization on the inlined promoted items. pub phase: MirPhase, /// A list of source scopes; these are referenced by statements /// and used for debuginfo. Indexed by a `SourceScope`. pub source_scopes: IndexVec<SourceScope, SourceScopeData>, /// Crate-local information for each source scope, that can't (and /// needn't) be tracked across crates. pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>, /// The yield type of the function, if it is a generator. pub yield_ty: Option<Ty<'tcx>>, /// Generator drop glue. pub generator_drop: Option<Box<Body<'tcx>>>, /// The layout of a generator. Produced by the state transformation. pub generator_layout: Option<GeneratorLayout<'tcx>>, /// Declarations of locals. /// /// The first local is the return value pointer, followed by `arg_count` /// locals for the function arguments, followed by any user-declared /// variables and temporaries. pub local_decls: LocalDecls<'tcx>, /// User type annotations. pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>, /// The number of arguments this function takes. /// /// Starting at local 1, `arg_count` locals will be provided by the caller /// and can be assumed to be initialized. /// /// If this MIR was built for a constant, this will be 0. pub arg_count: usize, /// Mark an argument local (which must be a tuple) as getting passed as /// its individual components at the LLVM level. /// /// This is used for the "rust-call" ABI. pub spread_arg: Option<Local>, /// Names and capture modes of all the closure upvars, assuming /// the first argument is either the closure or a reference to it. // // NOTE(eddyb) This is *strictly* a temporary hack for codegen // debuginfo generation, and will be removed at some point. // Do **NOT** use it for anything else; upvar information should not be // in the MIR, so please rely on local crate HIR or other side-channels. pub __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>, /// Mark this MIR of a const context other than const functions as having converted a `&&` or /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop /// this conversion from happening and use short circuiting, we will cause the following code /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };` /// /// List of places where control flow was destroyed. Used for error reporting. pub control_flow_destroyed: Vec<(Span, String)>, /// A span representing this MIR, for error reporting. pub span: Span, /// A cache for various calculations. cache: cache::Cache, } impl<'tcx> Body<'tcx> { pub fn new( basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>, source_scopes: IndexVec<SourceScope, SourceScopeData>, source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>, yield_ty: Option<Ty<'tcx>>, local_decls: LocalDecls<'tcx>, user_type_annotations: CanonicalUserTypeAnnotations<'tcx>, arg_count: usize, __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>, span: Span, control_flow_destroyed: Vec<(Span, String)>, ) -> Self { // We need `arg_count` locals, and one for the return place. assert!( local_decls.len() >= arg_count + 1, "expected at least {} locals, got {}", arg_count + 1, local_decls.len() ); Body { phase: MirPhase::Build, basic_blocks, source_scopes, source_scope_local_data, yield_ty, generator_drop: None, generator_layout: None, local_decls, user_type_annotations, arg_count, __upvar_debuginfo_codegen_only_do_not_use, spread_arg: None, span, cache: cache::Cache::new(), control_flow_destroyed, } } #[inline] pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> { &self.basic_blocks } #[inline] pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> { self.cache.invalidate(); &mut self.basic_blocks } #[inline] pub fn basic_blocks_and_local_decls_mut( &mut self, ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) { self.cache.invalidate(); (&mut self.basic_blocks, &mut self.local_decls) } #[inline] pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> { self.cache.predecessors(self) } #[inline] pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> { MappedReadGuard::map(self.predecessors(), |p| &p[bb]) } #[inline] pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ { let if_zero_locations = if loc.statement_index == 0 { let predecessor_blocks = self.predecessors_for(loc.block); let num_predecessor_blocks = predecessor_blocks.len(); Some( (0..num_predecessor_blocks) .map(move |i| predecessor_blocks[i]) .map(move |bb| self.terminator_loc(bb)), ) } else { None }; let if_not_zero_locations = if loc.statement_index == 0 { None } else { Some(Location { block: loc.block, statement_index: loc.statement_index - 1 }) }; if_zero_locations.into_iter().flatten().chain(if_not_zero_locations) } #[inline] pub fn dominators(&self) -> Dominators<BasicBlock> { dominators(self) } /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the /// `START_BLOCK`. pub fn is_cfg_cyclic(&self) -> bool { graph::is_cyclic(self) } #[inline] pub fn local_kind(&self, local: Local) -> LocalKind { let index = local.as_usize(); if index == 0 { debug_assert!( self.local_decls[local].mutability == Mutability::Mut, "return place should be mutable" ); LocalKind::ReturnPointer } else if index < self.arg_count + 1 { LocalKind::Arg } else if self.local_decls[local].name.is_some() { LocalKind::Var } else { LocalKind::Temp } } /// Returns an iterator over all temporaries. #[inline] pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a { (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| { let local = Local::new(index); if self.local_decls[local].is_user_variable.is_some() { None } else { Some(local) } }) } /// Returns an iterator over all user-declared locals. #[inline] pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a { (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| { let local = Local::new(index); if self.local_decls[local].is_user_variable.is_some() { Some(local) } else { None } }) } /// Returns an iterator over all user-declared mutable locals. #[inline] pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a { (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| { let local = Local::new(index); let decl = &self.local_decls[local]; if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut { Some(local) } else { None } }) } /// Returns an iterator over all user-declared mutable arguments and locals. #[inline] pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a { (1..self.local_decls.len()).filter_map(move |index| { let local = Local::new(index); let decl = &self.local_decls[local]; if (decl.is_user_variable.is_some() || index < self.arg_count + 1) && decl.mutability == Mutability::Mut { Some(local) } else { None } }) } /// Returns an iterator over all function arguments. #[inline] pub fn args_iter(&self) -> impl Iterator<Item = Local> { let arg_count = self.arg_count; (1..=arg_count).map(Local::new) } /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all /// locals that are neither arguments nor the return place). #[inline] pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> { let arg_count = self.arg_count; let local_count = self.local_decls.len(); (arg_count + 1..local_count).map(Local::new) } /// Changes a statement to a nop. This is both faster than deleting instructions and avoids /// invalidating statement indices in `Location`s. pub fn make_statement_nop(&mut self, location: Location) { let block = &mut self[location.block]; debug_assert!(location.statement_index < block.statements.len()); block.statements[location.statement_index].make_nop() } /// Returns the source info associated with `location`. pub fn source_info(&self, location: Location) -> &SourceInfo { let block = &self[location.block]; let stmts = &block.statements; let idx = location.statement_index; if idx < stmts.len() { &stmts[idx].source_info } else { assert_eq!(idx, stmts.len()); &block.terminator().source_info } } /// Checks if `sub` is a sub scope of `sup` pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool { while sub != sup { match self.source_scopes[sub].parent_scope { None => return false, Some(p) => sub = p, } } true } /// Returns the return type; it always return first element from `local_decls` array. pub fn return_ty(&self) -> Ty<'tcx> { self.local_decls[RETURN_PLACE].ty } /// Gets the location of the terminator for the given block. pub fn terminator_loc(&self, bb: BasicBlock) -> Location { Location { block: bb, statement_index: self[bb].statements.len() } } } #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub enum Safety { Safe, /// Unsafe because of a PushUnsafeBlock BuiltinUnsafe, /// Unsafe because of an unsafe fn FnUnsafe, /// Unsafe because of an `unsafe` block ExplicitUnsafe(hir::HirId), } impl_stable_hash_for!(struct Body<'tcx> { phase, basic_blocks, source_scopes, source_scope_local_data, yield_ty, generator_drop, generator_layout, local_decls, user_type_annotations, arg_count, __upvar_debuginfo_codegen_only_do_not_use, spread_arg, control_flow_destroyed, span, cache }); impl<'tcx> Index<BasicBlock> for Body<'tcx> { type Output = BasicBlockData<'tcx>; #[inline] fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> { &self.basic_blocks()[index] } } impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> { #[inline] fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> { &mut self.basic_blocks_mut()[index] } } #[derive(Copy, Clone, Debug, HashStable)] pub enum ClearCrossCrate<T> { Clear, Set(T), } impl<T> ClearCrossCrate<T> { pub fn assert_crate_local(self) -> T { match self { ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"), ClearCrossCrate::Set(v) => v, } } } impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {} impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {} /// Grouped information about the source code origin of a MIR entity. /// Intended to be inspected by diagnostics and debuginfo. /// Most passes can work with it as a whole, within a single function. // The unoffical Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and // `Hash`. Please ping @bjorn3 if removing them. #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)] pub struct SourceInfo { /// The source span for the AST pertaining to this MIR entity. pub span: Span, /// The source scope, keeping track of which bindings can be /// seen by debuginfo, active lint levels, `unsafe {...}`, etc. pub scope: SourceScope, } /////////////////////////////////////////////////////////////////////////// // Mutability and borrow kinds #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)] pub enum Mutability { Mut, Not, } impl From<Mutability> for hir::Mutability { fn from(m: Mutability) -> Self { match m { Mutability::Mut => hir::MutMutable, Mutability::Not => hir::MutImmutable, } } } #[derive( Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable, )] pub enum BorrowKind { /// Data must be immutable and is aliasable. Shared, /// The immediately borrowed place must be immutable, but projections from /// it don't need to be. For example, a shallow borrow of `a.b` doesn't /// conflict with a mutable borrow of `a.b.c`. /// /// This is used when lowering matches: when matching on a place we want to /// ensure that place have the same value from the start of the match until /// an arm is selected. This prevents this code from compiling: /// /// let mut x = &Some(0); /// match *x { /// None => (), /// Some(_) if { x = &None; false } => (), /// Some(_) => (), /// } /// /// This can't be a shared borrow because mutably borrowing (*x as Some).0 /// should not prevent `if let None = x { ... }`, for example, because the /// mutating `(*x as Some).0` can't affect the discriminant of `x`. /// We can also report errors with this kind of borrow differently. Shallow, /// Data must be immutable but not aliasable. This kind of borrow /// cannot currently be expressed by the user and is used only in /// implicit closure bindings. It is needed when the closure is /// borrowing or mutating a mutable referent, e.g.: /// /// let x: &mut isize = ...; /// let y = || *x += 5; /// /// If we were to try to translate this closure into a more explicit /// form, we'd encounter an error with the code as written: /// /// struct Env { x: & &mut isize } /// let x: &mut isize = ...; /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn /// fn fn_ptr(env: &mut Env) { **env.x += 5; } /// /// This is then illegal because you cannot mutate an `&mut` found /// in an aliasable location. To solve, you'd have to translate with /// an `&mut` borrow: /// /// struct Env { x: & &mut isize } /// let x: &mut isize = ...; /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x /// fn fn_ptr(env: &mut Env) { **env.x += 5; } /// /// Now the assignment to `**env.x` is legal, but creating a /// mutable pointer to `x` is not because `x` is not mutable. We /// could fix this by declaring `x` as `let mut x`. This is ok in /// user code, if awkward, but extra weird for closures, since the /// borrow is hidden. /// /// So we introduce a "unique imm" borrow -- the referent is /// immutable, but not aliasable. This solves the problem. For /// simplicity, we don't give users the way to express this /// borrow, it's just used when translating closures. Unique, /// Data is mutable and not aliasable. Mut { /// `true` if this borrow arose from method-call auto-ref /// (i.e., `adjustment::Adjust::Borrow`). allow_two_phase_borrow: bool, }, } impl BorrowKind { pub fn allows_two_phase_borrow(&self) -> bool { match *self { BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false, BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow, } } } /////////////////////////////////////////////////////////////////////////// // Variables and temps rustc_index::newtype_index! { pub struct Local { derive [HashStable] DEBUG_FORMAT = "_{}", const RETURN_PLACE = 0, } } impl Atom for Local { fn index(self) -> usize { Idx::index(self) } } /// Classifies locals into categories. See `Body::local_kind`. #[derive(PartialEq, Eq, Debug, HashStable)] pub enum LocalKind { /// User-declared variable binding. Var, /// Compiler-introduced temporary. Temp, /// Function argument. Arg, /// Location of function's return value. ReturnPointer, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct VarBindingForm<'tcx> { /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`? pub binding_mode: ty::BindingMode, /// If an explicit type was provided for this variable binding, /// this holds the source Span of that type. /// /// NOTE: if you want to change this to a `HirId`, be wary that /// doing so breaks incremental compilation (as of this writing), /// while a `Span` does not cause our tests to fail. pub opt_ty_info: Option<Span>, /// Place of the RHS of the =, or the subject of the `match` where this /// variable is initialized. None in the case of `let PATTERN;`. /// Some((None, ..)) in the case of and `let [mut] x = ...` because /// (a) the right-hand side isn't evaluated as a place expression. /// (b) it gives a way to separate this case from the remaining cases /// for diagnostics. pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>, /// The span of the pattern in which this variable was bound. pub pat_span: Span, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub enum BindingForm<'tcx> { /// This is a binding for a non-`self` binding, or a `self` that has an explicit type. Var(VarBindingForm<'tcx>), /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit. ImplicitSelf(ImplicitSelfKind), /// Reference used in a guard expression to ensure immutability. RefForGuard, } /// Represents what type of implicit self a function has, if any. #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable)] pub enum ImplicitSelfKind { /// Represents a `fn x(self);`. Imm, /// Represents a `fn x(mut self);`. Mut, /// Represents a `fn x(&self);`. ImmRef, /// Represents a `fn x(&mut self);`. MutRef, /// Represents when a function does not have a self argument or /// when a function has a `self: X` argument. None, } CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, } impl_stable_hash_for!(struct self::VarBindingForm<'tcx> { binding_mode, opt_ty_info, opt_match_place, pat_span }); impl_stable_hash_for!(enum self::ImplicitSelfKind { Imm, Mut, ImmRef, MutRef, None }); impl_stable_hash_for!(enum self::MirPhase { Build, Const, Validated, Optimized, }); mod binding_form_impl { use crate::ich::StableHashingContext; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { use super::BindingForm::*; ::std::mem::discriminant(self).hash_stable(hcx, hasher); match self { Var(binding) => binding.hash_stable(hcx, hasher), ImplicitSelf(kind) => kind.hash_stable(hcx, hasher), RefForGuard => (), } } } } /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries /// created during evaluation of expressions in a block tail /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`. /// /// It is used to improve diagnostics when such temporaries are /// involved in borrow_check errors, e.g., explanations of where the /// temporaries come from, when their destructors are run, and/or how /// one might revise the code to satisfy the borrow checker's rules. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct BlockTailInfo { /// If `true`, then the value resulting from evaluating this tail /// expression is ignored by the block's expression context. /// /// Examples include `{ ...; tail };` and `let _ = { ...; tail };` /// but not e.g., `let _x = { ...; tail };` pub tail_result_is_ignored: bool, } impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored }); /// A MIR local. /// /// This can be a binding declared by the user, a temporary inserted by the compiler, a function /// argument, or the return place. #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct LocalDecl<'tcx> { /// Whether this is a mutable minding (i.e., `let x` or `let mut x`). /// /// Temporaries and the return place are always mutable. pub mutability: Mutability, /// `Some(binding_mode)` if this corresponds to a user-declared local variable. /// /// This is solely used for local diagnostics when generating /// warnings/errors when compiling the current crate, and /// therefore it need not be visible across crates. pnkfelix /// currently hypothesized we *need* to wrap this in a /// `ClearCrossCrate` as long as it carries as `HirId`. pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>, /// `true` if this is an internal local. /// /// These locals are not based on types in the source code and are only used /// for a few desugarings at the moment. /// /// The generator transformation will sanity check the locals which are live /// across a suspension point against the type components of the generator /// which type checking knows are live across a suspension point. We need to /// flag drop flags to avoid triggering this check as they are introduced /// after typeck. /// /// Unsafety checking will also ignore dereferences of these locals, /// so they can be used for raw pointers only used in a desugaring. /// /// This should be sound because the drop flags are fully algebraic, and /// therefore don't affect the OIBIT or outlives properties of the /// generator. pub internal: bool, /// If this local is a temporary and `is_block_tail` is `Some`, /// then it is a temporary created for evaluation of some /// subexpression of some block's tail expression (with no /// intervening statement context). pub is_block_tail: Option<BlockTailInfo>, /// The type of this local. pub ty: Ty<'tcx>, /// If the user manually ascribed a type to this variable, /// e.g., via `let x: T`, then we carry that type here. The MIR /// borrow checker needs this information since it can affect /// region inference. pub user_ty: UserTypeProjections, /// The name of the local, used in debuginfo and pretty-printing. /// /// Note that function arguments can also have this set to `Some(_)` /// to generate better debuginfo. pub name: Option<Name>, /// The *syntactic* (i.e., not visibility) source scope the local is defined /// in. If the local was defined in a let-statement, this /// is *within* the let-statement, rather than outside /// of it. /// /// This is needed because the visibility source scope of locals within /// a let-statement is weird. /// /// The reason is that we want the local to be *within* the let-statement /// for lint purposes, but we want the local to be *after* the let-statement /// for names-in-scope purposes. /// /// That's it, if we have a let-statement like the one in this /// function: /// /// ``` /// fn foo(x: &str) { /// #[allow(unused_mut)] /// let mut x: u32 = { // <- one unused mut /// let mut y: u32 = x.parse().unwrap(); /// y + 2 /// }; /// drop(x); /// } /// ``` /// /// Then, from a lint point of view, the declaration of `x: u32` /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the /// lint scopes are the same as the AST/HIR nesting. /// /// However, from a name lookup point of view, the scopes look more like /// as if the let-statements were `match` expressions: /// /// ``` /// fn foo(x: &str) { /// match { /// match x.parse().unwrap() { /// y => y + 2 /// } /// } { /// x => drop(x) /// }; /// } /// ``` /// /// We care about the name-lookup scopes for debuginfo - if the /// debuginfo instruction pointer is at the call to `x.parse()`, we /// want `x` to refer to `x: &str`, but if it is at the call to /// `drop(x)`, we want it to refer to `x: u32`. /// /// To allow both uses to work, we need to have more than a single scope /// for a local. We have the `source_info.scope` represent the /// "syntactic" lint scope (with a variable being under its let /// block) while the `visibility_scope` represents the "local variable" /// scope (where the "rest" of a block is under all prior let-statements). /// /// The end result looks like this: /// /// ```text /// ROOT SCOPE /// │{ argument x: &str } /// │ /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes /// │ │ // in practice because I'm lazy. /// │ │ /// │ │← x.source_info.scope /// │ │← `x.parse().unwrap()` /// │ │ /// │ │ │← y.source_info.scope /// │ │ /// │ │ │{ let y: u32 } /// │ │ │ /// │ │ │← y.visibility_scope /// │ │ │← `y + 2` /// │ /// │ │{ let x: u32 } /// │ │← x.visibility_scope /// │ │← `drop(x)` // This accesses `x: u32`. /// ``` pub source_info: SourceInfo, /// Source scope within which the local is visible (for debuginfo) /// (see `source_info` for more details). pub visibility_scope: SourceScope, } impl<'tcx> LocalDecl<'tcx> { /// Returns `true` only if local is a binding that can itself be /// made mutable via the addition of the `mut` keyword, namely /// something like the occurrences of `x` in: /// - `fn foo(x: Type) { ... }`, /// - `let x = ...`, /// - or `match ... { C(x) => ... }` pub fn can_be_made_mutable(&self) -> bool { match self.is_user_variable { Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm { binding_mode: ty::BindingMode::BindByValue(_), opt_ty_info: _, opt_match_place: _, pat_span: _, }))) => true, Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm))) => true, _ => false, } } /// Returns `true` if local is definitely not a `ref ident` or /// `ref mut ident` binding. (Such bindings cannot be made into /// mutable bindings, but the inverse does not necessarily hold). pub fn is_nonref_binding(&self) -> bool { match self.is_user_variable { Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm { binding_mode: ty::BindingMode::BindByValue(_), opt_ty_info: _, opt_match_place: _, pat_span: _, }))) => true, Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true, _ => false, } } /// Returns `true` if this is a reference to a variable bound in a `match` /// expression that is used to access said variable for the guard of the /// match arm. pub fn is_ref_for_guard(&self) -> bool { match self.is_user_variable { Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true, _ => false, } } /// Returns `true` is the local is from a compiler desugaring, e.g., /// `__next` from a `for` loop. #[inline] pub fn from_compiler_desugaring(&self) -> bool { self.source_info.span.desugaring_kind().is_some() } /// Creates a new `LocalDecl` for a temporary. #[inline] pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self { Self::new_local(ty, Mutability::Mut, false, span) } /// Converts `self` into same `LocalDecl` except tagged as immutable. #[inline] pub fn immutable(mut self) -> Self { self.mutability = Mutability::Not; self } /// Converts `self` into same `LocalDecl` except tagged as internal temporary. #[inline] pub fn block_tail(mut self, info: BlockTailInfo) -> Self { assert!(self.is_block_tail.is_none()); self.is_block_tail = Some(info); self } /// Creates a new `LocalDecl` for a internal temporary. #[inline] pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self { Self::new_local(ty, Mutability::Mut, true, span) } #[inline] fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self { LocalDecl { mutability, ty, user_ty: UserTypeProjections::none(), name: None, source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }, visibility_scope: OUTERMOST_SOURCE_SCOPE, internal, is_user_variable: None, is_block_tail: None, } } /// Builds a `LocalDecl` for the return place. /// /// This must be inserted into the `local_decls` list as the first local. #[inline] pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> { LocalDecl { mutability: Mutability::Mut, ty: return_ty, user_ty: UserTypeProjections::none(), source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }, visibility_scope: OUTERMOST_SOURCE_SCOPE, internal: false, is_block_tail: None, name: None, // FIXME maybe we do want some name here? is_user_variable: None, } } } /// A closure capture, with its name and mode. #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct UpvarDebuginfo { pub debug_name: Name, /// If true, the capture is behind a reference. pub by_ref: bool, } /////////////////////////////////////////////////////////////////////////// // BasicBlock rustc_index::newtype_index! { pub struct BasicBlock { derive [HashStable] DEBUG_FORMAT = "bb{}", const START_BLOCK = 0, } } impl BasicBlock { pub fn start_location(self) -> Location { Location { block: self, statement_index: 0 } } } /////////////////////////////////////////////////////////////////////////// // BasicBlockData and Terminator #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct BasicBlockData<'tcx> { /// List of statements in this block. pub statements: Vec<Statement<'tcx>>, /// Terminator for this block. /// /// N.B., this should generally ONLY be `None` during construction. /// Therefore, you should generally access it via the /// `terminator()` or `terminator_mut()` methods. The only /// exception is that certain passes, such as `simplify_cfg`, swap /// out the terminator temporarily with `None` while they continue /// to recurse over the set of basic blocks. pub terminator: Option<Terminator<'tcx>>, /// If true, this block lies on an unwind path. This is used /// during codegen where distinct kinds of basic blocks may be /// generated (particularly for MSVC cleanup). Unwind blocks must /// only branch to other unwind blocks. pub is_cleanup: bool, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct Terminator<'tcx> { pub source_info: SourceInfo, pub kind: TerminatorKind<'tcx>, } #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] pub enum TerminatorKind<'tcx> { /// Block should have one successor in the graph; we jump there. Goto { target: BasicBlock }, /// Operand evaluates to an integer; jump depending on its value /// to one of the targets, and otherwise fallback to `otherwise`. SwitchInt { /// The discriminant value being tested. discr: Operand<'tcx>, /// The type of value being tested. switch_ty: Ty<'tcx>, /// Possible values. The locations to branch to in each case /// are found in the corresponding indices from the `targets` vector. values: Cow<'tcx, [u128]>, /// Possible branch sites. The last element of this vector is used /// for the otherwise branch, so targets.len() == values.len() + 1 /// should hold. // // This invariant is quite non-obvious and also could be improved. // One way to make this invariant is to have something like this instead: // // branches: Vec<(ConstInt, BasicBlock)>, // otherwise: Option<BasicBlock> // exhaustive if None // // However we’ve decided to keep this as-is until we figure a case // where some other approach seems to be strictly better than other. targets: Vec<BasicBlock>, }, /// Indicates that the landing pad is finished and unwinding should /// continue. Emitted by `build::scope::diverge_cleanup`. Resume, /// Indicates that the landing pad is finished and that the process /// should abort. Used to prevent unwinding for foreign items. Abort, /// Indicates a normal return. The return place should have /// been filled in by now. This should occur at most once. Return, /// Indicates a terminator that can never be reached. Unreachable, /// Drop the `Place`. Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> }, /// Drop the `Place` and assign the new value over it. This ensures /// that the assignment to `P` occurs *even if* the destructor for /// place unwinds. Its semantics are best explained by the /// elaboration: /// /// ``` /// BB0 { /// DropAndReplace(P <- V, goto BB1, unwind BB2) /// } /// ``` /// /// becomes /// /// ``` /// BB0 { /// Drop(P, goto BB1, unwind BB2) /// } /// BB1 { /// // P is now uninitialized /// P <- V /// } /// BB2 { /// // P is now uninitialized -- its dtor panicked /// P <- V /// } /// ``` DropAndReplace { location: Place<'tcx>, value: Operand<'tcx>, target: BasicBlock, unwind: Option<BasicBlock>, }, /// Block ends with a call of a converging function. Call { /// The function that’s being called. func: Operand<'tcx>, /// Arguments the function is called with. /// These are owned by the callee, which is free to modify them. /// This allows the memory occupied by "by-value" arguments to be /// reused across function calls without duplicating the contents. args: Vec<Operand<'tcx>>, /// Destination for the return value. If some, the call is converging. destination: Option<(Place<'tcx>, BasicBlock)>, /// Cleanups to be done if the call unwinds. cleanup: Option<BasicBlock>, /// `true` if this is from a call in HIR rather than from an overloaded /// operator. True for overloaded function call. from_hir_call: bool, }, /// Jump to the target if the condition has the expected value, /// otherwise panic with a message and a cleanup target. Assert { cond: Operand<'tcx>, expected: bool, msg: AssertMessage<'tcx>, target: BasicBlock, cleanup: Option<BasicBlock>, }, /// A suspend point. Yield { /// The value to return. value: Operand<'tcx>, /// Where to resume to. resume: BasicBlock, /// Cleanup to be done if the generator is dropped at this suspend point. drop: Option<BasicBlock>, }, /// Indicates the end of the dropping of a generator. GeneratorDrop, /// A block where control flow only ever takes one real path, but borrowck /// needs to be more conservative. FalseEdges { /// The target normal control flow will take. real_target: BasicBlock, /// A block control flow could conceptually jump to, but won't in /// practice. imaginary_target: BasicBlock, }, /// A terminator for blocks that only take one path in reality, but where we /// reserve the right to unwind in borrowck, even if it won't happen in practice. /// This can arise in infinite loops with no function calls for example. FalseUnwind { /// The target normal control flow will take. real_target: BasicBlock, /// The imaginary cleanup block link. This particular path will never be taken /// in practice, but in order to avoid fragility we want to always /// consider it in borrowck. We don't want to accept programs which /// pass borrowck only when `panic=abort` or some assertions are disabled /// due to release vs. debug mode builds. This needs to be an `Option` because /// of the `remove_noop_landing_pads` and `no_landing_pads` passes. unwind: Option<BasicBlock>, }, } pub type Successors<'a> = iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>; pub type SuccessorsMut<'a> = iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>; impl<'tcx> Terminator<'tcx> { pub fn successors(&self) -> Successors<'_> { self.kind.successors() } pub fn successors_mut(&mut self) -> SuccessorsMut<'_> { self.kind.successors_mut() } pub fn unwind(&self) -> Option<&Option<BasicBlock>> { self.kind.unwind() } pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> { self.kind.unwind_mut() } } impl<'tcx> TerminatorKind<'tcx> { pub fn if_( tcx: TyCtxt<'tcx>, cond: Operand<'tcx>, t: BasicBlock, f: BasicBlock, ) -> TerminatorKind<'tcx> { static BOOL_SWITCH_FALSE: &'static [u128] = &[0]; TerminatorKind::SwitchInt { discr: cond, switch_ty: tcx.types.bool, values: From::from(BOOL_SWITCH_FALSE), targets: vec![f, t], } } pub fn successors(&self) -> Successors<'_> { use self::TerminatorKind::*; match *self { Resume | Abort | GeneratorDrop | Return | Unreachable | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]), Goto { target: ref t } | Call { destination: None, cleanup: Some(ref t), .. } | Call { destination: Some((_, ref t)), cleanup: None, .. } | Yield { resume: ref t, drop: None, .. } | DropAndReplace { target: ref t, unwind: None, .. } | Drop { target: ref t, unwind: None, .. } | Assert { target: ref t, cleanup: None, .. } | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]), Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. } | Yield { resume: ref t, drop: Some(ref u), .. } | DropAndReplace { target: ref t, unwind: Some(ref u), .. } | Drop { target: ref t, unwind: Some(ref u), .. } | Assert { target: ref t, cleanup: Some(ref u), .. } | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => { Some(t).into_iter().chain(slice::from_ref(u)) } SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]), FalseEdges { ref real_target, ref imaginary_target } => { Some(real_target).into_iter().chain(slice::from_ref(imaginary_target)) } } } pub fn successors_mut(&mut self) -> SuccessorsMut<'_> { use self::TerminatorKind::*; match *self { Resume | Abort | GeneratorDrop | Return | Unreachable | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []), Goto { target: ref mut t } | Call { destination: None, cleanup: Some(ref mut t), .. } | Call { destination: Some((_, ref mut t)), cleanup: None, .. } | Yield { resume: ref mut t, drop: None, .. } | DropAndReplace { target: ref mut t, unwind: None, .. } | Drop { target: ref mut t, unwind: None, .. } | Assert { target: ref mut t, cleanup: None, .. } | FalseUnwind { real_target: ref mut t, unwind: None } => { Some(t).into_iter().chain(&mut []) } Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. } | Yield { resume: ref mut t, drop: Some(ref mut u), .. } | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. } | Drop { target: ref mut t, unwind: Some(ref mut u), .. } | Assert { target: ref mut t, cleanup: Some(ref mut u), .. } | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => { Some(t).into_iter().chain(slice::from_mut(u)) } SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]), FalseEdges { ref mut real_target, ref mut imaginary_target } => { Some(real_target).into_iter().chain(slice::from_mut(imaginary_target)) } } } pub fn unwind(&self) -> Option<&Option<BasicBlock>> { match *self { TerminatorKind::Goto { .. } | TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Return | TerminatorKind::Unreachable | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } | TerminatorKind::SwitchInt { .. } | TerminatorKind::FalseEdges { .. } => None, TerminatorKind::Call { cleanup: ref unwind, .. } | TerminatorKind::Assert { cleanup: ref unwind, .. } | TerminatorKind::DropAndReplace { ref unwind, .. } | TerminatorKind::Drop { ref unwind, .. } | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind), } } pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> { match *self { TerminatorKind::Goto { .. } | TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Return | TerminatorKind::Unreachable | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } | TerminatorKind::SwitchInt { .. } | TerminatorKind::FalseEdges { .. } => None, TerminatorKind::Call { cleanup: ref mut unwind, .. } | TerminatorKind::Assert { cleanup: ref mut unwind, .. } | TerminatorKind::DropAndReplace { ref mut unwind, .. } | TerminatorKind::Drop { ref mut unwind, .. } | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind), } } } impl<'tcx> BasicBlockData<'tcx> { pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> { BasicBlockData { statements: vec![], terminator, is_cleanup: false } } /// Accessor for terminator. /// /// Terminator may not be None after construction of the basic block is complete. This accessor /// provides a convenience way to reach the terminator. pub fn terminator(&self) -> &Terminator<'tcx> { self.terminator.as_ref().expect("invalid terminator state") } pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> { self.terminator.as_mut().expect("
ator state") } pub fn retain_statements<F>(&mut self, mut f: F) where F: FnMut(&mut Statement<'_>) -> bool, { for s in &mut self.statements { if !f(s) { s.make_nop(); } } } pub fn expand_statements<F, I>(&mut self, mut f: F) where F: FnMut(&mut Statement<'tcx>) -> Option<I>, I: iter::TrustedLen<Item = Statement<'tcx>>, { // Gather all the iterators we'll need to splice in, and their positions. let mut splices: Vec<(usize, I)> = vec![]; let mut extra_stmts = 0; for (i, s) in self.statements.iter_mut().enumerate() { if let Some(mut new_stmts) = f(s) { if let Some(first) = new_stmts.next() { // We can already store the first new statement. *s = first; // Save the other statements for optimized splicing. let remaining = new_stmts.size_hint().0; if remaining > 0 { splices.push((i + 1 + extra_stmts, new_stmts)); extra_stmts += remaining; } } else { s.make_nop(); } } } // Splice in the new statements, from the end of the block. // FIXME(eddyb) This could be more efficient with a "gap buffer" // where a range of elements ("gap") is left uninitialized, with // splicing adding new elements to the end of that gap and moving // existing elements from before the gap to the end of the gap. // For now, this is safe code, emulating a gap but initializing it. let mut gap = self.statements.len()..self.statements.len() + extra_stmts; self.statements.resize( gap.end, Statement { source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE }, kind: StatementKind::Nop, }, ); for (splice_start, new_stmts) in splices.into_iter().rev() { let splice_end = splice_start + new_stmts.size_hint().0; while gap.end > splice_end { gap.start -= 1; gap.end -= 1; self.statements.swap(gap.start, gap.end); } self.statements.splice(splice_start..splice_end, new_stmts); gap.end = splice_start; } } pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> { if index < self.statements.len() { &self.statements[index] } else { &self.terminator } } } impl<'tcx> Debug for TerminatorKind<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { self.fmt_head(fmt)?; let successor_count = self.successors().count(); let labels = self.fmt_successor_labels(); assert_eq!(successor_count, labels.len()); match successor_count { 0 => Ok(()), 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()), _ => { write!(fmt, " -> [")?; for (i, target) in self.successors().enumerate() { if i > 0 { write!(fmt, ", ")?; } write!(fmt, "{}: {:?}", labels[i], target)?; } write!(fmt, "]") } } } } impl<'tcx> TerminatorKind<'tcx> { /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the /// successor basic block, if any. The only information not included is the list of possible /// successors, which may be rendered differently between the text and the graphviz format. pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result { use self::TerminatorKind::*; match *self { Goto { .. } => write!(fmt, "goto"), SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place), Return => write!(fmt, "return"), GeneratorDrop => write!(fmt, "generator_drop"), Resume => write!(fmt, "resume"), Abort => write!(fmt, "abort"), Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value), Unreachable => write!(fmt, "unreachable"), Drop { ref location, .. } => write!(fmt, "drop({:?})", location), DropAndReplace { ref location, ref value, .. } => { write!(fmt, "replace({:?} <- {:?})", location, value) } Call { ref func, ref args, ref destination, .. } => { if let Some((ref destination, _)) = *destination { write!(fmt, "{:?} = ", destination)?; } write!(fmt, "{:?}(", func)?; for (index, arg) in args.iter().enumerate() { if index > 0 { write!(fmt, ", ")?; } write!(fmt, "{:?}", arg)?; } write!(fmt, ")") } Assert { ref cond, expected, ref msg, .. } => { write!(fmt, "assert(")?; if !expected { write!(fmt, "!")?; } write!(fmt, "{:?}, \"{:?}\")", cond, msg) } FalseEdges { .. } => write!(fmt, "falseEdges"), FalseUnwind { .. } => write!(fmt, "falseUnwind"), } } /// Returns the list of labels for the edges to the successor basic blocks. pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> { use self::TerminatorKind::*; match *self { Return | Resume | Abort | Unreachable | GeneratorDrop => vec![], Goto { .. } => vec!["".into()], SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| { let param_env = ty::ParamEnv::empty(); let switch_ty = tcx.lift(&switch_ty).unwrap(); let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size; values .iter() .map(|&u| { tcx.mk_const(ty::Const { val: ConstValue::Scalar(Scalar::from_uint(u, size).into()), ty: switch_ty, }) .to_string() .into() }) .chain(iter::once("otherwise".into())) .collect() }), Call { destination: Some(_), cleanup: Some(_), .. } => { vec!["return".into(), "unwind".into()] } Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()], Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()], Call { destination: None, cleanup: None, .. } => vec![], Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()], Yield { drop: None, .. } => vec!["resume".into()], DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => { vec!["return".into()] } DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => { vec!["return".into(), "unwind".into()] } Assert { cleanup: None, .. } => vec!["".into()], Assert { .. } => vec!["success".into(), "unwind".into()], FalseEdges { .. } => vec!["real".into(), "imaginary".into()], FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()], FalseUnwind { unwind: None, .. } => vec!["real".into()], } } } /////////////////////////////////////////////////////////////////////////// // Statements #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] pub struct Statement<'tcx> { pub source_info: SourceInfo, pub kind: StatementKind<'tcx>, } // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] static_assert_size!(Statement<'_>, 32); impl Statement<'_> { /// Changes a statement to a nop. This is both faster than deleting instructions and avoids /// invalidating statement indices in `Location`s. pub fn make_nop(&mut self) { self.kind = StatementKind::Nop } /// Changes a statement to a nop and returns the original statement. pub fn replace_nop(&mut self) -> Self { Statement { source_info: self.source_info, kind: mem::replace(&mut self.kind, StatementKind::Nop), } } } #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub enum StatementKind<'tcx> { /// Write the RHS Rvalue to the LHS Place. Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>), /// This represents all the reading that a pattern match may do /// (e.g., inspecting constants and discriminant values), and the /// kind of pattern it comes from. This is in order to adapt potential /// error messages to these specific patterns. /// /// Note that this also is emitted for regular `let` bindings to ensure that locals that are /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;` FakeRead(FakeReadCause, Box<Place<'tcx>>), /// Write the discriminant for a variant to the enum Place. SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx }, /// Start a live range for the storage of the local. StorageLive(Local), /// End the current live range for the storage of the local. StorageDead(Local), /// Executes a piece of inline Assembly. Stored in a Box to keep the size /// of `StatementKind` low. InlineAsm(Box<InlineAsm<'tcx>>), /// Retag references in the given place, ensuring they got fresh tags. This is /// part of the Stacked Borrows model. These statements are currently only interpreted /// by miri and only generated when "-Z mir-emit-retag" is passed. /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/> /// for more details. Retag(RetagKind, Box<Place<'tcx>>), /// Encodes a user's type ascription. These need to be preserved /// intact so that NLL can respect them. For example: /// /// let a: T = y; /// /// The effect of this annotation is to relate the type `T_y` of the place `y` /// to the user-given type `T`. The effect depends on the specified variance: /// /// - `Covariant` -- requires that `T_y <: T` /// - `Contravariant` -- requires that `T_y :> T` /// - `Invariant` -- requires that `T_y == T` /// - `Bivariant` -- no effect AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance), /// No-op. Useful for deleting instructions without affecting statement indices. Nop, } /// Describes what kind of retag is to be performed. #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)] pub enum RetagKind { /// The initial retag when entering a function. FnEntry, /// Retag preparing for a two-phase borrow. TwoPhase, /// Retagging raw pointers. Raw, /// A "normal" retag. Default, } /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists. #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] pub enum FakeReadCause { /// Inject a fake read of the borrowed input at the end of each guards /// code. /// /// This should ensure that you cannot change the variant for an enum while /// you are in the midst of matching on it. ForMatchGuard, /// `let x: !; match x {}` doesn't generate any read of x so we need to /// generate a read of x to check that it is initialized and safe. ForMatchedPlace, /// A fake read of the RefWithinGuard version of a bind-by-value variable /// in a match guard to ensure that it's value hasn't change by the time /// we create the OutsideGuard version. ForGuardBinding, /// Officially, the semantics of /// /// `let pattern = <expr>;` /// /// is that `<expr>` is evaluated into a temporary and then this temporary is /// into the pattern. /// /// However, if we see the simple pattern `let var = <expr>`, we optimize this to /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable, /// but in some cases it can affect the borrow checker, as in #53695. /// Therefore, we insert a "fake read" here to ensure that we get /// appropriate errors. ForLet, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct InlineAsm<'tcx> { pub asm: HirInlineAsm, pub outputs: Box<[Place<'tcx>]>, pub inputs: Box<[(Span, Operand<'tcx>)]>, } impl Debug for Statement<'_> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { use self::StatementKind::*; match self.kind { Assign(box(ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv), FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place), Retag(ref kind, ref place) => write!( fmt, "Retag({}{:?})", match kind { RetagKind::FnEntry => "[fn entry] ", RetagKind::TwoPhase => "[2phase] ", RetagKind::Raw => "[raw] ", RetagKind::Default => "", }, place, ), StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place), StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place), SetDiscriminant { ref place, variant_index } => { write!(fmt, "discriminant({:?}) = {:?}", place, variant_index) } InlineAsm(ref asm) => { write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs) } AscribeUserType(box(ref place, ref c_ty), ref variance) => { write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty) } Nop => write!(fmt, "nop"), } } } /////////////////////////////////////////////////////////////////////////// // Places /// A path to a value; something that can be evaluated without /// changing or disturbing program state. #[derive( Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable, )] pub struct Place<'tcx> { pub base: PlaceBase<'tcx>, /// projection out of a place (access a field, deref a pointer, etc) pub projection: &'tcx List<PlaceElem<'tcx>>, } impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {} #[derive( Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable, )] pub enum PlaceBase<'tcx> { /// local variable Local(Local), /// static or static mut variable Static(Box<Static<'tcx>>), } /// We store the normalized type to avoid requiring normalization when reading MIR #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] pub struct Static<'tcx> { pub ty: Ty<'tcx>, pub kind: StaticKind<'tcx>, /// The `DefId` of the item this static was declared in. For promoted values, usually, this is /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in. /// However, after inlining, that might no longer be the case as inlined `Place`s are copied /// into the calling frame. pub def_id: DefId, } #[derive( Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable, )] pub enum StaticKind<'tcx> { /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize /// it. Usually, these substs are just the identity substs for the item. However, the inliner /// will adjust these substs when it inlines a function based on the substs at the callsite. Promoted(Promoted, SubstsRef<'tcx>), Static, } impl_stable_hash_for!(struct Static<'tcx> { ty, kind, def_id }); #[derive( Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable, )] pub enum ProjectionElem<V, T> { Deref, Field(Field, T), Index(V), /// These indices are generated by slice patterns. Easiest to explain /// by example: /// /// ``` /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false }, /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false }, /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true }, /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true }, /// ``` ConstantIndex { /// index or -index (in Python terms), depending on from_end offset: u32, /// thing being indexed must be at least this long min_length: u32, /// counting backwards from end? from_end: bool, }, /// These indices are generated by slice patterns. /// /// slice[from:-to] in Python terms. Subslice { from: u32, to: u32, }, /// "Downcast" to a variant of an ADT. Currently, we only introduce /// this for ADTs with more than one variant. It may be better to /// just introduce it always, or always for enums. /// /// The included Symbol is the name of the variant, used for printing MIR. Downcast(Option<Symbol>, VariantIdx), } impl<V, T> ProjectionElem<V, T> { /// Returns `true` if the target of this projection may refer to a different region of memory /// than the base. fn is_indirect(&self) -> bool { match self { Self::Deref => true, | Self::Field(_, _) | Self::Index(_) | Self::ConstantIndex { .. } | Self::Subslice { .. } | Self::Downcast(_, _) => false } } } /// Alias for projections as they appear in places, where the base is a place /// and the index is a local. pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>; impl<'tcx> Copy for PlaceElem<'tcx> { } // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers. #[cfg(target_arch = "x86_64")] static_assert_size!(PlaceElem<'_>, 16); /// Alias for projections as they appear in `UserTypeProjection`, where we /// need neither the `V` parameter for `Index` nor the `T` for `Field`. pub type ProjectionKind = ProjectionElem<(), ()>; rustc_index::newtype_index! { pub struct Field { derive [HashStable] DEBUG_FORMAT = "field[{}]" } } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PlaceRef<'a, 'tcx> { pub base: &'a PlaceBase<'tcx>, pub projection: &'a [PlaceElem<'tcx>], } impl<'tcx> Place<'tcx> { // FIXME change this to a const fn by also making List::empty a const fn. pub fn return_place() -> Place<'tcx> { Place { base: PlaceBase::Local(RETURN_PLACE), projection: List::empty(), } } /// Returns `true` if this `Place` contains a `Deref` projection. /// /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the /// same region of memory as its base. pub fn is_indirect(&self) -> bool { self.projection.iter().any(|elem| elem.is_indirect()) } /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or /// a single deref of a local. // // FIXME: can we safely swap the semantics of `fn base_local` below in here instead? pub fn local_or_deref_local(&self) -> Option<Local> { match self.as_ref() { PlaceRef { base: &PlaceBase::Local(local), projection: &[], } | PlaceRef { base: &PlaceBase::Local(local), projection: &[ProjectionElem::Deref], } => Some(local), _ => None, } } /// If this place represents a local variable like `_X` with no /// projections, return `Some(_X)`. pub fn as_local(&self) -> Option<Local> { self.as_ref().as_local() } pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> { PlaceRef { base: &self.base, projection: &self.projection, } } } impl From<Local> for Place<'_> { fn from(local: Local) -> Self { Place { base: local.into(), projection: List::empty(), } } } impl From<Local> for PlaceBase<'_> { fn from(local: Local) -> Self { PlaceBase::Local(local) } } impl<'a, 'tcx> PlaceRef<'a, 'tcx> { /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or /// a single deref of a local. // // FIXME: can we safely swap the semantics of `fn base_local` below in here instead? pub fn local_or_deref_local(&self) -> Option<Local> { match self { PlaceRef { base: PlaceBase::Local(local), projection: [], } | PlaceRef { base: PlaceBase::Local(local), projection: [ProjectionElem::Deref], } => Some(*local), _ => None, } } /// If this place represents a local variable like `_X` with no /// projections, return `Some(_X)`. pub fn as_local(&self) -> Option<Local> { match self { PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l), _ => None, } } } impl Debug for Place<'_> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { for elem in self.projection.iter().rev() { match elem { ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => { write!(fmt, "(").unwrap(); } ProjectionElem::Deref => { write!(fmt, "(*").unwrap(); } ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {} } } write!(fmt, "{:?}", self.base)?; for elem in self.projection.iter() { match elem { ProjectionElem::Downcast(Some(name), _index) => { write!(fmt, " as {})", name)?; } ProjectionElem::Downcast(None, index) => { write!(fmt, " as variant#{:?})", index)?; } ProjectionElem::Deref => { write!(fmt, ")")?; } ProjectionElem::Field(field, ty) => { write!(fmt, ".{:?}: {:?})", field.index(), ty)?; } ProjectionElem::Index(ref index) => { write!(fmt, "[{:?}]", index)?; } ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => { write!(fmt, "[{:?} of {:?}]", offset, min_length)?; } ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => { write!(fmt, "[-{:?} of {:?}]", offset, min_length)?; } ProjectionElem::Subslice { from, to } if *to == 0 => { write!(fmt, "[{:?}:]", from)?; } ProjectionElem::Subslice { from, to } if *from == 0 => { write!(fmt, "[:-{:?}]", to)?; } ProjectionElem::Subslice { from, to } => { write!(fmt, "[{:?}:-{:?}]", from, to)?; } } } Ok(()) } } impl Debug for PlaceBase<'_> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { match *self { PlaceBase::Local(id) => write!(fmt, "{:?}", id), PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => { write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty) } PlaceBase::Static(box self::Static { ty, kind: StaticKind::Promoted(promoted, _), def_id: _ }) => { write!(fmt, "({:?}: {:?})", promoted, ty) } } } } /////////////////////////////////////////////////////////////////////////// // Scopes rustc_index::newtype_index! { pub struct SourceScope { derive [HashStable] DEBUG_FORMAT = "scope[{}]", const OUTERMOST_SOURCE_SCOPE = 0, } } #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct SourceScopeData { pub span: Span, pub parent_scope: Option<SourceScope>, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct SourceScopeLocalData { /// An `HirId` with lint levels equivalent to this scope's lint levels. pub lint_root: hir::HirId, /// The unsafe block that contains this node. pub safety: Safety, } /////////////////////////////////////////////////////////////////////////// // Operands /// These are values that can appear inside an rvalue. They are intentionally /// limited to prevent rvalues from being nested in one another. #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)] pub enum Operand<'tcx> { /// Copy: The value must be available for use afterwards. /// /// This implies that the type of the place must be `Copy`; this is true /// by construction during build, but also checked by the MIR type checker. Copy(Place<'tcx>), /// Move: The value (including old borrows of it) will not be used again. /// /// Safe for values of all types (modulo future developments towards `?Move`). /// Correct usage patterns are enforced by the borrow checker for safe code. /// `Copy` may be converted to `Move` to enable "last-use" optimizations. Move(Place<'tcx>), /// Synthesizes a constant value. Constant(Box<Constant<'tcx>>), } impl<'tcx> Debug for Operand<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { use self::Operand::*; match *self { Constant(ref a) => write!(fmt, "{:?}", a), Copy(ref place) => write!(fmt, "{:?}", place), Move(ref place) => write!(fmt, "move {:?}", place), } } } impl<'tcx> Operand<'tcx> { /// Convenience helper to make a constant that refers to the fn /// with given `DefId` and substs. Since this is used to synthesize /// MIR, assumes `user_ty` is None. pub fn function_handle( tcx: TyCtxt<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>, span: Span, ) -> Self { let ty = tcx.type_of(def_id).subst(tcx, substs); Operand::Constant(box Constant { span, user_ty: None, literal: ty::Const::zero_sized(tcx, ty), }) } pub fn to_copy(&self) -> Self { match *self { Operand::Copy(_) | Operand::Constant(_) => self.clone(), Operand::Move(ref place) => Operand::Copy(place.clone()), } } } /////////////////////////////////////////////////////////////////////////// /// Rvalues #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] pub enum Rvalue<'tcx> { /// x (either a move or copy, depending on type of x) Use(Operand<'tcx>), /// [x; 32] Repeat(Operand<'tcx>, u64), /// &x or &mut x Ref(Region<'tcx>, BorrowKind, Place<'tcx>), /// length of a [X] or [X;n] value Len(Place<'tcx>), Cast(CastKind, Operand<'tcx>, Ty<'tcx>), BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>), CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>), NullaryOp(NullOp, Ty<'tcx>), UnaryOp(UnOp, Operand<'tcx>), /// Read the discriminant of an ADT. /// /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot /// be defined to return, say, a 0) if ADT is not an enum. Discriminant(Place<'tcx>), /// Creates an aggregate value, like a tuple or struct. This is /// only needed because we want to distinguish `dest = Foo { x: /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case /// that `Foo` has a destructor. These rvalues can be optimized /// away after type-checking and before lowering. Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>), } #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)] pub enum CastKind { Misc, Pointer(PointerCast), } #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)] pub enum AggregateKind<'tcx> { /// The type is of the element Array(Ty<'tcx>), Tuple, /// The second field is the variant index. It's equal to 0 for struct /// and union expressions. The fourth field is /// active field number and is present only for union expressions /// -- e.g., for a union expression `SomeUnion { c: .. }`, the /// active field index would identity the field `c` Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>), Closure(DefId, SubstsRef<'tcx>), Generator(DefId, SubstsRef<'tcx>, hir::GeneratorMovability), } #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)] pub enum BinOp { /// The `+` operator (addition) Add, /// The `-` operator (subtraction) Sub, /// The `*` operator (multiplication) Mul, /// The `/` operator (division) Div, /// The `%` operator (modulus) Rem, /// The `^` operator (bitwise xor) BitXor, /// The `&` operator (bitwise and) BitAnd, /// The `|` operator (bitwise or) BitOr, /// The `<<` operator (shift left) Shl, /// The `>>` operator (shift right) Shr, /// The `==` operator (equality) Eq, /// The `<` operator (less than) Lt, /// The `<=` operator (less than or equal to) Le, /// The `!=` operator (not equal to) Ne, /// The `>=` operator (greater than or equal to) Ge, /// The `>` operator (greater than) Gt, /// The `ptr.offset` operator Offset, } impl BinOp { pub fn is_checkable(self) -> bool { use self::BinOp::*; match self { Add | Sub | Mul | Shl | Shr => true, _ => false, } } } #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)] pub enum NullOp { /// Returns the size of a value of that type SizeOf, /// Creates a new uninitialized box for a value of that type Box, } #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)] pub enum UnOp { /// The `!` operator for logical inversion Not, /// The `-` operator for negation Neg, } impl<'tcx> Debug for Rvalue<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { use self::Rvalue::*; match *self { Use(ref place) => write!(fmt, "{:?}", place), Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b), Len(ref a) => write!(fmt, "Len({:?})", a), Cast(ref kind, ref place, ref ty) => { write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind) } BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b), CheckedBinaryOp(ref op, ref a, ref b) => { write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b) } UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a), Discriminant(ref place) => write!(fmt, "discriminant({:?})", place), NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t), Ref(region, borrow_kind, ref place) => { let kind_str = match borrow_kind { BorrowKind::Shared => "", BorrowKind::Shallow => "shallow ", BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ", }; // When printing regions, add trailing space if necessary. let print_region = ty::tls::with(|tcx| { tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions }); let region = if print_region { let mut region = region.to_string(); if region.len() > 0 { region.push(' '); } region } else { // Do not even print 'static String::new() }; write!(fmt, "&{}{}{:?}", region, kind_str, place) } Aggregate(ref kind, ref places) => { fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result { let mut tuple_fmt = fmt.debug_tuple(""); for place in places { tuple_fmt.field(place); } tuple_fmt.finish() } match **kind { AggregateKind::Array(_) => write!(fmt, "{:?}", places), AggregateKind::Tuple => match places.len() { 0 => write!(fmt, "()"), 1 => write!(fmt, "({:?},)", places[0]), _ => fmt_tuple(fmt, places), }, AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => { let variant_def = &adt_def.variants[variant]; let f = &mut *fmt; ty::tls::with(|tcx| { let substs = tcx.lift(&substs).expect("could not lift for printing"); FmtPrinter::new(tcx, f, Namespace::ValueNS) .print_def_path(variant_def.def_id, substs)?; Ok(()) })?; match variant_def.ctor_kind { CtorKind::Const => Ok(()), CtorKind::Fn => fmt_tuple(fmt, places), CtorKind::Fictive => { let mut struct_fmt = fmt.debug_struct(""); for (field, place) in variant_def.fields.iter().zip(places) { struct_fmt.field(&field.ident.as_str(), place); } struct_fmt.finish() } } } AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| { if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) { let name = if tcx.sess.opts.debugging_opts.span_free_formats { format!("[closure@{:?}]", hir_id) } else { format!("[closure@{:?}]", tcx.hir().span(hir_id)) }; let mut struct_fmt = fmt.debug_struct(&name); if let Some(upvars) = tcx.upvars(def_id) { for (&var_id, place) in upvars.keys().zip(places) { let var_name = tcx.hir().name(var_id); struct_fmt.field(&var_name.as_str(), place); } } struct_fmt.finish() } else { write!(fmt, "[closure]") } }), AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| { if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) { let name = format!("[generator@{:?}]", tcx.hir().span(hir_id)); let mut struct_fmt = fmt.debug_struct(&name); if let Some(upvars) = tcx.upvars(def_id) { for (&var_id, place) in upvars.keys().zip(places) { let var_name = tcx.hir().name(var_id); struct_fmt.field(&var_name.as_str(), place); } } struct_fmt.finish() } else { write!(fmt, "[generator]") } }), } } } } } /////////////////////////////////////////////////////////////////////////// /// Constants /// /// Two constants are equal if they are the same constant. Note that /// this does not necessarily mean that they are "==" in Rust -- in /// particular one must be wary of `NaN`! #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)] pub struct Constant<'tcx> { pub span: Span, /// Optional user-given type: for something like /// `collect::<Vec<_>>`, this would be present and would /// indicate that `Vec<_>` was explicitly specified. /// /// Needed for NLL to impose user-given type constraints. pub user_ty: Option<UserTypeAnnotationIndex>, pub literal: &'tcx ty::Const<'tcx>, } /// A collection of projections into user types. /// /// They are projections because a binding can occur a part of a /// parent pattern that has been ascribed a type. /// /// Its a collection because there can be multiple type ascriptions on /// the path from the root of the pattern down to the binding itself. /// /// An example: /// /// ```rust /// struct S<'a>((i32, &'a str), String); /// let S((_, w): (i32, &'static str), _): S = ...; /// // ------ ^^^^^^^^^^^^^^^^^^^ (1) /// // --------------------------------- ^ (2) /// ``` /// /// The highlights labelled `(1)` show the subpattern `(_, w)` being /// ascribed the type `(i32, &'static str)`. /// /// The highlights labelled `(2)` show the whole pattern being /// ascribed the type `S`. /// /// In this example, when we descend to `w`, we will have built up the /// following two projected types: /// /// * base: `S`, projection: `(base.0).1` /// * base: `(i32, &'static str)`, projection: `base.1` /// /// The first will lead to the constraint `w: &'1 str` (for some /// inferred region `'1`). The second will lead to the constraint `w: /// &'static str`. #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct UserTypeProjections { pub(crate) contents: Vec<(UserTypeProjection, Span)>, } BraceStructTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections { contents } } impl<'tcx> UserTypeProjections { pub fn none() -> Self { UserTypeProjections { contents: vec![] } } pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self { UserTypeProjections { contents: projs.collect() } } pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> { self.contents.iter() } pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> { self.contents.iter().map(|&(ref user_type, _span)| user_type) } pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self { self.contents.push((user_ty.clone(), span)); self } fn map_projections( mut self, mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection, ) -> Self { self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect(); self } pub fn index(self) -> Self { self.map_projections(|pat_ty_proj| pat_ty_proj.index()) } pub fn subslice(self, from: u32, to: u32) -> Self { self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to)) } pub fn deref(self) -> Self { self.map_projections(|pat_ty_proj| pat_ty_proj.deref()) } pub fn leaf(self, field: Field) -> Self { self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field)) } pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self { self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field)) } } /// Encodes the effect of a user-supplied type annotation on the /// subcomponents of a pattern. The effect is determined by applying the /// given list of proejctions to some underlying base type. Often, /// the projection element list `projs` is empty, in which case this /// directly encodes a type in `base`. But in the case of complex patterns with /// subpatterns and bindings, we want to apply only a *part* of the type to a variable, /// in which case the `projs` vector is used. /// /// Examples: /// /// * `let x: T = ...` -- here, the `projs` vector is empty. /// /// * `let (x, _): T = ...` -- here, the `projs` vector would contain /// `field[0]` (aka `.0`), indicating that the type of `s` is /// determined by finding the type of the `.0` field from `T`. #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct UserTypeProjection { pub base: UserTypeAnnotationIndex, pub projs: Vec<ProjectionKind>, } impl Copy for ProjectionKind {} impl UserTypeProjection { pub(crate) fn index(mut self) -> Self { self.projs.push(ProjectionElem::Index(())); self } pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self { self.projs.push(ProjectionElem::Subslice { from, to }); self } pub(crate) fn deref(mut self) -> Self { self.projs.push(ProjectionElem::Deref); self } pub(crate) fn leaf(mut self, field: Field) -> Self { self.projs.push(ProjectionElem::Field(field, ())); self } pub(crate) fn variant( mut self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field, ) -> Self { self.projs.push(ProjectionElem::Downcast( Some(adt_def.variants[variant_index].ident.name), variant_index, )); self.projs.push(ProjectionElem::Field(field, ())); self } } CloneTypeFoldableAndLiftImpls! { ProjectionKind, } impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { use crate::mir::ProjectionElem::*; let base = self.base.fold_with(folder); let projs: Vec<_> = self .projs .iter() .map(|elem| match elem { Deref => Deref, Field(f, ()) => Field(f.clone(), ()), Index(()) => Index(()), elem => elem.clone(), }) .collect(); UserTypeProjection { base, projs } } fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool { self.base.visit_with(visitor) // Note: there's nothing in `self.proj` to visit. } } rustc_index::newtype_index! { pub struct Promoted { derive [HashStable] DEBUG_FORMAT = "promoted[{}]" } } impl<'tcx> Debug for Constant<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { write!(fmt, "{}", self) } } impl<'tcx> Display for Constant<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { write!(fmt, "const ")?; // FIXME make the default pretty printing of raw pointers more detailed. Here we output the // debug representation of raw pointers, so that the raw pointers in the mir dump output are // detailed and just not '{pointer}'. if let ty::RawPtr(_) = self.literal.ty.kind { write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty) } else { write!(fmt, "{}", self.literal) } } } impl<'tcx> graph::DirectedGraph for Body<'tcx> { type Node = BasicBlock; } impl<'tcx> graph::WithNumNodes for Body<'tcx> { fn num_nodes(&self) -> usize { self.basic_blocks.len() } } impl<'tcx> graph::WithStartNode for Body<'tcx> { fn start_node(&self) -> Self::Node { START_BLOCK } } impl<'tcx> graph::WithPredecessors for Body<'tcx> { fn predecessors( &self, node: Self::Node, ) -> <Self as GraphPredecessors<'_>>::Iter { self.predecessors_for(node).clone().into_iter() } } impl<'tcx> graph::WithSuccessors for Body<'tcx> { fn successors( &self, node: Self::Node, ) -> <Self as GraphSuccessors<'_>>::Iter { self.basic_blocks[node].terminator().successors().cloned() } } impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> { type Item = BasicBlock; type Iter = IntoIter<BasicBlock>; } impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> { type Item = BasicBlock; type Iter = iter::Cloned<Successors<'b>>; } #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)] pub struct Location { /// The block that the location is within. pub block: BasicBlock, /// The location is the position of the start of the statement; or, if /// `statement_index` equals the number of statements, then the start of the /// terminator. pub statement_index: usize, } impl fmt::Debug for Location { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{:?}[{}]", self.block, self.statement_index) } } impl Location { pub const START: Location = Location { block: START_BLOCK, statement_index: 0 }; /// Returns the location immediately after this one within the enclosing block. /// /// Note that if this location represents a terminator, then the /// resulting location would be out of bounds and invalid. pub fn successor_within_block(&self) -> Location { Location { block: self.block, statement_index: self.statement_index + 1 } } /// Returns `true` if `other` is earlier in the control flow graph than `self`. pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool { // If we are in the same block as the other location and are an earlier statement // then we are a predecessor of `other`. if self.block == other.block && self.statement_index < other.statement_index { return true; } // If we're in another block, then we want to check that block is a predecessor of `other`. let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).clone(); let mut visited = FxHashSet::default(); while let Some(block) = queue.pop() { // If we haven't visited this block before, then make sure we visit it's predecessors. if visited.insert(block) { queue.append(&mut body.predecessors_for(block).clone()); } else { continue; } // If we found the block that `self` is in, then we are a predecessor of `other` (since // we found that block by looking at the predecessors of `other`). if self.block == block { return true; } } false } pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool { if self.block == other.block { self.statement_index <= other.statement_index } else { dominators.is_dominated_by(other.block, self.block) } } } #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)] pub enum UnsafetyViolationKind { General, /// Permitted both in `const fn`s and regular `fn`s. GeneralAndConstFn, ExternStatic(hir::HirId), BorrowPacked(hir::HirId), } #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)] pub struct UnsafetyViolation { pub source_info: SourceInfo, pub description: Symbol, pub details: Symbol, pub kind: UnsafetyViolationKind, } #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] pub struct UnsafetyCheckResult { /// Violations that are propagated *upwards* from this function. pub violations: Lrc<[UnsafetyViolation]>, /// `unsafe` blocks in this function, along with whether they are used. This is /// used for the "unused_unsafe" lint. pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>, } rustc_index::newtype_index! { pub struct GeneratorSavedLocal { derive [HashStable] DEBUG_FORMAT = "_{}", } } /// The layout of generator state. #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct GeneratorLayout<'tcx> { /// The type of every local stored inside the generator. pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>, /// Which of the above fields are in each variant. Note that one field may /// be stored in multiple variants. pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>, /// Which saved locals are storage-live at the same time. Locals that do not /// have conflicts with each other are allowed to overlap in the computed /// layout. pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>, /// The names and scopes of all the stored generator locals. /// /// N.B., this is *strictly* a temporary hack for codegen /// debuginfo generation, and will be removed at some point. /// Do **NOT** use it for anything else, local information should not be /// in the MIR, please rely on local crate HIR or other side-channels. // // FIXME(tmandry): see above. pub __local_debuginfo_codegen_only_do_not_use: IndexVec<GeneratorSavedLocal, LocalDecl<'tcx>>, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct BorrowCheckResult<'tcx> { pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>, pub used_mut_upvars: SmallVec<[Field; 8]>, } /// After we borrow check a closure, we are left with various /// requirements that we have inferred between the free regions that /// appear in the closure's signature or on its field types. These /// requirements are then verified and proved by the closure's /// creating function. This struct encodes those requirements. /// /// The requirements are listed as being between various /// `RegionVid`. The 0th region refers to `'static`; subsequent region /// vids refer to the free regions that appear in the closure (or /// generator's) type, in order of appearance. (This numbering is /// actually defined by the `UniversalRegions` struct in the NLL /// region checker. See for example /// `UniversalRegions::closure_mapping`.) Note that we treat the free /// regions in the closure's type "as if" they were erased, so their /// precise identity is not important, only their position. /// /// Example: If type check produces a closure with the closure substs: /// /// ```text /// ClosureSubsts = [ /// i8, // the "closure kind" /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature" /// &'a String, // some upvar /// ] /// ``` /// /// here, there is one unique free region (`'a`) but it appears /// twice. We would "renumber" each occurrence to a unique vid, as follows: /// /// ```text /// ClosureSubsts = [ /// i8, // the "closure kind" /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature" /// &'2 String, // some upvar /// ] /// ``` /// /// Now the code might impose a requirement like `'1: '2`. When an /// instance of the closure is created, the corresponding free regions /// can be extracted from its type and constrained to have the given /// outlives relationship. /// /// In some cases, we have to record outlives requirements between /// types and regions as well. In that case, if those types include /// any regions, those regions are recorded as `ReClosureBound` /// instances assigned one of these same indices. Those regions will /// be substituted away by the creator. We use `ReClosureBound` in /// that case because the regions must be allocated in the global /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use /// internally within the rest of the NLL code). #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct ClosureRegionRequirements<'tcx> { /// The number of external regions defined on the closure. In our /// example above, it would be 3 -- one for `'static`, then `'1` /// and `'2`. This is just used for a sanity check later on, to /// make sure that the number of regions we see at the callsite /// matches. pub num_external_vids: usize, /// Requirements between the various free regions defined in /// indices. pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>, } /// Indicates an outlives-constraint between a type or between two /// free regions declared on the closure. #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct ClosureOutlivesRequirement<'tcx> { // This region or type ... pub subject: ClosureOutlivesSubject<'tcx>, // ... must outlive this one. pub outlived_free_region: ty::RegionVid, // If not, report an error here ... pub blame_span: Span, // ... due to this reason. pub category: ConstraintCategory, } /// Outlives-constraints can be categorized to determine whether and why they /// are interesting (for error reporting). Order of variants indicates sort /// order of the category, thereby influencing diagnostic output. /// /// See also [rustc_mir::borrow_check::nll::constraints]. #[derive( Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable, )] pub enum ConstraintCategory { Return, Yield, UseAsConst, UseAsStatic, TypeAnnotation, Cast, /// A constraint that came from checking the body of a closure. /// /// We try to get the category that the closure used when reporting this. ClosureBounds, CallArgument, CopyBound, SizedBound, Assignment, OpaqueType, /// A "boring" constraint (caused by the given location) is one that /// the user probably doesn't want to see described in diagnostics, /// because it is kind of an artifact of the type system setup. /// Example: `x = Foo { field: y }` technically creates /// intermediate regions representing the "type of `Foo { field: y /// }`", and data flows from `y` into those variables, but they /// are not very interesting. The assignment into `x` on the other /// hand might be. Boring, // Boring and applicable everywhere. BoringNoLocation, /// A constraint that doesn't correspond to anything the user sees. Internal, } /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing /// that must outlive some region. #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub enum ClosureOutlivesSubject<'tcx> { /// Subject is a type, typically a type parameter, but could also /// be a projection. Indicates a requirement like `T: 'a` being /// passed to the caller, where the type here is `T`. /// /// The type here is guaranteed not to contain any free regions at /// present. Ty(Ty<'tcx>), /// Subject is a free region from the closure. Indicates a requirement /// like `'a: 'b` being passed to the caller; the region here is `'a`. Region(ty::RegionVid), } /* * `TypeFoldable` implementations for MIR types */ CloneTypeFoldableAndLiftImpls! { BlockTailInfo, MirPhase, Mutability, SourceInfo, UpvarDebuginfo, FakeReadCause, RetagKind, SourceScope, SourceScopeData, SourceScopeLocalData, UserTypeAnnotationIndex, } BraceStructTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for Body<'tcx> { phase, basic_blocks, source_scopes, source_scope_local_data, yield_ty, generator_drop, generator_layout, local_decls, user_type_annotations, arg_count, __upvar_debuginfo_codegen_only_do_not_use, spread_arg, control_flow_destroyed, span, cache, } } BraceStructTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> { field_tys, variant_fields, storage_conflicts, __local_debuginfo_codegen_only_do_not_use, } } BraceStructTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> { mutability, is_user_variable, internal, ty, user_ty, name, source_info, is_block_tail, visibility_scope, } } BraceStructTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> { statements, terminator, is_cleanup, } } BraceStructTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> { source_info, kind } } EnumTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> { (StatementKind::Assign)(a), (StatementKind::FakeRead)(cause, place), (StatementKind::SetDiscriminant) { place, variant_index }, (StatementKind::StorageLive)(a), (StatementKind::StorageDead)(a), (StatementKind::InlineAsm)(a), (StatementKind::Retag)(kind, place), (StatementKind::AscribeUserType)(a, v), (StatementKind::Nop), } } BraceStructTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for InlineAsm<'tcx> { asm, outputs, inputs, } } EnumTypeFoldableImpl! { impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> { (ClearCrossCrate::Clear), (ClearCrossCrate::Set)(a), } where T: TypeFoldable<'tcx> } impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { use crate::mir::TerminatorKind::*; let kind = match self.kind { Goto { target } => Goto { target }, SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt { discr: discr.fold_with(folder), switch_ty: switch_ty.fold_with(folder), values: values.clone(), targets: targets.clone(), }, Drop { ref location, target, unwind } => { Drop { location: location.fold_with(folder), target, unwind } } DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace { location: location.fold_with(folder), value: value.fold_with(folder), target, unwind, }, Yield { ref value, resume, drop } => { Yield { value: value.fold_with(folder), resume: resume, drop: drop } } Call { ref func, ref args, ref destination, cleanup, from_hir_call } => { let dest = destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest)); Call { func: func.fold_with(folder), args: args.fold_with(folder), destination: dest, cleanup, from_hir_call, } } Assert { ref cond, expected, ref msg, target, cleanup } => { use PanicInfo::*; let msg = match msg { BoundsCheck { ref len, ref index } => BoundsCheck { len: len.fold_with(folder), index: index.fold_with(folder), }, Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero | GeneratorResumedAfterReturn | GeneratorResumedAfterPanic => msg.clone(), }; Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup } } GeneratorDrop => GeneratorDrop, Resume => Resume, Abort => Abort, Return => Return, Unreachable => Unreachable, FalseEdges { real_target, imaginary_target } => { FalseEdges { real_target, imaginary_target } } FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind }, }; Terminator { source_info: self.source_info, kind } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { use crate::mir::TerminatorKind::*; match self.kind { SwitchInt { ref discr, switch_ty, .. } => { discr.visit_with(visitor) || switch_ty.visit_with(visitor) } Drop { ref location, .. } => location.visit_with(visitor), DropAndReplace { ref location, ref value, .. } => { location.visit_with(visitor) || value.visit_with(visitor) } Yield { ref value, .. } => value.visit_with(visitor), Call { ref func, ref args, ref destination, .. } => { let dest = if let Some((ref loc, _)) = *destination { loc.visit_with(visitor) } else { false }; dest || func.visit_with(visitor) || args.visit_with(visitor) } Assert { ref cond, ref msg, .. } => { if cond.visit_with(visitor) { use PanicInfo::*; match msg { BoundsCheck { ref len, ref index } => len.visit_with(visitor) || index.visit_with(visitor), Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero | GeneratorResumedAfterReturn | GeneratorResumedAfterPanic => false } } else { false } } Goto { .. } | Resume | Abort | Return | GeneratorDrop | Unreachable | FalseEdges { .. } | FalseUnwind { .. } => false, } } } impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { Place { base: self.base.fold_with(folder), projection: self.projection.fold_with(folder), } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { self.base.visit_with(visitor) || self.projection.visit_with(visitor) } } impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { match self { PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)), PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)), } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { match self { PlaceBase::Local(local) => local.visit_with(visitor), PlaceBase::Static(static_) => (**static_).visit_with(visitor), } } } impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>(); folder.tcx().intern_place_elems(&v) } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { self.iter().any(|t| t.visit_with(visitor)) } } impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { Static { ty: self.ty.fold_with(folder), kind: self.kind.fold_with(folder), def_id: self.def_id, } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { let Static { ty, kind, def_id: _ } = self; ty.visit_with(visitor) || kind.visit_with(visitor) } } impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { match self { StaticKind::Promoted(promoted, substs) => StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder)), StaticKind::Static => StaticKind::Static } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { match self { StaticKind::Promoted(promoted, substs) => promoted.visit_with(visitor) || substs.visit_with(visitor), StaticKind::Static => { false } } } } impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { use crate::mir::Rvalue::*; match *self { Use(ref op) => Use(op.fold_with(folder)), Repeat(ref op, len) => Repeat(op.fold_with(folder), len), Ref(region, bk, ref place) => { Ref(region.fold_with(folder), bk, place.fold_with(folder)) } Len(ref place) => Len(place.fold_with(folder)), Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)), BinaryOp(op, ref rhs, ref lhs) => { BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)) } CheckedBinaryOp(op, ref rhs, ref lhs) => { CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)) } UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)), Discriminant(ref place) => Discriminant(place.fold_with(folder)), NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)), Aggregate(ref kind, ref fields) => { let kind = box match **kind { AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)), AggregateKind::Tuple => AggregateKind::Tuple, AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt( def, v, substs.fold_with(folder), user_ty.fold_with(folder), n, ), AggregateKind::Closure(id, substs) => { AggregateKind::Closure(id, substs.fold_with(folder)) } AggregateKind::Generator(id, substs, movablity) => { AggregateKind::Generator(id, substs.fold_with(folder), movablity) } }; Aggregate(kind, fields.fold_with(folder)) } } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { use crate::mir::Rvalue::*; match *self { Use(ref op) => op.visit_with(visitor), Repeat(ref op, _) => op.visit_with(visitor), Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor), Len(ref place) => place.visit_with(visitor), Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor), BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => { rhs.visit_with(visitor) || lhs.visit_with(visitor) } UnaryOp(_, ref val) => val.visit_with(visitor), Discriminant(ref place) => place.visit_with(visitor), NullaryOp(_, ty) => ty.visit_with(visitor), Aggregate(ref kind, ref fields) => { (match **kind { AggregateKind::Array(ty) => ty.visit_with(visitor), AggregateKind::Tuple => false, AggregateKind::Adt(_, _, substs, user_ty, _) => { substs.visit_with(visitor) || user_ty.visit_with(visitor) } AggregateKind::Closure(_, substs) => substs.visit_with(visitor), AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor), }) || fields.visit_with(visitor) } } } } impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { match *self { Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)), Operand::Move(ref place) => Operand::Move(place.fold_with(folder)), Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)), } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { match *self { Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor), Operand::Constant(ref c) => c.visit_with(visitor), } } } impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { use crate::mir::ProjectionElem::*; match self { Deref => Deref, Field(f, ty) => Field(*f, ty.fold_with(folder)), Index(v) => Index(v.fold_with(folder)), elem => elem.clone(), } } fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool { use crate::mir::ProjectionElem::*; match self { Field(_, ty) => ty.visit_with(visitor), Index(v) => v.visit_with(visitor), _ => false, } } } impl<'tcx> TypeFoldable<'tcx> for Field { fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self { *self } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool { false } } impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal { fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self { *self } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool { false } } impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self { self.clone() } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool { false } } impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { Constant { span: self.span.clone(), user_ty: self.user_ty.fold_with(folder), literal: self.literal.fold_with(folder), } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { self.literal.visit_with(visitor) } }
invalid termin
tzc_rom0_r0.rs
#[doc = "Register `tzc_rom0_r0` reader"] pub struct R(crate::R<TZC_ROM0_R0_SPEC>); impl core::ops::Deref for R { type Target = crate::R<TZC_ROM0_R0_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::convert::From<crate::R<TZC_ROM0_R0_SPEC>> for R { fn from(reader: crate::R<TZC_ROM0_R0_SPEC>) -> Self { R(reader) } } #[doc = "Register `tzc_rom0_r0` writer"] pub struct W(crate::W<TZC_ROM0_R0_SPEC>); impl core::ops::Deref for W { type Target = crate::W<TZC_ROM0_R0_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl core::convert::From<crate::W<TZC_ROM0_R0_SPEC>> for W { fn from(writer: crate::W<TZC_ROM0_R0_SPEC>) -> Self { W(writer) } } #[doc = "Field `tzc_rom0_r0_start` reader - "] pub struct TZC_ROM0_R0_START_R(crate::FieldReader<u16, u16>); impl TZC_ROM0_R0_START_R { pub(crate) fn new(bits: u16) -> Self { TZC_ROM0_R0_START_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for TZC_ROM0_R0_START_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `tzc_rom0_r0_start` writer - "] pub struct TZC_ROM0_R0_START_W<'a> { w: &'a mut W, } impl<'a> TZC_ROM0_R0_START_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0xffff << 16)) | (((value as u32) & 0xffff) << 16); self.w } } #[doc = "Field `tzc_rom0_r0_end` reader - "] pub struct TZC_ROM0_R0_END_R(crate::FieldReader<u16, u16>); impl TZC_ROM0_R0_END_R { pub(crate) fn new(bits: u16) -> Self { TZC_ROM0_R0_END_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for TZC_ROM0_R0_END_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `tzc_rom0_r0_end` writer - "] pub struct
<'a> { w: &'a mut W, } impl<'a> TZC_ROM0_R0_END_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } impl R { #[doc = "Bits 16:31"] #[inline(always)] pub fn tzc_rom0_r0_start(&self) -> TZC_ROM0_R0_START_R { TZC_ROM0_R0_START_R::new(((self.bits >> 16) & 0xffff) as u16) } #[doc = "Bits 0:15"] #[inline(always)] pub fn tzc_rom0_r0_end(&self) -> TZC_ROM0_R0_END_R { TZC_ROM0_R0_END_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 16:31"] #[inline(always)] pub fn tzc_rom0_r0_start(&mut self) -> TZC_ROM0_R0_START_W { TZC_ROM0_R0_START_W { w: self } } #[doc = "Bits 0:15"] #[inline(always)] pub fn tzc_rom0_r0_end(&mut self) -> TZC_ROM0_R0_END_W { TZC_ROM0_R0_END_W { w: self } } #[doc = "Writes raw bits to the register."] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "tzc_rom0_r0.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tzc_rom0_r0](index.html) module"] pub struct TZC_ROM0_R0_SPEC; impl crate::RegisterSpec for TZC_ROM0_R0_SPEC { type Ux = u32; } #[doc = "`read()` method returns [tzc_rom0_r0::R](R) reader structure"] impl crate::Readable for TZC_ROM0_R0_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [tzc_rom0_r0::W](W) writer structure"] impl crate::Writable for TZC_ROM0_R0_SPEC { type Writer = W; } #[doc = "`reset()` method sets tzc_rom0_r0 to value 0"] impl crate::Resettable for TZC_ROM0_R0_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
TZC_ROM0_R0_END_W
Card.js
import React from "react"; import styled from "styled-components";
background: white; `; export const CardTitle = styled.div` font-size: 18px; padding: 2em; `; export const CardContent = styled.div``; const Card = ({ title, children, style, ...props }) => ( <CardWrapper style={style} {...props}> {title && typeof title === String ? <CardTitle>{title}</CardTitle> : null} {children} </CardWrapper> ); export default Card;
export const CardWrapper = styled.div`
currencies_test.go
package goney import ( "reflect" "testing" ) func
(t *testing.T) { type args struct { code string } tests := []struct { name string args args want Currency }{ {"returns the currency with provided code, if found", args{"JPY"}, JPY, }, {"returns XXX (no currency), if not found", args{"OMG"}, XXX, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Find(tt.args.code); !reflect.DeepEqual(got, tt.want) { t.Errorf("Find() = %v, want %v", got, tt.want) } }) } }
TestFind
echarts-liquidfill.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("echarts")); else if(typeof define === 'function' && define.amd) define(["echarts"], factory); else if(typeof exports === 'object') exports["echarts-liquidfill"] = factory(require("echarts")); else root["echarts-liquidfill"] = factory(root["echarts"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!******************!*\ !*** ./index.js ***! \******************/ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./src/liquidFill */ 1); /***/ }, /* 1 */ /*!***************************!*\ !*** ./src/liquidFill.js ***! \***************************/ /***/ function(module, exports, __webpack_require__) { var echarts = __webpack_require__(/*! echarts/lib/echarts */ 2); __webpack_require__(/*! ./liquidFillSeries */ 3); __webpack_require__(/*! ./liquidFillView */ 14); echarts.registerVisual( echarts.util.curry( __webpack_require__(/*! echarts/lib/visual/dataColor */ 77), 'liquidFill' ) ); /***/ }, /* 2 */ /*!**************************!*\ !*** external "echarts" ***! \**************************/ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /*!*********************************!*\ !*** ./src/liquidFillSeries.js ***! \*********************************/ /***/ function(module, exports, __webpack_require__) { var completeDimensions = __webpack_require__(/*! echarts/lib/data/helper/completeDimensions */ 4); var echarts = __webpack_require__(/*! echarts/lib/echarts */ 2); echarts.extendSeriesModel({ type: 'series.liquidFill', visualColorAccessPath: 'textStyle.normal.color', optionUpdated: function () { var option = this.option; option.gridSize = Math.max(Math.floor(option.gridSize), 4); }, getInitialData: function (option, ecModel) { var dimensions = completeDimensions(['value'], option.data); var list = new echarts.List(dimensions, this); list.initData(option.data); return list; }, defaultOption: { color: ['#294D99', '#156ACF', '#1598ED', '#45BDFF'], center: ['50%', '50%'], radius: '50%', amplitude: '8%', waveLength: '80%', phase: 'auto', period: 'auto', direction: 'right', shape: 'circle', waveAnimation: true, animationEasing: 'linear', animationEasingUpdate: 'linear', animationDuration: 2000, animationDurationUpdate: 1000, outline: { show: true, borderDistance: 8, itemStyle: { color: 'none', borderColor: '#294D99', borderWidth: 8, shadowBlur: 20, shadowColor: 'rgba(0, 0, 0, 0.25)' } }, backgroundStyle: { color: '#E3F7FF' }, itemStyle: { opacity: 0.95, shadowBlur: 50, shadowColor: 'rgba(0, 0, 0, 0.4)' }, label: { show: true, color: '#294D99', insideColor: '#fff', fontSize: 50, fontWeight: 'bold', align: 'center', baseline: 'middle', position: 'inside' }, emphasis: { itemStyle: { opacity: 0.8 } } } }); /***/ }, /* 4 */ /*!*********************************************************!*\ !*** ./~/echarts/lib/data/helper/completeDimensions.js ***! \*********************************************************/ /***/ function(module, exports, __webpack_require__) { var _util = __webpack_require__(/*! zrender/lib/core/util */ 5); var createHashMap = _util.createHashMap; var each = _util.each; var isString = _util.isString; var defaults = _util.defaults; var extend = _util.extend; var isObject = _util.isObject; var clone = _util.clone; var _model = __webpack_require__(/*! ../../util/model */ 6); var normalizeToArray = _model.normalizeToArray; var _sourceHelper = __webpack_require__(/*! ./sourceHelper */ 7); var guessOrdinal = _sourceHelper.guessOrdinal; var Source = __webpack_require__(/*! ../Source */ 10); var _dimensionHelper = __webpack_require__(/*! ./dimensionHelper */ 13); var OTHER_DIMENSIONS = _dimensionHelper.OTHER_DIMENSIONS; /* * 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. */ /** * @deprecated * Use `echarts/data/helper/createDimensions` instead. */ /** * @see {module:echarts/test/ut/spec/data/completeDimensions} * * Complete the dimensions array, by user defined `dimension` and `encode`, * and guessing from the data structure. * If no 'value' dimension specified, the first no-named dimension will be * named as 'value'. * * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which * provides not only dim template, but also default order. * properties: 'name', 'type', 'displayName'. * `name` of each item provides default coord name. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and * provide dims count that the sysDim required. * [{ordinalMeta}] can be specified. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious) * @param {Object} [opt] * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions * For example: ['asdf', {name, type}, ...]. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3} * @param {string} [opt.generateCoord] Generate coord dim with the given name. * If not specified, extra dim names will be: * 'value', 'value0', 'value1', ... * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`. * If `generateCoordCount` specified, the generated dim names will be: * `generateCoord` + 0, `generateCoord` + 1, ... * can be Infinity, indicate that use all of the remain columns. * @param {number} [opt.dimCount] If not specified, guess by the first data item. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim. * @return {Array.<Object>} [{ * name: string mandatory, * displayName: string, the origin name in dimsDef, see source helper. * If displayName given, the tooltip will displayed vertically. * coordDim: string mandatory, * coordDimIndex: number mandatory, * type: string optional, * otherDims: { never null/undefined * tooltip: number optional, * label: number optional, * itemName: number optional, * seriesName: number optional, * }, * isExtraCoord: boolean true if coord is generated * (not specified in encode and not series specified) * other props ... * }] */ function completeDimensions(sysDims, source, opt) { if (!Source.isInstance(source)) { source = Source.seriesDataToSource(source); } opt = opt || {}; sysDims = (sysDims || []).slice(); var dimsDef = (opt.dimsDef || []).slice(); var encodeDef = createHashMap(opt.encodeDef); var dataDimNameMap = createHashMap(); var coordDimNameMap = createHashMap(); // var valueCandidate; var result = []; var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount); // Apply user defined dims (`name` and `type`) and init result. for (var i = 0; i < dimCount; i++) { var dimDefItem = dimsDef[i] = extend({}, isObject(dimsDef[i]) ? dimsDef[i] : { name: dimsDef[i] }); var userDimName = dimDefItem.name; var resultItem = result[i] = { otherDims: {} }; // Name will be applied later for avoiding duplication. if (userDimName != null && dataDimNameMap.get(userDimName) == null) { // Only if `series.dimensions` is defined in option // displayName, will be set, and dimension will be diplayed vertically in // tooltip by default. resultItem.name = resultItem.displayName = userDimName; dataDimNameMap.set(userDimName, i); } dimDefItem.type != null && (resultItem.type = dimDefItem.type); dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName); } // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`. encodeDef.each(function (dataDims, coordDim) { dataDims = normalizeToArray(dataDims).slice(); var validDataDims = encodeDef.set(coordDim, []); each(dataDims, function (resultDimIdx, idx) { // The input resultDimIdx can be dim name or index. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx)); if (resultDimIdx != null && resultDimIdx < dimCount) { validDataDims[idx] = resultDimIdx; applyDim(result[resultDimIdx], coordDim, idx); } }); }); // Apply templetes and default order from `sysDims`. var availDimIdx = 0; each(sysDims, function (sysDimItem, sysDimIndex) { var coordDim; var sysDimItem; var sysDimItemDimsDef; var sysDimItemOtherDims; if (isString(sysDimItem)) { coordDim = sysDimItem; sysDimItem = {}; } else { coordDim = sysDimItem.name; var ordinalMeta = sysDimItem.ordinalMeta; sysDimItem.ordinalMeta = null; sysDimItem = clone(sysDimItem); sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly. sysDimItemDimsDef = sysDimItem.dimsDef; sysDimItemOtherDims = sysDimItem.otherDims; sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null; } var dataDims = normalizeToArray(encodeDef.get(coordDim)); // dimensions provides default dim sequences. if (!dataDims.length) { for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) { while (availDimIdx < result.length && result[availDimIdx].coordDim != null) { availDimIdx++; } availDimIdx < result.length && dataDims.push(availDimIdx++); } } // Apply templates. each(dataDims, function (resultDimIdx, coordDimIndex) { var resultItem = result[resultDimIdx]; applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex); if (resultItem.name == null && sysDimItemDimsDef) { var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex]; !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = { name: sysDimItemDimsDefItem }); resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name; resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip; } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}} sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims); }); }); function applyDim(resultItem, coordDim, coordDimIndex) { if (OTHER_DIMENSIONS.get(coordDim) != null) { resultItem.otherDims[coordDim] = coordDimIndex; } else { resultItem.coordDim = coordDim; resultItem.coordDimIndex = coordDimIndex; coordDimNameMap.set(coordDim, true); } } // Make sure the first extra dim is 'value'. var generateCoord = opt.generateCoord; var generateCoordCount = opt.generateCoordCount; var fromZero = generateCoordCount != null; generateCoordCount = generateCoord ? generateCoordCount || 1 : 0; var extra = generateCoord || 'value'; // Set dim `name` and other `coordDim` and other props. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) { var resultItem = result[resultDimIdx] = result[resultDimIdx] || {}; var coordDim = resultItem.coordDim; if (coordDim == null) { resultItem.coordDim = genName(extra, coordDimNameMap, fromZero); resultItem.coordDimIndex = 0; if (!generateCoord || generateCoordCount <= 0) { resultItem.isExtraCoord = true; } generateCoordCount--; } resultItem.name == null && (resultItem.name = genName(resultItem.coordDim, dataDimNameMap)); if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) { resultItem.type = 'ordinal'; } } return result; } // ??? TODO // Originally detect dimCount by data[0]. Should we // optimize it to only by sysDims and dimensions and encode. // So only necessary dims will be initialized. // But // (1) custom series should be considered. where other dims // may be visited. // (2) sometimes user need to calcualte bubble size or use visualMap // on other dimensions besides coordSys needed. // So, dims that is not used by system, should be shared in storage? function getDimCount(source, sysDims, dimsDef, optDimCount) { // Note that the result dimCount should not small than columns count // of data, otherwise `dataDimNameMap` checking will be incorrect. var dimCount = Math.max(source.dimensionsDetectCount || 1, sysDims.length, dimsDef.length, optDimCount || 0); each(sysDims, function (sysDimItem) { var sysDimItemDimsDef = sysDimItem.dimsDef; sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length)); }); return dimCount; } function genName(name, map, fromZero) { if (fromZero || map.get(name) != null) { var i = 0; while (map.get(name + i) != null) { i++; } name += i; } map.set(name, true); return name; } var _default = completeDimensions; module.exports = _default; /***/ }, /* 5 */ /*!**********************************************!*\ !*** ./~/echarts/~/zrender/lib/core/util.js ***! \**********************************************/ /***/ function(module, exports) { /** * @module zrender/core/util */ // 用于处理merge时无法遍历Date等对象的问题 var BUILTIN_OBJECT = { '[object Function]': 1, '[object RegExp]': 1, '[object Date]': 1, '[object Error]': 1, '[object CanvasGradient]': 1, '[object CanvasPattern]': 1, // For node-canvas '[object Image]': 1, '[object Canvas]': 1 }; var TYPED_ARRAY = { '[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 }; var objToString = Object.prototype.toString; var arrayProto = Array.prototype; var nativeForEach = arrayProto.forEach; var nativeFilter = arrayProto.filter; var nativeSlice = arrayProto.slice; var nativeMap = arrayProto.map; var nativeReduce = arrayProto.reduce; // Avoid assign to an exported variable, for transforming to cjs. var methods = {}; function $override(name, fn) { // Clear ctx instance for different environment if (name === 'createCanvas') { _ctx = null; } methods[name] = fn; } /** * Those data types can be cloned: * Plain object, Array, TypedArray, number, string, null, undefined. * Those data types will be assgined using the orginal data: * BUILTIN_OBJECT * Instance of user defined class will be cloned to a plain object, without * properties in prototype. * Other data types is not supported (not sure what will happen). * * Caution: do not support clone Date, for performance consideration. * (There might be a large number of date in `series.data`). * So date should not be modified in and out of echarts. * * @param {*} source * @return {*} new */ function clone(source) { if (source == null || typeof source != 'object') { return source; } var result = source; var typeStr = objToString.call(source); if (typeStr === '[object Array]') { if (!isPrimitive(source)) { result = []; for (var i = 0, len = source.length; i < len; i++) { result[i] = clone(source[i]); } } } else if (TYPED_ARRAY[typeStr]) { if (!isPrimitive(source)) { var Ctor = source.constructor; if (source.constructor.from) { result = Ctor.from(source); } else { result = new Ctor(source.length); for (var i = 0, len = source.length; i < len; i++) { result[i] = clone(source[i]); } } } } else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) { result = {}; for (var key in source) { if (source.hasOwnProperty(key)) { result[key] = clone(source[key]); } } } return result; } /** * @memberOf module:zrender/core/util * @param {*} target * @param {*} source * @param {boolean} [overwrite=false] */ function merge(target, source, overwrite) { // We should escapse that source is string // and enter for ... in ... if (!isObject(source) || !isObject(target)) { return overwrite ? clone(source) : target; } for (var key in source) { if (source.hasOwnProperty(key)) { var targetProp = target[key]; var sourceProp = source[key]; if (isObject(sourceProp) && isObject(targetProp) && !isArray(sourceProp) && !isArray(targetProp) && !isDom(sourceProp) && !isDom(targetProp) && !isBuiltInObject(sourceProp) && !isBuiltInObject(targetProp) && !isPrimitive(sourceProp) && !isPrimitive(targetProp)) { // 如果需要递归覆盖,就递归调用merge merge(targetProp, sourceProp, overwrite); } else if (overwrite || !(key in target)) { // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况 // NOTE,在 target[key] 不存在的时候也是直接覆盖 target[key] = clone(source[key], true); } } } return target; } /** * @param {Array} targetAndSources The first item is target, and the rests are source. * @param {boolean} [overwrite=false] * @return {*} target */ function mergeAll(targetAndSources, overwrite) { var result = targetAndSources[0]; for (var i = 1, len = targetAndSources.length; i < len; i++) { result = merge(result, targetAndSources[i], overwrite); } return result; } /** * @param {*} target * @param {*} source * @memberOf module:zrender/core/util */ function extend(target, source) { for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } return target; } /** * @param {*} target * @param {*} source * @param {boolean} [overlay=false] * @memberOf module:zrender/core/util */ function defaults(target, source, overlay) { for (var key in source) { if (source.hasOwnProperty(key) && (overlay ? source[key] != null : target[key] == null)) { target[key] = source[key]; } } return target; } var createCanvas = function () { return methods.createCanvas(); }; methods.createCanvas = function () { return document.createElement('canvas'); }; // FIXME var _ctx; function getContext() { if (!_ctx) { // Use util.createCanvas instead of createCanvas // because createCanvas may be overwritten in different environment _ctx = createCanvas().getContext('2d'); } return _ctx; } /** * 查询数组中元素的index * @memberOf module:zrender/core/util */ function indexOf(array, value) { if (array) { if (array.indexOf) { return array.indexOf(value); } for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } } return -1; } /** * 构造类继承关系 * * @memberOf module:zrender/core/util * @param {Function} clazz 源类 * @param {Function} baseClazz 基类 */ function inherits(clazz, baseClazz) { var clazzPrototype = clazz.prototype; function F() {} F.prototype = baseClazz.prototype; clazz.prototype = new F(); for (var prop in clazzPrototype) { clazz.prototype[prop] = clazzPrototype[prop]; } clazz.prototype.constructor = clazz; clazz.superClass = baseClazz; } /** * @memberOf module:zrender/core/util * @param {Object|Function} target * @param {Object|Function} sorce * @param {boolean} overlay */ function mixin(target, source, overlay) { target = 'prototype' in target ? target.prototype : target; source = 'prototype' in source ? source.prototype : source; defaults(target, source, overlay); } /** * Consider typed array. * @param {Array|TypedArray} data */ function isArrayLike(data) { if (!data) { return; } if (typeof data == 'string') { return false; } return typeof data.length == 'number'; } /** * 数组或对象遍历 * @memberOf module:zrender/core/util * @param {Object|Array} obj * @param {Function} cb * @param {*} [context] */ function each(obj, cb, context) { if (!(obj && cb)) { return; } if (obj.forEach && obj.forEach === nativeForEach) { obj.forEach(cb, context); } else if (obj.length === +obj.length) { for (var i = 0, len = obj.length; i < len; i++) { cb.call(context, obj[i], i, obj); } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { cb.call(context, obj[key], key, obj); } } } } /** * 数组映射 * @memberOf module:zrender/core/util * @param {Array} obj * @param {Function} cb * @param {*} [context] * @return {Array} */ function map(obj, cb, context) { if (!(obj && cb)) { return; } if (obj.map && obj.map === nativeMap) { return obj.map(cb, context); } else { var result = []; for (var i = 0, len = obj.length; i < len; i++) { result.push(cb.call(context, obj[i], i, obj)); } return result; } } /** * @memberOf module:zrender/core/util * @param {Array} obj * @param {Function} cb * @param {Object} [memo] * @param {*} [context] * @return {Array} */ function reduce(obj, cb, memo, context) { if (!(obj && cb)) { return; } if (obj.reduce && obj.reduce === nativeReduce) { return obj.reduce(cb, memo, context); } else { for (var i = 0, len = obj.length; i < len; i++) { memo = cb.call(context, memo, obj[i], i, obj); } return memo; } } /** * 数组过滤 * @memberOf module:zrender/core/util * @param {Array} obj * @param {Function} cb * @param {*} [context] * @return {Array} */ function filter(obj, cb, context) { if (!(obj && cb)) { return; } if (obj.filter && obj.filter === nativeFilter) { return obj.filter(cb, context); } else { var result = []; for (var i = 0, len = obj.length; i < len; i++) { if (cb.call(context, obj[i], i, obj)) { result.push(obj[i]); } } return result; } } /** * 数组项查找 * @memberOf module:zrender/core/util * @param {Array} obj * @param {Function} cb * @param {*} [context] * @return {*} */ function find(obj, cb, context) { if (!(obj && cb)) { return; } for (var i = 0, len = obj.length; i < len; i++) { if (cb.call(context, obj[i], i, obj)) { return obj[i]; } } } /** * @memberOf module:zrender/core/util * @param {Function} func * @param {*} context * @return {Function} */ function bind(func, context) { var args = nativeSlice.call(arguments, 2); return function () { return func.apply(context, args.concat(nativeSlice.call(arguments))); }; } /** * @memberOf module:zrender/core/util * @param {Function} func * @return {Function} */ function curry(func) { var args = nativeSlice.call(arguments, 1); return function () { return func.apply(this, args.concat(nativeSlice.call(arguments))); }; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isArray(value) { return objToString.call(value) === '[object Array]'; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isFunction(value) { return typeof value === 'function'; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isString(value) { return objToString.call(value) === '[object String]'; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return type === 'function' || !!value && type == 'object'; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isBuiltInObject(value) { return !!BUILTIN_OBJECT[objToString.call(value)]; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isTypedArray(value) { return !!TYPED_ARRAY[objToString.call(value)]; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isDom(value) { return typeof value === 'object' && typeof value.nodeType === 'number' && typeof value.ownerDocument === 'object'; } /** * Whether is exactly NaN. Notice isNaN('a') returns true. * @param {*} value * @return {boolean} */ function eqNaN(value) { return value !== value; } /** * If value1 is not null, then return value1, otherwise judget rest of values. * Low performance. * @memberOf module:zrender/core/util * @return {*} Final value */ function retrieve(values) { for (var i = 0, len = arguments.length; i < len; i++) { if (arguments[i] != null) { return arguments[i]; } } } function retrieve2(value0, value1) { return value0 != null ? value0 : value1; } function retrieve3(value0, value1, value2) { return value0 != null ? value0 : value1 != null ? value1 : value2; } /** * @memberOf module:zrender/core/util * @param {Array} arr * @param {number} startIndex * @param {number} endIndex * @return {Array} */ function slice() { return Function.call.apply(nativeSlice, arguments); } /** * Normalize css liked array configuration * e.g. * 3 => [3, 3, 3, 3] * [4, 2] => [4, 2, 4, 2] * [4, 3, 2] => [4, 3, 2, 3] * @param {number|Array.<number>} val * @return {Array.<number>} */ function normalizeCssArray(val) { if (typeof val === 'number') { return [val, val, val, val]; } var len = val.length; if (len === 2) { // vertical | horizontal return [val[0], val[1], val[0], val[1]]; } else if (len === 3) { // top | horizontal | bottom return [val[0], val[1], val[2], val[1]]; } return val; } /** * @memberOf module:zrender/core/util * @param {boolean} condition * @param {string} message */ function assert(condition, message) { if (!condition) { throw new Error(message); } } /** * @memberOf module:zrender/core/util * @param {string} str string to be trimed * @return {string} trimed string */ function trim(str) { if (str == null) { return null; } else if (typeof str.trim === 'function') { return str.trim(); } else { return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); } } var primitiveKey = '__ec_primitive__'; /** * Set an object as primitive to be ignored traversing children in clone or merge */ function setAsPrimitive(obj) { obj[primitiveKey] = true; } function isPrimitive(obj) { return obj[primitiveKey]; } /** * @constructor * @param {Object} obj Only apply `ownProperty`. */ function HashMap(obj) { var isArr = isArray(obj); var thisMap = this; obj instanceof HashMap ? obj.each(visit) : obj && each(obj, visit); function visit(value, key) { isArr ? thisMap.set(value, key) :
p.set(key, value); } } // Add prefix to avoid conflict with Object.prototype. HashMap.prototype = { constructor: HashMap, // Do not provide `has` method to avoid defining what is `has`. // (We usually treat `null` and `undefined` as the same, different // from ES6 Map). get: function (key) { return this.hasOwnProperty(key) ? this[key] : null; }, set: function (key, value) { // Comparing with invocation chaining, `return value` is more commonly // used in this case: `var someVal = map.set('a', genVal());` return this[key] = value; }, // Although util.each can be performed on this hashMap directly, user // should not use the exposed keys, who are prefixed. each: function (cb, context) { context !== void 0 && (cb = bind(cb, context)); for (var key in this) { this.hasOwnProperty(key) && cb(this[key], key); } }, // Do not use this method if performance sensitive. removeKey: function (key) { delete this[key]; } }; function createHashMap(obj) { return new HashMap(obj); } function concatArray(a, b) { var newArray = new a.constructor(a.length + b.length); for (var i = 0; i < a.length; i++) { newArray[i] = a[i]; } var offset = a.length; for (i = 0; i < b.length; i++) { newArray[i + offset] = b[i]; } return newArray; } function noop() {} exports.$override = $override; exports.clone = clone; exports.merge = merge; exports.mergeAll = mergeAll; exports.extend = extend; exports.defaults = defaults; exports.createCanvas = createCanvas; exports.getContext = getContext; exports.indexOf = indexOf; exports.inherits = inherits; exports.mixin = mixin; exports.isArrayLike = isArrayLike; exports.each = each; exports.map = map; exports.reduce = reduce; exports.filter = filter; exports.find = find; exports.bind = bind; exports.curry = curry; exports.isArray = isArray; exports.isFunction = isFunction; exports.isString = isString; exports.isObject = isObject; exports.isBuiltInObject = isBuiltInObject; exports.isTypedArray = isTypedArray; exports.isDom = isDom; exports.eqNaN = eqNaN; exports.retrieve = retrieve; exports.retrieve2 = retrieve2; exports.retrieve3 = retrieve3; exports.slice = slice; exports.normalizeCssArray = normalizeCssArray; exports.assert = assert; exports.trim = trim; exports.setAsPrimitive = setAsPrimitive; exports.isPrimitive = isPrimitive; exports.createHashMap = createHashMap; exports.concatArray = concatArray; exports.noop = noop; /***/ }, /* 6 */ /*!*************************************!*\ !*** ./~/echarts/lib/util/model.js ***! \*************************************/ /***/ function(module, exports, __webpack_require__) { var zrUtil = __webpack_require__(/*! zrender/lib/core/util */ 5); /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var each = zrUtil.each; var isObject = zrUtil.isObject; var isArray = zrUtil.isArray; /** * Make the name displayable. But we should * make sure it is not duplicated with user * specified name, so use '\0'; */ var DUMMY_COMPONENT_NAME_PREFIX = 'series\0'; /** * If value is not array, then translate it to array. * @param {*} value * @return {Array} [value] or value */ function normalizeToArray(value) { return value instanceof Array ? value : value == null ? [] : [value]; } /** * Sync default option between normal and emphasis like `position` and `show` * In case some one will write code like * label: { * show: false, * position: 'outside', * fontSize: 18 * }, * emphasis: { * label: { show: true } * } * @param {Object} opt * @param {string} key * @param {Array.<string>} subOpts */ function defaultEmphasis(opt, key, subOpts) { // Caution: performance sensitive. if (opt) { opt[key] = opt[key] || {}; opt.emphasis = opt.emphasis || {}; opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal for (var i = 0, len = subOpts.length; i < len; i++) { var subOptName = subOpts[i]; if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) { opt.emphasis[key][subOptName] = opt[key][subOptName]; } } } } var TEXT_STYLE_OPTIONS = ['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']; // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([ // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter', // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily', // // FIXME: deprecated, check and remove it. // 'textStyle' // ]); /** * The method do not ensure performance. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}] * This helper method retieves value from data. * @param {string|number|Date|Array|Object} dataItem * @return {number|string|Date|Array.<number|string|Date>} */ function getDataItemValue(dataItem) { return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem; } /** * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}] * This helper method determine if dataItem has extra option besides value * @param {string|number|Date|Array|Object} dataItem */ function isDataItemOption(dataItem) { return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array)); } /** * Mapping to exists for merge. * * @public * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists * @param {Object|Array.<Object>} newCptOptions * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}], * index of which is the same as exists. */ function mappingToExists(exists, newCptOptions) { // Mapping by the order by original option (but not order of // new option) in merge mode. Because we should ensure // some specified index (like xAxisIndex) is consistent with // original option, which is easy to understand, espatially in // media query. And in most case, merge option is used to // update partial option but not be expected to change order. newCptOptions = (newCptOptions || []).slice(); var result = zrUtil.map(exists || [], function (obj, index) { return { exist: obj }; }); // Mapping by id or name if specified. each(newCptOptions, function (cptOption, index) { if (!isObject(cptOption)) { return; } // id has highest priority. for (var i = 0; i < result.length; i++) { if (!result[i].option // Consider name: two map to one. && cptOption.id != null && result[i].exist.id === cptOption.id + '') { result[i].option = cptOption; newCptOptions[index] = null; return; } } for (var i = 0; i < result.length; i++) { var exist = result[i].exist; if (!result[i].option // Consider name: two map to one. // Can not match when both ids exist but different. && (exist.id == null || cptOption.id == null) && cptOption.name != null && !isIdInner(cptOption) && !isIdInner(exist) && exist.name === cptOption.name + '') { result[i].option = cptOption; newCptOptions[index] = null; return; } } }); // Otherwise mapping by index. each(newCptOptions, function (cptOption, index) { if (!isObject(cptOption)) { return; } var i = 0; for (; i < result.length; i++) { var exist = result[i].exist; if (!result[i].option // Existing model that already has id should be able to // mapped to (because after mapping performed model may // be assigned with a id, whish should not affect next // mapping), except those has inner id. && !isIdInner(exist) // Caution: // Do not overwrite id. But name can be overwritten, // because axis use name as 'show label text'. // 'exist' always has id and name and we dont // need to check it. && cptOption.id == null) { result[i].option = cptOption; break; } } if (i >= result.length) { result.push({ option: cptOption }); } }); return result; } /** * Make id and name for mapping result (result of mappingToExists) * into `keyInfo` field. * * @public * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}], * which order is the same as exists. * @return {Array.<Object>} The input. */ function makeIdAndName(mapResult) { // We use this id to hash component models and view instances // in echarts. id can be specified by user, or auto generated. // The id generation rule ensures new view instance are able // to mapped to old instance when setOption are called in // no-merge mode. So we generate model id by name and plus // type in view id. // name can be duplicated among components, which is convenient // to specify multi components (like series) by one name. // Ensure that each id is distinct. var idMap = zrUtil.createHashMap(); each(mapResult, function (item, index) { var existCpt = item.exist; existCpt && idMap.set(existCpt.id, item); }); each(mapResult, function (item, index) { var opt = item.option; zrUtil.assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id)); opt && opt.id != null && idMap.set(opt.id, item); !item.keyInfo && (item.keyInfo = {}); }); // Make name and id. each(mapResult, function (item, index) { var existCpt = item.exist; var opt = item.option; var keyInfo = item.keyInfo; if (!isObject(opt)) { return; } // name can be overwitten. Consider case: axis.name = '20km'. // But id generated by name will not be changed, which affect // only in that case: setOption with 'not merge mode' and view // instance will be recreated, which can be accepted. keyInfo.name = opt.name != null ? opt.name + '' : existCpt ? existCpt.name // Avoid diffferent series has the same name, // because name may be used like in color pallet. : DUMMY_COMPONENT_NAME_PREFIX + index; if (existCpt) { keyInfo.id = existCpt.id; } else if (opt.id != null) { keyInfo.id = opt.id + ''; } else { // Consider this situatoin: // optionA: [{name: 'a'}, {name: 'a'}, {..}] // optionB [{..}, {name: 'a'}, {name: 'a'}] // Series with the same name between optionA and optionB // should be mapped. var idNum = 0; do { keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++; } while (idMap.get(keyInfo.id)); } idMap.set(keyInfo.id, item); }); } function isNameSpecified(componentModel) { var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX)); } /** * @public * @param {Object} cptOption * @return {boolean} */ function isIdInner(cptOption) { return isObject(cptOption) && cptOption.id && (cptOption.id + '').indexOf('\0_ec_\0') === 0; } /** * A helper for removing duplicate items between batchA and batchB, * and in themselves, and categorize by series. * * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...] * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...] * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB] */ function compressBatches(batchA, batchB) { var mapA = {}; var mapB = {}; makeMap(batchA || [], mapA); makeMap(batchB || [], mapB, mapA); return [mapToArray(mapA), mapToArray(mapB)]; function makeMap(sourceBatch, map, otherMap) { for (var i = 0, len = sourceBatch.length; i < len; i++) { var seriesId = sourceBatch[i].seriesId; var dataIndices = normalizeToArray(sourceBatch[i].dataIndex); var otherDataIndices = otherMap && otherMap[seriesId]; for (var j = 0, lenj = dataIndices.length; j < lenj; j++) { var dataIndex = dataIndices[j]; if (otherDataIndices && otherDataIndices[dataIndex]) { otherDataIndices[dataIndex] = null; } else { (map[seriesId] || (map[seriesId] = {}))[dataIndex] = 1; } } } } function mapToArray(map, isData) { var result = []; for (var i in map) { if (map.hasOwnProperty(i) && map[i] != null) { if (isData) { result.push(+i); } else { var dataIndices = mapToArray(map[i], true); dataIndices.length && result.push({ seriesId: i, dataIndex: dataIndices }); } } } return result; } } /** * @param {module:echarts/data/List} data * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name * each of which can be Array or primary type. * @return {number|Array.<number>} dataIndex If not found, return undefined/null. */ function queryDataIndex(data, payload) { if (payload.dataIndexInside != null) { return payload.dataIndexInside; } else if (payload.dataIndex != null) { return zrUtil.isArray(payload.dataIndex) ? zrUtil.map(payload.dataIndex, function (value) { return data.indexOfRawIndex(value); }) : data.indexOfRawIndex(payload.dataIndex); } else if (payload.name != null) { return zrUtil.isArray(payload.name) ? zrUtil.map(payload.name, function (value) { return data.indexOfName(value); }) : data.indexOfName(payload.name); } } /** * Enable property storage to any host object. * Notice: Serialization is not supported. * * For example: * var inner = zrUitl.makeInner(); * * function some1(hostObj) { * inner(hostObj).someProperty = 1212; * ... * } * function some2() { * var fields = inner(this); * fields.someProperty1 = 1212; * fields.someProperty2 = 'xx'; * ... * } * * @return {Function} */ function makeInner() { // Consider different scope by es module import. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5); return function (hostObj) { return hostObj[key] || (hostObj[key] = {}); }; } var innerUniqueIndex = 0; /** * @param {module:echarts/model/Global} ecModel * @param {string|Object} finder * If string, e.g., 'geo', means {geoIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex, seriesId, seriesName, * geoIndex, geoId, geoName, * bmapIndex, bmapId, bmapName, * xAxisIndex, xAxisId, xAxisName, * yAxisIndex, yAxisId, yAxisName, * gridIndex, gridId, gridName, * ... (can be extended) * } * Each properties can be number|string|Array.<number>|Array.<string> * For example, a finder could be * { * seriesIndex: 3, * geoId: ['aa', 'cc'], * gridName: ['xx', 'rr'] * } * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify) * If nothing or null/undefined specified, return nothing. * @param {Object} [opt] * @param {string} [opt.defaultMainType] * @param {Array.<string>} [opt.includeMainTypes] * @return {Object} result like: * { * seriesModels: [seriesModel1, seriesModel2], * seriesModel: seriesModel1, // The first model * geoModels: [geoModel1, geoModel2], * geoModel: geoModel1, // The first model * ... * } */ function parseFinder(ecModel, finder, opt) { if (zrUtil.isString(finder)) { var obj = {}; obj[finder + 'Index'] = 0; finder = obj; } var defaultMainType = opt && opt.defaultMainType; if (defaultMainType && !has(finder, defaultMainType + 'Index') && !has(finder, defaultMainType + 'Id') && !has(finder, defaultMainType + 'Name')) { finder[defaultMainType + 'Index'] = 0; } var result = {}; each(finder, function (value, key) { var value = finder[key]; // Exclude 'dataIndex' and other illgal keys. if (key === 'dataIndex' || key === 'dataIndexInside') { result[key] = value; return; } var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || []; var mainType = parsedKey[1]; var queryType = (parsedKey[2] || '').toLowerCase(); if (!mainType || !queryType || value == null || queryType === 'index' && value === 'none' || opt && opt.includeMainTypes && zrUtil.indexOf(opt.includeMainTypes, mainType) < 0) { return; } var queryParam = { mainType: mainType }; if (queryType !== 'index' || value !== 'all') { queryParam[queryType] = value; } var models = ecModel.queryComponents(queryParam); result[mainType + 'Models'] = models; result[mainType + 'Model'] = models[0]; }); return result; } function has(obj, prop) { return obj && obj.hasOwnProperty(prop); } function setAttribute(dom, key, value) { dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value; } function getAttribute(dom, key) { return dom.getAttribute ? dom.getAttribute(key) : dom[key]; } exports.normalizeToArray = normalizeToArray; exports.defaultEmphasis = defaultEmphasis; exports.TEXT_STYLE_OPTIONS = TEXT_STYLE_OPTIONS; exports.getDataItemValue = getDataItemValue; exports.isDataItemOption = isDataItemOption; exports.mappingToExists = mappingToExists; exports.makeIdAndName = makeIdAndName; exports.isNameSpecified = isNameSpecified; exports.isIdInner = isIdInner; exports.compressBatches = compressBatches; exports.queryDataIndex = queryDataIndex; exports.makeInner = makeInner; exports.parseFinder = parseFinder; exports.setAttribute = setAttribute; exports.getAttribute = getAttribute; /***/ }, /* 7 */ /*!***************************************************!*\ !*** ./~/echarts/lib/data/helper/sourceHelper.js ***! \***************************************************/ /***/ function(module, exports, __webpack_require__) { var _config = __webpack_require__(/*! ../../config */ 8); var __DEV__ = _config.__DEV__; var _model = __webpack_require__(/*! ../../util/model */ 6); var makeInner = _model.makeInner; var getDataItemValue = _model.getDataItemValue; var _referHelper = __webpack_require__(/*! ../../model/referHelper */ 9); var getCoordSysDefineBySeries = _referHelper.getCoordSysDefineBySeries; var _util = __webpack_require__(/*! zrender/lib/core/util */ 5); var createHashMap = _util.createHashMap; var each = _util.each; var map = _util.map; var isArray = _util.isArray; var isString = _util.isString; var isObject = _util.isObject; var isTypedArray = _util.isTypedArray; var isArrayLike = _util.isArrayLike; var extend = _util.extend; var assert = _util.assert; var Source = __webpack_require__(/*! ../Source */ 10); var _sourceType = __webpack_require__(/*! ./sourceType */ 12); var SOURCE_FORMAT_ORIGINAL = _sourceType.SOURCE_FORMAT_ORIGINAL; var SOURCE_FORMAT_ARRAY_ROWS = _sourceType.SOURCE_FORMAT_ARRAY_ROWS; var SOURCE_FORMAT_OBJECT_ROWS = _sourceType.SOURCE_FORMAT_OBJECT_ROWS; var SOURCE_FORMAT_KEYED_COLUMNS = _sourceType.SOURCE_FORMAT_KEYED_COLUMNS; var SOURCE_FORMAT_UNKNOWN = _sourceType.SOURCE_FORMAT_UNKNOWN; var SOURCE_FORMAT_TYPED_ARRAY = _sourceType.SOURCE_FORMAT_TYPED_ARRAY; var SERIES_LAYOUT_BY_ROW = _sourceType.SERIES_LAYOUT_BY_ROW; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var inner = makeInner(); /** * @see {module:echarts/data/Source} * @param {module:echarts/component/dataset/DatasetModel} datasetModel * @return {string} sourceFormat */ function detectSourceFormat(datasetModel) { var data = datasetModel.option.source; var sourceFormat = SOURCE_FORMAT_UNKNOWN; if (isTypedArray(data)) { sourceFormat = SOURCE_FORMAT_TYPED_ARRAY; } else if (isArray(data)) { // FIXME Whether tolerate null in top level array? for (var i = 0, len = data.length; i < len; i++) { var item = data[i]; if (item == null) { continue; } else if (isArray(item)) { sourceFormat = SOURCE_FORMAT_ARRAY_ROWS; break; } else if (isObject(item)) { sourceFormat = SOURCE_FORMAT_OBJECT_ROWS; break; } } } else if (isObject(data)) { for (var key in data) { if (data.hasOwnProperty(key) && isArrayLike(data[key])) { sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS; break; } } } else if (data != null) { throw new Error('Invalid data'); } inner(datasetModel).sourceFormat = sourceFormat; } /** * [Scenarios]: * (1) Provide source data directly: * series: { * encode: {...}, * dimensions: [...] * seriesLayoutBy: 'row', * data: [[...]] * } * (2) Refer to datasetModel. * series: [{ * encode: {...} * // Ignore datasetIndex means `datasetIndex: 0` * // and the dimensions defination in dataset is used * }, { * encode: {...}, * seriesLayoutBy: 'column', * datasetIndex: 1 * }] * * Get data from series itself or datset. * @return {module:echarts/data/Source} source */ function getSource(seriesModel) { return inner(seriesModel).source; } /** * MUST be called before mergeOption of all series. * @param {module:echarts/model/Global} ecModel */ function resetSourceDefaulter(ecModel) { // `datasetMap` is used to make default encode. inner(ecModel).datasetMap = createHashMap(); } /** * [Caution]: * MUST be called after series option merged and * before "series.getInitailData()" called. * * [The rule of making default encode]: * Category axis (if exists) alway map to the first dimension. * Each other axis occupies a subsequent dimension. * * [Why make default encode]: * Simplify the typing of encode in option, avoiding the case like that: * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}], * where the "y" have to be manually typed as "1, 2, 3, ...". * * @param {module:echarts/model/Series} seriesModel */ function prepareSource(seriesModel) { var seriesOption = seriesModel.option; var data = seriesOption.data; var sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL; var fromDataset = false; var seriesLayoutBy = seriesOption.seriesLayoutBy; var sourceHeader = seriesOption.sourceHeader; var dimensionsDefine = seriesOption.dimensions; var datasetModel = getDatasetModel(seriesModel); if (datasetModel) { var datasetOption = datasetModel.option; data = datasetOption.source; sourceFormat = inner(datasetModel).sourceFormat; fromDataset = true; // These settings from series has higher priority. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy; sourceHeader == null && (sourceHeader = datasetOption.sourceHeader); dimensionsDefine = dimensionsDefine || datasetOption.dimensions; } var completeResult = completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine); // Note: dataset option does not have `encode`. var encodeDefine = seriesOption.encode; if (!encodeDefine && datasetModel) { encodeDefine = makeDefaultEncode(seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult); } inner(seriesModel).source = new Source({ data: data, fromDataset: fromDataset, seriesLayoutBy: seriesLayoutBy, sourceFormat: sourceFormat, dimensionsDefine: completeResult.dimensionsDefine, startIndex: completeResult.startIndex, dimensionsDetectCount: completeResult.dimensionsDetectCount, encodeDefine: encodeDefine }); } // return {startIndex, dimensionsDefine, dimensionsCount} function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) { if (!data) { return { dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine) }; } var dimensionsDetectCount; var startIndex; var findPotentialName; if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) { // Rule: Most of the first line are string: it is header. // Caution: consider a line with 5 string and 1 number, // it still can not be sure it is a head, because the // 5 string may be 5 values of category columns. if (sourceHeader === 'auto' || sourceHeader == null) { arrayRowsTravelFirst(function (val) { // '-' is regarded as null/undefined. if (val != null && val !== '-') { if (isString(val)) { startIndex == null && (startIndex = 1); } else { startIndex = 0; } } // 10 is an experience number, avoid long loop. }, seriesLayoutBy, data, 10); } else { startIndex = sourceHeader ? 1 : 0; } if (!dimensionsDefine && startIndex === 1) { dimensionsDefine = []; arrayRowsTravelFirst(function (val, index) { dimensionsDefine[index] = val != null ? val : ''; }, seriesLayoutBy, data); } dimensionsDetectCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? data.length : data[0] ? data[0].length : null; } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) { if (!dimensionsDefine) { dimensionsDefine = objectRowsCollectDimensions(data); findPotentialName = true; } } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) { if (!dimensionsDefine) { dimensionsDefine = []; findPotentialName = true; each(data, function (colArr, key) { dimensionsDefine.push(key); }); } } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) { var value0 = getDataItemValue(data[0]); dimensionsDetectCount = isArray(value0) && value0.length || 1; } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {} var potentialNameDimIndex; if (findPotentialName) { each(dimensionsDefine, function (dim, idx) { if ((isObject(dim) ? dim.name : dim) === 'name') { potentialNameDimIndex = idx; } }); } return { startIndex: startIndex, dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine), dimensionsDetectCount: dimensionsDetectCount, potentialNameDimIndex: potentialNameDimIndex // TODO: potentialIdDimIdx }; } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'], // which is reasonable. But dimension name is duplicated. // Returns undefined or an array contains only object without null/undefiend or string. function normalizeDimensionsDefine(dimensionsDefine) { if (!dimensionsDefine) { // The meaning of null/undefined is different from empty array. return; } var nameMap = createHashMap(); return map(dimensionsDefine, function (item, index) { item = extend({}, isObject(item) ? item : { name: item }); // User can set null in dimensions. // We dont auto specify name, othewise a given name may // cause it be refered unexpectedly. if (item.name == null) { return item; } // Also consider number form like 2012. item.name += ''; // User may also specify displayName. // displayName will always exists except user not // specified or dim name is not specified or detected. // (A auto generated dim name will not be used as // displayName). if (item.displayName == null) { item.displayName = item.name; } var exist = nameMap.get(item.name); if (!exist) { nameMap.set(item.name, { count: 1 }); } else { item.name += '-' + exist.count++; } return item; }); } function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) { maxLoop == null && (maxLoop = Infinity); if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) { for (var i = 0; i < data.length && i < maxLoop; i++) { cb(data[i] ? data[i][0] : null, i); } } else { var value0 = data[0] || []; for (var i = 0; i < value0.length && i < maxLoop; i++) { cb(value0[i], i); } } } function objectRowsCollectDimensions(data) { var firstIndex = 0; var obj; while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line if (obj) { var dimensions = []; each(obj, function (value, key) { dimensions.push(key); }); return dimensions; } } // ??? TODO merge to completedimensions, where also has // default encode making logic. And the default rule // should depends on series? consider 'map'. function makeDefaultEncode(seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult) { var coordSysDefine = getCoordSysDefineBySeries(seriesModel); var encode = {}; // var encodeTooltip = []; // var encodeLabel = []; var encodeItemName = []; var encodeSeriesName = []; var seriesType = seriesModel.subType; // ??? TODO refactor: provide by series itself. // Consider the case: 'map' series is based on geo coordSys, // 'graph', 'heatmap' can be based on cartesian. But can not // give default rule simply here. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']); var cSeriesMap = createHashMap(['line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot']); // Usually in this case series will use the first data // dimension as the "value" dimension, or other default // processes respectively. if (coordSysDefine && cSeriesMap.get(seriesType) != null) { var ecModel = seriesModel.ecModel; var datasetMap = inner(ecModel).datasetMap; var key = datasetModel.uid + '_' + seriesLayoutBy; var datasetRecord = datasetMap.get(key) || datasetMap.set(key, { categoryWayDim: 1, valueWayDim: 0 }); // TODO // Auto detect first time axis and do arrangement. each(coordSysDefine.coordSysDims, function (coordDim) { // In value way. if (coordSysDefine.firstCategoryDimIndex == null) { var dataDim = datasetRecord.valueWayDim++; encode[coordDim] = dataDim; // ??? TODO give a better default series name rule? // especially when encode x y specified. // consider: when mutiple series share one dimension // category axis, series name should better use // the other dimsion name. On the other hand, use // both dimensions name. encodeSeriesName.push(dataDim); // encodeTooltip.push(dataDim); // encodeLabel.push(dataDim); } // In category way, category axis. else if (coordSysDefine.categoryAxisMap.get(coordDim)) { encode[coordDim] = 0; encodeItemName.push(0); } // In category way, non-category axis. else { var dataDim = datasetRecord.categoryWayDim++; encode[coordDim] = dataDim; // encodeTooltip.push(dataDim); // encodeLabel.push(dataDim); encodeSeriesName.push(dataDim); } }); } // Do not make a complex rule! Hard to code maintain and not necessary. // ??? TODO refactor: provide by series itself. // [{name: ..., value: ...}, ...] like: else if (nSeriesMap.get(seriesType) != null) { // Find the first not ordinal. (5 is an experience value) var firstNotOrdinal; for (var i = 0; i < 5 && firstNotOrdinal == null; i++) { if (!doGuessOrdinal(data, sourceFormat, seriesLayoutBy, completeResult.dimensionsDefine, completeResult.startIndex, i)) { firstNotOrdinal = i; } } if (firstNotOrdinal != null) { encode.value = firstNotOrdinal; var nameDimIndex = completeResult.potentialNameDimIndex || Math.max(firstNotOrdinal - 1, 0); // By default, label use itemName in charts. // So we dont set encodeLabel here. encodeSeriesName.push(nameDimIndex); encodeItemName.push(nameDimIndex); // encodeTooltip.push(firstNotOrdinal); } } // encodeTooltip.length && (encode.tooltip = encodeTooltip); // encodeLabel.length && (encode.label = encodeLabel); encodeItemName.length && (encode.itemName = encodeItemName); encodeSeriesName.length && (encode.seriesName = encodeSeriesName); return encode; } /** * If return null/undefined, indicate that should not use datasetModel. */ function getDatasetModel(seriesModel) { var option = seriesModel.option; // Caution: consider the scenario: // A dataset is declared and a series is not expected to use the dataset, // and at the beginning `setOption({series: { noData })` (just prepare other // option but no data), then `setOption({series: {data: [...]}); In this case, // the user should set an empty array to avoid that dataset is used by default. var thisData = option.data; if (!thisData) { return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0); } } /** * The rule should not be complex, otherwise user might not * be able to known where the data is wrong. * The code is ugly, but how to make it neat? * * @param {module:echars/data/Source} source * @param {number} dimIndex * @return {boolean} Whether ordinal. */ function guessOrdinal(source, dimIndex) { return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex); } // dimIndex may be overflow source data. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) { var result; // Experience value. var maxLoop = 5; if (isTypedArray(data)) { return false; } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine // always exists in source. var dimName; if (dimensionsDefine) { dimName = dimensionsDefine[dimIndex]; dimName = isObject(dimName) ? dimName.name : dimName; } if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) { if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) { var sample = data[dimIndex]; for (var i = 0; i < (sample || []).length && i < maxLoop; i++) { if ((result = detectValue(sample[startIndex + i])) != null) { return result; } } } else { for (var i = 0; i < data.length && i < maxLoop; i++) { var row = data[startIndex + i]; if (row && (result = detectValue(row[dimIndex])) != null) { return result; } } } } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) { if (!dimName) { return; } for (var i = 0; i < data.length && i < maxLoop; i++) { var item = data[i]; if (item && (result = detectValue(item[dimName])) != null) { return result; } } } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) { if (!dimName) { return; } var sample = data[dimName]; if (!sample || isTypedArray(sample)) { return false; } for (var i = 0; i < sample.length && i < maxLoop; i++) { if ((result = detectValue(sample[i])) != null) { return result; } } } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) { for (var i = 0; i < data.length && i < maxLoop; i++) { var item = data[i]; var val = getDataItemValue(item); if (!isArray(val)) { return false; } if ((result = detectValue(val[dimIndex])) != null) { return result; } } } function detectValue(val) { // Consider usage convenience, '1', '2' will be treated as "number". // `isFinit('')` get `true`. if (val != null && isFinite(val) && val !== '') { return false; } else if (isString(val) && val !== '-') { return true; } } return false; } exports.detectSourceFormat = detectSourceFormat; exports.getSource = getSource; exports.resetSourceDefaulter = resetSourceDefaulter; exports.prepareSource = prepareSource; exports.guessOrdinal = guessOrdinal; /***/ }, /* 8 */ /*!*********************************!*\ !*** ./~/echarts/lib/config.js ***! \*********************************/ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/* * 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. */ // (1) The code `if (__DEV__) ...` can be removed by build tool. // (2) If intend to use `__DEV__`, this module should be imported. Use a global // variable `__DEV__` may cause that miss the declaration (see #6535), or the // declaration is behind of the using position (for example in `Model.extent`, // And tools like rollup can not analysis the dependency if not import). var dev; // In browser if (typeof window !== 'undefined') { dev = window.__DEV__; } // In node else if (typeof global !== 'undefined') { dev = global.__DEV__; } if (typeof dev === 'undefined') { dev = true; } var __DEV__ = dev; exports.__DEV__ = __DEV__; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 9 */ /*!********************************************!*\ !*** ./~/echarts/lib/model/referHelper.js ***! \********************************************/ /***/ function(module, exports, __webpack_require__) { var _config = __webpack_require__(/*! ../config */ 8); var __DEV__ = _config.__DEV__; var _util = __webpack_require__(/*! zrender/lib/core/util */ 5); var createHashMap = _util.createHashMap; var retrieve = _util.retrieve; var each = _util.each; /* * 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. */ /** * Helper for model references. * There are many manners to refer axis/coordSys. */ // TODO // merge relevant logic to this file? // check: "modelHelper" of tooltip and "BrushTargetManager". /** * @return {Object} For example: * { * coordSysName: 'cartesian2d', * coordSysDims: ['x', 'y', ...], * axisMap: HashMap({ * x: xAxisModel, * y: yAxisModel * }), * categoryAxisMap: HashMap({ * x: xAxisModel, * y: undefined * }), * // It also indicate that whether there is category axis. * firstCategoryDimIndex: 1, * // To replace user specified encode. * } */ function getCoordSysDefineBySeries(seriesModel) { var coordSysName = seriesModel.get('coordinateSystem'); var result = { coordSysName: coordSysName, coordSysDims: [], axisMap: createHashMap(), categoryAxisMap: createHashMap() }; var fetch = fetchers[coordSysName]; if (fetch) { fetch(seriesModel, result, result.axisMap, result.categoryAxisMap); return result; } } var fetchers = { cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) { var xAxisModel = seriesModel.getReferringComponents('xAxis')[0]; var yAxisModel = seriesModel.getReferringComponents('yAxis')[0]; result.coordSysDims = ['x', 'y']; axisMap.set('x', xAxisModel); axisMap.set('y', yAxisModel); if (isCategory(xAxisModel)) { categoryAxisMap.set('x', xAxisModel); result.firstCategoryDimIndex = 0; } if (isCategory(yAxisModel)) { categoryAxisMap.set('y', yAxisModel); result.firstCategoryDimIndex = 1; } }, singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) { var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0]; result.coordSysDims = ['single']; axisMap.set('single', singleAxisModel); if (isCategory(singleAxisModel)) { categoryAxisMap.set('single', singleAxisModel); result.firstCategoryDimIndex = 0; } }, polar: function (seriesModel, result, axisMap, categoryAxisMap) { var polarModel = seriesModel.getReferringComponents('polar')[0]; var radiusAxisModel = polarModel.findAxisModel('radiusAxis'); var angleAxisModel = polarModel.findAxisModel('angleAxis'); result.coordSysDims = ['radius', 'angle']; axisMap.set('radius', radiusAxisModel); axisMap.set('angle', angleAxisModel); if (isCategory(radiusAxisModel)) { categoryAxisMap.set('radius', radiusAxisModel); result.firstCategoryDimIndex = 0; } if (isCategory(angleAxisModel)) { categoryAxisMap.set('angle', angleAxisModel); result.firstCategoryDimIndex = 1; } }, geo: function (seriesModel, result, axisMap, categoryAxisMap) { result.coordSysDims = ['lng', 'lat']; }, parallel: function (seriesModel, result, axisMap, categoryAxisMap) { var ecModel = seriesModel.ecModel; var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex')); var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice(); each(parallelModel.parallelAxisIndex, function (axisIndex, index) { var axisModel = ecModel.getComponent('parallelAxis', axisIndex); var axisDim = coordSysDims[index]; axisMap.set(axisDim, axisModel); if (isCategory(axisModel) && result.firstCategoryDimIndex == null) { categoryAxisMap.set(axisDim, axisModel); result.firstCategoryDimIndex = index; } }); } }; function isCategory(axisModel) { return axisModel.get('type') === 'category'; } exports.getCoordSysDefineBySeries = getCoordSysDefineBySeries; /***/ }, /* 10 */ /*!**************************************!*\ !*** ./~/echarts/lib/data/Source.js ***! \**************************************/ /***/ function(module, exports, __webpack_require__) { var _util = __webpack_require__(/*! zrender/lib/core/util */ 5); var createHashMap = _util.createHashMap; var isTypedArray = _util.isTypedArray; var _clazz = __webpack_require__(/*! ../util/clazz */ 11); var enableClassCheck = _clazz.enableClassCheck; var _sourceType = __webpack_require__(/*! ./helper/sourceType */ 12); var SOURCE_FORMAT_ORIGINAL = _sourceType.SOURCE_FORMAT_ORIGINAL; var SERIES_LAYOUT_BY_COLUMN = _sourceType.SERIES_LAYOUT_BY_COLUMN; var SOURCE_FORMAT_UNKNOWN = _sourceType.SOURCE_FORMAT_UNKNOWN; var SOURCE_FORMAT_TYPED_ARRAY = _sourceType.SOURCE_FORMAT_TYPED_ARRAY; var SOURCE_FORMAT_KEYED_COLUMNS = _sourceType.SOURCE_FORMAT_KEYED_COLUMNS; /* * 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. */ /** * [sourceFormat] * * + "original": * This format is only used in series.data, where * itemStyle can be specified in data item. * * + "arrayRows": * [ * ['product', 'score', 'amount'], * ['Matcha Latte', 89.3, 95.8], * ['Milk Tea', 92.1, 89.4], * ['Cheese Cocoa', 94.4, 91.2], * ['Walnut Brownie', 85.4, 76.9] * ] * * + "objectRows": * [ * {product: 'Matcha Latte', score: 89.3, amount: 95.8}, * {product: 'Milk Tea', score: 92.1, amount: 89.4}, * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2}, * {product: 'Walnut Brownie', score: 85.4, amount: 76.9} * ] * * + "keyedColumns": * { * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'], * 'count': [823, 235, 1042, 988], * 'score': [95.8, 81.4, 91.2, 76.9] * } * * + "typedArray" * * + "unknown" */ /** * @constructor * @param {Object} fields * @param {string} fields.sourceFormat * @param {Array|Object} fields.fromDataset * @param {Array|Object} [fields.data] * @param {string} [seriesLayoutBy='column'] * @param {Array.<Object|string>} [dimensionsDefine] * @param {Objet|HashMap} [encodeDefine] * @param {number} [startIndex=0] * @param {number} [dimensionsDetectCount] */ function Source(fields) { /** * @type {boolean} */ this.fromDataset = fields.fromDataset; /** * Not null/undefined. * @type {Array|Object} */ this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []); /** * See also "detectSourceFormat". * Not null/undefined. * @type {string} */ this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; /** * 'row' or 'column' * Not null/undefined. * @type {string} seriesLayoutBy */ this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN; /** * dimensions definition in option. * can be null/undefined. * @type {Array.<Object|string>} */ this.dimensionsDefine = fields.dimensionsDefine; /** * encode definition in option. * can be null/undefined. * @type {Objet|HashMap} */ this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine); /** * Not null/undefined, uint. * @type {number} */ this.startIndex = fields.startIndex || 0; /** * Can be null/undefined (when unknown), uint. * @type {number} */ this.dimensionsDetectCount = fields.dimensionsDetectCount; } /** * Wrap original series data for some compatibility cases. */ Source.seriesDataToSource = function (data) { return new Source({ data: data, sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL, fromDataset: false }); }; enableClassCheck(Source); var _default = Source; module.exports = _default; /***/ }, /* 11 */ /*!*************************************!*\ !*** ./~/echarts/lib/util/clazz.js ***! \*************************************/ /***/ function(module, exports, __webpack_require__) { var _config = __webpack_require__(/*! ../config */ 8); var __DEV__ = _config.__DEV__; var zrUtil = __webpack_require__(/*! zrender/lib/core/util */ 5); /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var TYPE_DELIMITER = '.'; var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___'; /** * Notice, parseClassType('') should returns {main: '', sub: ''} * @public */ function parseClassType(componentType) { var ret = { main: '', sub: '' }; if (componentType) { componentType = componentType.split(TYPE_DELIMITER); ret.main = componentType[0] || ''; ret.sub = componentType[1] || ''; } return ret; } /** * @public */ function checkClassType(componentType) { zrUtil.assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal'); } /** * @public */ function enableClassExtend(RootClass, mandatoryMethods) { RootClass.$constructor = RootClass; RootClass.extend = function (proto) { var superClass = this; var ExtendedClass = function () { if (!proto.$constructor) { superClass.apply(this, arguments); } else { proto.$constructor.apply(this, arguments); } }; zrUtil.extend(ExtendedClass.prototype, proto); ExtendedClass.extend = this.extend; ExtendedClass.superCall = superCall; ExtendedClass.superApply = superApply; zrUtil.inherits(ExtendedClass, this); ExtendedClass.superClass = superClass; return ExtendedClass; }; } var classBase = 0; /** * Can not use instanceof, consider different scope by * cross domain or es module import in ec extensions. * Mount a method "isInstance()" to Clz. */ function enableClassCheck(Clz) { var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_'); Clz.prototype[classAttr] = true; Clz.isInstance = function (obj) { return !!(obj && obj[classAttr]); }; } // superCall should have class info, which can not be fetch from 'this'. // Consider this case: // class A has method f, // class B inherits class A, overrides method f, f call superApply('f'), // class C inherits class B, do not overrides method f, // then when method of class C is called, dead loop occured. function superCall(context, methodName) { var args = zrUtil.slice(arguments, 2); return this.superClass.prototype[methodName].apply(context, args); } function superApply(context, methodName, args) { return this.superClass.prototype[methodName].apply(context, args); } /** * @param {Object} entity * @param {Object} options * @param {boolean} [options.registerWhenExtend] * @public */ function enableClassManagement(entity, options) { options = options || {}; /** * Component model classes * key: componentType, * value: * componentClass, when componentType is 'xxx' * or Object.<subKey, componentClass>, when componentType is 'xxx.yy' * @type {Object} */ var storage = {}; entity.registerClass = function (Clazz, componentType) { if (componentType) { checkClassType(componentType); componentType = parseClassType(componentType); if (!componentType.sub) { storage[componentType.main] = Clazz; } else if (componentType.sub !== IS_CONTAINER) { var container = makeContainer(componentType); container[componentType.sub] = Clazz; } } return Clazz; }; entity.getClass = function (componentMainType, subType, throwWhenNotFound) { var Clazz = storage[componentMainType]; if (Clazz && Clazz[IS_CONTAINER]) { Clazz = subType ? Clazz[subType] : null; } if (throwWhenNotFound && !Clazz) { throw new Error(!subType ? componentMainType + '.' + 'type should be specified.' : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'); } return Clazz; }; entity.getClassesByMainType = function (componentType) { componentType = parseClassType(componentType); var result = []; var obj = storage[componentType.main]; if (obj && obj[IS_CONTAINER]) { zrUtil.each(obj, function (o, type) { type !== IS_CONTAINER && result.push(o); }); } else { result.push(obj); } return result; }; entity.hasClass = function (componentType) { // Just consider componentType.main. componentType = parseClassType(componentType); return !!storage[componentType.main]; }; /** * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx'] */ entity.getAllClassMainTypes = function () { var types = []; zrUtil.each(storage, function (obj, type) { types.push(type); }); return types; }; /** * If a main type is container and has sub types * @param {string} mainType * @return {boolean} */ entity.hasSubTypes = function (componentType) { componentType = parseClassType(componentType); var obj = storage[componentType.main]; return obj && obj[IS_CONTAINER]; }; entity.parseClassType = parseClassType; function makeContainer(componentType) { var container = storage[componentType.main]; if (!container || !container[IS_CONTAINER]) { container = storage[componentType.main] = {}; container[IS_CONTAINER] = true; } return container; } if (options.registerWhenExtend) { var originalExtend = entity.extend; if (originalExtend) { entity.extend = function (proto) { var ExtendedClass = originalExtend.call(this, proto); return entity.registerClass(ExtendedClass, proto.type); }; } } return entity; } /** * @param {string|Array.<string>} properties */ function setReadOnly(obj, properties) {// FIXME It seems broken in IE8 simulation of IE11 // if (!zrUtil.isArray(properties)) { // properties = properties != null ? [properties] : []; // } // zrUtil.each(properties, function (prop) { // var value = obj[prop]; // Object.defineProperty // && Object.defineProperty(obj, prop, { // value: value, writable: false // }); // zrUtil.isArray(obj[prop]) // && Object.freeze // && Object.freeze(obj[prop]); // }); } exports.parseClassType = parseClassType; exports.enableClassExtend = enableClassExtend; exports.enableClassCheck = enableClassCheck; exports.enableClassManagement = enableClassManagement; exports.setReadOnly = setReadOnly; /***/ }, /* 12 */ /*!*************************************************!*\ !*** ./~/echarts/lib/data/helper/sourceType.js ***! \*************************************************/ /***/ function(module, exports) { /* * 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. */ // Avoid typo. var SOURCE_FORMAT_ORIGINAL = 'original'; var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows'; var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows'; var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns'; var SOURCE_FORMAT_UNKNOWN = 'unknown'; // ??? CHANGE A NAME var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray'; var SERIES_LAYOUT_BY_COLUMN = 'column'; var SERIES_LAYOUT_BY_ROW = 'row'; exports.SOURCE_FORMAT_ORIGINAL = SOURCE_FORMAT_ORIGINAL; exports.SOURCE_FORMAT_ARRAY_ROWS = SOURCE_FORMAT_ARRAY_ROWS; exports.SOURCE_FORMAT_OBJECT_ROWS = SOURCE_FORMAT_OBJECT_ROWS; exports.SOURCE_FORMAT_KEYED_COLUMNS = SOURCE_FORMAT_KEYED_COLUMNS; exports.SOURCE_FORMAT_UNKNOWN = SOURCE_FORMAT_UNKNOWN; exports.SOURCE_FORMAT_TYPED_ARRAY = SOURCE_FORMAT_TYPED_ARRAY; exports.SERIES_LAYOUT_BY_COLUMN = SERIES_LAYOUT_BY_COLUMN; exports.SERIES_LAYOUT_BY_ROW = SERIES_LAYOUT_BY_ROW; /***/ }, /* 13 */ /*!******************************************************!*\ !*** ./~/echarts/lib/data/helper/dimensionHelper.js ***! \******************************************************/ /***/ function(module, exports, __webpack_require__) { var _util = __webpack_require__(/*! zrender/lib/core/util */ 5); var each = _util.each; var createHashMap = _util.createHashMap; var assert = _util.assert; var _config = __webpack_require__(/*! ../../config */ 8); var __DEV__ = _config.__DEV__; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var OTHER_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'seriesName']); function summarizeDimensions(data) { var summary = {}; var encode = summary.encode = {}; var notExtraCoordDimMap = createHashMap(); var defaultedLabel = []; var defaultedTooltip = []; each(data.dimensions, function (dimName) { var dimItem = data.getDimensionInfo(dimName); var coordDim = dimItem.coordDim; if (coordDim) { var coordDimArr = encode[coordDim]; if (!encode.hasOwnProperty(coordDim)) { coordDimArr = encode[coordDim] = []; } coordDimArr[dimItem.coordDimIndex] = dimName; if (!dimItem.isExtraCoord) { notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label, // because when dataset is used, it is hard to guess which dimension // can be value dimension. If both show x, y on label is not look good, // and conventionally y axis is focused more. if (mayLabelDimType(dimItem.type)) { defaultedLabel[0] = dimName; } } if (dimItem.defaultTooltip) { defaultedTooltip.push(dimName); } } OTHER_DIMENSIONS.each(function (v, otherDim) { var otherDimArr = encode[otherDim]; if (!encode.hasOwnProperty(otherDim)) { otherDimArr = encode[otherDim] = []; } var dimIndex = dimItem.otherDims[otherDim]; if (dimIndex != null && dimIndex !== false) { otherDimArr[dimIndex] = dimItem.name; } }); }); var dataDimsOnCoord = []; var encodeFirstDimNotExtra = {}; notExtraCoordDimMap.each(function (v, coordDim) { var dimArr = encode[coordDim]; // ??? FIXME extra coord should not be set in dataDimsOnCoord. // But should fix the case that radar axes: simplify the logic // of `completeDimension`, remove `extraPrefix`. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data // dim canot on more than one coordDim. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr); }); summary.dataDimsOnCoord = dataDimsOnCoord; summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra; var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set // in this way. Use label.formatter instead. May be remove this approach someday. if (encodeLabel && encodeLabel.length) { defaultedLabel = encodeLabel.slice(); } var encodeTooltip = encode.tooltip; if (encodeTooltip && encodeTooltip.length) { defaultedTooltip = encodeTooltip.slice(); } else if (!defaultedTooltip.length) { defaultedTooltip = defaultedLabel.slice(); } encode.defaultedLabel = defaultedLabel; encode.defaultedTooltip = defaultedTooltip; return summary; } function getDimensionTypeByAxis(axisType) { return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float'; } function mayLabelDimType(dimType) { // In most cases, ordinal and time do not suitable for label. // Ordinal info can be displayed on axis. Time is too long. return !(dimType === 'ordinal' || dimType === 'time'); } // function findTheLastDimMayLabel(data) { // // Get last value dim // var dimensions = data.dimensions.slice(); // var valueType; // var valueDim; // while (dimensions.length && ( // valueDim = dimensions.pop(), // valueType = data.getDimensionInfo(valueDim).type, // valueType === 'ordinal' || valueType === 'time' // )) {} // jshint ignore:line // return valueDim; // } exports.OTHER_DIMENSIONS = OTHER_DIMENSIONS; exports.summarizeDimensions = summarizeDimensions; exports.getDimensionTypeByAxis = getDimensionTypeByAxis; /***/ }, /* 14 */ /*!*******************************!*\ !*** ./src/liquidFillView.js ***! \*******************************/ /***/ function(module, exports, __webpack_require__) { var echarts = __webpack_require__(/*! echarts/lib/echarts */ 2); var numberUtil = echarts.number; var symbolUtil = __webpack_require__(/*! echarts/lib/util/symbol */ 15); var parsePercent = numberUtil.parsePercent; var LiquidLayout = __webpack_require__(/*! ./liquidFillLayout */ 76); function getShallow(model, path) { return model && model.getShallow(path); } echarts.extendChartView({ type: 'liquidFill', render: function (seriesModel, ecModel, api) { var group = this.group; group.removeAll(); var data = seriesModel.getData(); var itemModel = data.getItemModel(0); var center = itemModel.get('center'); var radius = itemModel.get('radius'); var width = api.getWidth(); var height = api.getHeight(); var size = Math.min(width, height); // itemStyle var outlineDistance = 0; var outlineBorderWidth = 0; var showOutline = seriesModel.get('outline.show'); if (showOutline) { outlineDistance = seriesModel.get('outline.borderDistance'); outlineBorderWidth = parsePercent( seriesModel.get('outline.itemStyle.borderWidth'), size ); } var cx = parsePercent(center[0], width); var cy = parsePercent(center[1], height); var outterRadius; var innerRadius; var paddingRadius; var isFillContainer = false; var symbol = seriesModel.get('shape'); if (symbol === 'container') { // a shape that fully fills the container isFillContainer = true; outterRadius = [ width / 2, height / 2 ]; innerRadius = [ outterRadius[0] - outlineBorderWidth / 2, outterRadius[1] - outlineBorderWidth / 2 ]; paddingRadius = [ parsePercent(outlineDistance, width), parsePercent(outlineDistance, height) ]; radius = [ innerRadius[0] - paddingRadius[0], innerRadius[1] - paddingRadius[1] ]; } else { outterRadius = parsePercent(radius, size) / 2; innerRadius = outterRadius - outlineBorderWidth / 2; paddingRadius = parsePercent(outlineDistance, size); radius = innerRadius - paddingRadius; } if (showOutline) { var outline = getOutline(); outline.style.lineWidth = outlineBorderWidth; group.add(getOutline()); } var left = isFillContainer ? 0 : cx - radius; var top = isFillContainer ? 0 : cy - radius; var wavePath = null; group.add(getBackground()); // each data item for a wave var oldData = this._data; var waves = []; data.diff(oldData) .add(function (idx) { var wave = getWave(idx, false); var waterLevel = wave.shape.waterLevel; wave.shape.waterLevel = isFillContainer ? radius[1] : radius; echarts.graphic.initProps(wave, { shape: { waterLevel: waterLevel } }, seriesModel); wave.z2 = 2; setWaveAnimation(idx, wave, null); group.add(wave); data.setItemGraphicEl(idx, wave); waves.push(wave); }) .update(function (newIdx, oldIdx) { var waveElement = oldData.getItemGraphicEl(oldIdx); // new wave is used to calculate position, but not added var newWave = getWave(newIdx, false, waveElement); // changes with animation var shape = {}; var shapeAttrs = ['amplitude', 'cx', 'cy', 'phase', 'radius', 'waterLevel', 'waveLength']; for (var i = 0; i < shapeAttrs.length; ++i) { var attr = shapeAttrs[i]; if (newWave.shape.hasOwnProperty(attr)) { shape[attr] = newWave.shape[attr]; } } var style = {}; var styleAttrs = ['fill', 'opacity', 'shadowBlur', 'shadowColor']; for (var i = 0; i < styleAttrs.length; ++i) { var attr = shapeAttrs[i]; if (newWave.style.hasOwnProperty(attr)) { style[attr] = newWave.style[attr]; } } // changes with animation echarts.graphic.updateProps(waveElement, { shape: shape, style: style }, seriesModel); // instant changes waveElement.position = newWave.position; waveElement.setClipPath(newWave.clipPath); waveElement.shape.inverse = newWave.inverse; setWaveAnimation(newIdx, waveElement, waveElement); group.add(waveElement); data.setItemGraphicEl(newIdx, waveElement); waves.push(waveElement); }) .remove(function (idx) { var wave = oldData.getItemGraphicEl(idx); group.remove(wave); }) .execute(); if (itemModel.get('label.show')) { group.add(getText(waves)); } this._data = data; /** * Get path for outline, background and clipping * * @param {number} r outter radius of shape * @param {boolean|undefined} isForClipping if the shape is used * for clipping */ function getPath(r, isForClipping) { if (symbol) { // customed symbol path if (symbol.indexOf('path://') === 0) { var path = echarts.graphic.makePath(symbol.slice(7), {}); var bouding = path.getBoundingRect(); var w = bouding.width; var h = bouding.height; if (w > h) { h = r * 2 / w * h; w = r * 2; } else { w = r * 2 / h * w; h = r * 2; } var left = isForClipping ? 0 : cx - w / 2; var top = isForClipping ? 0 : cy - h / 2; path = echarts.graphic.makePath( symbol.slice(7), {}, new echarts.graphic.BoundingRect(left, top, w, h) ); if (isForClipping) { path.position = [-w / 2, -h / 2]; } return path; } else if (isFillContainer) { // fully fill the container var x = isForClipping ? -r[0] : cx - r[0]; var y = isForClipping ? -r[1] : cy - r[1]; return symbolUtil.createSymbol( 'rect', x, y, r[0] * 2, r[1] * 2 ); } else { var x = isForClipping ? -r : cx - r; var y = isForClipping ? -r : cy - r; if (symbol === 'pin') { y += r; } else if (symbol === 'arrow') { y -= r; } return symbolUtil.createSymbol(symbol, x, y, r * 2, r * 2); } } return new echarts.graphic.Circle({ shape: { cx: isForClipping ? 0 : cx, cy: isForClipping ? 0 : cy, r: r } }); } /** * Create outline */ function getOutline() { var outlinePath = getPath(outterRadius); outlinePath.style.fill = null; outlinePath.setStyle(seriesModel.getModel('outline.itemStyle') .getItemStyle()); return outlinePath; } /** * Create background */ function getBackground() { // Seperate stroke and fill, so we can use stroke to cover the alias of clipping. var strokePath = getPath(radius); strokePath.setStyle(seriesModel.getModel('backgroundStyle') .getItemStyle()); strokePath.style.fill = null; // Stroke is front of wave strokePath.z2 = 5; var fillPath = getPath(radius); fillPath.setStyle(seriesModel.getModel('backgroundStyle') .getItemStyle()); fillPath.style.stroke = null; var group = new echarts.graphic.Group(); group.add(strokePath); group.add(fillPath); return group; } /** * wave shape */ function getWave(idx, isInverse, oldWave) { var radiusX = isFillContainer ? radius[0] : radius; var radiusY = isFillContainer ? radius[1] : radius; var itemModel = data.getItemModel(idx); var itemStyleModel = itemModel.getModel('itemStyle'); var phase = itemModel.get('phase'); var amplitude = parsePercent(itemModel.get('amplitude'), radiusY * 2); var waveLength = parsePercent(itemModel.get('waveLength'), radiusX * 2); var value = data.get('value', idx); var waterLevel = radiusY - value * radiusY * 2; phase = oldWave ? oldWave.shape.phase : (phase === 'auto' ? idx * Math.PI / 4 : phase); var normalStyle = itemStyleModel.getItemStyle(); if (!normalStyle.fill) { var seriesColor = seriesModel.get('color'); var id = idx % seriesColor.length; normalStyle.fill = seriesColor[id]; } var x = radiusX * 2; var wave = new LiquidLayout({ shape: { waveLength: waveLength, radius: radiusX, cx: x, cy: 0, waterLevel: waterLevel, amplitude: amplitude, phase: phase, inverse: isInverse }, style: normalStyle, position: [cx, cy] }); wave.shape._waterLevel = waterLevel; var hoverStyle = itemModel.getModel('emphasis.itemStyle') .getItemStyle(); hoverStyle.lineWidth = 0; echarts.graphic.setHoverStyle(wave, hoverStyle); // clip out the part outside the circle var clip = getPath(radius, true); // set fill for clipPath, otherwise it will not trigger hover event clip.setStyle({ fill: 'white' }); wave.setClipPath(clip); return wave; } function setWaveAnimation(idx, wave, oldWave) { var itemModel = data.getItemModel(idx); var maxSpeed = itemModel.get('period'); var direction = itemModel.get('direction'); var value = data.get('value', idx); var phase = itemModel.get('phase'); phase = oldWave ? oldWave.shape.phase : (phase === 'auto' ? idx * Math.PI / 4 : phase); var defaultSpeed = function (maxSpeed) { var cnt = data.count(); return cnt === 0 ? maxSpeed : maxSpeed * (0.2 + (cnt - idx) / cnt * 0.8); }; var speed = 0; if (maxSpeed === 'auto') { speed = defaultSpeed(5000); } else { speed = typeof maxSpeed === 'function' ? maxSpeed(value, idx) : maxSpeed; } // phase for moving left/right var phaseOffset = 0; if (direction === 'right' || direction == null) { phaseOffset = Math.PI; } else if (direction === 'left') { phaseOffset = -Math.PI; } else if (direction === 'none') { phaseOffset = 0; } else { console.error('Illegal direction value for liquid fill.'); } // wave animation of moving left/right if (direction !== 'none' && itemModel.get('waveAnimation')) { wave .animate('shape', true) .when(0, { phase: phase }) .when(speed / 2, { phase: phaseOffset + phase }) .when(speed, { phase: phaseOffset * 2 + phase }) .during(function () { if (wavePath) { wavePath.dirty(true); } }) .start(); } } /** * text on wave */ function getText(waves) { var labelModel = itemModel.getModel('label'); function formatLabel() { var formatted = seriesModel.getFormattedLabel(0, 'normal'); var defaultVal = (data.get('value', 0) * 100); var defaultLabel = data.getName(0) || seriesModel.name; if (!isNaN(defaultVal)) { defaultLabel = defaultVal.toFixed(0) + '%'; } return formatted == null ? defaultLabel : formatted; } var textOption = { z2: 10, shape: { x: left, y: top, width: (isFillContainer ? radius[0] : radius) * 2, height: (isFillContainer ? radius[1] : radius) * 2 }, style: { fill: 'transparent', text: formatLabel(), textAlign: labelModel.get('align'), textVerticalAlign: labelModel.get('baseline') }, silent: true }; var outsideTextRect = new echarts.graphic.Rect(textOption); var color = labelModel.get('color'); echarts.graphic.setText(outsideTextRect.style, labelModel, color); var insideTextRect = new echarts.graphic.Rect(textOption); var insColor = labelModel.get('insideColor'); echarts.graphic.setText(insideTextRect.style, labelModel, insColor); insideTextRect.style.textFill = insColor; var group = new echarts.graphic.Group(); group.add(outsideTextRect); group.add(insideTextRect); // clip out waves for insideText var boundingCircle = getPath(radius, true); wavePath = new echarts.graphic.CompoundPath({ shape: { paths: waves }, position: [cx, cy] }); wavePath.setClipPath(boundingCircle); insideTextRect.setClipPath(wavePath); return group; } }, dispose: function () { // dispose nothing here } }); /***/ }, /* 15 */ /*!**************************************!*\ !*** ./~/echarts/lib/util/symbol.js ***! \**************************************/ /***/ function(module, exports, __webpack_require__) { var zrUtil = __webpack_require__(/*! zrender/lib/core/util */ 5); var graphic = __webpack_require__(/*! ./graphic */ 16); var BoundingRect = __webpack_require__(/*! zrender/lib/core/BoundingRect */ 39); /* * 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. */ // Symbol factory /** * Triangle shape * @inner */ var Triangle = graphic.extendShape({ type: 'triangle', shape: { cx: 0, cy: 0, width: 0, height: 0 }, buildPath: function (path, shape) { var cx = shape.cx; var cy = shape.cy; var width = shape.width / 2; var height = shape.height / 2; path.moveTo(cx, cy - height); path.lineTo(cx + width, cy + height); path.lineTo(cx - width, cy + height); path.closePath(); } }); /** * Diamond shape * @inner */ var Diamond = graphic.extendShape({ type: 'diamond', shape: { cx: 0, cy: 0, width: 0, height: 0 }, buildPath: function (path, shape) { var cx = shape.cx; var cy = shape.cy; var width = shape.width / 2; var height = shape.height / 2; path.moveTo(cx, cy - height); path.lineTo(cx + width, cy); path.lineTo(cx, cy + height); path.lineTo(cx - width, cy); path.closePath(); } }); /** * Pin shape * @inner */ var Pin = graphic.extendShape({ type: 'pin', shape: { // x, y on the cusp x: 0, y: 0, width: 0, height: 0 }, buildPath: function (path, shape) { var x = shape.x; var y = shape.y; var w = shape.width / 5 * 3; // Height must be larger than width var h = Math.max(w, shape.height); var r = w / 2; // Dist on y with tangent point and circle center var dy = r * r / (h - r); var cy = y - h + r + dy; var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center var dx = Math.cos(angle) * r; var tanX = Math.sin(angle); var tanY = Math.cos(angle); var cpLen = r * 0.6; var cpLen2 = r * 0.7; path.moveTo(x - dx, cy + dy); path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle); path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y); path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy); path.closePath(); } }); /** * Arrow shape * @inner */ var Arrow = graphic.extendShape({ type: 'arrow', shape: { x: 0, y: 0, width: 0, height: 0 }, buildPath: function (ctx, shape) { var height = shape.height; var width = shape.width; var x = shape.x; var y = shape.y; var dx = width / 3 * 2; ctx.moveTo(x, y); ctx.lineTo(x + dx, y + height); ctx.lineTo(x, y + height / 4 * 3); ctx.lineTo(x - dx, y + height); ctx.lineTo(x, y); ctx.closePath(); } }); /** * Map of path contructors * @type {Object.<string, module:zrender/graphic/Path>} */ var symbolCtors = { line: graphic.Line, rect: graphic.Rect, roundRect: graphic.Rect, square: graphic.Rect, circle: graphic.Circle, diamond: Diamond, pin: Pin, arrow: Arrow, triangle: Triangle }; var symbolShapeMakers = { line: function (x, y, w, h, shape) { // FIXME shape.x1 = x; shape.y1 = y + h / 2; shape.x2 = x + w; shape.y2 = y + h / 2; }, rect: function (x, y, w, h, shape) { shape.x = x; shape.y = y; shape.width = w; shape.height = h; }, roundRect: function (x, y, w, h, shape) { shape.x = x; shape.y = y; shape.width = w; shape.height = h; shape.r = Math.min(w, h) / 4; }, square: function (x, y, w, h, shape) { var size = Math.min(w, h); shape.x = x; shape.y = y; shape.width = size; shape.height = size; }, circle: function (x, y, w, h, shape) { // Put circle in the center of square shape.cx = x + w / 2; shape.cy = y + h / 2; shape.r = Math.min(w, h) / 2; }, diamond: function (x, y, w, h, shape) { shape.cx = x + w / 2; shape.cy = y + h / 2; shape.width = w; shape.height = h; }, pin: function (x, y, w, h, shape) { shape.x = x + w / 2; shape.y = y + h / 2; shape.width = w; shape.height = h; }, arrow: function (x, y, w, h, shape) { shape.x = x + w / 2; shape.y = y + h / 2; shape.width = w; shape.height = h; }, triangle: function (x, y, w, h, shape) { shape.cx = x + w / 2; shape.cy = y + h / 2; shape.width = w; shape.height = h; } }; var symbolBuildProxies = {}; zrUtil.each(symbolCtors, function (Ctor, name) { symbolBuildProxies[name] = new Ctor(); }); var SymbolClz = graphic.extendShape({ type: 'symbol', shape: { symbolType: '', x: 0, y: 0, width: 0, height: 0 }, beforeBrush: function () { var style = this.style; var shape = this.shape; // FIXME if (shape.symbolType === 'pin' && style.textPosition === 'inside') { style.textPosition = ['50%', '40%']; style.textAlign = 'center'; style.textVerticalAlign = 'middle'; } }, buildPath: function (ctx, shape, inBundle) { var symbolType = shape.symbolType; var proxySymbol = symbolBuildProxies[symbolType]; if (shape.symbolType !== 'none') { if (!proxySymbol) { // Default rect symbolType = 'rect'; proxySymbol = symbolBuildProxies[symbolType]; } symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape); proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle); } } }); // Provide setColor helper method to avoid determine if set the fill or stroke outside function symbolPathSetColor(color, innerColor) { if (this.type !== 'image') { var symbolStyle = this.style; var symbolShape = this.shape; if (symbolShape && symbolShape.symbolType === 'line') { symbolStyle.stroke = color; } else if (this.__isEmptyBrush) { symbolStyle.stroke = color; symbolStyle.fill = innerColor || '#fff'; } else { // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ? symbolStyle.fill && (symbolStyle.fill = color); symbolStyle.stroke && (symbolStyle.stroke = color); } this.dirty(false); } } /** * Create a symbol element with given symbol configuration: shape, x, y, width, height, color * @param {string} symbolType * @param {number} x * @param {number} y * @param {number} w * @param {number} h * @param {string} color * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h, * for path and image only. */ function createSymbol(symbolType, x, y, w, h, color, keepAspect) { // TODO Support image object, DynamicImage. var isEmpty = symbolType.indexOf('empty') === 0; if (isEmpty) { symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6); } var symbolPath; if (symbolType.indexOf('image://') === 0) { symbolPath = graphic.makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover'); } else if (symbolType.indexOf('path://') === 0) { symbolPath = graphic.makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover'); } else { symbolPath = new SymbolClz({ shape: { symbolType: symbolType, x: x, y: y, width: w, height: h } }); } symbolPath.__isEmptyBrush = isEmpty; symbolPath.setColor = symbolPathSetColor; symbolPath.setColor(color); return symbolPath; } exports.createSymbol = createSymbol; /***/ }, /* 16 */ /*!***************************************!*\ !*** ./~/echarts/lib/util/graphic.js ***! \***************************************/ /***/ function(module, exports, __webpack_require__) { var zrUtil = __webpack_require__(/*! zrender/lib/core/util */ 5); var pathTool = __webpack_require__(/*! zrender/lib/tool/path */ 17); var colorTool = __webpack_require__(/*! zrender/lib/tool/color */ 32); var matrix = __webpack_require__(/*! zrender/lib/core/matrix */ 26); var vector = __webpack_require__(/*! zrender/lib/core/vector */ 27); var Path = __webpack_require__(/*! zrender/lib/graphic/Path */ 18); var Transformable = __webpack_require__(/*! zrender/lib/mixin/Transformable */ 25); var ZImage = __webpack_require__(/*! zrender/lib/graphic/Image */ 54); exports.Image = ZImage; var Group = __webpack_require__(/*! zrender/lib/container/Group */ 55); exports.Group = Group; var Text = __webpack_require__(/*! zrender/lib/graphic/Text */ 56); exports.Text = Text; var Circle = __webpack_require__(/*! zrender/lib/graphic/shape/Circle */ 57); exports.Circle = Circle; var Sector = __webpack_require__(/*! zrender/lib/graphic/shape/Sector */ 58); exports.Sector = Sector; var Ring = __webpack_require__(/*! zrender/lib/graphic/shape/Ring */ 61); exports.Ring = Ring; var Polygon = __webpack_require__(/*! zrender/lib/graphic/shape/Polygon */ 62); exports.Polygon = Polygon; var Polyline = __webpack_require__(/*! zrender/lib/graphic/shape/Polyline */ 66); exports.Polyline = Polyline; var Rect = __webpack_require__(/*! zrender/lib/graphic/shape/Rect */ 67); exports.Rect = Rect; var Line = __webpack_require__(/*! zrender/lib/graphic/shape/Line */ 68); exports.Line = Line; var BezierCurve = __webpack_require__(/*! zrender/lib/graphic/shape/BezierCurve */ 69); exports.BezierCurve = BezierCurve; var Arc = __webpack_require__(/*! zrender/lib/graphic/shape/Arc */ 70); exports.Arc = Arc; var CompoundPath = __webpack_require__(/*! zrender/lib/graphic/CompoundPath */ 71); exports.CompoundPath = CompoundPath; var LinearGradient = __webpack_require__(/*! zrender/lib/graphic/LinearGradient */ 72); exports.LinearGradient = LinearGradient; var RadialGradient = __webpack_require__(/*! zrender/lib/graphic/RadialGradient */ 74); exports.RadialGradient = RadialGradient; var BoundingRect = __webpack_require__(/*! zrender/lib/core/BoundingRect */ 39); exports.BoundingRect = BoundingRect; var IncrementalDisplayable = __webpack_require__(/*! zrender/lib/graphic/IncrementalDisplayable */ 75); exports.IncrementalDisplayable = IncrementalDisplayable; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var round = Math.round; var mathMax = Math.max; var mathMin = Math.min; var EMPTY_OBJ = {}; /** * Extend shape with parameters */ function extendShape(opts) { return Path.extend(opts); } /** * Extend path */ function extendPath(pathData, opts) { return pathTool.extendFromString(pathData, opts); } /** * Create a path element from path data string * @param {string} pathData * @param {Object} opts * @param {module:zrender/core/BoundingRect} rect * @param {string} [layout=cover] 'center' or 'cover' */ function makePath(pathData, opts, rect, layout) { var path = pathTool.createFromString(pathData, opts); var boundingRect = path.getBoundingRect(); if (rect) { if (layout === 'center') { rect = centerGraphic(rect, boundingRect); } resizePath(path, rect); } return path; } /** * Create a image element from image url * @param {string} imageUrl image url * @param {Object} opts options * @param {module:zrender/core/BoundingRect} rect constrain rect * @param {string} [layout=cover] 'center' or 'cover' */ function makeImage(imageUrl, rect, layout) { var path = new ZImage({ style: { image: imageUrl, x: rect.x, y: rect.y, width: rect.width, height: rect.height }, onload: function (img) { if (layout === 'center') { var boundingRect = { width: img.width, height: img.height }; path.setStyle(centerGraphic(rect, boundingRect)); } } }); return path; } /** * Get position of centered element in bounding box. * * @param {Object} rect element local bounding box * @param {Object} boundingRect constraint bounding box * @return {Object} element position containing x, y, width, and height */ function centerGraphic(rect, boundingRect) { // Set rect to center, keep width / height ratio. var aspect = boundingRect.width / boundingRect.height; var width = rect.height * aspect; var height; if (width <= rect.width) { height = rect.height; } else { width = rect.width; height = width / aspect; } var cx = rect.x + rect.width / 2; var cy = rect.y + rect.height / 2; return { x: cx - width / 2, y: cy - height / 2, width: width, height: height }; } var mergePath = pathTool.mergePath; /** * Resize a path to fit the rect * @param {module:zrender/graphic/Path} path * @param {Object} rect */ function resizePath(path, rect) { if (!path.applyTransform) { return; } var pathRect = path.getBoundingRect(); var m = pathRect.calculateTransform(rect); path.applyTransform(m); } /** * Sub pixel optimize line for canvas * * @param {Object} param * @param {Object} [param.shape] * @param {number} [param.shape.x1] * @param {number} [param.shape.y1] * @param {number} [param.shape.x2] * @param {number} [param.shape.y2] * @param {Object} [param.style] * @param {number} [param.style.lineWidth] * @return {Object} Modified param */ function subPixelOptimizeLine(param) { var shape = param.shape; var lineWidth = param.style.lineWidth; if (round(shape.x1 * 2) === round(shape.x2 * 2)) { shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true); } if (round(shape.y1 * 2) === round(shape.y2 * 2)) { shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true); } return param; } /** * Sub pixel optimize rect for canvas * * @param {Object} param * @param {Object} [param.shape] * @param {number} [param.shape.x] * @param {number} [param.shape.y] * @param {number} [param.shape.width] * @param {number} [param.shape.height] * @param {Object} [param.style] * @param {number} [param.style.lineWidth] * @return {Object} Modified param */ function subPixelOptimizeRect(param) { var shape = param.shape; var lineWidth = param.style.lineWidth; var originX = shape.x; var originY = shape.y; var originWidth = shape.width; var originHeight = shape.height; shape.x = subPixelOptimize(shape.x, lineWidth, true); shape.y = subPixelOptimize(shape.y, lineWidth, true); shape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x, originWidth === 0 ? 0 : 1); shape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y, originHeight === 0 ? 0 : 1); return param; } /** * Sub pixel optimize for canvas * * @param {number} position Coordinate, such as x, y * @param {number} lineWidth Should be nonnegative integer. * @param {boolean=} positiveOrNegative Default false (negative). * @return {number} Optimized position. */ function subPixelOptimize(position, lineWidth, positiveOrNegative) { // Assure that (position + lineWidth / 2) is near integer edge, // otherwise line will be fuzzy in canvas. var doubledPosition = round(position * 2); return (doubledPosition + round(lineWidth)) % 2 === 0 ? doubledPosition / 2 : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2; } function hasFillOrStroke(fillOrStroke) { return fillOrStroke != null && fillOrStroke != 'none'; } function liftColor(color) { return typeof color === 'string' ? colorTool.lift(color, -0.1) : color; } /** * @private */ function cacheElementStl(el) { if (el.__hoverStlDirty) { var stroke = el.style.stroke; var fill = el.style.fill; // Create hoverStyle on mouseover var hoverStyle = el.__hoverStl; hoverStyle.fill = hoverStyle.fill || (hasFillOrStroke(fill) ? liftColor(fill) : null); hoverStyle.stroke = hoverStyle.stroke || (hasFillOrStroke(stroke) ? liftColor(stroke) : null); var normalStyle = {}; for (var name in hoverStyle) { // See comment in `doSingleEnterHover`. if (hoverStyle[name] != null) { normalStyle[name] = el.style[name]; } } el.__normalStl = normalStyle; el.__hoverStlDirty = false; } } /** * @private */ function doSingleEnterHover(el) { if (el.__isHover) { return; } cacheElementStl(el); if (el.useHoverLayer) { el.__zr && el.__zr.addHover(el, el.__hoverStl); } else { var style = el.style; var insideRollbackOpt = style.insideRollbackOpt; // Consider case: only `position: 'top'` is set on emphasis, then text // color should be returned to `autoColor`, rather than remain '#fff'. // So we should rollback then apply again after style merging. insideRollbackOpt && rollbackInsideStyle(style); // styles can be: // { // label: { // show: false, // position: 'outside', // fontSize: 18 // }, // emphasis: { // label: { // show: true // } // } // }, // where properties of `emphasis` may not appear in `normal`. We previously use // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`. // But consider rich text and setOption in merge mode, it is impossible to cover // all properties in merge. So we use merge mode when setting style here, where // only properties that is not `null/undefined` can be set. The disadventage: // null/undefined can not be used to remove style any more in `emphasis`. style.extendFrom(el.__hoverStl); // Do not save `insideRollback`. if (insideRollbackOpt) { applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt); // textFill may be rollbacked to null. if (style.textFill == null) { style.textFill = insideRollbackOpt.autoColor; } } el.dirty(false); el.z2 += 1; } el.__isHover = true; } /** * @inner */ function doSingleLeaveHover(el) { if (!el.__isHover) { return; } var normalStl = el.__normalStl; if (el.useHoverLayer) { el.__zr && el.__zr.removeHover(el); } else { // Consider null/undefined value, should use // `setStyle` but not `extendFrom(stl, true)`. normalStl && el.setStyle(normalStl); el.z2 -= 1; } el.__isHover = false; } /** * @inner */ function doEnterHover(el) { el.type === 'group' ? el.traverse(function (child) { if (child.type !== 'group') { doSingleEnterHover(child); } }) : doSingleEnterHover(el); } function doLeaveHover(el) { el.type === 'group' ? el.traverse(function (child) { if (child.type !== 'group') { doSingleLeaveHover(child); } }) : doSingleLeaveHover(el); } /** * @inner */ function setElementHoverStl(el, hoverStl) { // If element has sepcified hoverStyle, then use it instead of given hoverStyle // Often used when item group has a label element and it's hoverStyle is different el.__hoverStl = el.hoverStyle || hoverStl || {}; el.__hoverStlDirty = true; if (el.__isHover) { cacheElementStl(el); } } /** * @inner */ function onElementMouseOver(e) { if (this.__hoverSilentOnTouch && e.zrByTouch) { return; } // Only if element is not in emphasis status !this.__isEmphasis && doEnterHover(this); } /** * @inner */ function onElementMouseOut(e) { if (this.__hoverSilentOnTouch && e.zrByTouch) { return; } // Only if element is not in emphasis status !this.__isEmphasis && doLeaveHover(this); } /** * @inner */ function enterEmphasis() { this.__isEmphasis = true; doEnterHover(this); } /** * @inner */ function leaveEmphasis() { this.__isEmphasis = false; doLeaveHover(this); } /** * Set hover style of element. * This method can be called repeatly without side-effects. * @param {module:zrender/Element} el * @param {Object} [hoverStyle] * @param {Object} [opt] * @param {boolean} [opt.hoverSilentOnTouch=false] * In touch device, mouseover event will be trigger on touchstart event * (see module:zrender/dom/HandlerProxy). By this mechanism, we can * conviniently use hoverStyle when tap on touch screen without additional * code for compatibility. * But if the chart/component has select feature, which usually also use * hoverStyle, there might be conflict between 'select-highlight' and * 'hover-highlight' especially when roam is enabled (see geo for example). * In this case, hoverSilentOnTouch should be used to disable hover-highlight * on touch device. */ function setHoverStyle(el, hoverStyle, opt) { el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch; el.type === 'group' ? el.traverse(function (child) { if (child.type !== 'group') { setElementHoverStl(child, hoverStyle); } }) : setElementHoverStl(el, hoverStyle); // Duplicated function will be auto-ignored, see Eventful.js. el.on('mouseover', onElementMouseOver).on('mouseout', onElementMouseOut); // Emphasis, normal can be triggered manually el.on('emphasis', enterEmphasis).on('normal', leaveEmphasis); } /** * @param {Object|module:zrender/graphic/Style} normalStyle * @param {Object} emphasisStyle * @param {module:echarts/model/Model} normalModel * @param {module:echarts/model/Model} emphasisModel * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props. * @param {string|Function} [opt.defaultText] * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)` * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)` * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)` * @param {Object} [normalSpecified] * @param {Object} [emphasisSpecified] */ function setLabelStyle(normalStyle, emphasisStyle, normalModel, emphasisModel, opt, normalSpecified, emphasisSpecified) { opt = opt || EMPTY_OBJ; var labelFetcher = opt.labelFetcher; var labelDataIndex = opt.labelDataIndex; var labelDimIndex = opt.labelDimIndex; // This scenario, `label.normal.show = true; label.emphasis.show = false`, // is not supported util someone requests. var showNormal = normalModel.getShallow('show'); var showEmphasis = emphasisModel.getShallow('show'); // Consider performance, only fetch label when necessary. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set, // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`. var baseText; if (showNormal || showEmphasis) { if (labelFetcher) { baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex); } if (baseText == null) { baseText = zrUtil.isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText; } } var normalStyleText = showNormal ? baseText : null; var emphasisStyleText = showEmphasis ? zrUtil.retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex) : null, baseText) : null; // Optimize: If style.text is null, text will not be drawn. if (normalStyleText != null || emphasisStyleText != null) { // Always set `textStyle` even if `normalStyle.text` is null, because default // values have to be set on `normalStyle`. // If we set default values on `emphasisStyle`, consider case: // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);` // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);` // Then the 'red' will not work on emphasis. setTextStyle(normalStyle, normalModel, normalSpecified, opt); setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true); } normalStyle.text = normalStyleText; emphasisStyle.text = emphasisStyleText; } /** * Set basic textStyle properties. * @param {Object|module:zrender/graphic/Style} textStyle * @param {module:echarts/model/Model} model * @param {Object} [specifiedTextStyle] Can be overrided by settings in model. * @param {Object} [opt] See `opt` of `setTextStyleCommon`. * @param {boolean} [isEmphasis] */ function setTextStyle(textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis) { setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis); specifiedTextStyle && zrUtil.extend(textStyle, specifiedTextStyle); textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false); return textStyle; } /** * Set text option in the style. * @deprecated * @param {Object} textStyle * @param {module:echarts/model/Model} labelModel * @param {string|boolean} defaultColor Default text color. * If set as false, it will be processed as a emphasis style. */ function setText(textStyle, labelModel, defaultColor) { var opt = { isRectText: true }; var isEmphasis; if (defaultColor === false) { isEmphasis = true; } else { // Support setting color as 'auto' to get visual color. opt.autoColor = defaultColor; } setTextStyleCommon(textStyle, labelModel, opt, isEmphasis); textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false); } /** * { * disableBox: boolean, Whether diable drawing box of block (outer most). * isRectText: boolean, * autoColor: string, specify a color when color is 'auto', * for textFill, textStroke, textBackgroundColor, and textBorderColor. * If autoColor specified, it is used as default textFill. * useInsideStyle: * `true`: Use inside style (textFill, textStroke, textStrokeWidth) * if `textFill` is not specified. * `false`: Do not use inside style. * `null/undefined`: use inside style if `isRectText` is true and * `textFill` is not specified and textPosition contains `'inside'`. * forceRich: boolean * } */ function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) { // Consider there will be abnormal when merge hover style to normal style if given default value. opt = opt || EMPTY_OBJ; if (opt.isRectText) { var textPosition = textStyleModel.getShallow('position') || (isEmphasis ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used // in bar series, and magric type should be considered. textPosition === 'outside' && (textPosition = 'top'); textStyle.textPosition = textPosition; textStyle.textOffset = textStyleModel.getShallow('offset'); var labelRotate = textStyleModel.getShallow('rotate'); labelRotate != null && (labelRotate *= Math.PI / 180); textStyle.textRotation = labelRotate; textStyle.textDistance = zrUtil.retrieve2(textStyleModel.getShallow('distance'), isEmphasis ? null : 5); } var ecModel = textStyleModel.ecModel; var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case: // { // data: [{ // value: 12, // label: { // rich: { // // no 'a' here but using parent 'a'. // } // } // }], // rich: { // a: { ... } // } // } var richItemNames = getRichItemNames(textStyleModel); var richResult; if (richItemNames) { richResult = {}; for (var name in richItemNames) { if (richItemNames.hasOwnProperty(name)) { // Cascade is supported in rich. var richTextStyle = textStyleModel.getModel(['rich', name]); // In rich, never `disableBox`. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis); } } } textStyle.rich = richResult; setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true); if (opt.forceRich && !opt.textStyle) { opt.textStyle = {}; } return textStyle; } // Consider case: // { // data: [{ // value: 12, // label: { // rich: { // // no 'a' here but using parent 'a'. // } // } // }], // rich: { // a: { ... } // } // } function getRichItemNames(textStyleModel) { // Use object to remove duplicated names. var richItemNameMap; while (textStyleModel && textStyleModel !== textStyleModel.ecModel) { var rich = (textStyleModel.option || EMPTY_OBJ).rich; if (rich) { richItemNameMap = richItemNameMap || {}; for (var name in rich) { if (rich.hasOwnProperty(name)) { richItemNameMap[name] = 1; } } } textStyleModel = textStyleModel.parentModel; } return richItemNameMap; } function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) { // In merge mode, default value should not be given. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ; textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt) || globalTextStyle.color; textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt) || globalTextStyle.textBorderColor; textStyle.textStrokeWidth = zrUtil.retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth); if (!isEmphasis) { if (isBlock) { // Always set `insideRollback`, for clearing previous. var originalTextPosition = textStyle.textPosition; textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt); // Save original textPosition, because style.textPosition will be repalced by // real location (like [10, 30]) in zrender. textStyle.insideOriginalTextPosition = originalTextPosition; textStyle.insideRollbackOpt = opt; } // Set default finally. if (textStyle.textFill == null) { textStyle.textFill = opt.autoColor; } } // Do not use `getFont` here, because merge should be supported, where // part of these properties may be changed in emphasis style, and the // others should remain their original value got from normal style. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle; textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight; textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize; textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily; textStyle.textAlign = textStyleModel.getShallow('align'); textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign') || textStyleModel.getShallow('baseline'); textStyle.textLineHeight = textStyleModel.getShallow('lineHeight'); textStyle.textWidth = textStyleModel.getShallow('width'); textStyle.textHeight = textStyleModel.getShallow('height'); textStyle.textTag = textStyleModel.getShallow('tag'); if (!isBlock || !opt.disableBox) { textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt); textStyle.textPadding = textStyleModel.getShallow('padding'); textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt); textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth'); textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius'); textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor'); textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur'); textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX'); textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY'); } textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor') || globalTextStyle.textShadowColor; textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur') || globalTextStyle.textShadowBlur; textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX') || globalTextStyle.textShadowOffsetX; textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY') || globalTextStyle.textShadowOffsetY; } function getAutoColor(color, opt) { return color !== 'auto' ? color : opt && opt.autoColor ? opt.autoColor : null; } function applyInsideStyle(textStyle, textPosition, opt) { var useInsideStyle = opt.useInsideStyle; var insideRollback; if (textStyle.textFill == null && useInsideStyle !== false && (useInsideStyle === true || opt.isRectText && textPosition // textPosition can be [10, 30] && typeof textPosition === 'string' && textPosition.indexOf('inside') >= 0)) { insideRollback = { textFill: null, textStroke: textStyle.textStroke, textStrokeWidth: textStyle.textStrokeWidth }; textStyle.textFill = '#fff'; // Consider text with #fff overflow its container. if (textStyle.textStroke == null) { textStyle.textStroke = opt.autoColor; textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2); } } return insideRollback; } function rollbackInsideStyle(style) { var insideRollback = style.insideRollback; if (insideRollback) { style.textFill = insideRollback.textFill; style.textStroke = insideRollback.textStroke; style.textStrokeWidth = insideRollback.textStrokeWidth; } } function getFont(opt, ecModel) { // ecModel or default text style model. var gTextStyleModel = ecModel || ecModel.getModel('textStyle'); return zrUtil.trim([// FIXME in node-canvas fontWeight is before fontStyle opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '', opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '', (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px', opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'].join(' ')); } function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) { if (typeof dataIndex === 'function') { cb = dataIndex; dataIndex = null; } // Do not check 'animation' property directly here. Consider this case: // animation model is an `itemModel`, whose does not have `isAnimationEnabled` // but its parent model (`seriesModel`) does. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled(); if (animationEnabled) { var postfix = isUpdate ? 'Update' : ''; var duration = animatableModel.getShallow('animationDuration' + postfix); var animationEasing = animatableModel.getShallow('animationEasing' + postfix); var animationDelay = animatableModel.getShallow('animationDelay' + postfix); if (typeof animationDelay === 'function') { animationDelay = animationDelay(dataIndex, animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null); } if (typeof duration === 'function') { duration = duration(dataIndex); } duration > 0 ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb) : (el.stopAnimation(), el.attr(props), cb && cb()); } else { el.stopAnimation(); el.attr(props); cb && cb(); } } /** * Update graphic element properties with or without animation according to the * configuration in series. * * Caution: this method will stop previous animation. * So if do not use this method to one element twice before * animation starts, unless you know what you are doing. * * @param {module:zrender/Element} el * @param {Object} props * @param {module:echarts/model/Model} [animatableModel] * @param {number} [dataIndex] * @param {Function} [cb] * @example * graphic.updateProps(el, { * position: [100, 100] * }, seriesModel, dataIndex, function () { console.log('Animation done!'); }); * // Or * graphic.updateProps(el, { * position: [100, 100] * }, seriesModel, function () { console.log('Animation done!'); }); */ function updateProps(el, props, animatableModel, dataIndex, cb) { animateOrSetProps(true, el, props, animatableModel, dataIndex, cb); } /** * Init graphic element properties with or without animation according to the * configuration in series. * * Caution: this method will stop previous animation. * So if do not use this method to one element twice before * animation starts, unless you know what you are doing. * * @param {module:zrender/Element} el * @param {Object} props * @param {module:echarts/model/Model} [animatableModel] * @param {number} [dataIndex] * @param {Function} cb */ function initProps(el, props, animatableModel, dataIndex, cb) { animateOrSetProps(false, el, props, animatableModel, dataIndex, cb); } /** * Get transform matrix of target (param target), * in coordinate of its ancestor (param ancestor) * * @param {module:zrender/mixin/Transformable} target * @param {module:zrender/mixin/Transformable} [ancestor] */ function getTransform(target, ancestor) { var mat = matrix.identity([]); while (target && target !== ancestor) { matrix.mul(mat, target.getLocalTransform(), mat); target = target.parent; } return mat; } /** * Apply transform to an vertex. * @param {Array.<number>} target [x, y] * @param {Array.<number>|TypedArray.<number>|Object} transform Can be: * + Transform matrix: like [1, 0, 0, 1, 0, 0] * + {position, rotation, scale}, the same as `zrender/Transformable`. * @param {boolean=} invert Whether use invert matrix. * @return {Array.<number>} [x, y] */ function applyTransform(target, transform, invert) { if (transform && !zrUtil.isArrayLike(transform)) { transform = Transformable.getLocalTransform(transform); } if (invert) { transform = matrix.invert([], transform); } return vector.applyTransform([], target, transform); } /** * @param {string} direction 'left' 'right' 'top' 'bottom' * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0] * @param {boolean=} invert Whether use invert matrix. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom' */ function transformDirection(direction, transform, invert) { // Pick a base, ensure that transform result will not be (0, 0). var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]); var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]); var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0]; vertex = applyTransform(vertex, transform, invert); return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top'; } /** * Apply group transition animation from g1 to g2. * If no animatableModel, no animation. */ function groupTransition(g1, g2, animatableModel, cb) { if (!g1 || !g2) { return; } function getElMap(g) { var elMap = {}; g.traverse(function (el) { if (!el.isGroup && el.anid) { elMap[el.anid] = el; } }); return elMap; } function getAnimatableProps(el) { var obj = { position: vector.clone(el.position), rotation: el.rotation }; if (el.shape) { obj.shape = zrUtil.extend({}, el.shape); } return obj; } var elMap1 = getElMap(g1); g2.traverse(function (el) { if (!el.isGroup && el.anid) { var oldEl = elMap1[el.anid]; if (oldEl) { var newProp = getAnimatableProps(el); el.attr(getAnimatableProps(oldEl)); updateProps(el, newProp, animatableModel, el.dataIndex); } // else { // if (el.previousProps) { // graphic.updateProps // } // } } }); } /** * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...] * @param {Object} rect {x, y, width, height} * @return {Array.<Array.<number>>} A new clipped points. */ function clipPointsByRect(points, rect) { return zrUtil.map(points, function (point) { var x = point[0]; x = mathMax(x, rect.x); x = mathMin(x, rect.x + rect.width); var y = point[1]; y = mathMax(y, rect.y); y = mathMin(y, rect.y + rect.height); return [x, y]; }); } /** * @param {Object} targetRect {x, y, width, height} * @param {Object} rect {x, y, width, height} * @return {Object} A new clipped rect. If rect size are negative, return undefined. */ function clipRectByRect(targetRect, rect) { var x = mathMax(targetRect.x, rect.x); var x2 = mathMin(targetRect.x + targetRect.width, rect.x + rect.width); var y = mathMax(targetRect.y, rect.y); var y2 = mathMin(targetRect.y + targetRect.height, rect.y + rect.height); if (x2 >= x && y2 >= y) { return { x: x, y: y, width: x2 - x, height: y2 - y }; } } /** * @param {string} iconStr Support 'image://' or 'path://' or direct svg path. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`. * @param {Object} [rect] {x, y, width, height} * @return {module:zrender/Element} Icon path or image element. */ function createIcon(iconStr, opt, rect) { opt = zrUtil.extend({ rectHover: true }, opt); var style = opt.style = { strokeNoScale: true }; rect = rect || { x: -1, y: -1, width: 2, height: 2 }; if (iconStr) { return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), zrUtil.defaults(style, rect), new ZImage(opt)) : makePath(iconStr.replace('path://', ''), opt, rect, 'center'); } } exports.extendShape = extendShape; exports.extendPath = extendPath; exports.makePath = makePath; exports.makeImage = makeImage; exports.mergePath = mergePath; exports.resizePath = resizePath; exports.subPixelOptimizeLine = subPixelOptimizeLine; exports.subPixelOptimizeRect = subPixelOptimizeRect; exports.subPixelOptimize = subPixelOptimize; exports.setHoverStyle = setHoverStyle; exports.setLabelStyle = setLabelStyle; exports.setTextStyle = setTextStyle; exports.setText = setText; exports.getFont = getFont; exports.updateProps = updateProps; exports.initProps = initProps; exports.getTransform = getTransform; exports.applyTransform = applyTransform; exports.transformDirection = transformDirection; exports.groupTransition = groupTransition; exports.clipPointsByRect = clipPointsByRect; exports.clipRectByRect = clipRectByRect; exports.createIcon = createIcon; /***/ }, /* 17 */ /*!**********************************************!*\ !*** ./~/echarts/~/zrender/lib/tool/path.js ***! \**********************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../graphic/Path */ 18); var PathProxy = __webpack_require__(/*! ../core/PathProxy */ 42); var transformPath = __webpack_require__(/*! ./transformPath */ 53); // command chars var cc = ['m', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z', 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A']; var mathSqrt = Math.sqrt; var mathSin = Math.sin; var mathCos = Math.cos; var PI = Math.PI; var vMag = function (v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); }; var vRatio = function (u, v) { return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); }; var vAngle = function (u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); }; function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) { var psi = psiDeg * (PI / 180.0); var xp = mathCos(psi) * (x1 - x2) / 2.0 + mathSin(psi) * (y1 - y2) / 2.0; var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0 + mathCos(psi) * (y1 - y2) / 2.0; var lambda = xp * xp / (rx * rx) + yp * yp / (ry * ry); if (lambda > 1) { rx *= mathSqrt(lambda); ry *= mathSqrt(lambda); } var f = (fa === fs ? -1 : 1) * mathSqrt((rx * rx * (ry * ry) - rx * rx * (yp * yp) - ry * ry * (xp * xp)) / (rx * rx * (yp * yp) + ry * ry * (xp * xp))) || 0; var cxp = f * rx * yp / ry; var cyp = f * -ry * xp / rx; var cx = (x1 + x2) / 2.0 + mathCos(psi) * cxp - mathSin(psi) * cyp; var cy = (y1 + y2) / 2.0 + mathSin(psi) * cxp + mathCos(psi) * cyp; var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]); var u = [(xp - cxp) / rx, (yp - cyp) / ry]; var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry]; var dTheta = vAngle(u, v); if (vRatio(u, v) <= -1) { dTheta = PI; } if (vRatio(u, v) >= 1) { dTheta = 0; } if (fs === 0 && dTheta > 0) { dTheta = dTheta - 2 * PI; } if (fs === 1 && dTheta < 0) { dTheta = dTheta + 2 * PI; } path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs); } function createPathProxyFromString(data) { if (!data) { return []; } // command string var cs = data.replace(/-/g, ' -').replace(/ /g, ' ').replace(/ /g, ',').replace(/,,/g, ','); var n; // create pipes so that we can split the data for (n = 0; n < cc.length; n++) { cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]); } // create array var arr = cs.split('|'); // init context point var cpx = 0; var cpy = 0; var path = new PathProxy(); var CMD = PathProxy.CMD; var prevCmd; for (n = 1; n < arr.length; n++) { var str = arr[n]; var c = str.charAt(0); var off = 0; var p = str.slice(1).replace(/e,-/g, 'e-').split(','); var cmd; if (p.length > 0 && p[0] === '') { p.shift(); } for (var i = 0; i < p.length; i++) { p[i] = parseFloat(p[i]); } while (off < p.length && !isNaN(p[off])) { if (isNaN(p[0])) { break; } var ctlPtx; var ctlPty; var rx; var ry; var psi; var fa; var fs; var x1 = cpx; var y1 = cpy; // convert l, H, h, V, and v to L switch (c) { case 'l': cpx += p[off++]; cpy += p[off++]; cmd = CMD.L; path.addData(cmd, cpx, cpy); break; case 'L': cpx = p[off++]; cpy = p[off++]; cmd = CMD.L; path.addData(cmd, cpx, cpy); break; case 'm': cpx += p[off++]; cpy += p[off++]; cmd = CMD.M; path.addData(cmd, cpx, cpy); c = 'l'; break; case 'M': cpx = p[off++]; cpy = p[off++]; cmd = CMD.M; path.addData(cmd, cpx, cpy); c = 'L'; break; case 'h': cpx += p[off++]; cmd = CMD.L; path.addData(cmd, cpx, cpy); break; case 'H': cpx = p[off++]; cmd = CMD.L; path.addData(cmd, cpx, cpy); break; case 'v': cpy += p[off++]; cmd = CMD.L; path.addData(cmd, cpx, cpy); break; case 'V': cpy = p[off++]; cmd = CMD.L; path.addData(cmd, cpx, cpy); break; case 'C': cmd = CMD.C; path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]); cpx = p[off - 2]; cpy = p[off - 1]; break; case 'c': cmd = CMD.C; path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy); cpx += p[off - 2]; cpy += p[off - 1]; break; case 'S': ctlPtx = cpx; ctlPty = cpy; var len = path.len(); var pathData = path.data; if (prevCmd === CMD.C) { ctlPtx += cpx - pathData[len - 4]; ctlPty += cpy - pathData[len - 3]; } cmd = CMD.C; x1 = p[off++]; y1 = p[off++]; cpx = p[off++]; cpy = p[off++]; path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy); break; case 's': ctlPtx = cpx; ctlPty = cpy; var len = path.len(); var pathData = path.data; if (prevCmd === CMD.C) { ctlPtx += cpx - pathData[len - 4]; ctlPty += cpy - pathData[len - 3]; } cmd = CMD.C; x1 = cpx + p[off++]; y1 = cpy + p[off++]; cpx += p[off++]; cpy += p[off++]; path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy); break; case 'Q': x1 = p[off++]; y1 = p[off++]; cpx = p[off++]; cpy = p[off++]; cmd = CMD.Q; path.addData(cmd, x1, y1, cpx, cpy); break; case 'q': x1 = p[off++] + cpx; y1 = p[off++] + cpy; cpx += p[off++]; cpy += p[off++]; cmd = CMD.Q; path.addData(cmd, x1, y1, cpx, cpy); break; case 'T': ctlPtx = cpx; ctlPty = cpy; var len = path.len(); var pathData = path.data; if (prevCmd === CMD.Q) { ctlPtx += cpx - pathData[len - 4]; ctlPty += cpy - pathData[len - 3]; } cpx = p[off++]; cpy = p[off++]; cmd = CMD.Q; path.addData(cmd, ctlPtx, ctlPty, cpx, cpy); break; case 't': ctlPtx = cpx; ctlPty = cpy; var len = path.len(); var pathData = path.data; if (prevCmd === CMD.Q) { ctlPtx += cpx - pathData[len - 4]; ctlPty += cpy - pathData[len - 3]; } cpx += p[off++]; cpy += p[off++]; cmd = CMD.Q; path.addData(cmd, ctlPtx, ctlPty, cpx, cpy); break; case 'A': rx = p[off++]; ry = p[off++]; psi = p[off++]; fa = p[off++]; fs = p[off++]; x1 = cpx, y1 = cpy; cpx = p[off++]; cpy = p[off++]; cmd = CMD.A; processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path); break; case 'a': rx = p[off++]; ry = p[off++]; psi = p[off++]; fa = p[off++]; fs = p[off++]; x1 = cpx, y1 = cpy; cpx += p[off++]; cpy += p[off++]; cmd = CMD.A; processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path); break; } } if (c === 'z' || c === 'Z') { cmd = CMD.Z; path.addData(cmd); } prevCmd = cmd; } path.toStatic(); return path; } // TODO Optimize double memory cost problem function createPathOptions(str, opts) { var pathProxy = createPathProxyFromString(str); opts = opts || {}; opts.buildPath = function (path) { if (path.setData) { path.setData(pathProxy.data); // Svg and vml renderer don't have context var ctx = path.getContext(); if (ctx) { path.rebuildPath(ctx); } } else { var ctx = path; pathProxy.rebuildPath(ctx); } }; opts.applyTransform = function (m) { transformPath(pathProxy, m); this.dirty(true); }; return opts; } /** * Create a Path object from path string data * http://www.w3.org/TR/SVG/paths.html#PathData * @param {Object} opts Other options */ function createFromString(str, opts) { return new Path(createPathOptions(str, opts)); } /** * Create a Path class from path string data * @param {string} str * @param {Object} opts Other options */ function extendFromString(str, opts) { return Path.extend(createPathOptions(str, opts)); } /** * Merge multiple paths */ // TODO Apply transform // TODO stroke dash // TODO Optimize double memory cost problem function mergePath(pathEls, opts) { var pathList = []; var len = pathEls.length; for (var i = 0; i < len; i++) { var pathEl = pathEls[i]; if (!pathEl.path) { pathEl.createPathProxy(); } if (pathEl.__dirtyPath) { pathEl.buildPath(pathEl.path, pathEl.shape, true); } pathList.push(pathEl.path); } var pathBundle = new Path(opts); // Need path proxy. pathBundle.createPathProxy(); pathBundle.buildPath = function (path) { path.appendPath(pathList); // Svg and vml renderer don't have context var ctx = path.getContext(); if (ctx) { path.rebuildPath(ctx); } }; return pathBundle; } exports.createFromString = createFromString; exports.extendFromString = extendFromString; exports.mergePath = mergePath; /***/ }, /* 18 */ /*!*************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/Path.js ***! \*************************************************/ /***/ function(module, exports, __webpack_require__) { var Displayable = __webpack_require__(/*! ./Displayable */ 19); var zrUtil = __webpack_require__(/*! ../core/util */ 5); var PathProxy = __webpack_require__(/*! ../core/PathProxy */ 42); var pathContain = __webpack_require__(/*! ../contain/path */ 45); var Pattern = __webpack_require__(/*! ./Pattern */ 52); var getCanvasPattern = Pattern.prototype.getCanvasPattern; var abs = Math.abs; var pathProxyForDraw = new PathProxy(true); /** * @alias module:zrender/graphic/Path * @extends module:zrender/graphic/Displayable * @constructor * @param {Object} opts */ function Path(opts) { Displayable.call(this, opts); /** * @type {module:zrender/core/PathProxy} * @readOnly */ this.path = null; } Path.prototype = { constructor: Path, type: 'path', __dirtyPath: true, strokeContainThreshold: 5, brush: function (ctx, prevEl) { var style = this.style; var path = this.path || pathProxyForDraw; var hasStroke = style.hasStroke(); var hasFill = style.hasFill(); var fill = style.fill; var stroke = style.stroke; var hasFillGradient = hasFill && !!fill.colorStops; var hasStrokeGradient = hasStroke && !!stroke.colorStops; var hasFillPattern = hasFill && !!fill.image; var hasStrokePattern = hasStroke && !!stroke.image; style.bind(ctx, this, prevEl); this.setTransform(ctx); if (this.__dirty) { var rect; // Update gradient because bounding rect may changed if (hasFillGradient) { rect = rect || this.getBoundingRect(); this._fillGradient = style.getGradient(ctx, fill, rect); } if (hasStrokeGradient) { rect = rect || this.getBoundingRect(); this._strokeGradient = style.getGradient(ctx, stroke, rect); } } // Use the gradient or pattern if (hasFillGradient) { // PENDING If may have affect the state ctx.fillStyle = this._fillGradient; } else if (hasFillPattern) { ctx.fillStyle = getCanvasPattern.call(fill, ctx); } if (hasStrokeGradient) { ctx.strokeStyle = this._strokeGradient; } else if (hasStrokePattern) { ctx.strokeStyle = getCanvasPattern.call(stroke, ctx); } var lineDash = style.lineDash; var lineDashOffset = style.lineDashOffset; var ctxLineDash = !!ctx.setLineDash; // Update path sx, sy var scale = this.getGlobalScale(); path.setScale(scale[0], scale[1]); // Proxy context // Rebuild path in following 2 cases // 1. Path is dirty // 2. Path needs javascript implemented lineDash stroking. // In this case, lineDash information will not be saved in PathProxy if (this.__dirtyPath || lineDash && !ctxLineDash && hasStroke) { path.beginPath(ctx); // Setting line dash before build path if (lineDash && !ctxLineDash) { path.setLineDash(lineDash); path.setLineDashOffset(lineDashOffset); } this.buildPath(path, this.shape, false); // Clear path dirty flag if (this.path) { this.__dirtyPath = false; } } else { // Replay path building ctx.beginPath(); this.path.rebuildPath(ctx); } hasFill && path.fill(ctx); if (lineDash && ctxLineDash) { ctx.setLineDash(lineDash); ctx.lineDashOffset = lineDashOffset; } hasStroke && path.stroke(ctx); if (lineDash && ctxLineDash) { // PENDING // Remove lineDash ctx.setLineDash([]); } // Draw rect text if (style.text != null) { // Only restore transform when needs draw text. this.restoreTransform(ctx); this.drawRectText(ctx, this.getBoundingRect()); } }, // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath // Like in circle buildPath: function (ctx, shapeCfg, inBundle) {}, createPathProxy: function () { this.path = new PathProxy(); }, getBoundingRect: function () { var rect = this._rect; var style = this.style; var needsUpdateRect = !rect; if (needsUpdateRect) { var path = this.path; if (!path) { // Create path on demand. path = this.path = new PathProxy(); } if (this.__dirtyPath) { path.beginPath(); this.buildPath(path, this.shape, false); } rect = path.getBoundingRect(); } this._rect = rect; if (style.hasStroke()) { // Needs update rect with stroke lineWidth when // 1. Element changes scale or lineWidth // 2. Shape is changed var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone()); if (this.__dirty || needsUpdateRect) { rectWithStroke.copy(rect); // FIXME Must after updateTransform var w = style.lineWidth; // PENDING, Min line width is needed when line is horizontal or vertical var lineScale = style.strokeNoScale ? this.getLineScale() : 1; // Only add extra hover lineWidth when there are no fill if (!style.hasFill()) { w = Math.max(w, this.strokeContainThreshold || 4); } // Consider line width // Line scale can't be 0; if (lineScale > 1e-10) { rectWithStroke.width += w / lineScale; rectWithStroke.height += w / lineScale; rectWithStroke.x -= w / lineScale / 2; rectWithStroke.y -= w / lineScale / 2; } } // Return rect with stroke return rectWithStroke; } return rect; }, contain: function (x, y) { var localPos = this.transformCoordToLocal(x, y); var rect = this.getBoundingRect(); var style = this.style; x = localPos[0]; y = localPos[1]; if (rect.contain(x, y)) { var pathData = this.path.data; if (style.hasStroke()) { var lineWidth = style.lineWidth; var lineScale = style.strokeNoScale ? this.getLineScale() : 1; // Line scale can't be 0; if (lineScale > 1e-10) { // Only add extra hover lineWidth when there are no fill if (!style.hasFill()) { lineWidth = Math.max(lineWidth, this.strokeContainThreshold); } if (pathContain.containStroke(pathData, lineWidth / lineScale, x, y)) { return true; } } } if (style.hasFill()) { return pathContain.contain(pathData, x, y); } } return false; }, /** * @param {boolean} dirtyPath */ dirty: function (dirtyPath) { if (dirtyPath == null) { dirtyPath = true; } // Only mark dirty, not mark clean if (dirtyPath) { this.__dirtyPath = dirtyPath; this._rect = null; } this.__dirty = true; this.__zr && this.__zr.refresh(); // Used as a clipping path if (this.__clipTarget) { this.__clipTarget.dirty(); } }, /** * Alias for animate('shape') * @param {boolean} loop */ animateShape: function (loop) { return this.animate('shape', loop); }, // Overwrite attrKV attrKV: function (key, value) { // FIXME if (key === 'shape') { this.setShape(value); this.__dirtyPath = true; this._rect = null; } else { Displayable.prototype.attrKV.call(this, key, value); } }, /** * @param {Object|string} key * @param {*} value */ setShape: function (key, value) { var shape = this.shape; // Path from string may not have shape if (shape) { if (zrUtil.isObject(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { shape[name] = key[name]; } } } else { shape[key] = value; } this.dirty(true); } return this; }, getLineScale: function () { var m = this.transform; // Get the line scale. // Determinant of `m` means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10 ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1])) : 1; } }; /** * 扩展一个 Path element, 比如星形,圆等。 * Extend a path element * @param {Object} props * @param {string} props.type Path type * @param {Function} props.init Initialize * @param {Function} props.buildPath Overwrite buildPath method * @param {Object} [props.style] Extended default style config * @param {Object} [props.shape] Extended default shape config */ Path.extend = function (defaults) { var Sub = function (opts) { Path.call(this, opts); if (defaults.style) { // Extend default style this.style.extendFrom(defaults.style, false); } // Extend default shape var defaultShape = defaults.shape; if (defaultShape) { this.shape = this.shape || {}; var thisShape = this.shape; for (var name in defaultShape) { if (!thisShape.hasOwnProperty(name) && defaultShape.hasOwnProperty(name)) { thisShape[name] = defaultShape[name]; } } } defaults.init && defaults.init.call(this, opts); }; zrUtil.inherits(Sub, Path); // FIXME 不能 extend position, rotation 等引用对象 for (var name in defaults) { // Extending prototype values and methods if (name !== 'style' && name !== 'shape') { Sub.prototype[name] = defaults[name]; } } return Sub; }; zrUtil.inherits(Path, Displayable); var _default = Path; module.exports = _default; /***/ }, /* 19 */ /*!********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/Displayable.js ***! \********************************************************/ /***/ function(module, exports, __webpack_require__) { var zrUtil = __webpack_require__(/*! ../core/util */ 5); var Style = __webpack_require__(/*! ./Style */ 20); var Element = __webpack_require__(/*! ../Element */ 22); var RectText = __webpack_require__(/*! ./mixin/RectText */ 36); /** * 可绘制的图形基类 * Base class of all displayable graphic objects * @module zrender/graphic/Displayable */ /** * @alias module:zrender/graphic/Displayable * @extends module:zrender/Element * @extends module:zrender/graphic/mixin/RectText */ function Displayable(opts) { opts = opts || {}; Element.call(this, opts); // Extend properties for (var name in opts) { if (opts.hasOwnProperty(name) && name !== 'style') { this[name] = opts[name]; } } /** * @type {module:zrender/graphic/Style} */ this.style = new Style(opts.style, this); this._rect = null; // Shapes for cascade clipping. this.__clipPaths = []; // FIXME Stateful must be mixined after style is setted // Stateful.call(this, opts); } Displayable.prototype = { constructor: Displayable, type: 'displayable', /** * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制 * Dirty flag. From which painter will determine if this displayable object needs brush * @name module:zrender/graphic/Displayable#__dirty * @type {boolean} */ __dirty: true, /** * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件 * If ignore drawing of the displayable object. Mouse event will still be triggered * @name module:/zrender/graphic/Displayable#invisible * @type {boolean} * @default false */ invisible: false, /** * @name module:/zrender/graphic/Displayable#z * @type {number} * @default 0 */ z: 0, /** * @name module:/zrender/graphic/Displayable#z * @type {number} * @default 0 */ z2: 0, /** * z层level,决定绘画在哪层canvas中 * @name module:/zrender/graphic/Displayable#zlevel * @type {number} * @default 0 */ zlevel: 0, /** * 是否可拖拽 * @name module:/zrender/graphic/Displayable#draggable * @type {boolean} * @default false */ draggable: false, /** * 是否正在拖拽 * @name module:/zrender/graphic/Displayable#draggable * @type {boolean} * @default false */ dragging: false, /** * 是否相应鼠标事件 * @name module:/zrender/graphic/Displayable#silent * @type {boolean} * @default false */ silent: false, /** * If enable culling * @type {boolean} * @default false */ culling: false, /** * Mouse cursor when hovered * @name module:/zrender/graphic/Displayable#cursor * @type {string} */ cursor: 'pointer', /** * If hover area is bounding rect * @name module:/zrender/graphic/Displayable#rectHover * @type {string} */ rectHover: false, /** * Render the element progressively when the value >= 0, * usefull for large data. * @type {boolean} */ progressive: false, /** * @type {boolean} */ incremental: false, // inplace is used with incremental inplace: false, beforeBrush: function (ctx) {}, afterBrush: function (ctx) {}, /** * 图形绘制方法 * @param {CanvasRenderingContext2D} ctx */ // Interface brush: function (ctx, prevEl) {}, /** * 获取最小包围盒 * @return {module:zrender/core/BoundingRect} */ // Interface getBoundingRect: function () {}, /** * 判断坐标 x, y 是否在图形上 * If displayable element contain coord x, y * @param {number} x * @param {number} y * @return {boolean} */ contain: function (x, y) { return this.rectContain(x, y); }, /** * @param {Function} cb * @param {} context */ traverse: function (cb, context) { cb.call(context, this); }, /** * 判断坐标 x, y 是否在图形的包围盒上 * If bounding rect of element contain coord x, y * @param {number} x * @param {number} y * @return {boolean} */ rectContain: function (x, y) { var coord = this.transformCoordToLocal(x, y); var rect = this.getBoundingRect(); return rect.contain(coord[0], coord[1]); }, /** * 标记图形元素为脏,并且在下一帧重绘 * Mark displayable element dirty and refresh next frame */ dirty: function () { this.__dirty = true; this._rect = null; this.__zr && this.__zr.refresh(); }, /** * 图形是否会触发事件 * If displayable object binded any event * @return {boolean} */ // TODO, 通过 bind 绑定的事件 // isSilent: function () { // return !( // this.hoverable || this.draggable // || this.onmousemove || this.onmouseover || this.onmouseout // || this.onmousedown || this.onmouseup || this.onclick // || this.ondragenter || this.ondragover || this.ondragleave // || this.ondrop // ); // }, /** * Alias for animate('style') * @param {boolean} loop */ animateStyle: function (loop) { return this.animate('style', loop); }, attrKV: function (key, value) { if (key !== 'style') { Element.prototype.attrKV.call(this, key, value); } else { this.style.set(value); } }, /** * @param {Object|string} key * @param {*} value */ setStyle: function (key, value) { this.style.set(key, value); this.dirty(false); return this; }, /** * Use given style object * @param {Object} obj */ useStyle: function (obj) { this.style = new Style(obj, this); this.dirty(false); return this; } }; zrUtil.inherits(Displayable, Element); zrUtil.mixin(Displayable, RectText); // zrUtil.mixin(Displayable, Stateful); var _default = Displayable; module.exports = _default; /***/ }, /* 20 */ /*!**************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/Style.js ***! \**************************************************/ /***/ function(module, exports, __webpack_require__) { var fixShadow = __webpack_require__(/*! ./helper/fixShadow */ 21); var STYLE_COMMON_PROPS = [['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'], ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]]; // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4); // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4); var Style = function (opts, host) { this.extendFrom(opts, false); this.host = host; }; function createLinearGradient(ctx, obj, rect) { var x = obj.x == null ? 0 : obj.x; var x2 = obj.x2 == null ? 1 : obj.x2; var y = obj.y == null ? 0 : obj.y; var y2 = obj.y2 == null ? 0 : obj.y2; if (!obj.global) { x = x * rect.width + rect.x; x2 = x2 * rect.width + rect.x; y = y * rect.height + rect.y; y2 = y2 * rect.height + rect.y; } // Fix NaN when rect is Infinity x = isNaN(x) ? 0 : x; x2 = isNaN(x2) ? 1 : x2; y = isNaN(y) ? 0 : y; y2 = isNaN(y2) ? 0 : y2; var canvasGradient = ctx.createLinearGradient(x, y, x2, y2); return canvasGradient; } function createRadialGradient(ctx, obj, rect) { var width = rect.width; var height = rect.height; var min = Math.min(width, height); var x = obj.x == null ? 0.5 : obj.x; var y = obj.y == null ? 0.5 : obj.y; var r = obj.r == null ? 0.5 : obj.r; if (!obj.global) { x = x * width + rect.x; y = y * height + rect.y; r = r * min; } var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r); return canvasGradient; } Style.prototype = { constructor: Style, /** * @type {module:zrender/graphic/Displayable} */ host: null, /** * @type {string} */ fill: '#000', /** * @type {string} */ stroke: null, /** * @type {number} */ opacity: 1, /** * @type {Array.<number>} */ lineDash: null, /** * @type {number} */ lineDashOffset: 0, /** * @type {number} */ shadowBlur: 0, /** * @type {number} */ shadowOffsetX: 0, /** * @type {number} */ shadowOffsetY: 0, /** * @type {number} */ lineWidth: 1, /** * If stroke ignore scale * @type {Boolean} */ strokeNoScale: false, // Bounding rect text configuration // Not affected by element transform /** * @type {string} */ text: null, /** * If `fontSize` or `fontFamily` exists, `font` will be reset by * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`. * So do not visit it directly in upper application (like echarts), * but use `contain/text#makeFont` instead. * @type {string} */ font: null, /** * The same as font. Use font please. * @deprecated * @type {string} */ textFont: null, /** * It helps merging respectively, rather than parsing an entire font string. * @type {string} */ fontStyle: null, /** * It helps merging respectively, rather than parsing an entire font string. * @type {string} */ fontWeight: null, /** * It helps merging respectively, rather than parsing an entire font string. * Should be 12 but not '12px'. * @type {number} */ fontSize: null, /** * It helps merging respectively, rather than parsing an entire font string. * @type {string} */ fontFamily: null, /** * Reserved for special functinality, like 'hr'. * @type {string} */ textTag: null, /** * @type {string} */ textFill: '#000', /** * @type {string} */ textStroke: null, /** * @type {number} */ textWidth: null, /** * Only for textBackground. * @type {number} */ textHeight: null, /** * textStroke may be set as some color as a default * value in upper applicaion, where the default value * of textStrokeWidth should be 0 to make sure that * user can choose to do not use text stroke. * @type {number} */ textStrokeWidth: 0, /** * @type {number} */ textLineHeight: null, /** * 'inside', 'left', 'right', 'top', 'bottom' * [x, y] * Based on x, y of rect. * @type {string|Array.<number>} * @default 'inside' */ textPosition: 'inside', /** * If not specified, use the boundingRect of a `displayable`. * @type {Object} */ textRect: null, /** * [x, y] * @type {Array.<number>} */ textOffset: null, /** * @type {string} */ textAlign: null, /** * @type {string} */ textVerticalAlign: null, /** * @type {number} */ textDistance: 5, /** * @type {string} */ textShadowColor: 'transparent', /** * @type {number} */ textShadowBlur: 0, /** * @type {number} */ textShadowOffsetX: 0, /** * @type {number} */ textShadowOffsetY: 0, /** * @type {string} */ textBoxShadowColor: 'transparent', /** * @type {number} */ textBoxShadowBlur: 0, /** * @type {number} */ textBoxShadowOffsetX: 0, /** * @type {number} */ textBoxShadowOffsetY: 0, /** * Whether transform text. * Only useful in Path and Image element * @type {boolean} */ transformText: false, /** * Text rotate around position of Path or Image * Only useful in Path and Image element and transformText is false. */ textRotation: 0, /** * Text origin of text rotation, like [10, 40]. * Based on x, y of rect. * Useful in label rotation of circular symbol. * By default, this origin is textPosition. * Can be 'center'. * @type {string|Array.<number>} */ textOrigin: null, /** * @type {string} */ textBackgroundColor: null, /** * @type {string} */ textBorderColor: null, /** * @type {number} */ textBorderWidth: 0, /** * @type {number} */ textBorderRadius: 0, /** * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]` * @type {number|Array.<number>} */ textPadding: null, /** * Text styles for rich text. * @type {Object} */ rich: null, /** * {outerWidth, outerHeight, ellipsis, placeholder} * @type {Object} */ truncate: null, /** * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation * @type {string} */ blend: null, /** * @param {CanvasRenderingContext2D} ctx */ bind: function (ctx, el, prevEl) { var style = this; var prevStyle = prevEl && prevEl.style; var firstDraw = !prevStyle; for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) { var prop = STYLE_COMMON_PROPS[i]; var styleName = prop[0]; if (firstDraw || style[styleName] !== prevStyle[styleName]) { // FIXME Invalid property value will cause style leak from previous element. ctx[styleName] = fixShadow(ctx, styleName, style[styleName] || prop[1]); } } if (firstDraw || style.fill !== prevStyle.fill) { ctx.fillStyle = style.fill; } if (firstDraw || style.stroke !== prevStyle.stroke) { ctx.strokeStyle = style.stroke; } if (firstDraw || style.opacity !== prevStyle.opacity) { ctx.globalAlpha = style.opacity == null ? 1 : style.opacity; } if (firstDraw || style.blend !== prevStyle.blend) { ctx.globalCompositeOperation = style.blend || 'source-over'; } if (this.hasStroke()) { var lineWidth = style.lineWidth; ctx.lineWidth = lineWidth / (this.strokeNoScale && el && el.getLineScale ? el.getLineScale() : 1); } }, hasFill: function () { var fill = this.fill; return fill != null && fill !== 'none'; }, hasStroke: function () { var stroke = this.stroke; return stroke != null && stroke !== 'none' && this.lineWidth > 0; }, /** * Extend from other style * @param {zrender/graphic/Style} otherStyle * @param {boolean} overwrite true: overwrirte any way. * false: overwrite only when !target.hasOwnProperty * others: overwrite when property is not null/undefined. */ extendFrom: function (otherStyle, overwrite) { if (otherStyle) { for (var name in otherStyle) { if (otherStyle.hasOwnProperty(name) && (overwrite === true || (overwrite === false ? !this.hasOwnProperty(name) : otherStyle[name] != null))) { this[name] = otherStyle[name]; } } } }, /** * Batch setting style with a given object * @param {Object|string} obj * @param {*} [obj] */ set: function (obj, value) { if (typeof obj === 'string') { this[obj] = value; } else { this.extendFrom(obj, true); } }, /** * Clone * @return {zrender/graphic/Style} [description] */ clone: function () { var newStyle = new this.constructor(); newStyle.extendFrom(this, true); return newStyle; }, getGradient: function (ctx, obj, rect) { var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient; var canvasGradient = method(ctx, obj, rect); var colorStops = obj.colorStops; for (var i = 0; i < colorStops.length; i++) { canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color); } return canvasGradient; } }; var styleProto = Style.prototype; for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) { var prop = STYLE_COMMON_PROPS[i]; if (!(prop[0] in styleProto)) { styleProto[prop[0]] = prop[1]; } } // Provide for others Style.getGradient = styleProto.getGradient; var _default = Style; module.exports = _default; /***/ }, /* 21 */ /*!*************************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/helper/fixShadow.js ***! \*************************************************************/ /***/ function(module, exports) { var SHADOW_PROPS = { 'shadowBlur': 1, 'shadowOffsetX': 1, 'shadowOffsetY': 1, 'textShadowBlur': 1, 'textShadowOffsetX': 1, 'textShadowOffsetY': 1, 'textBoxShadowBlur': 1, 'textBoxShadowOffsetX': 1, 'textBoxShadowOffsetY': 1 }; function _default(ctx, propName, value) { if (SHADOW_PROPS.hasOwnProperty(propName)) { return value *= ctx.dpr; } return value; } module.exports = _default; /***/ }, /* 22 */ /*!********************************************!*\ !*** ./~/echarts/~/zrender/lib/Element.js ***! \********************************************/ /***/ function(module, exports, __webpack_require__) { var guid = __webpack_require__(/*! ./core/guid */ 23); var Eventful = __webpack_require__(/*! ./mixin/Eventful */ 24); var Transformable = __webpack_require__(/*! ./mixin/Transformable */ 25); var Animatable = __webpack_require__(/*! ./mixin/Animatable */ 28); var zrUtil = __webpack_require__(/*! ./core/util */ 5); /** * @alias module:zrender/Element * @constructor * @extends {module:zrender/mixin/Animatable} * @extends {module:zrender/mixin/Transformable} * @extends {module:zrender/mixin/Eventful} */ var Element = function (opts) { // jshint ignore:line Transformable.call(this, opts); Eventful.call(this, opts); Animatable.call(this, opts); /** * 画布元素ID * @type {string} */ this.id = opts.id || guid(); }; Element.prototype = { /** * 元素类型 * Element type * @type {string} */ type: 'element', /** * 元素名字 * Element name * @type {string} */ name: '', /** * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值 * ZRender instance will be assigned when element is associated with zrender * @name module:/zrender/Element#__zr * @type {module:zrender/ZRender} */ __zr: null, /** * 图形是否忽略,为true时忽略图形的绘制以及事件触发 * If ignore drawing and events of the element object * @name module:/zrender/Element#ignore * @type {boolean} * @default false */ ignore: false, /** * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪 * 该路径会继承被裁减对象的变换 * @type {module:zrender/graphic/Path} * @see http://www.w3.org/TR/2dcontext/#clipping-region * @readOnly */ clipPath: null, /** * 是否是 Group * @type {boolean} */ isGroup: false, /** * Drift element * @param {number} dx dx on the global space * @param {number} dy dy on the global space */ drift: function (dx, dy) { switch (this.draggable) { case 'horizontal': dy = 0; break; case 'vertical': dx = 0; break; } var m = this.transform; if (!m) { m = this.transform = [1, 0, 0, 1, 0, 0]; } m[4] += dx; m[5] += dy; this.decomposeTransform(); this.dirty(false); }, /** * Hook before update */ beforeUpdate: function () {}, /** * Hook after update */ afterUpdate: function () {}, /** * Update each frame */ update: function () { this.updateTransform(); }, /** * @param {Function} cb * @param {} context */ traverse: function (cb, context) {}, /** * @protected */ attrKV: function (key, value) { if (key === 'position' || key === 'scale' || key === 'origin') { // Copy the array if (value) { var target = this[key]; if (!target) { target = this[key] = []; } target[0] = value[0]; target[1] = value[1]; } } else { this[key] = value; } }, /** * Hide the element */ hide: function () { this.ignore = true; this.__zr && this.__zr.refresh(); }, /** * Show the element */ show: function () { this.ignore = false; this.__zr && this.__zr.refresh(); }, /** * @param {string|Object} key * @param {*} value */ attr: function (key, value) { if (typeof key === 'string') { this.attrKV(key, value); } else if (zrUtil.isObject(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { this.attrKV(name, key[name]); } } } this.dirty(false); return this; }, /** * @param {module:zrender/graphic/Path} clipPath */ setClipPath: function (clipPath) { var zr = this.__zr; if (zr) { clipPath.addSelfToZr(zr); } // Remove previous clip path if (this.clipPath && this.clipPath !== clipPath) { this.removeClipPath(); } this.clipPath = clipPath; clipPath.__zr = zr; clipPath.__clipTarget = this; this.dirty(false); }, /** */ removeClipPath: function () { var clipPath = this.clipPath; if (clipPath) { if (clipPath.__zr) { clipPath.removeSelfFromZr(clipPath.__zr); } clipPath.__zr = null; clipPath.__clipTarget = null; this.clipPath = null; this.dirty(false); } }, /** * Add self from zrender instance. * Not recursively because it will be invoked when element added to storage. * @param {module:zrender/ZRender} zr */ addSelfToZr: function (zr) { this.__zr = zr; // 添加动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.addAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.addSelfToZr(zr); } }, /** * Remove self from zrender instance. * Not recursively because it will be invoked when element added to storage. * @param {module:zrender/ZRender} zr */ removeSelfFromZr: function (zr) { this.__zr = null; // 移除动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.removeAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.removeSelfFromZr(zr); } } }; zrUtil.mixin(Element, Animatable); zrUtil.mixin(Element, Transformable); zrUtil.mixin(Element, Eventful); var _default = Element; module.exports = _default; /***/ }, /* 23 */ /*!**********************************************!*\ !*** ./~/echarts/~/zrender/lib/core/guid.js ***! \**********************************************/ /***/ function(module, exports) { /** * zrender: 生成唯一id * * @author errorrik ([email protected]) */ var idStart = 0x0907; function _default() { return idStart++; } module.exports = _default; /***/ }, /* 24 */ /*!***************************************************!*\ !*** ./~/echarts/~/zrender/lib/mixin/Eventful.js ***! \***************************************************/ /***/ function(module, exports) { /** * 事件扩展 * @module zrender/mixin/Eventful * @author Kener (@Kener-林峰, [email protected]) * pissang (https://www.github.com/pissang) */ var arrySlice = Array.prototype.slice; /** * 事件分发器 * @alias module:zrender/mixin/Eventful * @constructor */ var Eventful = function () { this._$handlers = {}; }; Eventful.prototype = { constructor: Eventful, /** * 单次触发绑定,trigger后销毁 * * @param {string} event 事件名 * @param {Function} handler 响应函数 * @param {Object} context */ one: function (event, handler, context) { var _h = this._$handlers; if (!handler || !event) { return this; } if (!_h[event]) { _h[event] = []; } for (var i = 0; i < _h[event].length; i++) { if (_h[event][i].h === handler) { return this; } } _h[event].push({ h: handler, one: true, ctx: context || this }); return this; }, /** * 绑定事件 * @param {string} event 事件名 * @param {Function} handler 事件处理函数 * @param {Object} [context] */ on: function (event, handler, context) { var _h = this._$handlers; if (!handler || !event) { return this; } if (!_h[event]) { _h[event] = []; } for (var i = 0; i < _h[event].length; i++) { if (_h[event][i].h === handler) { return this; } } _h[event].push({ h: handler, one: false, ctx: context || this }); return this; }, /** * 是否绑定了事件 * @param {string} event * @return {boolean} */ isSilent: function (event) { var _h = this._$handlers; return _h[event] && _h[event].length; }, /** * 解绑事件 * @param {string} event 事件名 * @param {Function} [handler] 事件处理函数 */ off: function (event, handler) { var _h = this._$handlers; if (!event) { this._$handlers = {}; return this; } if (handler) { if (_h[event]) { var newList = []; for (var i = 0, l = _h[event].length; i < l; i++) { if (_h[event][i]['h'] != handler) { newList.push(_h[event][i]); } } _h[event] = newList; } if (_h[event] && _h[event].length === 0) { delete _h[event]; } } else { delete _h[event]; } return this; }, /** * 事件分发 * * @param {string} type 事件类型 */ trigger: function (type) { if (this._$handlers[type]) { var args = arguments; var argLen = args.length; if (argLen > 3) { args = arrySlice.call(args, 1); } var _h = this._$handlers[type]; var len = _h.length; for (var i = 0; i < len;) { // Optimize advise from backbone switch (argLen) { case 1: _h[i]['h'].call(_h[i]['ctx']); break; case 2: _h[i]['h'].call(_h[i]['ctx'], args[1]); break; case 3: _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]); break; default: // have more than 2 given arguments _h[i]['h'].apply(_h[i]['ctx'], args); break; } if (_h[i]['one']) { _h.splice(i, 1); len--; } else { i++; } } } return this; }, /** * 带有context的事件分发, 最后一个参数是事件回调的context * @param {string} type 事件类型 */ triggerWithContext: function (type) { if (this._$handlers[type]) { var args = arguments; var argLen = args.length; if (argLen > 4) { args = arrySlice.call(args, 1, args.length - 1); } var ctx = args[args.length - 1]; var _h = this._$handlers[type]; var len = _h.length; for (var i = 0; i < len;) { // Optimize advise from backbone switch (argLen) { case 1: _h[i]['h'].call(ctx); break; case 2: _h[i]['h'].call(ctx, args[1]); break; case 3: _h[i]['h'].call(ctx, args[1], args[2]); break; default: // have more than 2 given arguments _h[i]['h'].apply(ctx, args); break; } if (_h[i]['one']) { _h.splice(i, 1); len--; } else { i++; } } } return this; } }; // 对象可以通过 onxxxx 绑定事件 /** * @event module:zrender/mixin/Eventful#onclick * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#onmouseover * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#onmouseout * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#onmousemove * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#onmousewheel * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#onmousedown * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#onmouseup * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#ondrag * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#ondragstart * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#ondragend * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#ondragenter * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#ondragleave * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#ondragover * @type {Function} * @default null */ /** * @event module:zrender/mixin/Eventful#ondrop * @type {Function} * @default null */ var _default = Eventful; module.exports = _default; /***/ }, /* 25 */ /*!********************************************************!*\ !*** ./~/echarts/~/zrender/lib/mixin/Transformable.js ***! \********************************************************/ /***/ function(module, exports, __webpack_require__) { var matrix = __webpack_require__(/*! ../core/matrix */ 26); var vector = __webpack_require__(/*! ../core/vector */ 27); /** * 提供变换扩展 * @module zrender/mixin/Transformable * @author pissang (https://www.github.com/pissang) */ var mIdentity = matrix.identity; var EPSILON = 5e-5; function isNotAroundZero(val) { return val > EPSILON || val < -EPSILON; } /** * @alias module:zrender/mixin/Transformable * @constructor */ var Transformable = function (opts) { opts = opts || {}; // If there are no given position, rotation, scale if (!opts.position) { /** * 平移 * @type {Array.<number>} * @default [0, 0] */ this.position = [0, 0]; } if (opts.rotation == null) { /** * 旋转 * @type {Array.<number>} * @default 0 */ this.rotation = 0; } if (!opts.scale) { /** * 缩放 * @type {Array.<number>} * @default [1, 1] */ this.scale = [1, 1]; } /** * 旋转和缩放的原点 * @type {Array.<number>} * @default null */ this.origin = this.origin || null; }; var transformableProto = Transformable.prototype; transformableProto.transform = null; /** * 判断是否需要有坐标变换 * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵 */ transformableProto.needLocalTransform = function () { return isNotAroundZero(this.rotation) || isNotAroundZero(this.position[0]) || isNotAroundZero(this.position[1]) || isNotAroundZero(this.scale[0] - 1) || isNotAroundZero(this.scale[1] - 1); }; transformableProto.updateTransform = function () { var parent = this.parent; var parentHasTransform = parent && parent.transform; var needLocalTransform = this.needLocalTransform(); var m = this.transform; if (!(needLocalTransform || parentHasTransform)) { m && mIdentity(m); return; } m = m || matrix.create(); if (needLocalTransform) { this.getLocalTransform(m); } else { mIdentity(m); } // 应用父节点变换 if (parentHasTransform) { if (needLocalTransform) { matrix.mul(m, parent.transform, m); } else { matrix.copy(m, parent.transform); } } // 保存这个变换矩阵 this.transform = m; this.invTransform = this.invTransform || matrix.create(); matrix.invert(this.invTransform, m); }; transformableProto.getLocalTransform = function (m) { return Transformable.getLocalTransform(this, m); }; /** * 将自己的transform应用到context上 * @param {CanvasRenderingContext2D} ctx */ transformableProto.setTransform = function (ctx) { var m = this.transform; var dpr = ctx.dpr || 1; if (m) { ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]); } else { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); } }; transformableProto.restoreTransform = function (ctx) { var dpr = ctx.dpr || 1; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }; var tmpTransform = []; /** * 分解`transform`矩阵到`position`, `rotation`, `scale` */ transformableProto.decomposeTransform = function () { if (!this.transform) { return; } var parent = this.parent; var m = this.transform; if (parent && parent.transform) { // Get local transform and decompose them to position, scale, rotation matrix.mul(tmpTransform, parent.invTransform, m); m = tmpTransform; } var sx = m[0] * m[0] + m[1] * m[1]; var sy = m[2] * m[2] + m[3] * m[3]; var position = this.position; var scale = this.scale; if (isNotAroundZero(sx - 1)) { sx = Math.sqrt(sx); } if (isNotAroundZero(sy - 1)) { sy = Math.sqrt(sy); } if (m[0] < 0) { sx = -sx; } if (m[3] < 0) { sy = -sy; } position[0] = m[4]; position[1] = m[5]; scale[0] = sx; scale[1] = sy; this.rotation = Math.atan2(-m[1] / sy, m[0] / sx); }; /** * Get global scale * @return {Array.<number>} */ transformableProto.getGlobalScale = function () { var m = this.transform; if (!m) { return [1, 1]; } var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]); var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]); if (m[0] < 0) { sx = -sx; } if (m[3] < 0) { sy = -sy; } return [sx, sy]; }; /** * 变换坐标位置到 shape 的局部坐标空间 * @method * @param {number} x * @param {number} y * @return {Array.<number>} */ transformableProto.transformCoordToLocal = function (x, y) { var v2 = [x, y]; var invTransform = this.invTransform; if (invTransform) { vector.applyTransform(v2, v2, invTransform); } return v2; }; /** * 变换局部坐标位置到全局坐标空间 * @method * @param {number} x * @param {number} y * @return {Array.<number>} */ transformableProto.transformCoordToGlobal = function (x, y) { var v2 = [x, y]; var transform = this.transform; if (transform) { vector.applyTransform(v2, v2, transform); } return v2; }; /** * @static * @param {Object} target * @param {Array.<number>} target.origin * @param {number} target.rotation * @param {Array.<number>} target.position * @param {Array.<number>} [m] */ Transformable.getLocalTransform = function (target, m) { m = m || []; mIdentity(m); var origin = target.origin; var scale = target.scale || [1, 1]; var rotation = target.rotation || 0; var position = target.position || [0, 0]; if (origin) { // Translate to origin m[4] -= origin[0]; m[5] -= origin[1]; } matrix.scale(m, m, scale); if (rotation) { matrix.rotate(m, m, rotation); } if (origin) { // Translate back from origin m[4] += origin[0]; m[5] += origin[1]; } m[4] += position[0]; m[5] += position[1]; return m; }; var _default = Transformable; module.exports = _default; /***/ }, /* 26 */ /*!************************************************!*\ !*** ./~/echarts/~/zrender/lib/core/matrix.js ***! \************************************************/ /***/ function(module, exports) { /** * 3x2矩阵操作类 * @exports zrender/tool/matrix */ var ArrayCtor = typeof Float32Array === 'undefined' ? Array : Float32Array; /** * Create a identity matrix. * @return {Float32Array|Array.<number>} */ function create() { var out = new ArrayCtor(6); identity(out); return out; } /** * 设置矩阵为单位矩阵 * @param {Float32Array|Array.<number>} out */ function identity(out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 1; out[4] = 0; out[5] = 0; return out; } /** * 复制矩阵 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} m */ function copy(out, m) { out[0] = m[0]; out[1] = m[1]; out[2] = m[2]; out[3] = m[3]; out[4] = m[4]; out[5] = m[5]; return out; } /** * 矩阵相乘 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} m1 * @param {Float32Array|Array.<number>} m2 */ function mul(out, m1, m2) { // Consider matrix.mul(m, m2, m); // where out is the same as m2. // So use temp variable to escape error. var out0 = m1[0] * m2[0] + m1[2] * m2[1]; var out1 = m1[1] * m2[0] + m1[3] * m2[1]; var out2 = m1[0] * m2[2] + m1[2] * m2[3]; var out3 = m1[1] * m2[2] + m1[3] * m2[3]; var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4]; var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5]; out[0] = out0; out[1] = out1; out[2] = out2; out[3] = out3; out[4] = out4; out[5] = out5; return out; } /** * 平移变换 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} a * @param {Float32Array|Array.<number>} v */ function translate(out, a, v) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4] + v[0]; out[5] = a[5] + v[1]; return out; } /** * 旋转变换 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} a * @param {number} rad */ function rotate(out, a, rad) { var aa = a[0]; var ac = a[2]; var atx = a[4]; var ab = a[1]; var ad = a[3]; var aty = a[5]; var st = Math.sin(rad); var ct = Math.cos(rad); out[0] = aa * ct + ab * st; out[1] = -aa * st + ab * ct; out[2] = ac * ct + ad * st; out[3] = -ac * st + ct * ad; out[4] = ct * atx + st * aty; out[5] = ct * aty - st * atx; return out; } /** * 缩放变换 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} a * @param {Float32Array|Array.<number>} v */ function scale(out, a, v) { var vx = v[0]; var vy = v[1]; out[0] = a[0] * vx; out[1] = a[1] * vy; out[2] = a[2] * vx; out[3] = a[3] * vy; out[4] = a[4] * vx; out[5] = a[5] * vy; return out; } /** * 求逆矩阵 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} a */ function invert(out, a) { var aa = a[0]; var ac = a[2]; var atx = a[4]; var ab = a[1]; var ad = a[3]; var aty = a[5]; var det = aa * ad - ab * ac; if (!det) { return null; } det = 1.0 / det; out[0] = ad * det; out[1] = -ab * det; out[2] = -ac * det; out[3] = aa * det; out[4] = (ac * aty - ad * atx) * det; out[5] = (ab * atx - aa * aty) * det; return out; } /** * Clone a new matrix. * @param {Float32Array|Array.<number>} a */ function clone(a) { var b = create(); copy(b, a); return b; } exports.create = create; exports.identity = identity; exports.copy = copy; exports.mul = mul; exports.translate = translate; exports.rotate = rotate; exports.scale = scale; exports.invert = invert; exports.clone = clone; /***/ }, /* 27 */ /*!************************************************!*\ !*** ./~/echarts/~/zrender/lib/core/vector.js ***! \************************************************/ /***/ function(module, exports) { var ArrayCtor = typeof Float32Array === 'undefined' ? Array : Float32Array; /** * 创建一个向量 * @param {number} [x=0] * @param {number} [y=0] * @return {Vector2} */ function create(x, y) { var out = new ArrayCtor(2); if (x == null) { x = 0; } if (y == null) { y = 0; } out[0] = x; out[1] = y; return out; } /** * 复制向量数据 * @param {Vector2} out * @param {Vector2} v * @return {Vector2} */ function copy(out, v) { out[0] = v[0]; out[1] = v[1]; return out; } /** * 克隆一个向量 * @param {Vector2} v * @return {Vector2} */ function clone(v) { var out = new ArrayCtor(2); out[0] = v[0]; out[1] = v[1]; return out; } /** * 设置向量的两个项 * @param {Vector2} out * @param {number} a * @param {number} b * @return {Vector2} 结果 */ function set(out, a, b) { out[0] = a; out[1] = b; return out; } /** * 向量相加 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function add(out, v1, v2) { out[0] = v1[0] + v2[0]; out[1] = v1[1] + v2[1]; return out; } /** * 向量缩放后相加 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 * @param {number} a */ function scaleAndAdd(out, v1, v2, a) { out[0] = v1[0] + v2[0] * a; out[1] = v1[1] + v2[1] * a; return out; } /** * 向量相减 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function sub(out, v1, v2) { out[0] = v1[0] - v2[0]; out[1] = v1[1] - v2[1]; return out; } /** * 向量长度 * @param {Vector2} v * @return {number} */ function len(v) { return Math.sqrt(lenSquare(v)); } var length = len; // jshint ignore:line /** * 向量长度平方 * @param {Vector2} v * @return {number} */ function lenSquare(v) { return v[0] * v[0] + v[1] * v[1]; } var lengthSquare = lenSquare; /** * 向量乘法 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function mul(out, v1, v2) { out[0] = v1[0] * v2[0]; out[1] = v1[1] * v2[1]; return out; } /** * 向量除法 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function div(out, v1, v2) { out[0] = v1[0] / v2[0]; out[1] = v1[1] / v2[1]; return out; } /** * 向量点乘 * @param {Vector2} v1 * @param {Vector2} v2 * @return {number} */ function dot(v1, v2) { return v1[0] * v2[0] + v1[1] * v2[1]; } /** * 向量缩放 * @param {Vector2} out * @param {Vector2} v * @param {number} s */ function scale(out, v, s) { out[0] = v[0] * s; out[1] = v[1] * s; return out; } /** * 向量归一化 * @param {Vector2} out * @param {Vector2} v */ function normalize(out, v) { var d = len(v); if (d === 0) { out[0] = 0; out[1] = 0; } else { out[0] = v[0] / d; out[1] = v[1] / d; } return out; } /** * 计算向量间距离 * @param {Vector2} v1 * @param {Vector2} v2 * @return {number} */ function distance(v1, v2) { return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1])); } var dist = distance; /** * 向量距离平方 * @param {Vector2} v1 * @param {Vector2} v2 * @return {number} */ function distanceSquare(v1, v2) { return (v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]); } var distSquare = distanceSquare; /** * 求负向量 * @param {Vector2} out * @param {Vector2} v */ function negate(out, v) { out[0] = -v[0]; out[1] = -v[1]; return out; } /** * 插值两个点 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 * @param {number} t */ function lerp(out, v1, v2, t) { out[0] = v1[0] + t * (v2[0] - v1[0]); out[1] = v1[1] + t * (v2[1] - v1[1]); return out; } /** * 矩阵左乘向量 * @param {Vector2} out * @param {Vector2} v * @param {Vector2} m */ function applyTransform(out, v, m) { var x = v[0]; var y = v[1]; out[0] = m[0] * x + m[2] * y + m[4]; out[1] = m[1] * x + m[3] * y + m[5]; return out; } /** * 求两个向量最小值 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function min(out, v1, v2) { out[0] = Math.min(v1[0], v2[0]); out[1] = Math.min(v1[1], v2[1]); return out; } /** * 求两个向量最大值 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function max(out, v1, v2) { out[0] = Math.max(v1[0], v2[0]); out[1] = Math.max(v1[1], v2[1]); return out; } exports.create = create; exports.copy = copy; exports.clone = clone; exports.set = set; exports.add = add; exports.scaleAndAdd = scaleAndAdd; exports.sub = sub; exports.len = len; exports.length = length; exports.lenSquare = lenSquare; exports.lengthSquare = lengthSquare; exports.mul = mul; exports.div = div; exports.dot = dot; exports.scale = scale; exports.normalize = normalize; exports.distance = distance; exports.dist = dist; exports.distanceSquare = distanceSquare; exports.distSquare = distSquare; exports.negate = negate; exports.lerp = lerp; exports.applyTransform = applyTransform; exports.min = min; exports.max = max; /***/ }, /* 28 */ /*!*****************************************************!*\ !*** ./~/echarts/~/zrender/lib/mixin/Animatable.js ***! \*****************************************************/ /***/ function(module, exports, __webpack_require__) { var Animator = __webpack_require__(/*! ../animation/Animator */ 29); var log = __webpack_require__(/*! ../core/log */ 34); var _util = __webpack_require__(/*! ../core/util */ 5); var isString = _util.isString; var isFunction = _util.isFunction; var isObject = _util.isObject; var isArrayLike = _util.isArrayLike; var indexOf = _util.indexOf; /** * @alias modue:zrender/mixin/Animatable * @constructor */ var Animatable = function () { /** * @type {Array.<module:zrender/animation/Animator>} * @readOnly */ this.animators = []; }; Animatable.prototype = { constructor: Animatable, /** * 动画 * * @param {string} path The path to fetch value from object, like 'a.b.c'. * @param {boolean} [loop] Whether to loop animation. * @return {module:zrender/animation/Animator} * @example: * el.animate('style', false) * .when(1000, {x: 10} ) * .done(function(){ // Animation done }) * .start() */ animate: function (path, loop) { var target; var animatingShape = false; var el = this; var zr = this.__zr; if (path) { var pathSplitted = path.split('.'); var prop = el; // If animating shape animatingShape = pathSplitted[0] === 'shape'; for (var i = 0, l = pathSplitted.length; i < l; i++) { if (!prop) { continue; } prop = prop[pathSplitted[i]]; } if (prop) { target = prop; } } else { target = el; } if (!target) { log('Property "' + path + '" is not existed in element ' + el.id); return; } var animators = el.animators; var animator = new Animator(target, loop); animator.during(function (target) { el.dirty(animatingShape); }).done(function () { // FIXME Animator will not be removed if use `Animator#stop` to stop animation animators.splice(indexOf(animators, animator), 1); }); animators.push(animator); // If animate after added to the zrender if (zr) { zr.animation.addAnimator(animator); } return animator; }, /** * 停止动画 * @param {boolean} forwardToLast If move to last frame before stop */ stopAnimation: function (forwardToLast) { var animators = this.animators; var len = animators.length; for (var i = 0; i < len; i++) { animators[i].stop(forwardToLast); } animators.length = 0; return this; }, /** * Caution: this method will stop previous animation. * So do not use this method to one element twice before * animation starts, unless you know what you are doing. * @param {Object} target * @param {number} [time=500] Time in ms * @param {string} [easing='linear'] * @param {number} [delay=0] * @param {Function} [callback] * @param {Function} [forceAnimate] Prevent stop animation and callback * immediently when target values are the same as current values. * * @example * // Animate position * el.animateTo({ * position: [10, 10] * }, function () { // done }) * * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing * el.animateTo({ * shape: { * width: 500 * }, * style: { * fill: 'red' * } * position: [10, 10] * }, 100, 100, 'cubicOut', function () { // done }) */ // TODO Return animation key animateTo: function (target, time, delay, easing, callback, forceAnimate) { // animateTo(target, time, easing, callback); if (isString(delay)) { callback = easing; easing = delay; delay = 0; } // animateTo(target, time, delay, callback); else if (isFunction(easing)) { callback = easing; easing = 'linear'; delay = 0; } // animateTo(target, time, callback); else if (isFunction(delay)) { callback = delay; delay = 0; } // animateTo(target, callback) else if (isFunction(time)) { callback = time; time = 500; } // animateTo(target) else if (!time) { time = 500; } // Stop all previous animations this.stopAnimation(); this._animateToShallow('', this, target, time, delay); // Animators may be removed immediately after start // if there is nothing to animate var animators = this.animators.slice(); var count = animators.length; function done() { count--; if (!count) { callback && callback(); } } // No animators. This should be checked before animators[i].start(), // because 'done' may be executed immediately if no need to animate. if (!count) { callback && callback(); } // Start after all animators created // Incase any animator is done immediately when all animation properties are not changed for (var i = 0; i < animators.length; i++) { animators[i].done(done).start(easing, forceAnimate); } }, /** * @private * @param {string} path='' * @param {Object} source=this * @param {Object} target * @param {number} [time=500] * @param {number} [delay=0] * * @example * // Animate position * el._animateToShallow({ * position: [10, 10] * }) * * // Animate shape, style and position in 100ms, delayed 100ms * el._animateToShallow({ * shape: { * width: 500 * }, * style: { * fill: 'red' * } * position: [10, 10] * }, 100, 100) */ _animateToShallow: function (path, source, target, time, delay) { var objShallow = {}; var propertyCount = 0; for (var name in target) { if (!target.hasOwnProperty(name)) { continue; } if (source[name] != null) { if (isObject(target[name]) && !isArrayLike(target[name])) { this._animateToShallow(path ? path + '.' + name : name, source[name], target[name], time, delay); } else { objShallow[name] = target[name]; propertyCount++; } } else if (target[name] != null) { // Attr directly if not has property // FIXME, if some property not needed for element ? if (!path) { this.attr(name, target[name]); } else { // Shape or style var props = {}; props[path] = {}; props[path][name] = target[name]; this.attr(props); } } } if (propertyCount > 0) { this.animate(path, false).when(time == null ? 500 : time, objShallow).delay(delay || 0); } return this; } }; var _default = Animatable; module.exports = _default; /***/ }, /* 29 */ /*!*******************************************************!*\ !*** ./~/echarts/~/zrender/lib/animation/Animator.js ***! \*******************************************************/ /***/ function(module, exports, __webpack_require__) { var Clip = __webpack_require__(/*! ./Clip */ 30); var color = __webpack_require__(/*! ../tool/color */ 32); var _util = __webpack_require__(/*! ../core/util */ 5); var isArrayLike = _util.isArrayLike; /** * @module echarts/animation/Animator */ var arraySlice = Array.prototype.slice; function defaultGetter(target, key) { return target[key]; } function defaultSetter(target, key, value) { target[key] = value; } /** * @param {number} p0 * @param {number} p1 * @param {number} percent * @return {number} */ function interpolateNumber(p0, p1, percent) { return (p1 - p0) * percent + p0; } /** * @param {string} p0 * @param {string} p1 * @param {number} percent * @return {string} */ function interpolateString(p0, p1, percent) { return percent > 0.5 ? p1 : p0; } /** * @param {Array} p0 * @param {Array} p1 * @param {number} percent * @param {Array} out * @param {number} arrDim */ function interpolateArray(p0, p1, percent, out, arrDim) { var len = p0.length; if (arrDim == 1) { for (var i = 0; i < len; i++) { out[i] = interpolateNumber(p0[i], p1[i], percent); } } else { var len2 = len && p0[0].length; for (var i = 0; i < len; i++) { for (var j = 0; j < len2; j++) { out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent); } } } } // arr0 is source array, arr1 is target array. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1 function fillArr(arr0, arr1, arrDim) { var arr0Len = arr0.length; var arr1Len = arr1.length; if (arr0Len !== arr1Len) { // FIXME Not work for TypedArray var isPreviousLarger = arr0Len > arr1Len; if (isPreviousLarger) { // Cut the previous arr0.length = arr1Len; } else { // Fill the previous for (var i = arr0Len; i < arr1Len; i++) { arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])); } } } // Handling NaN value var len2 = arr0[0] && arr0[0].length; for (var i = 0; i < arr0.length; i++) { if (arrDim === 1) { if (isNaN(arr0[i])) { arr0[i] = arr1[i]; } } else { for (var j = 0; j < len2; j++) { if (isNaN(arr0[i][j])) { arr0[i][j] = arr1[i][j]; } } } } } /** * @param {Array} arr0 * @param {Array} arr1 * @param {number} arrDim * @return {boolean} */ function isArraySame(arr0, arr1, arrDim) { if (arr0 === arr1) { return true; } var len = arr0.length; if (len !== arr1.length) { return false; } if (arrDim === 1) { for (var i = 0; i < len; i++) { if (arr0[i] !== arr1[i]) { return false; } } } else { var len2 = arr0[0].length; for (var i = 0; i < len; i++) { for (var j = 0; j < len2; j++) { if (arr0[i][j] !== arr1[i][j]) { return false; } } } } return true; } /** * Catmull Rom interpolate array * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @param {number} t * @param {number} t2 * @param {number} t3 * @param {Array} out * @param {number} arrDim */ function catmullRomInterpolateArray(p0, p1, p2, p3, t, t2, t3, out, arrDim) { var len = p0.length; if (arrDim == 1) { for (var i = 0; i < len; i++) { out[i] = catmullRomInterpolate(p0[i], p1[i], p2[i], p3[i], t, t2, t3); } } else { var len2 = p0[0].length; for (var i = 0; i < len; i++) { for (var j = 0; j < len2; j++) { out[i][j] = catmullRomInterpolate(p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3); } } } } /** * Catmull Rom interpolate number * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} t * @param {number} t2 * @param {number} t3 * @return {number} */ function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) { var v0 = (p2 - p0) * 0.5; var v1 = (p3 - p1) * 0.5; return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1; } function cloneValue(value) { if (isArrayLike(value)) { var len = value.length; if (isArrayLike(value[0])) { var ret = []; for (var i = 0; i < len; i++) { ret.push(arraySlice.call(value[i])); } return ret; } return arraySlice.call(value); } return value; } function rgba2String(rgba) { rgba[0] = Math.floor(rgba[0]); rgba[1] = Math.floor(rgba[1]); rgba[2] = Math.floor(rgba[2]); return 'rgba(' + rgba.join(',') + ')'; } function getArrayDim(keyframes) { var lastValue = keyframes[keyframes.length - 1].value; return isArrayLike(lastValue && lastValue[0]) ? 2 : 1; } function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) { var getter = animator._getter; var setter = animator._setter; var useSpline = easing === 'spline'; var trackLen = keyframes.length; if (!trackLen) { return; } // Guess data type var firstVal = keyframes[0].value; var isValueArray = isArrayLike(firstVal); var isValueColor = false; var isValueString = false; // For vertices morphing var arrDim = isValueArray ? getArrayDim(keyframes) : 0; var trackMaxTime; // Sort keyframe as ascending keyframes.sort(function (a, b) { return a.time - b.time; }); trackMaxTime = keyframes[trackLen - 1].time; // Percents of each keyframe var kfPercents = []; // Value of each keyframe var kfValues = []; var prevValue = keyframes[0].value; var isAllValueEqual = true; for (var i = 0; i < trackLen; i++) { kfPercents.push(keyframes[i].time / trackMaxTime); // Assume value is a color when it is a string var value = keyframes[i].value; // Check if value is equal, deep check if value is array if (!(isValueArray && isArraySame(value, prevValue, arrDim) || !isValueArray && value === prevValue)) { isAllValueEqual = false; } prevValue = value; // Try converting a string to a color array if (typeof value == 'string') { var colorArray = color.parse(value); if (colorArray) { value = colorArray; isValueColor = true; } else { isValueString = true; } } kfValues.push(value); } if (!forceAnimate && isAllValueEqual) { return; } var lastValue = kfValues[trackLen - 1]; // Polyfill array and NaN value for (var i = 0; i < trackLen - 1; i++) { if (isValueArray) { fillArr(kfValues[i], lastValue, arrDim); } else { if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) { kfValues[i] = lastValue; } } } isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim); // Cache the key of last frame to speed up when // animation playback is sequency var lastFrame = 0; var lastFramePercent = 0; var start; var w; var p0; var p1; var p2; var p3; if (isValueColor) { var rgba = [0, 0, 0, 0]; } var onframe = function (target, percent) { // Find the range keyframes // kf1-----kf2---------current--------kf3 // find kf2 and kf3 and do interpolation var frame; // In the easing function like elasticOut, percent may less than 0 if (percent < 0) { frame = 0; } else if (percent < lastFramePercent) { // Start from next key // PENDING start from lastFrame ? start = Math.min(lastFrame + 1, trackLen - 1); for (frame = start; frame >= 0; frame--) { if (kfPercents[frame] <= percent) { break; } } // PENDING really need to do this ? frame = Math.min(frame, trackLen - 2); } else { for (frame = lastFrame; frame < trackLen; frame++) { if (kfPercents[frame] > percent) { break; } } frame = Math.min(frame - 1, trackLen - 2); } lastFrame = frame; lastFramePercent = percent; var range = kfPercents[frame + 1] - kfPercents[frame]; if (range === 0) { return; } else { w = (percent - kfPercents[frame]) / range; } if (useSpline) { p1 = kfValues[frame]; p0 = kfValues[frame === 0 ? frame : frame - 1]; p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1]; p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2]; if (isValueArray) { catmullRomInterpolateArray(p0, p1, p2, p3, w, w * w, w * w * w, getter(target, propName), arrDim); } else { var value; if (isValueColor) { value = catmullRomInterpolateArray(p0, p1, p2, p3, w, w * w, w * w * w, rgba, 1); value = rgba2String(rgba); } else if (isValueString) { // String is step(0.5) return interpolateString(p1, p2, w); } else { value = catmullRomInterpolate(p0, p1, p2, p3, w, w * w, w * w * w); } setter(target, propName, value); } } else { if (isValueArray) { interpolateArray(kfValues[frame], kfValues[frame + 1], w, getter(target, propName), arrDim); } else { var value; if (isValueColor) { interpolateArray(kfValues[frame], kfValues[frame + 1], w, rgba, 1); value = rgba2String(rgba); } else if (isValueString) { // String is step(0.5) return interpolateString(kfValues[frame], kfValues[frame + 1], w); } else { value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w); } setter(target, propName, value); } } }; var clip = new Clip({ target: animator._target, life: trackMaxTime, loop: animator._loop, delay: animator._delay, onframe: onframe, ondestroy: oneTrackDone }); if (easing && easing !== 'spline') { clip.easing = easing; } return clip; } /** * @alias module:zrender/animation/Animator * @constructor * @param {Object} target * @param {boolean} loop * @param {Function} getter * @param {Function} setter */ var Animator = function (target, loop, getter, setter) { this._tracks = {}; this._target = target; this._loop = loop || false; this._getter = getter || defaultGetter; this._setter = setter || defaultSetter; this._clipCount = 0; this._delay = 0; this._doneList = []; this._onframeList = []; this._clipList = []; }; Animator.prototype = { /** * 设置动画关键帧 * @param {number} time 关键帧时间,单位是ms * @param {Object} props 关键帧的属性值,key-value表示 * @return {module:zrender/animation/Animator} */ when: function (time /* ms */ , props) { var tracks = this._tracks; for (var propName in props) { if (!props.hasOwnProperty(propName)) { continue; } if (!tracks[propName]) { tracks[propName] = []; // Invalid value var value = this._getter(this._target, propName); if (value == null) { // zrLog('Invalid property ' + propName); continue; } // If time is 0 // Then props is given initialize value // Else // Initialize value from current prop value if (time !== 0) { tracks[propName].push({ time: 0, value: cloneValue(value) }); } } tracks[propName].push({ time: time, value: props[propName] }); } return this; }, /** * 添加动画每一帧的回调函数 * @param {Function} callback * @return {module:zrender/animation/Animator} */ during: function (callback) { this._onframeList.push(callback); return this; }, pause: function () { for (var i = 0; i < this._clipList.length; i++) { this._clipList[i].pause(); } this._paused = true; }, resume: function () { for (var i = 0; i < this._clipList.length; i++) { this._clipList[i].resume(); } this._paused = false; }, isPaused: function () { return !!this._paused; }, _doneCallback: function () { // Clear all tracks this._tracks = {}; // Clear all clips this._clipList.length = 0; var doneList = this._doneList; var len = doneList.length; for (var i = 0; i < len; i++) { doneList[i].call(this); } }, /** * 开始执行动画 * @param {string|Function} [easing] * 动画缓动函数,详见{@link module:zrender/animation/easing} * @param {boolean} forceAnimate * @return {module:zrender/animation/Animator} */ start: function (easing, forceAnimate) { var self = this; var clipCount = 0; var oneTrackDone = function () { clipCount--; if (!clipCount) { self._doneCallback(); } }; var lastClip; for (var propName in this._tracks) { if (!this._tracks.hasOwnProperty(propName)) { continue; } var clip = createTrackClip(this, easing, oneTrackDone, this._tracks[propName], propName, forceAnimate); if (clip) { this._clipList.push(clip); clipCount++; // If start after added to animation if (this.animation) { this.animation.addClip(clip); } lastClip = clip; } } // Add during callback on the last clip if (lastClip) { var oldOnFrame = lastClip.onframe; lastClip.onframe = function (target, percent) { oldOnFrame(target, percent); for (var i = 0; i < self._onframeList.length; i++) { self._onframeList[i](target, percent); } }; } // This optimization will help the case that in the upper application // the view may be refreshed frequently, where animation will be // called repeatly but nothing changed. if (!clipCount) { this._doneCallback(); } return this; }, /** * 停止动画 * @param {boolean} forwardToLast If move to last frame before stop */ stop: function (forwardToLast) { var clipList = this._clipList; var animation = this.animation; for (var i = 0; i < clipList.length; i++) { var clip = clipList[i]; if (forwardToLast) { // Move to last frame before stop clip.onframe(this._target, 1); } animation && animation.removeClip(clip); } clipList.length = 0; }, /** * 设置动画延迟开始的时间 * @param {number} time 单位ms * @return {module:zrender/animation/Animator} */ delay: function (time) { this._delay = time; return this; }, /** * 添加动画结束的回调 * @param {Function} cb * @return {module:zrender/animation/Animator} */ done: function (cb) { if (cb) { this._doneList.push(cb); } return this; }, /** * @return {Array.<module:zrender/animation/Clip>} */ getClips: function () { return this._clipList; } }; var _default = Animator; module.exports = _default; /***/ }, /* 30 */ /*!***************************************************!*\ !*** ./~/echarts/~/zrender/lib/animation/Clip.js ***! \***************************************************/ /***/ function(module, exports, __webpack_require__) { var easingFuncs = __webpack_require__(/*! ./easing */ 31); /** * 动画主控制器 * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件 * @config life(1000) 动画时长 * @config delay(0) 动画延迟时间 * @config loop(true) * @config gap(0) 循环的间隔时间 * @config onframe * @config easing(optional) * @config ondestroy(optional) * @config onrestart(optional) * * TODO pause */ function Clip(options) { this._target = options.target; // 生命周期 this._life = options.life || 1000; // 延时 this._delay = options.delay || 0; // 开始时间 // this._startTime = new Date().getTime() + this._delay;// 单位毫秒 this._initialized = false; // 是否循环 this.loop = options.loop == null ? false : options.loop; this.gap = options.gap || 0; this.easing = options.easing || 'Linear'; this.onframe = options.onframe; this.ondestroy = options.ondestroy; this.onrestart = options.onrestart; this._pausedTime = 0; this._paused = false; } Clip.prototype = { constructor: Clip, step: function (globalTime, deltaTime) { // Set startTime on first step, or _startTime may has milleseconds different between clips // PENDING if (!this._initialized) { this._startTime = globalTime + this._delay; this._initialized = true; } if (this._paused) { this._pausedTime += deltaTime; return; } var percent = (globalTime - this._startTime - this._pausedTime) / this._life; // 还没开始 if (percent < 0) { return; } percent = Math.min(percent, 1); var easing = this.easing; var easingFunc = typeof easing == 'string' ? easingFuncs[easing] : easing; var schedule = typeof easingFunc === 'function' ? easingFunc(percent) : percent; this.fire('frame', schedule); // 结束 if (percent == 1) { if (this.loop) { this.restart(globalTime); // 重新开始周期 // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件 return 'restart'; } // 动画完成将这个控制器标识为待删除 // 在Animation.update中进行批量删除 this._needsRemove = true; return 'destroy'; } return null; }, restart: function (globalTime) { var remainder = (globalTime - this._startTime - this._pausedTime) % this._life; this._startTime = globalTime - remainder + this.gap; this._pausedTime = 0; this._needsRemove = false; }, fire: function (eventType, arg) { eventType = 'on' + eventType; if (this[eventType]) { this[eventType](this._target, arg); } }, pause: function () { this._paused = true; }, resume: function () { this._paused = false; } }; var _default = Clip; module.exports = _default; /***/ }, /* 31 */ /*!*****************************************************!*\ !*** ./~/echarts/~/zrender/lib/animation/easing.js ***! \*****************************************************/ /***/ function(module, exports) { /** * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js * @see http://sole.github.io/tween.js/examples/03_graphs.html * @exports zrender/animation/easing */ var easing = { /** * @param {number} k * @return {number} */ linear: function (k) { return k; }, /** * @param {number} k * @return {number} */ quadraticIn: function (k) { return k * k; }, /** * @param {number} k * @return {number} */ quadraticOut: function (k) { return k * (2 - k); }, /** * @param {number} k * @return {number} */ quadraticInOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k; } return -0.5 * (--k * (k - 2) - 1); }, // 三次方的缓动(t^3) /** * @param {number} k * @return {number} */ cubicIn: function (k) { return k * k * k; }, /** * @param {number} k * @return {number} */ cubicOut: function (k) { return --k * k * k + 1; }, /** * @param {number} k * @return {number} */ cubicInOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k * k; } return 0.5 * ((k -= 2) * k * k + 2); }, // 四次方的缓动(t^4) /** * @param {number} k * @return {number} */ quarticIn: function (k) { return k * k * k * k; }, /** * @param {number} k * @return {number} */ quarticOut: function (k) { return 1 - --k * k * k * k; }, /** * @param {number} k * @return {number} */ quarticInOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k; } return -0.5 * ((k -= 2) * k * k * k - 2); }, // 五次方的缓动(t^5) /** * @param {number} k * @return {number} */ quinticIn: function (k) { return k * k * k * k * k; }, /** * @param {number} k * @return {number} */ quinticOut: function (k) { return --k * k * k * k * k + 1; }, /** * @param {number} k * @return {number} */ quinticInOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k * k; } return 0.5 * ((k -= 2) * k * k * k * k + 2); }, // 正弦曲线的缓动(sin(t)) /** * @param {number} k * @return {number} */ sinusoidalIn: function (k) { return 1 - Math.cos(k * Math.PI / 2); }, /** * @param {number} k * @return {number} */ sinusoidalOut: function (k) { return Math.sin(k * Math.PI / 2); }, /** * @param {number} k * @return {number} */ sinusoidalInOut: function (k) { return 0.5 * (1 - Math.cos(Math.PI * k)); }, // 指数曲线的缓动(2^t) /** * @param {number} k * @return {number} */ exponentialIn: function (k) { return k === 0 ? 0 : Math.pow(1024, k - 1); }, /** * @param {number} k * @return {number} */ exponentialOut: function (k) { return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); }, /** * @param {number} k * @return {number} */ exponentialInOut: function (k) { if (k === 0) { return 0; } if (k === 1) { return 1; } if ((k *= 2) < 1) { return 0.5 * Math.pow(1024, k - 1); } return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2); }, // 圆形曲线的缓动(sqrt(1-t^2)) /** * @param {number} k * @return {number} */ circularIn: function (k) { return 1 - Math.sqrt(1 - k * k); }, /** * @param {number} k * @return {number} */ circularOut: function (k) { return Math.sqrt(1 - --k * k); }, /** * @param {number} k * @return {number} */ circularInOut: function (k) { if ((k *= 2) < 1) { return -0.5 * (Math.sqrt(1 - k * k) - 1); } return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); }, // 创建类似于弹簧在停止前来回振荡的动画 /** * @param {number} k * @return {number} */ elasticIn: function (k) { var s; var a = 0.1; var p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (!a || a < 1) { a = 1; s = p / 4; } else { s = p * Math.asin(1 / a) / (2 * Math.PI); } return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); }, /** * @param {number} k * @return {number} */ elasticOut: function (k) { var s; var a = 0.1; var p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (!a || a < 1) { a = 1; s = p / 4; } else { s = p * Math.asin(1 / a) / (2 * Math.PI); } return a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1; }, /** * @param {number} k * @return {number} */ elasticInOut: function (k) { var s; var a = 0.1; var p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (!a || a < 1) { a = 1; s = p / 4; } else { s = p * Math.asin(1 / a) / (2 * Math.PI); } if ((k *= 2) < 1) { return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); } return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1; }, // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动 /** * @param {number} k * @return {number} */ backIn: function (k) { var s = 1.70158; return k * k * ((s + 1) * k - s); }, /** * @param {number} k * @return {number} */ backOut: function (k) { var s = 1.70158; return --k * k * ((s + 1) * k + s) + 1; }, /** * @param {number} k * @return {number} */ backInOut: function (k) { var s = 1.70158 * 1.525; if ((k *= 2) < 1) { return 0.5 * (k * k * ((s + 1) * k - s)); } return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); }, // 创建弹跳效果 /** * @param {number} k * @return {number} */ bounceIn: function (k) { return 1 - easing.bounceOut(1 - k); }, /** * @param {number} k * @return {number} */ bounceOut: function (k) { if (k < 1 / 2.75) { return 7.5625 * k * k; } else if (k < 2 / 2.75) { return 7.5625 * (k -= 1.5 / 2.75) * k + 0.75; } else if (k < 2.5 / 2.75) { return 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375; } else { return 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375; } }, /** * @param {number} k * @return {number} */ bounceInOut: function (k) { if (k < 0.5) { return easing.bounceIn(k * 2) * 0.5; } return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5; } }; var _default = easing; module.exports = _default; /***/ }, /* 32 */ /*!***********************************************!*\ !*** ./~/echarts/~/zrender/lib/tool/color.js ***! \***********************************************/ /***/ function(module, exports, __webpack_require__) { var LRU = __webpack_require__(/*! ../core/LRU */ 33); var kCSSColorTable = { '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] }; function clampCssByte(i) { // Clamp to integer 0 .. 255. i = Math.round(i); // Seems to be what Chrome does (vs truncation). return i < 0 ? 0 : i > 255 ? 255 : i; } function clampCssAngle(i) { // Clamp to integer 0 .. 360. i = Math.round(i); // Seems to be what Chrome does (vs truncation). return i < 0 ? 0 : i > 360 ? 360 : i; } function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0. return f < 0 ? 0 : f > 1 ? 1 : f; } function parseCssInt(str) { // int or percentage. if (str.length && str.charAt(str.length - 1) === '%') { return clampCssByte(parseFloat(str) / 100 * 255); } return clampCssByte(parseInt(str, 10)); } function parseCssFloat(str) { // float or percentage. if (str.length && str.charAt(str.length - 1) === '%') { return clampCssFloat(parseFloat(str) / 100); } return clampCssFloat(parseFloat(str)); } function cssHueToRgb(m1, m2, h) { if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } if (h * 2 < 1) { return m2; } if (h * 3 < 2) { return m1 + (m2 - m1) * (2 / 3 - h) * 6; } return m1; } function lerpNumber(a, b, p) { return a + (b - a) * p; } function setRgba(out, r, g, b, a) { out[0] = r; out[1] = g; out[2] = b; out[3] = a; return out; } function copyRgba(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; return out; } var colorCache = new LRU(20); var lastRemovedArr = null; function putToCache(colorStr, rgbaArr) { // Reuse removed array if (lastRemovedArr) { copyRgba(lastRemovedArr, rgbaArr); } lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || rgbaArr.slice()); } /** * @param {string} colorStr * @param {Array.<number>} out * @return {Array.<number>} * @memberOf module:zrender/util/color */ function parse(colorStr, rgbaArr) { if (!colorStr) { return; } rgbaArr = rgbaArr || []; var cached = colorCache.get(colorStr); if (cached) { return copyRgba(rgbaArr, cached); } // colorStr may be not string colorStr = colorStr + ''; // Remove all whitespace, not compliant, but should just be more accepting. var str = colorStr.replace(/ /g, '').toLowerCase(); // Color keywords (and transparent) lookup. if (str in kCSSColorTable) { copyRgba(rgbaArr, kCSSColorTable[str]); putToCache(colorStr, rgbaArr); return rgbaArr; } // #abc and #abc123 syntax. if (str.charAt(0) === '#') { if (str.length === 4) { var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. if (!(iv >= 0 && iv <= 0xfff)) { setRgba(rgbaArr, 0, 0, 0, 1); return; // Covers NaN. } setRgba(rgbaArr, (iv & 0xf00) >> 4 | (iv & 0xf00) >> 8, iv & 0xf0 | (iv & 0xf0) >> 4, iv & 0xf | (iv & 0xf) << 4, 1); putToCache(colorStr, rgbaArr); return rgbaArr; } else if (str.length === 7) { var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. if (!(iv >= 0 && iv <= 0xffffff)) { setRgba(rgbaArr, 0, 0, 0, 1); return; // Covers NaN. } setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, 1); putToCache(colorStr, rgbaArr); return rgbaArr; } return; } var op = str.indexOf('('), ep = str.indexOf(')'); if (op !== -1 && ep + 1 === str.length) { var fname = str.substr(0, op); var params = str.substr(op + 1, ep - (op + 1)).split(','); var alpha = 1; // To allow case fallthrough. switch (fname) { case 'rgba': if (params.length !== 4) { setRgba(rgbaArr, 0, 0, 0, 1); return; } alpha = parseCssFloat(params.pop()); // jshint ignore:line // Fall through. case 'rgb': if (params.length !== 3) { setRgba(rgbaArr, 0, 0, 0, 1); return; } setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha); putToCache(colorStr, rgbaArr); return rgbaArr; case 'hsla': if (params.length !== 4) { setRgba(rgbaArr, 0, 0, 0, 1); return; } params[3] = parseCssFloat(params[3]); hsla2rgba(params, rgbaArr); putToCache(colorStr, rgbaArr); return rgbaArr; case 'hsl': if (params.length !== 3) { setRgba(rgbaArr, 0, 0, 0, 1); return; } hsla2rgba(params, rgbaArr); putToCache(colorStr, rgbaArr); return rgbaArr; default: return; } } setRgba(rgbaArr, 0, 0, 0, 1); return; } /** * @param {Array.<number>} hsla * @param {Array.<number>} rgba * @return {Array.<number>} rgba */ function hsla2rgba(hsla, rgba) { var h = (parseFloat(hsla[0]) % 360 + 360) % 360 / 360; // 0 .. 1 // NOTE(deanm): According to the CSS spec s/l should only be // percentages, but we don't bother and let float or percentage. var s = parseCssFloat(hsla[1]); var l = parseCssFloat(hsla[2]); var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var m1 = l * 2 - m2; rgba = rgba || []; setRgba(rgba, clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255), clampCssByte(cssHueToRgb(m1, m2, h) * 255), clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255), 1); if (hsla.length === 4) { rgba[3] = hsla[3]; } return rgba; } /** * @param {Array.<number>} rgba * @return {Array.<number>} hsla */ function rgba2hsla(rgba) { if (!rgba) { return; } // RGB from 0 to 255 var R = rgba[0] / 255; var G = rgba[1] / 255; var B = rgba[2] / 255; var vMin = Math.min(R, G, B); // Min. value of RGB var vMax = Math.max(R, G, B); // Max. value of RGB var delta = vMax - vMin; // Delta RGB value var L = (vMax + vMin) / 2; var H; var S; // HSL results from 0 to 1 if (delta === 0) { H = 0; S = 0; } else { if (L < 0.5) { S = delta / (vMax + vMin); } else { S = delta / (2 - vMax - vMin); } var deltaR = ((vMax - R) / 6 + delta / 2) / delta; var deltaG = ((vMax - G) / 6 + delta / 2) / delta; var deltaB = ((vMax - B) / 6 + delta / 2) / delta; if (R === vMax) { H = deltaB - deltaG; } else if (G === vMax) { H = 1 / 3 + deltaR - deltaB; } else if (B === vMax) { H = 2 / 3 + deltaG - deltaR; } if (H < 0) { H += 1; } if (H > 1) { H -= 1; } } var hsla = [H * 360, S, L]; if (rgba[3] != null) { hsla.push(rgba[3]); } return hsla; } /** * @param {string} color * @param {number} level * @return {string} * @memberOf module:zrender/util/color */ function lift(color, level) { var colorArr = parse(color); if (colorArr) { for (var i = 0; i < 3; i++) { if (level < 0) { colorArr[i] = colorArr[i] * (1 - level) | 0; } else { colorArr[i] = (255 - colorArr[i]) * level + colorArr[i] | 0; } if (colorArr[i] > 255) { colorArr[i] = 255; } else if (color[i] < 0) { colorArr[i] = 0; } } return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb'); } } /** * @param {string} color * @return {string} * @memberOf module:zrender/util/color */ function toHex(color) { var colorArr = parse(color); if (colorArr) { return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + +colorArr[2]).toString(16).slice(1); } } /** * Map value to color. Faster than lerp methods because color is represented by rgba array. * @param {number} normalizedValue A float between 0 and 1. * @param {Array.<Array.<number>>} colors List of rgba color array * @param {Array.<number>} [out] Mapped gba color array * @return {Array.<number>} will be null/undefined if input illegal. */ function fastLerp(normalizedValue, colors, out) { if (!(colors && colors.length) || !(normalizedValue >= 0 && normalizedValue <= 1)) { return; } out = out || []; var value = normalizedValue * (colors.length - 1); var leftIndex = Math.floor(value); var rightIndex = Math.ceil(value); var leftColor = colors[leftIndex]; var rightColor = colors[rightIndex]; var dv = value - leftIndex; out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)); out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)); out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)); out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv)); return out; } /** * @deprecated */ var fastMapToColor = fastLerp; /** * @param {number} normalizedValue A float between 0 and 1. * @param {Array.<string>} colors Color list. * @param {boolean=} fullOutput Default false. * @return {(string|Object)} Result color. If fullOutput, * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...}, * @memberOf module:zrender/util/color */ function lerp(normalizedValue, colors, fullOutput) { if (!(colors && colors.length) || !(normalizedValue >= 0 && normalizedValue <= 1)) { return; } var value = normalizedValue * (colors.length - 1); var leftIndex = Math.floor(value); var rightIndex = Math.ceil(value); var leftColor = parse(colors[leftIndex]); var rightColor = parse(colors[rightIndex]); var dv = value - leftIndex; var color = stringify([clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)), clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)), clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)), clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))], 'rgba'); return fullOutput ? { color: color, leftIndex: leftIndex, rightIndex: rightIndex, value: value } : color; } /** * @deprecated */ var mapToColor = lerp; /** * @param {string} color * @param {number=} h 0 ~ 360, ignore when null. * @param {number=} s 0 ~ 1, ignore when null. * @param {number=} l 0 ~ 1, ignore when null. * @return {string} Color string in rgba format. * @memberOf module:zrender/util/color */ function modifyHSL(color, h, s, l) { color = parse(color); if (color) { color = rgba2hsla(color); h != null && (color[0] = clampCssAngle(h)); s != null && (color[1] = parseCssFloat(s)); l != null && (color[2] = parseCssFloat(l)); return stringify(hsla2rgba(color), 'rgba'); } } /** * @param {string} color * @param {number=} alpha 0 ~ 1 * @return {string} Color string in rgba format. * @memberOf module:zrender/util/color */ function modifyAlpha(color, alpha) { color = parse(color); if (color && alpha != null) { color[3] = clampCssFloat(alpha); return stringify(color, 'rgba'); } } /** * @param {Array.<number>} arrColor like [12,33,44,0.4] * @param {string} type 'rgba', 'hsva', ... * @return {string} Result color. (If input illegal, return undefined). */ function stringify(arrColor, type) { if (!arrColor || !arrColor.length) { return; } var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2]; if (type === 'rgba' || type === 'hsva' || type === 'hsla') { colorStr += ',' + arrColor[3]; } return type + '(' + colorStr + ')'; } exports.parse = parse; exports.lift = lift; exports.toHex = toHex; exports.fastLerp = fastLerp; exports.fastMapToColor = fastMapToColor; exports.lerp = lerp; exports.mapToColor = mapToColor; exports.modifyHSL = modifyHSL; exports.modifyAlpha = modifyAlpha; exports.stringify = stringify; /***/ }, /* 33 */ /*!*********************************************!*\ !*** ./~/echarts/~/zrender/lib/core/LRU.js ***! \*********************************************/ /***/ function(module, exports) { // Simple LRU cache use doubly linked list // @module zrender/core/LRU /** * Simple double linked list. Compared with array, it has O(1) remove operation. * @constructor */ var LinkedList = function () { /** * @type {module:zrender/core/LRU~Entry} */ this.head = null; /** * @type {module:zrender/core/LRU~Entry} */ this.tail = null; this._len = 0; }; var linkedListProto = LinkedList.prototype; /** * Insert a new value at the tail * @param {} val * @return {module:zrender/core/LRU~Entry} */ linkedListProto.insert = function (val) { var entry = new Entry(val); this.insertEntry(entry); return entry; }; /** * Insert an entry at the tail * @param {module:zrender/core/LRU~Entry} entry */ linkedListProto.insertEntry = function (entry) { if (!this.head) { this.head = this.tail = entry; } else { this.tail.next = entry; entry.prev = this.tail; entry.next = null; this.tail = entry; } this._len++; }; /** * Remove entry. * @param {module:zrender/core/LRU~Entry} entry */ linkedListProto.remove = function (entry) { var prev = entry.prev; var next = entry.next; if (prev) { prev.next = next; } else { // Is head this.head = next; } if (next) { next.prev = prev; } else { // Is tail this.tail = prev; } entry.next = entry.prev = null; this._len--; }; /** * @return {number} */ linkedListProto.len = function () { return this._len; }; /** * Clear list */ linkedListProto.clear = function () { this.head = this.tail = null; this._len = 0; }; /** * @constructor * @param {} val */ var Entry = function (val) { /** * @type {} */ this.value = val; /** * @type {module:zrender/core/LRU~Entry} */ this.next; /** * @type {module:zrender/core/LRU~Entry} */ this.prev; }; /** * LRU Cache * @constructor * @alias module:zrender/core/LRU */ var LRU = function (maxSize) { this._list = new LinkedList(); this._map = {}; this._maxSize = maxSize || 10; this._lastRemovedEntry = null; }; var LRUProto = LRU.prototype; /** * @param {string} key * @param {} value * @return {} Removed value */ LRUProto.put = function (key, value) { var list = this._list; var map = this._map; var removed = null; if (map[key] == null) { var len = list.len(); // Reuse last removed entry var entry = this._lastRemovedEntry; if (len >= this._maxSize && len > 0) { // Remove the least recently used var leastUsedEntry = list.head; list.remove(leastUsedEntry); delete map[leastUsedEntry.key]; removed = leastUsedEntry.value; this._lastRemovedEntry = leastUsedEntry; } if (entry) { entry.value = value; } else { entry = new Entry(value); } entry.key = key; list.insertEntry(entry); map[key] = entry; } return removed; }; /** * @param {string} key * @return {} */ LRUProto.get = function (key) { var entry = this._map[key]; var list = this._list; if (entry != null) { // Put the latest used entry in the tail if (entry !== list.tail) { list.remove(entry); list.insertEntry(entry); } return entry.value; } }; /** * Clear the cache */ LRUProto.clear = function () { this._list.clear(); this._map = {}; }; var _default = LRU; module.exports = _default; /***/ }, /* 34 */ /*!*********************************************!*\ !*** ./~/echarts/~/zrender/lib/core/log.js ***! \*********************************************/ /***/ function(module, exports, __webpack_require__) { var _config = __webpack_require__(/*! ../config */ 35); var debugMode = _config.debugMode; var log = function () {}; if (debugMode === 1) { log = function () { for (var k in arguments) { throw new Error(arguments[k]); } }; } else if (debugMode > 1) { log = function () { for (var k in arguments) { console.log(arguments[k]); } }; } var _default = log; module.exports = _default; /***/ }, /* 35 */ /*!*******************************************!*\ !*** ./~/echarts/~/zrender/lib/config.js ***! \*******************************************/ /***/ function(module, exports) { var dpr = 1; // If in browser environment if (typeof window !== 'undefined') { dpr = Math.max(window.devicePixelRatio || 1, 1); } /** * config默认配置项 * @exports zrender/config * @author Kener (@Kener-林峰, [email protected]) */ /** * debug日志选项:catchBrushException为true下有效 * 0 : 不生成debug数据,发布用 * 1 : 异常抛出,调试用 * 2 : 控制台输出,调试用 */ var debugMode = 0; // retina 屏幕优化 var devicePixelRatio = dpr; exports.debugMode = debugMode; exports.devicePixelRatio = devicePixelRatio; /***/ }, /* 36 */ /*!***********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/mixin/RectText.js ***! \***********************************************************/ /***/ function(module, exports, __webpack_require__) { var textHelper = __webpack_require__(/*! ../helper/text */ 37); var BoundingRect = __webpack_require__(/*! ../../core/BoundingRect */ 39); /** * Mixin for drawing text in a element bounding rect * @module zrender/mixin/RectText */ var tmpRect = new BoundingRect(); var RectText = function () {}; RectText.prototype = { constructor: RectText, /** * Draw text in a rect with specified position. * @param {CanvasRenderingContext2D} ctx * @param {Object} rect Displayable rect */ drawRectText: function (ctx, rect) { var style = this.style; rect = style.textRect || rect; // Optimize, avoid normalize every time. this.__dirty && textHelper.normalizeTextStyle(style, true); var text = style.text; // Convert to string text != null && (text += ''); if (!textHelper.needDrawText(text, style)) { return; } // FIXME ctx.save(); // Transform rect to view space var transform = this.transform; if (!style.transformText) { if (transform) { tmpRect.copy(rect); tmpRect.applyTransform(transform); rect = tmpRect; } } else { this.setTransform(ctx); } // transformText and textRotation can not be used at the same time. textHelper.renderText(this, ctx, text, style, rect); ctx.restore(); } }; var _default = RectText; module.exports = _default; /***/ }, /* 37 */ /*!********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/helper/text.js ***! \********************************************************/ /***/ function(module, exports, __webpack_require__) { var _util = __webpack_require__(/*! ../../core/util */ 5); var retrieve2 = _util.retrieve2; var retrieve3 = _util.retrieve3; var each = _util.each; var normalizeCssArray = _util.normalizeCssArray; var isString = _util.isString; var isObject = _util.isObject; var textContain = __webpack_require__(/*! ../../contain/text */ 38); var roundRectHelper = __webpack_require__(/*! ./roundRect */ 41); var imageHelper = __webpack_require__(/*! ./image */ 40); var fixShadow = __webpack_require__(/*! ./fixShadow */ 21); // TODO: Have not support 'start', 'end' yet. var VALID_TEXT_ALIGN = { left: 1, right: 1, center: 1 }; var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 }; /** * @param {module:zrender/graphic/Style} style * @return {module:zrender/graphic/Style} The input style. */ function normalizeTextStyle(style) { normalizeStyle(style); each(style.rich, normalizeStyle); return style; } function normalizeStyle(style) { if (style) { style.font = textContain.makeFont(style); var textAlign = style.textAlign; textAlign === 'middle' && (textAlign = 'center'); style.textAlign = textAlign == null || VALID_TEXT_ALIGN[textAlign] ? textAlign : 'left'; // Compatible with textBaseline. var textVerticalAlign = style.textVerticalAlign || style.textBaseline; textVerticalAlign === 'center' && (textVerticalAlign = 'middle'); style.textVerticalAlign = textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign] ? textVerticalAlign : 'top'; var textPadding = style.textPadding; if (textPadding) { style.textPadding = normalizeCssArray(style.textPadding); } } } /** * @param {CanvasRenderingContext2D} ctx * @param {string} text * @param {module:zrender/graphic/Style} style * @param {Object|boolean} [rect] {x, y, width, height} * If set false, rect text is not used. */ function renderText(hostEl, ctx, text, style, rect) { style.rich ? renderRichText(hostEl, ctx, text, style, rect) : renderPlainText(hostEl, ctx, text, style, rect); } function renderPlainText(hostEl, ctx, text, style, rect) { var font = setCtx(ctx, 'font', style.font || textContain.DEFAULT_FONT); var textPadding = style.textPadding; var contentBlock = hostEl.__textCotentBlock; if (!contentBlock || hostEl.__dirty) { contentBlock = hostEl.__textCotentBlock = textContain.parsePlainText(text, font, textPadding, style.truncate); } var outerHeight = contentBlock.outerHeight; var textLines = contentBlock.lines; var lineHeight = contentBlock.lineHeight; var boxPos = getBoxPosition(outerHeight, style, rect); var baseX = boxPos.baseX; var baseY = boxPos.baseY; var textAlign = boxPos.textAlign; var textVerticalAlign = boxPos.textVerticalAlign; // Origin of textRotation should be the base point of text drawing. applyTextRotation(ctx, style, rect, baseX, baseY); var boxY = textContain.adjustTextY(baseY, outerHeight, textVerticalAlign); var textX = baseX; var textY = boxY; var needDrawBg = needDrawBackground(style); if (needDrawBg || textPadding) { // Consider performance, do not call getTextWidth util necessary. var textWidth = textContain.getWidth(text, font); var outerWidth = textWidth; textPadding && (outerWidth += textPadding[1] + textPadding[3]); var boxX = textContain.adjustTextX(baseX, outerWidth, textAlign); needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight); if (textPadding) { textX = getTextXForPadding(baseX, textAlign, textPadding); textY += textPadding[0]; } } setCtx(ctx, 'textAlign', textAlign || 'left'); // Force baseline to be "middle". Otherwise, if using "top", the // text will offset downward a little bit in font "Microsoft YaHei". setCtx(ctx, 'textBaseline', 'middle'); // Always set shadowBlur and shadowOffset to avoid leak from displayable. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0); setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent'); setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0); setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0); // `textBaseline` is set as 'middle'. textY += lineHeight / 2; var textStrokeWidth = style.textStrokeWidth; var textStroke = getStroke(style.textStroke, textStrokeWidth); var textFill = getFill(style.textFill); if (textStroke) { setCtx(ctx, 'lineWidth', textStrokeWidth); setCtx(ctx, 'strokeStyle', textStroke); } if (textFill) { setCtx(ctx, 'fillStyle', textFill); } for (var i = 0; i < textLines.length; i++) { // Fill after stroke so the outline will not cover the main part. textStroke && ctx.strokeText(textLines[i], textX, textY); textFill && ctx.fillText(textLines[i], textX, textY); textY += lineHeight; } } function renderRichText(hostEl, ctx, text, style, rect) { var contentBlock = hostEl.__textCotentBlock; if (!contentBlock || hostEl.__dirty) { contentBlock = hostEl.__textCotentBlock = textContain.parseRichText(text, style); } drawRichText(hostEl, ctx, contentBlock, style, rect); } function drawRichText(hostEl, ctx, contentBlock, style, rect) { var contentWidth = contentBlock.width; var outerWidth = contentBlock.outerWidth; var outerHeight = contentBlock.outerHeight; var textPadding = style.textPadding; var boxPos = getBoxPosition(outerHeight, style, rect); var baseX = boxPos.baseX; var baseY = boxPos.baseY; var textAlign = boxPos.textAlign; var textVerticalAlign = boxPos.textVerticalAlign; // Origin of textRotation should be the base point of text drawing. applyTextRotation(ctx, style, rect, baseX, baseY); var boxX = textContain.adjustTextX(baseX, outerWidth, textAlign); var boxY = textContain.adjustTextY(baseY, outerHeight, textVerticalAlign); var xLeft = boxX; var lineTop = boxY; if (textPadding) { xLeft += textPadding[3]; lineTop += textPadding[0]; } var xRight = xLeft + contentWidth; needDrawBackground(style) && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight); for (var i = 0; i < contentBlock.lines.length; i++) { var line = contentBlock.lines[i]; var tokens = line.tokens; var tokenCount = tokens.length; var lineHeight = line.lineHeight; var usedWidth = line.width; var leftIndex = 0; var lineXLeft = xLeft; var lineXRight = xRight; var rightIndex = tokenCount - 1; var token; while (leftIndex < tokenCount && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')) { placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left'); usedWidth -= token.width; lineXLeft += token.width; leftIndex++; } while (rightIndex >= 0 && (token = tokens[rightIndex], token.textAlign === 'right')) { placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right'); usedWidth -= token.width; lineXRight -= token.width; rightIndex--; } // The other tokens are placed as textAlign 'center' if there is enough space. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2; while (leftIndex <= rightIndex) { token = tokens[leftIndex]; // Consider width specified by user, use 'center' rather than 'left'. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center'); lineXLeft += token.width; leftIndex++; } lineTop += lineHeight; } } function applyTextRotation(ctx, style, rect, x, y) { // textRotation only apply in RectText. if (rect && style.textRotation) { var origin = style.textOrigin; if (origin === 'center') { x = rect.width / 2 + rect.x; y = rect.height / 2 + rect.y; } else if (origin) { x = origin[0] + rect.x; y = origin[1] + rect.y; } ctx.translate(x, y); // Positive: anticlockwise ctx.rotate(-style.textRotation); ctx.translate(-x, -y); } } function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) { var tokenStyle = style.rich[token.styleName] || {}; // 'ctx.textBaseline' is always set as 'middle', for sake of // the bias of "Microsoft YaHei". var textVerticalAlign = token.textVerticalAlign; var y = lineTop + lineHeight / 2; if (textVerticalAlign === 'top') { y = lineTop + token.height / 2; } else if (textVerticalAlign === 'bottom') { y = lineTop + lineHeight - token.height / 2; } !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(hostEl, ctx, tokenStyle, textAlign === 'right' ? x - token.width : textAlign === 'center' ? x - token.width / 2 : x, y - token.height / 2, token.width, token.height); var textPadding = token.textPadding; if (textPadding) { x = getTextXForPadding(x, textAlign, textPadding); y -= token.height / 2 - textPadding[2] - token.textHeight / 2; } setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0)); setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent'); setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0)); setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0)); setCtx(ctx, 'textAlign', textAlign); // Force baseline to be "middle". Otherwise, if using "top", the // text will offset downward a little bit in font "Microsoft YaHei". setCtx(ctx, 'textBaseline', 'middle'); setCtx(ctx, 'font', token.font || textContain.DEFAULT_FONT); var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth); var textFill = getFill(tokenStyle.textFill || style.textFill); var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth); // Fill after stroke so the outline will not cover the main part. if (textStroke) { setCtx(ctx, 'lineWidth', textStrokeWidth); setCtx(ctx, 'strokeStyle', textStroke); ctx.strokeText(token.text, x, y); } if (textFill) { setCtx(ctx, 'fillStyle', textFill); ctx.fillText(token.text, x, y); } } function needDrawBackground(style) { return style.textBackgroundColor || style.textBorderWidth && style.textBorderColor; } // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius} // shape: {x, y, width, height} function drawBackground(hostEl, ctx, style, x, y, width, height) { var textBackgroundColor = style.textBackgroundColor; var textBorderWidth = style.textBorderWidth; var textBorderColor = style.textBorderColor; var isPlainBg = isString(textBackgroundColor); setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0); setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent'); setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0); setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0); if (isPlainBg || textBorderWidth && textBorderColor) { ctx.beginPath(); var textBorderRadius = style.textBorderRadius; if (!textBorderRadius) { ctx.rect(x, y, width, height); } else { roundRectHelper.buildPath(ctx, { x: x, y: y, width: width, height: height, r: textBorderRadius }); } ctx.closePath(); } if (isPlainBg) { setCtx(ctx, 'fillStyle', textBackgroundColor); ctx.fill(); } else if (isObject(textBackgroundColor)) { var image = textBackgroundColor.image; image = imageHelper.createOrUpdateImage(image, null, hostEl, onBgImageLoaded, textBackgroundColor); if (image && imageHelper.isImageReady(image)) { ctx.drawImage(image, x, y, width, height); } } if (textBorderWidth && textBorderColor) { setCtx(ctx, 'lineWidth', textBorderWidth); setCtx(ctx, 'strokeStyle', textBorderColor); ctx.stroke(); } } function onBgImageLoaded(image, textBackgroundColor) { // Replace image, so that `contain/text.js#parseRichText` // will get correct result in next tick. textBackgroundColor.image = image; } function getBoxPosition(blockHeiht, style, rect) { var baseX = style.x || 0; var baseY = style.y || 0; var textAlign = style.textAlign; var textVerticalAlign = style.textVerticalAlign; // Text position represented by coord if (rect) { var textPosition = style.textPosition; if (textPosition instanceof Array) { // Percent baseX = rect.x + parsePercent(textPosition[0], rect.width); baseY = rect.y + parsePercent(textPosition[1], rect.height); } else { var res = textContain.adjustTextPositionOnRect(textPosition, rect, style.textDistance); baseX = res.x; baseY = res.y; // Default align and baseline when has textPosition textAlign = textAlign || res.textAlign; textVerticalAlign = textVerticalAlign || res.textVerticalAlign; } // textOffset is only support in RectText, otherwise // we have to adjust boundingRect for textOffset. var textOffset = style.textOffset; if (textOffset) { baseX += textOffset[0]; baseY += textOffset[1]; } } return { baseX: baseX, baseY: baseY, textAlign: textAlign, textVerticalAlign: textVerticalAlign }; } function setCtx(ctx, prop, value) { ctx[prop] = fixShadow(ctx, prop, value); return ctx[prop]; } /** * @param {string} [stroke] If specified, do not check style.textStroke. * @param {string} [lineWidth] If specified, do not check style.textStroke. * @param {number} style */ function getStroke(stroke, lineWidth) { return stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none' ? null // TODO pattern and gradient? : stroke.image || stroke.colorStops ? '#000' : stroke; } function getFill(fill) { return fill == null || fill === 'none' ? null // TODO pattern and gradient? : fill.image || fill.colorStops ? '#000' : fill; } function parsePercent(value, maxValue) { if (typeof value === 'string') { if (value.lastIndexOf('%') >= 0) { return parseFloat(value) / 100 * maxValue; } return parseFloat(value); } return value; } function getTextXForPadding(x, textAlign, textPadding) { return textAlign === 'right' ? x - textPadding[1] : textAlign === 'center' ? x + textPadding[3] / 2 - textPadding[1] / 2 : x + textPadding[3]; } /** * @param {string} text * @param {module:zrender/Style} style * @return {boolean} */ function needDrawText(text, style) { return text != null && (text || style.textBackgroundColor || style.textBorderWidth && style.textBorderColor || style.textPadding); } exports.normalizeTextStyle = normalizeTextStyle; exports.renderText = renderText; exports.getStroke = getStroke; exports.getFill = getFill; exports.needDrawText = needDrawText; /***/ }, /* 38 */ /*!*************************************************!*\ !*** ./~/echarts/~/zrender/lib/contain/text.js ***! \*************************************************/ /***/ function(module, exports, __webpack_require__) { var BoundingRect = __webpack_require__(/*! ../core/BoundingRect */ 39); var imageHelper = __webpack_require__(/*! ../graphic/helper/image */ 40); var _util = __webpack_require__(/*! ../core/util */ 5); var getContext = _util.getContext; var extend = _util.extend; var retrieve2 = _util.retrieve2; var retrieve3 = _util.retrieve3; var trim = _util.trim; var textWidthCache = {}; var textWidthCacheCounter = 0; var TEXT_CACHE_MAX = 5000; var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g; var DEFAULT_FONT = '12px sans-serif'; // Avoid assign to an exported variable, for transforming to cjs. var methods = {}; function $override(name, fn) { methods[name] = fn; } /** * @public * @param {string} text * @param {string} font * @return {number} width */ function getWidth(text, font) { font = font || DEFAULT_FONT; var key = text + ':' + font; if (textWidthCache[key]) { return textWidthCache[key]; } var textLines = (text + '').split('\n'); var width = 0; for (var i = 0, l = textLines.length; i < l; i++) { // textContain.measureText may be overrided in SVG or VML width = Math.max(measureText(textLines[i], font).width, width); } if (textWidthCacheCounter > TEXT_CACHE_MAX) { textWidthCacheCounter = 0; textWidthCache = {}; } textWidthCacheCounter++; textWidthCache[key] = width; return width; } /** * @public * @param {string} text * @param {string} font * @param {string} [textAlign='left'] * @param {string} [textVerticalAlign='top'] * @param {Array.<number>} [textPadding] * @param {Object} [rich] * @param {Object} [truncate] * @return {Object} {x, y, width, height, lineHeight} */ function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) { return rich ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate); } function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) { var contentBlock = parsePlainText(text, font, textPadding, truncate); var outerWidth = getWidth(text, font); if (textPadding) { outerWidth += textPadding[1] + textPadding[3]; } var outerHeight = contentBlock.outerHeight; var x = adjustTextX(0, outerWidth, textAlign); var y = adjustTextY(0, outerHeight, textVerticalAlign); var rect = new BoundingRect(x, y, outerWidth, outerHeight); rect.lineHeight = contentBlock.lineHeight; return rect; } function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) { var contentBlock = parseRichText(text, { rich: rich, truncate: truncate, font: font, textAlign: textAlign, textPadding: textPadding }); var outerWidth = contentBlock.outerWidth; var outerHeight = contentBlock.outerHeight; var x = adjustTextX(0, outerWidth, textAlign); var y = adjustTextY(0, outerHeight, textVerticalAlign); return new BoundingRect(x, y, outerWidth, outerHeight); } /** * @public * @param {number} x * @param {number} width * @param {string} [textAlign='left'] * @return {number} Adjusted x. */ function adjustTextX(x, width, textAlign) { // FIXME Right to left language if (textAlign === 'right') { x -= width; } else if (textAlign === 'center') { x -= width / 2; } return x; } /** * @public * @param {number} y * @param {number} height * @param {string} [textVerticalAlign='top'] * @return {number} Adjusted y. */ function adjustTextY(y, height, textVerticalAlign) { if (textVerticalAlign === 'middle') { y -= height / 2; } else if (textVerticalAlign === 'bottom') { y -= height; } return y; } /** * @public * @param {stirng} textPosition * @param {Object} rect {x, y, width, height} * @param {number} distance * @return {Object} {x, y, textAlign, textVerticalAlign} */ function adjustTextPositionOnRect(textPosition, rect, distance) { var x = rect.x; var y = rect.y; var height = rect.height; var width = rect.width; var halfHeight = height / 2; var textAlign = 'left'; var textVerticalAlign = 'top'; switch (textPosition) { case 'left': x -= distance; y += halfHeight; textAlign = 'right'; textVerticalAlign = 'middle'; break; case 'right': x += distance + width; y += halfHeight; textVerticalAlign = 'middle'; break; case 'top': x += width / 2; y -= distance; textAlign = 'center'; textVerticalAlign = 'bottom'; break; case 'bottom': x += width / 2; y += height + distance; textAlign = 'center'; break; case 'inside': x += width / 2; y += halfHeight; textAlign = 'center'; textVerticalAlign = 'middle'; break; case 'insideLeft': x += distance; y += halfHeight; textVerticalAlign = 'middle'; break; case 'insideRight': x += width - distance; y += halfHeight; textAlign = 'right'; textVerticalAlign = 'middle'; break; case 'insideTop': x += width / 2; y += distance; textAlign = 'center'; break; case 'insideBottom': x += width / 2; y += height - distance; textAlign = 'center'; textVerticalAlign = 'bottom'; break; case 'insideTopLeft': x += distance; y += distance; break; case 'insideTopRight': x += width - distance; y += distance; textAlign = 'right'; break; case 'insideBottomLeft': x += distance; y += height - distance; textVerticalAlign = 'bottom'; break; case 'insideBottomRight': x += width - distance; y += height - distance; textAlign = 'right'; textVerticalAlign = 'bottom'; break; } return { x: x, y: y, textAlign: textAlign, textVerticalAlign: textVerticalAlign }; } /** * Show ellipsis if overflow. * * @public * @param {string} text * @param {string} containerWidth * @param {string} font * @param {number} [ellipsis='...'] * @param {Object} [options] * @param {number} [options.maxIterations=3] * @param {number} [options.minChar=0] If truncate result are less * then minChar, ellipsis will not show, which is * better for user hint in some cases. * @param {number} [options.placeholder=''] When all truncated, use the placeholder. * @return {string} */ function truncateText(text, containerWidth, font, ellipsis, options) { if (!containerWidth) { return ''; } var textLines = (text + '').split('\n'); options = prepareTruncateOptions(containerWidth, font, ellipsis, options); // FIXME // It is not appropriate that every line has '...' when truncate multiple lines. for (var i = 0, len = textLines.length; i < len; i++) { textLines[i] = truncateSingleLine(textLines[i], options); } return textLines.join('\n'); } function prepareTruncateOptions(containerWidth, font, ellipsis, options) { options = extend({}, options); options.font = font; var ellipsis = retrieve2(ellipsis, '...'); options.maxIterations = retrieve2(options.maxIterations, 2); var minChar = options.minChar = retrieve2(options.minChar, 0); // FIXME // Other languages? options.cnCharWidth = getWidth('国', font); // FIXME // Consider proportional font? var ascCharWidth = options.ascCharWidth = getWidth('a', font); options.placeholder = retrieve2(options.placeholder, ''); // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) { contentWidth -= ascCharWidth; } var ellipsisWidth = getWidth(ellipsis); if (ellipsisWidth > contentWidth) { ellipsis = ''; ellipsisWidth = 0; } contentWidth = containerWidth - ellipsisWidth; options.ellipsis = ellipsis; options.ellipsisWidth = ellipsisWidth; options.contentWidth = contentWidth; options.containerWidth = containerWidth; return options; } function truncateSingleLine(textLine, options) { var containerWidth = options.containerWidth; var font = options.font; var contentWidth = options.contentWidth; if (!containerWidth) { return ''; } var lineWidth = getWidth(textLine, font); if (lineWidth <= containerWidth) { return textLine; } for (var j = 0;; j++) { if (lineWidth <= contentWidth || j >= options.maxIterations) { textLine += options.ellipsis; break; } var subLength = j === 0 ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth) : lineWidth > 0 ? Math.floor(textLine.length * contentWidth / lineWidth) : 0; textLine = textLine.substr(0, subLength); lineWidth = getWidth(textLine, font); } if (textLine === '') { textLine = options.placeholder; } return textLine; } function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) { var width = 0; var i = 0; for (var len = text.length; i < len && width < contentWidth; i++) { var charCode = text.charCodeAt(i); width += 0 <= charCode && charCode <= 127 ? ascCharWidth : cnCharWidth; } return i; } /** * @public * @param {string} font * @return {number} line height */ function getLineHeight(font) { // FIXME A rough approach. return getWidth('国', font); } /** * @public * @param {string} text * @param {string} font * @return {Object} width */ function measureText(text, font) { return methods.measureText(text, font); } // Avoid assign to an exported variable, for transforming to cjs. methods.measureText = function (text, font) { var ctx = getContext(); ctx.font = font || DEFAULT_FONT; return ctx.measureText(text); }; /** * @public * @param {string} text * @param {string} font * @param {Object} [truncate] * @return {Object} block: {lineHeight, lines, height, outerHeight} * Notice: for performance, do not calculate outerWidth util needed. */ function parsePlainText(text, font, padding, truncate) { text != null && (text += ''); var lineHeight = getLineHeight(font); var lines = text ? text.split('\n') : []; var height = lines.length * lineHeight; var outerHeight = height; if (padding) { outerHeight += padding[0] + padding[2]; } if (text && truncate) { var truncOuterHeight = truncate.outerHeight; var truncOuterWidth = truncate.outerWidth; if (truncOuterHeight != null && outerHeight > truncOuterHeight) { text = ''; lines = []; } else if (truncOuterWidth != null) { var options = prepareTruncateOptions(truncOuterWidth - (padding ? padding[1] + padding[3] : 0), font, truncate.ellipsis, { minChar: truncate.minChar, placeholder: truncate.placeholder }); // FIXME // It is not appropriate that every line has '...' when truncate multiple lines. for (var i = 0, len = lines.length; i < len; i++) { lines[i] = truncateSingleLine(lines[i], options); } } } return { lines: lines, height: height, outerHeight: outerHeight, lineHeight: lineHeight }; } /** * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx' * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'. * * @public * @param {string} text * @param {Object} style * @return {Object} block * { * width, * height, * lines: [{ * lineHeight, * width, * tokens: [[{ * styleName, * text, * width, // include textPadding * height, // include textPadding * textWidth, // pure text width * textHeight, // pure text height * lineHeihgt, * font, * textAlign, * textVerticalAlign * }], [...], ...] * }, ...] * } * If styleName is undefined, it is plain text. */ function parseRichText(text, style) { var contentBlock = { lines: [], width: 0, height: 0 }; text != null && (text += ''); if (!text) { return contentBlock; } var lastIndex = STYLE_REG.lastIndex = 0; var result; while ((result = STYLE_REG.exec(text)) != null) { var matchedIndex = result.index; if (matchedIndex > lastIndex) { pushTokens(contentBlock, text.substring(lastIndex, matchedIndex)); } pushTokens(contentBlock, result[2], result[1]); lastIndex = STYLE_REG.lastIndex; } if (lastIndex < text.length) { pushTokens(contentBlock, text.substring(lastIndex, text.length)); } var lines = contentBlock.lines; var contentHeight = 0; var contentWidth = 0; // For `textWidth: 100%` var pendingList = []; var stlPadding = style.textPadding; var truncate = style.truncate; var truncateWidth = truncate && truncate.outerWidth; var truncateHeight = truncate && truncate.outerHeight; if (stlPadding) { truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]); truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]); } // Calculate layout info of tokens. for (var i = 0; i < lines.length; i++) { var line = lines[i]; var lineHeight = 0; var lineWidth = 0; for (var j = 0; j < line.tokens.length; j++) { var token = line.tokens[j]; var tokenStyle = token.styleName && style.rich[token.styleName] || {}; // textPadding should not inherit from style. var textPadding = token.textPadding = tokenStyle.textPadding; // textFont has been asigned to font by `normalizeStyle`. var font = token.font = tokenStyle.font || style.font; // textHeight can be used when textVerticalAlign is specified in token. var tokenHeight = token.textHeight = retrieve2( // textHeight should not be inherited, consider it can be specified // as box height of the block. tokenStyle.textHeight, getLineHeight(font)); textPadding && (tokenHeight += textPadding[0] + textPadding[2]); token.height = tokenHeight; token.lineHeight = retrieve3(tokenStyle.textLineHeight, style.textLineHeight, tokenHeight); token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign; token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle'; if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) { return { lines: [], width: 0, height: 0 }; } token.textWidth = getWidth(token.text, font); var tokenWidth = tokenStyle.textWidth; var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto'; // Percent width, can be `100%`, can be used in drawing separate // line when box width is needed to be auto. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') { token.percentWidth = tokenWidth; pendingList.push(token); tokenWidth = 0; // Do not truncate in this case, because there is no user case // and it is too complicated. } else { if (tokenWidthNotSpecified) { tokenWidth = token.textWidth; // FIXME: If image is not loaded and textWidth is not specified, calling // `getBoundingRect()` will not get correct result. var textBackgroundColor = tokenStyle.textBackgroundColor; var bgImg = textBackgroundColor && textBackgroundColor.image; // Use cases: // (1) If image is not loaded, it will be loaded at render phase and call // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded // image, and then the right size will be calculated here at the next tick. // See `graphic/helper/text.js`. // (2) If image loaded, and `textBackgroundColor.image` is image src string, // use `imageHelper.findExistImage` to find cached image. // `imageHelper.findExistImage` will always be called here before // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText` // which ensures that image will not be rendered before correct size calcualted. if (bgImg) { bgImg = imageHelper.findExistImage(bgImg); if (imageHelper.isImageReady(bgImg)) { tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height); } } } var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0; tokenWidth += paddingW; var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null; if (remianTruncWidth != null && remianTruncWidth < tokenWidth) { if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) { token.text = ''; token.textWidth = tokenWidth = 0; } else { token.text = truncateText(token.text, remianTruncWidth - paddingW, font, truncate.ellipsis, { minChar: truncate.minChar }); token.textWidth = getWidth(token.text, font); tokenWidth = token.textWidth + paddingW; } } } lineWidth += token.width = tokenWidth; tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight)); } line.width = lineWidth; line.lineHeight = lineHeight; contentHeight += lineHeight; contentWidth = Math.max(contentWidth, lineWidth); } contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth); contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight); if (stlPadding) { contentBlock.outerWidth += stlPadding[1] + stlPadding[3]; contentBlock.outerHeight += stlPadding[0] + stlPadding[2]; } for (var i = 0; i < pendingList.length; i++) { var token = pendingList[i]; var percentWidth = token.percentWidth; // Should not base on outerWidth, because token can not be placed out of padding. token.width = parseInt(percentWidth, 10) / 100 * contentWidth; } return contentBlock; } function pushTokens(block, str, styleName) { var isEmptyStr = str === ''; var strs = str.split('\n'); var lines = block.lines; for (var i = 0; i < strs.length; i++) { var text = strs[i]; var token = { styleName: styleName, text: text, isLineHolder: !text && !isEmptyStr }; // The first token should be appended to the last line. if (!i) { var tokens = (lines[lines.length - 1] || (lines[0] = { tokens: [] })).tokens; // Consider cases: // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item // (which is a placeholder) should be replaced by new token. // (2) A image backage, where token likes {a|}. // (3) A redundant '' will affect textAlign in line. // (4) tokens with the same tplName should not be merged, because // they should be displayed in different box (with border and padding). var tokensLen = tokens.length; tokensLen === 1 && tokens[0].isLineHolder ? tokens[0] = token : // Consider text is '', only insert when it is the "lineHolder" or // "emptyStr". Otherwise a redundant '' will affect textAlign in line. (text || !tokensLen || isEmptyStr) && tokens.push(token); } // Other tokens always start a new line. else { // If there is '', insert it as a placeholder. lines.push({ tokens: [token] }); } } } function makeFont(style) { // FIXME in node-canvas fontWeight is before fontStyle // Use `fontSize` `fontFamily` to check whether font properties are defined. var font = (style.fontSize || style.fontFamily) && [style.fontStyle, style.fontWeight, (style.fontSize || 12) + 'px', // If font properties are defined, `fontFamily` should not be ignored. style.fontFamily || 'sans-serif'].join(' '); return font && trim(font) || style.textFont || style.font; } exports.DEFAULT_FONT = DEFAULT_FONT; exports.$override = $override; exports.getWidth = getWidth; exports.getBoundingRect = getBoundingRect; exports.adjustTextX = adjustTextX; exports.adjustTextY = adjustTextY; exports.adjustTextPositionOnRect = adjustTextPositionOnRect; exports.truncateText = truncateText; exports.getLineHeight = getLineHeight; exports.measureText = measureText; exports.parsePlainText = parsePlainText; exports.parseRichText = parseRichText; exports.makeFont = makeFont; /***/ }, /* 39 */ /*!******************************************************!*\ !*** ./~/echarts/~/zrender/lib/core/BoundingRect.js ***! \******************************************************/ /***/ function(module, exports, __webpack_require__) { var vec2 = __webpack_require__(/*! ./vector */ 27); var matrix = __webpack_require__(/*! ./matrix */ 26); /** * @module echarts/core/BoundingRect */ var v2ApplyTransform = vec2.applyTransform; var mathMin = Math.min; var mathMax = Math.max; /** * @alias module:echarts/core/BoundingRect */ function BoundingRect(x, y, width, height) { if (width < 0) { x = x + width; width = -width; } if (height < 0) { y = y + height; height = -height; } /** * @type {number} */ this.x = x; /** * @type {number} */ this.y = y; /** * @type {number} */ this.width = width; /** * @type {number} */ this.height = height; } BoundingRect.prototype = { constructor: BoundingRect, /** * @param {module:echarts/core/BoundingRect} other */ union: function (other) { var x = mathMin(other.x, this.x); var y = mathMin(other.y, this.y); this.width = mathMax(other.x + other.width, this.x + this.width) - x; this.height = mathMax(other.y + other.height, this.y + this.height) - y; this.x = x; this.y = y; }, /** * @param {Array.<number>} m * @methods */ applyTransform: function () { var lt = []; var rb = []; var lb = []; var rt = []; return function (m) { // In case usage like this // el.getBoundingRect().applyTransform(el.transform) // And element has no transform if (!m) { return; } lt[0] = lb[0] = this.x; lt[1] = rt[1] = this.y; rb[0] = rt[0] = this.x + this.width; rb[1] = lb[1] = this.y + this.height; v2ApplyTransform(lt, lt, m); v2ApplyTransform(rb, rb, m); v2ApplyTransform(lb, lb, m); v2ApplyTransform(rt, rt, m); this.x = mathMin(lt[0], rb[0], lb[0], rt[0]); this.y = mathMin(lt[1], rb[1], lb[1], rt[1]); var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]); var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]); this.width = maxX - this.x; this.height = maxY - this.y; }; }(), /** * Calculate matrix of transforming from self to target rect * @param {module:zrender/core/BoundingRect} b * @return {Array.<number>} */ calculateTransform: function (b) { var a = this; var sx = b.width / a.width; var sy = b.height / a.height; var m = matrix.create(); // 矩阵右乘 matrix.translate(m, m, [-a.x, -a.y]); matrix.scale(m, m, [sx, sy]); matrix.translate(m, m, [b.x, b.y]); return m; }, /** * @param {(module:echarts/core/BoundingRect|Object)} b * @return {boolean} */ intersect: function (b) { if (!b) { return false; } if (!(b instanceof BoundingRect)) { // Normalize negative width/height. b = BoundingRect.create(b); } var a = this; var ax0 = a.x; var ax1 = a.x + a.width; var ay0 = a.y; var ay1 = a.y + a.height; var bx0 = b.x; var bx1 = b.x + b.width; var by0 = b.y; var by1 = b.y + b.height; return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0); }, contain: function (x, y) { var rect = this; return x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height; }, /** * @return {module:echarts/core/BoundingRect} */ clone: function () { return new BoundingRect(this.x, this.y, this.width, this.height); }, /** * Copy from another rect */ copy: function (other) { this.x = other.x; this.y = other.y; this.width = other.width; this.height = other.height; }, plain: function () { return { x: this.x, y: this.y, width: this.width, height: this.height }; } }; /** * @param {Object|module:zrender/core/BoundingRect} rect * @param {number} rect.x * @param {number} rect.y * @param {number} rect.width * @param {number} rect.height * @return {module:zrender/core/BoundingRect} */ BoundingRect.create = function (rect) { return new BoundingRect(rect.x, rect.y, rect.width, rect.height); }; var _default = BoundingRect; module.exports = _default; /***/ }, /* 40 */ /*!*********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/helper/image.js ***! \*********************************************************/ /***/ function(module, exports, __webpack_require__) { var LRU = __webpack_require__(/*! ../../core/LRU */ 33); var globalImageCache = new LRU(50); /** * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image */ function findExistImage(newImageOrSrc) { if (typeof newImageOrSrc === 'string') { var cachedImgObj = globalImageCache.get(newImageOrSrc); return cachedImgObj && cachedImgObj.image; } else { return newImageOrSrc; } } /** * Caution: User should cache loaded images, but not just count on LRU. * Consider if required images more than LRU size, will dead loop occur? * * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image. * @param {module:zrender/Element} [hostEl] For calling `dirty`. * @param {Function} [cb] params: (image, cbPayload) * @param {Object} [cbPayload] Payload on cb calling. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image */ function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) { if (!newImageOrSrc) { return image; } else if (typeof newImageOrSrc === 'string') { // Image should not be loaded repeatly. if (image && image.__zrImageSrc === newImageOrSrc || !hostEl) { return image; } // Only when there is no existent image or existent image src // is different, this method is responsible for load. var cachedImgObj = globalImageCache.get(newImageOrSrc); var pendingWrap = { hostEl: hostEl, cb: cb, cbPayload: cbPayload }; if (cachedImgObj) { image = cachedImgObj.image; !isImageReady(image) && cachedImgObj.pending.push(pendingWrap); } else { !image && (image = new Image()); image.onload = imageOnLoad; globalImageCache.put(newImageOrSrc, image.__cachedImgObj = { image: image, pending: [pendingWrap] }); image.src = image.__zrImageSrc = newImageOrSrc; } return image; } // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas else { return newImageOrSrc; } } function imageOnLoad() { var cachedImgObj = this.__cachedImgObj; this.onload = this.__cachedImgObj = null; for (var i = 0; i < cachedImgObj.pending.length; i++) { var pendingWrap = cachedImgObj.pending[i]; var cb = pendingWrap.cb; cb && cb(this, pendingWrap.cbPayload); pendingWrap.hostEl.dirty(); } cachedImgObj.pending.length = 0; } function isImageReady(image) { return image && image.width && image.height; } exports.findExistImage = findExistImage; exports.createOrUpdateImage = createOrUpdateImage; exports.isImageReady = isImageReady; /***/ }, /* 41 */ /*!*************************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/helper/roundRect.js ***! \*************************************************************/ /***/ function(module, exports) { function buildPath(ctx, shape) { var x = shape.x; var y = shape.y; var width = shape.width; var height = shape.height; var r = shape.r; var r1; var r2; var r3; var r4; // Convert width and height to positive for better borderRadius if (width < 0) { x = x + width; width = -width; } if (height < 0) { y = y + height; height = -height; } if (typeof r === 'number') { r1 = r2 = r3 = r4 = r; } else if (r instanceof Array) { if (r.length === 1) { r1 = r2 = r3 = r4 = r[0]; } else if (r.length === 2) { r1 = r3 = r[0]; r2 = r4 = r[1]; } else if (r.length === 3) { r1 = r[0]; r2 = r4 = r[1]; r3 = r[2]; } else { r1 = r[0]; r2 = r[1]; r3 = r[2]; r4 = r[3]; } } else { r1 = r2 = r3 = r4 = 0; } var total; if (r1 + r2 > width) { total = r1 + r2; r1 *= width / total; r2 *= width / total; } if (r3 + r4 > width) { total = r3 + r4; r3 *= width / total; r4 *= width / total; } if (r2 + r3 > height) { total = r2 + r3; r2 *= height / total; r3 *= height / total; } if (r1 + r4 > height) { total = r1 + r4; r1 *= height / total; r4 *= height / total; } ctx.moveTo(x + r1, y); ctx.lineTo(x + width - r2, y); r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0); ctx.lineTo(x + width, y + height - r3); r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2); ctx.lineTo(x + r4, y + height); r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI); ctx.lineTo(x, y + r1); r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5); } exports.buildPath = buildPath; /***/ }, /* 42 */ /*!***************************************************!*\ !*** ./~/echarts/~/zrender/lib/core/PathProxy.js ***! \***************************************************/ /***/ function(module, exports, __webpack_require__) { var curve = __webpack_require__(/*! ./curve */ 43); var vec2 = __webpack_require__(/*! ./vector */ 27); var bbox = __webpack_require__(/*! ./bbox */ 44); var BoundingRect = __webpack_require__(/*! ./BoundingRect */ 39); var _config = __webpack_require__(/*! ../config */ 35); var dpr = _config.devicePixelRatio; /** * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中 * 可以用于 isInsidePath 判断以及获取boundingRect * * @module zrender/core/PathProxy * @author Yi Shen (http://www.github.com/pissang) */ // TODO getTotalLength, getPointAtLength var CMD = { M: 1, L: 2, C: 3, Q: 4, A: 5, Z: 6, // Rect R: 7 }; // var CMD_MEM_SIZE = { // M: 3, // L: 3, // C: 7, // Q: 5, // A: 9, // R: 5, // Z: 1 // }; var min = []; var max = []; var min2 = []; var max2 = []; var mathMin = Math.min; var mathMax = Math.max; var mathCos = Math.cos; var mathSin = Math.sin; var mathSqrt = Math.sqrt; var mathAbs = Math.abs; var hasTypedArray = typeof Float32Array != 'undefined'; /** * @alias module:zrender/core/PathProxy * @constructor */ var PathProxy = function (notSaveData) { this._saveData = !(notSaveData || false); if (this._saveData) { /** * Path data. Stored as flat array * @type {Array.<Object>} */ this.data = []; } this._ctx = null; }; /** * 快速计算Path包围盒(并不是最小包围盒) * @return {Object} */ PathProxy.prototype = { constructor: PathProxy, _xi: 0, _yi: 0, _x0: 0, _y0: 0, // Unit x, Unit y. Provide for avoiding drawing that too short line segment _ux: 0, _uy: 0, _len: 0, _lineDash: null, _dashOffset: 0, _dashIdx: 0, _dashSum: 0, /** * @readOnly */ setScale: function (sx, sy) { this._ux = mathAbs(1 / dpr / sx) || 0; this._uy = mathAbs(1 / dpr / sy) || 0; }, getContext: function () { return this._ctx; }, /** * @param {CanvasRenderingContext2D} ctx * @return {module:zrender/core/PathProxy} */ beginPath: function (ctx) { this._ctx = ctx; ctx && ctx.beginPath(); ctx && (this.dpr = ctx.dpr); // Reset if (this._saveData) { this._len = 0; } if (this._lineDash) { this._lineDash = null; this._dashOffset = 0; } return this; }, /** * @param {number} x * @param {number} y * @return {module:zrender/core/PathProxy} */ moveTo: function (x, y) { this.addData(CMD.M, x, y); this._ctx && this._ctx.moveTo(x, y); // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用 // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。 // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要 // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持 this._x0 = x; this._y0 = y; this._xi = x; this._yi = y; return this; }, /** * @param {number} x * @param {number} y * @return {module:zrender/core/PathProxy} */ lineTo: function (x, y) { var exceedUnit = mathAbs(x - this._xi) > this._ux || mathAbs(y - this._yi) > this._uy // Force draw the first segment || this._len < 5; this.addData(CMD.L, x, y); if (this._ctx && exceedUnit) { this._needsDash() ? this._dashedLineTo(x, y) : this._ctx.lineTo(x, y); } if (exceedUnit) { this._xi = x; this._yi = y; } return this; }, /** * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @return {module:zrender/core/PathProxy} */ bezierCurveTo: function (x1, y1, x2, y2, x3, y3) { this.addData(CMD.C, x1, y1, x2, y2, x3, y3); if (this._ctx) { this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3) : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3); } this._xi = x3; this._yi = y3; return this; }, /** * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @return {module:zrender/core/PathProxy} */ quadraticCurveTo: function (x1, y1, x2, y2) { this.addData(CMD.Q, x1, y1, x2, y2); if (this._ctx) { this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2) : this._ctx.quadraticCurveTo(x1, y1, x2, y2); } this._xi = x2; this._yi = y2; return this; }, /** * @param {number} cx * @param {number} cy * @param {number} r * @param {number} startAngle * @param {number} endAngle * @param {boolean} anticlockwise * @return {module:zrender/core/PathProxy} */ arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) { this.addData(CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1); this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise); this._xi = mathCos(endAngle) * r + cx; this._yi = mathSin(endAngle) * r + cx; return this; }, // TODO arcTo: function (x1, y1, x2, y2, radius) { if (this._ctx) { this._ctx.arcTo(x1, y1, x2, y2, radius); } return this; }, // TODO rect: function (x, y, w, h) { this._ctx && this._ctx.rect(x, y, w, h); this.addData(CMD.R, x, y, w, h); return this; }, /** * @return {module:zrender/core/PathProxy} */ closePath: function () { this.addData(CMD.Z); var ctx = this._ctx; var x0 = this._x0; var y0 = this._y0; if (ctx) { this._needsDash() && this._dashedLineTo(x0, y0); ctx.closePath(); } this._xi = x0; this._yi = y0; return this; }, /** * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。 * stroke 同样 * @param {CanvasRenderingContext2D} ctx * @return {module:zrender/core/PathProxy} */ fill: function (ctx) { ctx && ctx.fill(); this.toStatic(); }, /** * @param {CanvasRenderingContext2D} ctx * @return {module:zrender/core/PathProxy} */ stroke: function (ctx) { ctx && ctx.stroke(); this.toStatic(); }, /** * 必须在其它绘制命令前调用 * Must be invoked before all other path drawing methods * @return {module:zrender/core/PathProxy} */ setLineDash: function (lineDash) { if (lineDash instanceof Array) { this._lineDash = lineDash; this._dashIdx = 0; var lineDashSum = 0; for (var i = 0; i < lineDash.length; i++) { lineDashSum += lineDash[i]; } this._dashSum = lineDashSum; } return this; }, /** * 必须在其它绘制命令前调用 * Must be invoked before all other path drawing methods * @return {module:zrender/core/PathProxy} */ setLineDashOffset: function (offset) { this._dashOffset = offset; return this; }, /** * * @return {boolean} */ len: function () { return this._len; }, /** * 直接设置 Path 数据 */ setData: function (data) { var len = data.length; if (!(this.data && this.data.length == len) && hasTypedArray) { this.data = new Float32Array(len); } for (var i = 0; i < len; i++) { this.data[i] = data[i]; } this._len = len; }, /** * 添加子路径 * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path */ appendPath: function (path) { if (!(path instanceof Array)) { path = [path]; } var len = path.length; var appendSize = 0; var offset = this._len; for (var i = 0; i < len; i++) { appendSize += path[i].len(); } if (hasTypedArray && this.data instanceof Float32Array) { this.data = new Float32Array(offset + appendSize); } for (var i = 0; i < len; i++) { var appendPathData = path[i].data; for (var k = 0; k < appendPathData.length; k++) { this.data[offset++] = appendPathData[k]; } } this._len = offset; }, /** * 填充 Path 数据。 * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。 */ addData: function (cmd) { if (!this._saveData) { return; } var data = this.data; if (this._len + arguments.length > data.length) { // 因为之前的数组已经转换成静态的 Float32Array // 所以不够用时需要扩展一个新的动态数组 this._expandData(); data = this.data; } for (var i = 0; i < arguments.length; i++) { data[this._len++] = arguments[i]; } this._prevCmd = cmd; }, _expandData: function () { // Only if data is Float32Array if (!(this.data instanceof Array)) { var newData = []; for (var i = 0; i < this._len; i++) { newData[i] = this.data[i]; } this.data = newData; } }, /** * If needs js implemented dashed line * @return {boolean} * @private */ _needsDash: function () { return this._lineDash; }, _dashedLineTo: function (x1, y1) { var dashSum = this._dashSum; var offset = this._dashOffset; var lineDash = this._lineDash; var ctx = this._ctx; var x0 = this._xi; var y0 = this._yi; var dx = x1 - x0; var dy = y1 - y0; var dist = mathSqrt(dx * dx + dy * dy); var x = x0; var y = y0; var dash; var nDash = lineDash.length; var idx; dx /= dist; dy /= dist; if (offset < 0) { // Convert to positive offset offset = dashSum + offset; } offset %= dashSum; x -= offset * dx; y -= offset * dy; while (dx > 0 && x <= x1 || dx < 0 && x >= x1 || dx == 0 && (dy > 0 && y <= y1 || dy < 0 && y >= y1)) { idx = this._dashIdx; dash = lineDash[idx]; x += dx * dash; y += dy * dash; this._dashIdx = (idx + 1) % nDash; // Skip positive offset if (dx > 0 && x < x0 || dx < 0 && x > x0 || dy > 0 && y < y0 || dy < 0 && y > y0) { continue; } ctx[idx % 2 ? 'moveTo' : 'lineTo'](dx >= 0 ? mathMin(x, x1) : mathMax(x, x1), dy >= 0 ? mathMin(y, y1) : mathMax(y, y1)); } // Offset for next lineTo dx = x - x1; dy = y - y1; this._dashOffset = -mathSqrt(dx * dx + dy * dy); }, // Not accurate dashed line to _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) { var dashSum = this._dashSum; var offset = this._dashOffset; var lineDash = this._lineDash; var ctx = this._ctx; var x0 = this._xi; var y0 = this._yi; var t; var dx; var dy; var cubicAt = curve.cubicAt; var bezierLen = 0; var idx = this._dashIdx; var nDash = lineDash.length; var x; var y; var tmpLen = 0; if (offset < 0) { // Convert to positive offset offset = dashSum + offset; } offset %= dashSum; // Bezier approx length for (t = 0; t < 1; t += 0.1) { dx = cubicAt(x0, x1, x2, x3, t + 0.1) - cubicAt(x0, x1, x2, x3, t); dy = cubicAt(y0, y1, y2, y3, t + 0.1) - cubicAt(y0, y1, y2, y3, t); bezierLen += mathSqrt(dx * dx + dy * dy); } // Find idx after add offset for (; idx < nDash; idx++) { tmpLen += lineDash[idx]; if (tmpLen > offset) { break; } } t = (tmpLen - offset) / bezierLen; while (t <= 1) { x = cubicAt(x0, x1, x2, x3, t); y = cubicAt(y0, y1, y2, y3, t); // Use line to approximate dashed bezier // Bad result if dash is long idx % 2 ? ctx.moveTo(x, y) : ctx.lineTo(x, y); t += lineDash[idx] / bezierLen; idx = (idx + 1) % nDash; } // Finish the last segment and calculate the new offset idx % 2 !== 0 && ctx.lineTo(x3, y3); dx = x3 - x; dy = y3 - y; this._dashOffset = -mathSqrt(dx * dx + dy * dy); }, _dashedQuadraticTo: function (x1, y1, x2, y2) { // Convert quadratic to cubic using degree elevation var x3 = x2; var y3 = y2; x2 = (x2 + 2 * x1) / 3; y2 = (y2 + 2 * y1) / 3; x1 = (this._xi + 2 * x1) / 3; y1 = (this._yi + 2 * y1) / 3; this._dashedBezierTo(x1, y1, x2, y2, x3, y3); }, /** * 转成静态的 Float32Array 减少堆内存占用 * Convert dynamic array to static Float32Array */ toStatic: function () { var data = this.data; if (data instanceof Array) { data.length = this._len; if (hasTypedArray) { this.data = new Float32Array(data); } } }, /** * @return {module:zrender/core/BoundingRect} */ getBoundingRect: function () { min[0] = min[1] = min2[0] = min2[1] = Number.MAX_VALUE; max[0] = max[1] = max2[0] = max2[1] = -Number.MAX_VALUE; var data = this.data; var xi = 0; var yi = 0; var x0 = 0; var y0 = 0; for (var i = 0; i < data.length;) { var cmd = data[i++]; if (i == 1) { // 如果第一个命令是 L, C, Q // 则 previous point 同绘制命令的第一个 point // // 第一个命令为 Arc 的情况下会在后面特殊处理 xi = data[i]; yi = data[i + 1]; x0 = xi; y0 = yi; } switch (cmd) { case CMD.M: // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点 // 在 closePath 的时候使用 x0 = data[i++]; y0 = data[i++]; xi = x0; yi = y0; min2[0] = x0; min2[1] = y0; max2[0] = x0; max2[1] = y0; break; case CMD.L: bbox.fromLine(xi, yi, data[i], data[i + 1], min2, max2); xi = data[i++]; yi = data[i++]; break; case CMD.C: bbox.fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2); xi = data[i++]; yi = data[i++]; break; case CMD.Q: bbox.fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2); xi = data[i++]; yi = data[i++]; break; case CMD.A: // TODO Arc 判断的开销比较大 var cx = data[i++]; var cy = data[i++]; var rx = data[i++]; var ry = data[i++]; var startAngle = data[i++]; var endAngle = data[i++] + startAngle; // TODO Arc 旋转 var psi = data[i++]; var anticlockwise = 1 - data[i++]; if (i == 1) { // 直接使用 arc 命令 // 第一个命令起点还未定义 x0 = mathCos(startAngle) * rx + cx; y0 = mathSin(startAngle) * ry + cy; } bbox.fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2); xi = mathCos(endAngle) * rx + cx; yi = mathSin(endAngle) * ry + cy; break; case CMD.R: x0 = xi = data[i++]; y0 = yi = data[i++]; var width = data[i++]; var height = data[i++]; // Use fromLine bbox.fromLine(x0, y0, x0 + width, y0 + height, min2, max2); break; case CMD.Z: xi = x0; yi = y0; break; } // Union vec2.min(min, min, min2); vec2.max(max, max, max2); } // No data if (i === 0) { min[0] = min[1] = max[0] = max[1] = 0; } return new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]); }, /** * Rebuild path from current data * Rebuild path will not consider javascript implemented line dash. * @param {CanvasRenderingContext2D} ctx */ rebuildPath: function (ctx) { var d = this.data; var x0, y0; var xi, yi; var x, y; var ux = this._ux; var uy = this._uy; var len = this._len; for (var i = 0; i < len;) { var cmd = d[i++]; if (i == 1) { // 如果第一个命令是 L, C, Q // 则 previous point 同绘制命令的第一个 point // // 第一个命令为 Arc 的情况下会在后面特殊处理 xi = d[i]; yi = d[i + 1]; x0 = xi; y0 = yi; } switch (cmd) { case CMD.M: x0 = xi = d[i++]; y0 = yi = d[i++]; ctx.moveTo(xi, yi); break; case CMD.L: x = d[i++]; y = d[i++]; // Not draw too small seg between if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len - 1) { ctx.lineTo(x, y); xi = x; yi = y; } break; case CMD.C: ctx.bezierCurveTo(d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]); xi = d[i - 2]; yi = d[i - 1]; break; case CMD.Q: ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]); xi = d[i - 2]; yi = d[i - 1]; break; case CMD.A: var cx = d[i++]; var cy = d[i++]; var rx = d[i++]; var ry = d[i++]; var theta = d[i++]; var dTheta = d[i++]; var psi = d[i++]; var fs = d[i++]; var r = rx > ry ? rx : ry; var scaleX = rx > ry ? 1 : rx / ry; var scaleY = rx > ry ? ry / rx : 1; var isEllipse = Math.abs(rx - ry) > 1e-3; var endAngle = theta + dTheta; if (isEllipse) { ctx.translate(cx, cy); ctx.rotate(psi); ctx.scale(scaleX, scaleY); ctx.arc(0, 0, r, theta, endAngle, 1 - fs); ctx.scale(1 / scaleX, 1 / scaleY); ctx.rotate(-psi); ctx.translate(-cx, -cy); } else { ctx.arc(cx, cy, r, theta, endAngle, 1 - fs); } if (i == 1) { // 直接使用 arc 命令 // 第一个命令起点还未定义 x0 = mathCos(theta) * rx + cx; y0 = mathSin(theta) * ry + cy; } xi = mathCos(endAngle) * rx + cx; yi = mathSin(endAngle) * ry + cy; break; case CMD.R: x0 = xi = d[i]; y0 = yi = d[i + 1]; ctx.rect(d[i++], d[i++], d[i++], d[i++]); break; case CMD.Z: ctx.closePath(); xi = x0; yi = y0; } } } }; PathProxy.CMD = CMD; var _default = PathProxy; module.exports = _default; /***/ }, /* 43 */ /*!***********************************************!*\ !*** ./~/echarts/~/zrender/lib/core/curve.js ***! \***********************************************/ /***/ function(module, exports, __webpack_require__) { var _vector = __webpack_require__(/*! ./vector */ 27); var v2Create = _vector.create; var v2DistSquare = _vector.distSquare; /** * 曲线辅助模块 * @module zrender/core/curve * @author pissang(https://www.github.com/pissang) */ var mathPow = Math.pow; var mathSqrt = Math.sqrt; var EPSILON = 1e-8; var EPSILON_NUMERIC = 1e-4; var THREE_SQRT = mathSqrt(3); var ONE_THIRD = 1 / 3; // 临时变量 var _v0 = v2Create(); var _v1 = v2Create(); var _v2 = v2Create(); function isAroundZero(val) { return val > -EPSILON && val < EPSILON; } function isNotAroundZero(val) { return val > EPSILON || val < -EPSILON; } /** * 计算三次贝塞尔值 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} t * @return {number} */ function cubicAt(p0, p1, p2, p3, t) { var onet = 1 - t; return onet * onet * (onet * p0 + 3 * t * p1) + t * t * (t * p3 + 3 * onet * p2); } /** * 计算三次贝塞尔导数值 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} t * @return {number} */ function cubicDerivativeAt(p0, p1, p2, p3, t) { var onet = 1 - t; return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet + (p3 - p2) * t * t); } /** * 计算三次贝塞尔方程根,使用盛金公式 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} val * @param {Array.<number>} roots * @return {number} 有效根数目 */ function cubicRootAt(p0, p1, p2, p3, val, roots) { // Evaluate roots of cubic functions var a = p3 + 3 * (p1 - p2) - p0; var b = 3 * (p2 - p1 * 2 + p0); var c = 3 * (p1 - p0); var d = p0 - val; var A = b * b - 3 * a * c; var B = b * c - 9 * a * d; var C = c * c - 3 * b * d; var n = 0; if (isAroundZero(A) && isAroundZero(B)) { if (isAroundZero(b)) { roots[0] = 0; } else { var t1 = -c / b; //t1, t2, t3, b is not zero if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } } else { var disc = B * B - 4 * A * C; if (isAroundZero(disc)) { var K = B / A; var t1 = -b / a + K; // t1, a is not zero var t2 = -K / 2; // t2, t3 if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } if (t2 >= 0 && t2 <= 1) { roots[n++] = t2; } } else if (disc > 0) { var discSqrt = mathSqrt(disc); var Y1 = A * b + 1.5 * a * (-B + discSqrt); var Y2 = A * b + 1.5 * a * (-B - discSqrt); if (Y1 < 0) { Y1 = -mathPow(-Y1, ONE_THIRD); } else { Y1 = mathPow(Y1, ONE_THIRD); } if (Y2 < 0) { Y2 = -mathPow(-Y2, ONE_THIRD); } else { Y2 = mathPow(Y2, ONE_THIRD); } var t1 = (-b - (Y1 + Y2)) / (3 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } else { var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A)); var theta = Math.acos(T) / 3; var ASqrt = mathSqrt(A); var tmp = Math.cos(theta); var t1 = (-b - 2 * ASqrt * tmp) / (3 * a); var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a); var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } if (t2 >= 0 && t2 <= 1) { roots[n++] = t2; } if (t3 >= 0 && t3 <= 1) { roots[n++] = t3; } } } return n; } /** * 计算三次贝塞尔方程极限值的位置 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {Array.<number>} extrema * @return {number} 有效数目 */ function cubicExtrema(p0, p1, p2, p3, extrema) { var b = 6 * p2 - 12 * p1 + 6 * p0; var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2; var c = 3 * p1 - 3 * p0; var n = 0; if (isAroundZero(a)) { if (isNotAroundZero(b)) { var t1 = -c / b; if (t1 >= 0 && t1 <= 1) { extrema[n++] = t1; } } } else { var disc = b * b - 4 * a * c; if (isAroundZero(disc)) { extrema[0] = -b / (2 * a); } else if (disc > 0) { var discSqrt = mathSqrt(disc); var t1 = (-b + discSqrt) / (2 * a); var t2 = (-b - discSqrt) / (2 * a); if (t1 >= 0 && t1 <= 1) { extrema[n++] = t1; } if (t2 >= 0 && t2 <= 1) { extrema[n++] = t2; } } } return n; } /** * 细分三次贝塞尔曲线 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} t * @param {Array.<number>} out */ function cubicSubdivide(p0, p1, p2, p3, t, out) { var p01 = (p1 - p0) * t + p0; var p12 = (p2 - p1) * t + p1; var p23 = (p3 - p2) * t + p2; var p012 = (p12 - p01) * t + p01; var p123 = (p23 - p12) * t + p12; var p0123 = (p123 - p012) * t + p012; // Seg0 out[0] = p0; out[1] = p01; out[2] = p012; out[3] = p0123; // Seg1 out[4] = p0123; out[5] = p123; out[6] = p23; out[7] = p3; } /** * 投射点到三次贝塞尔曲线上,返回投射距离。 * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @param {number} x * @param {number} y * @param {Array.<number>} [out] 投射点 * @return {number} */ function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) { // http://pomax.github.io/bezierinfo/#projections var t; var interval = 0.005; var d = Infinity; var prev; var next; var d1; var d2; _v0[0] = x; _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值 // PENDING for (var _t = 0; _t < 1; _t += 0.05) { _v1[0] = cubicAt(x0, x1, x2, x3, _t); _v1[1] = cubicAt(y0, y1, y2, y3, _t); d1 = v2DistSquare(_v0, _v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; // At most 32 iteration for (var i = 0; i < 32; i++) { if (interval < EPSILON_NUMERIC) { break; } prev = t - interval; next = t + interval; // t - interval _v1[0] = cubicAt(x0, x1, x2, x3, prev); _v1[1] = cubicAt(y0, y1, y2, y3, prev); d1 = v2DistSquare(_v1, _v0); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { // t + interval _v2[0] = cubicAt(x0, x1, x2, x3, next); _v2[1] = cubicAt(y0, y1, y2, y3, next); d2 = v2DistSquare(_v2, _v0); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } // t if (out) { out[0] = cubicAt(x0, x1, x2, x3, t); out[1] = cubicAt(y0, y1, y2, y3, t); } // console.log(interval, i); return mathSqrt(d); } /** * 计算二次方贝塞尔值 * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} t * @return {number} */ function quadraticAt(p0, p1, p2, t) { var onet = 1 - t; return onet * (onet * p0 + 2 * t * p1) + t * t * p2; } /** * 计算二次方贝塞尔导数值 * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} t * @return {number} */ function quadraticDerivativeAt(p0, p1, p2, t) { return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1)); } /** * 计算二次方贝塞尔方程根 * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} t * @param {Array.<number>} roots * @return {number} 有效根数目 */ function quadraticRootAt(p0, p1, p2, val, roots) { var a = p0 - 2 * p1 + p2; var b = 2 * (p1 - p0); var c = p0 - val; var n = 0; if (isAroundZero(a)) { if (isNotAroundZero(b)) { var t1 = -c / b; if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } } else { var disc = b * b - 4 * a * c; if (isAroundZero(disc)) { var t1 = -b / (2 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } else if (disc > 0) { var discSqrt = mathSqrt(disc); var t1 = (-b + discSqrt) / (2 * a); var t2 = (-b - discSqrt) / (2 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } if (t2 >= 0 && t2 <= 1) { roots[n++] = t2; } } } return n; } /** * 计算二次贝塞尔方程极限值 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @return {number} */ function quadraticExtremum(p0, p1, p2) { var divider = p0 + p2 - 2 * p1; if (divider === 0) { // p1 is center of p0 and p2 return 0.5; } else { return (p0 - p1) / divider; } } /** * 细分二次贝塞尔曲线 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} t * @param {Array.<number>} out */ function quadraticSubdivide(p0, p1, p2, t, out) { var p01 = (p1 - p0) * t + p0; var p12 = (p2 - p1) * t + p1; var p012 = (p12 - p01) * t + p01; // Seg0 out[0] = p0; out[1] = p01; out[2] = p012; // Seg1 out[3] = p012; out[4] = p12; out[5] = p2; } /** * 投射点到二次贝塞尔曲线上,返回投射距离。 * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x * @param {number} y * @param {Array.<number>} out 投射点 * @return {number} */ function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) { // http://pomax.github.io/bezierinfo/#projections var t; var interval = 0.005; var d = Infinity; _v0[0] = x; _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值 // PENDING for (var _t = 0; _t < 1; _t += 0.05) { _v1[0] = quadraticAt(x0, x1, x2, _t); _v1[1] = quadraticAt(y0, y1, y2, _t); var d1 = v2DistSquare(_v0, _v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; // At most 32 iteration for (var i = 0; i < 32; i++) { if (interval < EPSILON_NUMERIC) { break; } var prev = t - interval; var next = t + interval; // t - interval _v1[0] = quadraticAt(x0, x1, x2, prev); _v1[1] = quadraticAt(y0, y1, y2, prev); var d1 = v2DistSquare(_v1, _v0); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { // t + interval _v2[0] = quadraticAt(x0, x1, x2, next); _v2[1] = quadraticAt(y0, y1, y2, next); var d2 = v2DistSquare(_v2, _v0); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } // t if (out) { out[0] = quadraticAt(x0, x1, x2, t); out[1] = quadraticAt(y0, y1, y2, t); } // console.log(interval, i); return mathSqrt(d); } exports.cubicAt = cubicAt; exports.cubicDerivativeAt = cubicDerivativeAt; exports.cubicRootAt = cubicRootAt; exports.cubicExtrema = cubicExtrema; exports.cubicSubdivide = cubicSubdivide; exports.cubicProjectPoint = cubicProjectPoint; exports.quadraticAt = quadraticAt; exports.quadraticDerivativeAt = quadraticDerivativeAt; exports.quadraticRootAt = quadraticRootAt; exports.quadraticExtremum = quadraticExtremum; exports.quadraticSubdivide = quadraticSubdivide; exports.quadraticProjectPoint = quadraticProjectPoint; /***/ }, /* 44 */ /*!**********************************************!*\ !*** ./~/echarts/~/zrender/lib/core/bbox.js ***! \**********************************************/ /***/ function(module, exports, __webpack_require__) { var vec2 = __webpack_require__(/*! ./vector */ 27); var curve = __webpack_require__(/*! ./curve */ 43); /** * @author Yi Shen(https://github.com/pissang) */ var mathMin = Math.min; var mathMax = Math.max; var mathSin = Math.sin; var mathCos = Math.cos; var PI2 = Math.PI * 2; var start = vec2.create(); var end = vec2.create(); var extremity = vec2.create(); /** * 从顶点数组中计算出最小包围盒,写入`min`和`max`中 * @module zrender/core/bbox * @param {Array<Object>} points 顶点数组 * @param {number} min * @param {number} max */ function fromPoints(points, min, max) { if (points.length === 0) { return; } var p = points[0]; var left = p[0]; var right = p[0]; var top = p[1]; var bottom = p[1]; var i; for (i = 1; i < points.length; i++) { p = points[i]; left = mathMin(left, p[0]); right = mathMax(right, p[0]); top = mathMin(top, p[1]); bottom = mathMax(bottom, p[1]); } min[0] = left; min[1] = top; max[0] = right; max[1] = bottom; } /** * @memberOf module:zrender/core/bbox * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {Array.<number>} min * @param {Array.<number>} max */ function fromLine(x0, y0, x1, y1, min, max) { min[0] = mathMin(x0, x1); min[1] = mathMin(y0, y1); max[0] = mathMax(x0, x1); max[1] = mathMax(y0, y1); } var xDim = []; var yDim = []; /** * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中 * @memberOf module:zrender/core/bbox * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @param {Array.<number>} min * @param {Array.<number>} max */ function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) { var cubicExtrema = curve.cubicExtrema; var cubicAt = curve.cubicAt; var i; var n = cubicExtrema(x0, x1, x2, x3, xDim); min[0] = Infinity; min[1] = Infinity; max[0] = -Infinity; max[1] = -Infinity; for (i = 0; i < n; i++) { var x = cubicAt(x0, x1, x2, x3, xDim[i]); min[0] = mathMin(x, min[0]); max[0] = mathMax(x, max[0]); } n = cubicExtrema(y0, y1, y2, y3, yDim); for (i = 0; i < n; i++) { var y = cubicAt(y0, y1, y2, y3, yDim[i]); min[1] = mathMin(y, min[1]); max[1] = mathMax(y, max[1]); } min[0] = mathMin(x0, min[0]); max[0] = mathMax(x0, max[0]); min[0] = mathMin(x3, min[0]); max[0] = mathMax(x3, max[0]); min[1] = mathMin(y0, min[1]); max[1] = mathMax(y0, max[1]); min[1] = mathMin(y3, min[1]); max[1] = mathMax(y3, max[1]); } /** * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中 * @memberOf module:zrender/core/bbox * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {Array.<number>} min * @param {Array.<number>} max */ function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) { var quadraticExtremum = curve.quadraticExtremum; var quadraticAt = curve.quadraticAt; // Find extremities, where derivative in x dim or y dim is zero var tx = mathMax(mathMin(quadraticExtremum(x0, x1, x2), 1), 0); var ty = mathMax(mathMin(quadraticExtremum(y0, y1, y2), 1), 0); var x = quadraticAt(x0, x1, x2, tx); var y = quadraticAt(y0, y1, y2, ty); min[0] = mathMin(x0, x2, x); min[1] = mathMin(y0, y2, y); max[0] = mathMax(x0, x2, x); max[1] = mathMax(y0, y2, y); } /** * 从圆弧中计算出最小包围盒,写入`min`和`max`中 * @method * @memberOf module:zrender/core/bbox * @param {number} x * @param {number} y * @param {number} rx * @param {number} ry * @param {number} startAngle * @param {number} endAngle * @param {number} anticlockwise * @param {Array.<number>} min * @param {Array.<number>} max */ function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min, max) { var vec2Min = vec2.min; var vec2Max = vec2.max; var diff = Math.abs(startAngle - endAngle); if (diff % PI2 < 1e-4 && diff > 1e-4) { // Is a circle min[0] = x - rx; min[1] = y - ry; max[0] = x + rx; max[1] = y + ry; return; } start[0] = mathCos(startAngle) * rx + x; start[1] = mathSin(startAngle) * ry + y; end[0] = mathCos(endAngle) * rx + x; end[1] = mathSin(endAngle) * ry + y; vec2Min(min, start, end); vec2Max(max, start, end); // Thresh to [0, Math.PI * 2] startAngle = startAngle % PI2; if (startAngle < 0) { startAngle = startAngle + PI2; } endAngle = endAngle % PI2; if (endAngle < 0) { endAngle = endAngle + PI2; } if (startAngle > endAngle && !anticlockwise) { endAngle += PI2; } else if (startAngle < endAngle && anticlockwise) { startAngle += PI2; } if (anticlockwise) { var tmp = endAngle; endAngle = startAngle; startAngle = tmp; } // var number = 0; // var step = (anticlockwise ? -Math.PI : Math.PI) / 2; for (var angle = 0; angle < endAngle; angle += Math.PI / 2) { if (angle > startAngle) { extremity[0] = mathCos(angle) * rx + x; extremity[1] = mathSin(angle) * ry + y; vec2Min(min, extremity, min); vec2Max(max, extremity, max); } } } exports.fromPoints = fromPoints; exports.fromLine = fromLine; exports.fromCubic = fromCubic; exports.fromQuadratic = fromQuadratic; exports.fromArc = fromArc; /***/ }, /* 45 */ /*!*************************************************!*\ !*** ./~/echarts/~/zrender/lib/contain/path.js ***! \*************************************************/ /***/ function(module, exports, __webpack_require__) { var PathProxy = __webpack_require__(/*! ../core/PathProxy */ 42); var line = __webpack_require__(/*! ./line */ 46); var cubic = __webpack_require__(/*! ./cubic */ 47); var quadratic = __webpack_require__(/*! ./quadratic */ 48); var arc = __webpack_require__(/*! ./arc */ 49); var _util = __webpack_require__(/*! ./util */ 50); var normalizeRadian = _util.normalizeRadian; var curve = __webpack_require__(/*! ../core/curve */ 43); var windingLine = __webpack_require__(/*! ./windingLine */ 51); var CMD = PathProxy.CMD; var PI2 = Math.PI * 2; var EPSILON = 1e-4; function isAroundEqual(a, b) { return Math.abs(a - b) < EPSILON; } // 临时数组 var roots = [-1, -1, -1]; var extrema = [-1, -1]; function swapExtrema() { var tmp = extrema[0]; extrema[0] = extrema[1]; extrema[1] = tmp; } function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) { // Quick reject if (y > y0 && y > y1 && y > y2 && y > y3 || y < y0 && y < y1 && y < y2 && y < y3) { return 0; } var nRoots = curve.cubicRootAt(y0, y1, y2, y3, y, roots); if (nRoots === 0) { return 0; } else { var w = 0; var nExtrema = -1; var y0_, y1_; for (var i = 0; i < nRoots; i++) { var t = roots[i]; // Avoid winding error when intersection point is the connect point of two line of polygon var unit = t === 0 || t === 1 ? 0.5 : 1; var x_ = curve.cubicAt(x0, x1, x2, x3, t); if (x_ < x) { // Quick reject continue; } if (nExtrema < 0) { nExtrema = curve.cubicExtrema(y0, y1, y2, y3, extrema); if (extrema[1] < extrema[0] && nExtrema > 1) { swapExtrema(); } y0_ = curve.cubicAt(y0, y1, y2, y3, extrema[0]); if (nExtrema > 1) { y1_ = curve.cubicAt(y0, y1, y2, y3, extrema[1]); } } if (nExtrema == 2) { // 分成三段单调函数 if (t < extrema[0]) { w += y0_ < y0 ? unit : -unit; } else if (t < extrema[1]) { w += y1_ < y0_ ? unit : -unit; } else { w += y3 < y1_ ? unit : -unit; } } else { // 分成两段单调函数 if (t < extrema[0]) { w += y0_ < y0 ? unit : -unit; } else { w += y3 < y0_ ? unit : -unit; } } } return w; } } function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) { // Quick reject if (y > y0 && y > y1 && y > y2 || y < y0 && y < y1 && y < y2) { return 0; } var nRoots = curve.quadraticRootAt(y0, y1, y2, y, roots); if (nRoots === 0) { return 0; } else { var t = curve.quadraticExtremum(y0, y1, y2); if (t >= 0 && t <= 1) { var w = 0; var y_ = curve.quadraticAt(y0, y1, y2, t); for (var i = 0; i < nRoots; i++) { // Remove one endpoint. var unit = roots[i] === 0 || roots[i] === 1 ? 0.5 : 1; var x_ = curve.quadraticAt(x0, x1, x2, roots[i]); if (x_ < x) { // Quick reject continue; } if (roots[i] < t) { w += y_ < y0 ? unit : -unit; } else { w += y2 < y_ ? unit : -unit; } } return w; } else { // Remove one endpoint. var unit = roots[0] === 0 || roots[0] === 1 ? 0.5 : 1; var x_ = curve.quadraticAt(x0, x1, x2, roots[0]); if (x_ < x) { // Quick reject return 0; } return y2 < y0 ? unit : -unit; } } } // TODO // Arc 旋转 function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) { y -= cy; if (y > r || y < -r) { return 0; } var tmp = Math.sqrt(r * r - y * y); roots[0] = -tmp; roots[1] = tmp; var diff = Math.abs(startAngle - endAngle); if (diff < 1e-4) { return 0; } if (diff % PI2 < 1e-4) { // Is a circle startAngle = 0; endAngle = PI2; var dir = anticlockwise ? 1 : -1; if (x >= roots[0] + cx && x <= roots[1] + cx) { return dir; } else { return 0; } } if (anticlockwise) { var tmp = startAngle; startAngle = normalizeRadian(endAngle); endAngle = normalizeRadian(tmp); } else { startAngle = normalizeRadian(startAngle); endAngle = normalizeRadian(endAngle); } if (startAngle > endAngle) { endAngle += PI2; } var w = 0; for (var i = 0; i < 2; i++) { var x_ = roots[i]; if (x_ + cx > x) { var angle = Math.atan2(y, x_); var dir = anticlockwise ? 1 : -1; if (angle < 0) { angle = PI2 + angle; } if (angle >= startAngle && angle <= endAngle || angle + PI2 >= startAngle && angle + PI2 <= endAngle) { if (angle > Math.PI / 2 && angle < Math.PI * 1.5) { dir = -dir; } w += dir; } } } return w; } function containPath(data, lineWidth, isStroke, x, y) { var w = 0; var xi = 0; var yi = 0; var x0 = 0; var y0 = 0; for (var i = 0; i < data.length;) { var cmd = data[i++]; // Begin a new subpath if (cmd === CMD.M && i > 1) { // Close previous subpath if (!isStroke) { w += windingLine(xi, yi, x0, y0, x, y); } // 如果被任何一个 subpath 包含 // if (w !== 0) { // return true; // } } if (i == 1) { // 如果第一个命令是 L, C, Q // 则 previous point 同绘制命令的第一个 point // // 第一个命令为 Arc 的情况下会在后面特殊处理 xi = data[i]; yi = data[i + 1]; x0 = xi; y0 = yi; } switch (cmd) { case CMD.M: // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点 // 在 closePath 的时候使用 x0 = data[i++]; y0 = data[i++]; xi = x0; yi = y0; break; case CMD.L: if (isStroke) { if (line.containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) { return true; } } else { // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0; } xi = data[i++]; yi = data[i++]; break; case CMD.C: if (isStroke) { if (cubic.containStroke(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) { return true; } } else { w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0; } xi = data[i++]; yi = data[i++]; break; case CMD.Q: if (isStroke) { if (quadratic.containStroke(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) { return true; } } else { w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0; } xi = data[i++]; yi = data[i++]; break; case CMD.A: // TODO Arc 判断的开销比较大 var cx = data[i++]; var cy = data[i++]; var rx = data[i++]; var ry = data[i++]; var theta = data[i++]; var dTheta = data[i++]; // TODO Arc 旋转 var psi = data[i++]; var anticlockwise = 1 - data[i++]; var x1 = Math.cos(theta) * rx + cx; var y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令 if (i > 1) { w += windingLine(xi, yi, x1, y1, x, y); } else { // 第一个命令起点还未定义 x0 = x1; y0 = y1; } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放 var _x = (x - cx) * ry / rx + cx; if (isStroke) { if (arc.containStroke(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) { return true; } } else { w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y); } xi = Math.cos(theta + dTheta) * rx + cx; yi = Math.sin(theta + dTheta) * ry + cy; break; case CMD.R: x0 = xi = data[i++]; y0 = yi = data[i++]; var width = data[i++]; var height = data[i++]; var x1 = x0 + width; var y1 = y0 + height; if (isStroke) { if (line.containStroke(x0, y0, x1, y0, lineWidth, x, y) || line.containStroke(x1, y0, x1, y1, lineWidth, x, y) || line.containStroke(x1, y1, x0, y1, lineWidth, x, y) || line.containStroke(x0, y1, x0, y0, lineWidth, x, y)) { return true; } } else { // FIXME Clockwise ? w += windingLine(x1, y0, x1, y1, x, y); w += windingLine(x0, y1, x0, y0, x, y); } break; case CMD.Z: if (isStroke) { if (line.containStroke(xi, yi, x0, y0, lineWidth, x, y)) { return true; } } else { // Close a subpath w += windingLine(xi, yi, x0, y0, x, y); // 如果被任何一个 subpath 包含 // FIXME subpaths may overlap // if (w !== 0) { // return true; // } } xi = x0; yi = y0; break; } } if (!isStroke && !isAroundEqual(yi, y0)) { w += windingLine(xi, yi, x0, y0, x, y) || 0; } return w !== 0; } function contain(pathData, x, y) { return containPath(pathData, 0, false, x, y); } function containStroke(pathData, lineWidth, x, y) { return containPath(pathData, lineWidth, true, x, y); } exports.contain = contain; exports.containStroke = containStroke; /***/ }, /* 46 */ /*!*************************************************!*\ !*** ./~/echarts/~/zrender/lib/contain/line.js ***! \*************************************************/ /***/ function(module, exports) { /** * 线段包含判断 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} lineWidth * @param {number} x * @param {number} y * @return {boolean} */ function containStroke(x0, y0, x1, y1, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = lineWidth; var _a = 0; var _b = x0; // Quick reject if (y > y0 + _l && y > y1 + _l || y < y0 - _l && y < y1 - _l || x > x0 + _l && x > x1 + _l || x < x0 - _l && x < x1 - _l) { return false; } if (x0 !== x1) { _a = (y0 - y1) / (x0 - x1); _b = (x0 * y1 - x1 * y0) / (x0 - x1); } else { return Math.abs(x - x0) <= _l / 2; } var tmp = _a * x - y + _b; var _s = tmp * tmp / (_a * _a + 1); return _s <= _l / 2 * _l / 2; } exports.containStroke = containStroke; /***/ }, /* 47 */ /*!**************************************************!*\ !*** ./~/echarts/~/zrender/lib/contain/cubic.js ***! \**************************************************/ /***/ function(module, exports, __webpack_require__) { var curve = __webpack_require__(/*! ../core/curve */ 43); /** * 三次贝塞尔曲线描边包含判断 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @param {number} lineWidth * @param {number} x * @param {number} y * @return {boolean} */ function containStroke(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = lineWidth; // Quick reject if (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l || y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l || x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l || x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l) { return false; } var d = curve.cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null); return d <= _l / 2; } exports.containStroke = containStroke; /***/ }, /* 48 */ /*!******************************************************!*\ !*** ./~/echarts/~/zrender/lib/contain/quadratic.js ***! \******************************************************/ /***/ function(module, exports, __webpack_require__) { var _curve = __webpack_require__(/*! ../core/curve */ 43); var quadraticProjectPoint = _curve.quadraticProjectPoint; /** * 二次贝塞尔曲线描边包含判断 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} lineWidth * @param {number} x * @param {number} y * @return {boolean} */ function containStroke(x0, y0, x1, y1, x2, y2, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = lineWidth; // Quick reject if (y > y0 + _l && y > y1 + _l && y > y2 + _l || y < y0 - _l && y < y1 - _l && y < y2 - _l || x > x0 + _l && x > x1 + _l && x > x2 + _l || x < x0 - _l && x < x1 - _l && x < x2 - _l) { return false; } var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null); return d <= _l / 2; } exports.containStroke = containStroke; /***/ }, /* 49 */ /*!************************************************!*\ !*** ./~/echarts/~/zrender/lib/contain/arc.js ***! \************************************************/ /***/ function(module, exports, __webpack_require__) { var _util = __webpack_require__(/*! ./util */ 50); var normalizeRadian = _util.normalizeRadian; var PI2 = Math.PI * 2; /** * 圆弧描边包含判断 * @param {number} cx * @param {number} cy * @param {number} r * @param {number} startAngle * @param {number} endAngle * @param {boolean} anticlockwise * @param {number} lineWidth * @param {number} x * @param {number} y * @return {Boolean} */ function containStroke(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = lineWidth; x -= cx; y -= cy; var d = Math.sqrt(x * x + y * y); if (d - _l > r || d + _l < r) { return false; } if (Math.abs(startAngle - endAngle) % PI2 < 1e-4) { // Is a circle return true; } if (anticlockwise) { var tmp = startAngle; startAngle = normalizeRadian(endAngle); endAngle = normalizeRadian(tmp); } else { startAngle = normalizeRadian(startAngle); endAngle = normalizeRadian(endAngle); } if (startAngle > endAngle) { endAngle += PI2; } var angle = Math.atan2(y, x); if (angle < 0) { angle += PI2; } return angle >= startAngle && angle <= endAngle || angle + PI2 >= startAngle && angle + PI2 <= endAngle; } exports.containStroke = containStroke; /***/ }, /* 50 */ /*!*************************************************!*\ !*** ./~/echarts/~/zrender/lib/contain/util.js ***! \*************************************************/ /***/ function(module, exports) { var PI2 = Math.PI * 2; function normalizeRadian(angle) { angle %= PI2; if (angle < 0) { angle += PI2; } return angle; } exports.normalizeRadian = normalizeRadian; /***/ }, /* 51 */ /*!********************************************************!*\ !*** ./~/echarts/~/zrender/lib/contain/windingLine.js ***! \********************************************************/ /***/ function(module, exports) { function windingLine(x0, y0, x1, y1, x, y) { if (y > y0 && y > y1 || y < y0 && y < y1) { return 0; } // Ignore horizontal line if (y1 === y0) { return 0; } var dir = y1 < y0 ? 1 : -1; var t = (y - y0) / (y1 - y0); // Avoid winding error when intersection point is the connect point of two line of polygon if (t === 1 || t === 0) { dir = y1 < y0 ? 0.5 : -0.5; } var x_ = t * (x1 - x0) + x0; // If (x, y) on the line, considered as "contain". return x_ === x ? Infinity : x_ > x ? dir : 0; } module.exports = windingLine; /***/ }, /* 52 */ /*!****************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/Pattern.js ***! \****************************************************/ /***/ function(module, exports) { var Pattern = function (image, repeat) { // Should do nothing more in this constructor. Because gradient can be // declard by `color: {image: ...}`, where this constructor will not be called. this.image = image; this.repeat = repeat; // Can be cloned this.type = 'pattern'; }; Pattern.prototype.getCanvasPattern = function (ctx) { return ctx.createPattern(this.image, this.repeat || 'repeat'); }; var _default = Pattern; module.exports = _default; /***/ }, /* 53 */ /*!*******************************************************!*\ !*** ./~/echarts/~/zrender/lib/tool/transformPath.js ***! \*******************************************************/ /***/ function(module, exports, __webpack_require__) { var PathProxy = __webpack_require__(/*! ../core/PathProxy */ 42); var _vector = __webpack_require__(/*! ../core/vector */ 27); var v2ApplyTransform = _vector.applyTransform; var CMD = PathProxy.CMD; var points = [[], [], []]; var mathSqrt = Math.sqrt; var mathAtan2 = Math.atan2; function _default(path, m) { var data = path.data; var cmd; var nPoint; var i; var j; var k; var p; var M = CMD.M; var C = CMD.C; var L = CMD.L; var R = CMD.R; var A = CMD.A; var Q = CMD.Q; for (i = 0, j = 0; i < data.length;) { cmd = data[i++]; j = i; nPoint = 0; switch (cmd) { case M: nPoint = 1; break; case L: nPoint = 1; break; case C: nPoint = 3; break; case Q: nPoint = 2; break; case A: var x = m[4]; var y = m[5]; var sx = mathSqrt(m[0] * m[0] + m[1] * m[1]); var sy = mathSqrt(m[2] * m[2] + m[3] * m[3]); var angle = mathAtan2(-m[1] / sy, m[0] / sx); // cx data[i] *= sx; data[i++] += x; // cy data[i] *= sy; data[i++] += y; // Scale rx and ry // FIXME Assume psi is 0 here data[i++] *= sx; data[i++] *= sy; // Start angle data[i++] += angle; // end angle data[i++] += angle; // FIXME psi i += 2; j = i; break; case R: // x0, y0 p[0] = data[i++]; p[1] = data[i++]; v2ApplyTransform(p, p, m); data[j++] = p[0]; data[j++] = p[1]; // x1, y1 p[0] += data[i++]; p[1] += data[i++]; v2ApplyTransform(p, p, m); data[j++] = p[0]; data[j++] = p[1]; } for (k = 0; k < nPoint; k++) { var p = points[k]; p[0] = data[i++]; p[1] = data[i++]; v2ApplyTransform(p, p, m); // Write back data[j++] = p[0]; data[j++] = p[1]; } } } module.exports = _default; /***/ }, /* 54 */ /*!**************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/Image.js ***! \**************************************************/ /***/ function(module, exports, __webpack_require__) { var Displayable = __webpack_require__(/*! ./Displayable */ 19); var BoundingRect = __webpack_require__(/*! ../core/BoundingRect */ 39); var zrUtil = __webpack_require__(/*! ../core/util */ 5); var imageHelper = __webpack_require__(/*! ./helper/image */ 40); /** * @alias zrender/graphic/Image * @extends module:zrender/graphic/Displayable * @constructor * @param {Object} opts */ function ZImage(opts) { Displayable.call(this, opts); } ZImage.prototype = { constructor: ZImage, type: 'image', brush: function (ctx, prevEl) { var style = this.style; var src = style.image; // Must bind each time style.bind(ctx, this, prevEl); var image = this._image = imageHelper.createOrUpdateImage(src, this._image, this, this.onload); if (!image || !imageHelper.isImageReady(image)) { return; } // 图片已经加载完成 // if (image.nodeName.toUpperCase() == 'IMG') { // if (!image.complete) { // return; // } // } // Else is canvas var x = style.x || 0; var y = style.y || 0; var width = style.width; var height = style.height; var aspect = image.width / image.height; if (width == null && height != null) { // Keep image/height ratio width = height * aspect; } else if (height == null && width != null) { height = width / aspect; } else if (width == null && height == null) { width = image.width; height = image.height; } // 设置transform this.setTransform(ctx); if (style.sWidth && style.sHeight) { var sx = style.sx || 0; var sy = style.sy || 0; ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height); } else if (style.sx && style.sy) { var sx = style.sx; var sy = style.sy; var sWidth = width - sx; var sHeight = height - sy; ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height); } else { ctx.drawImage(image, x, y, width, height); } // Draw rect text if (style.text != null) { // Only restore transform when needs draw text. this.restoreTransform(ctx); this.drawRectText(ctx, this.getBoundingRect()); } }, getBoundingRect: function () { var style = this.style; if (!this._rect) { this._rect = new BoundingRect(style.x || 0, style.y || 0, style.width || 0, style.height || 0); } return this._rect; } }; zrUtil.inherits(ZImage, Displayable); var _default = ZImage; module.exports = _default; /***/ }, /* 55 */ /*!****************************************************!*\ !*** ./~/echarts/~/zrender/lib/container/Group.js ***! \****************************************************/ /***/ function(module, exports, __webpack_require__) { var zrUtil = __webpack_require__(/*! ../core/util */ 5); var Element = __webpack_require__(/*! ../Element */ 22); var BoundingRect = __webpack_require__(/*! ../core/BoundingRect */ 39); /** * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上 * @module zrender/graphic/Group * @example * var Group = require('zrender/container/Group'); * var Circle = require('zrender/graphic/shape/Circle'); * var g = new Group(); * g.position[0] = 100; * g.position[1] = 100; * g.add(new Circle({ * style: { * x: 100, * y: 100, * r: 20, * } * })); * zr.add(g); */ /** * @alias module:zrender/graphic/Group * @constructor * @extends module:zrender/mixin/Transformable * @extends module:zrender/mixin/Eventful */ var Group = function (opts) { opts = opts || {}; Element.call(this, opts); for (var key in opts) { if (opts.hasOwnProperty(key)) { this[key] = opts[key]; } } this._children = []; this.__storage = null; this.__dirty = true; }; Group.prototype = { constructor: Group, isGroup: true, /** * @type {string} */ type: 'group', /** * 所有子孙元素是否响应鼠标事件 * @name module:/zrender/container/Group#silent * @type {boolean} * @default false */ silent: false, /** * @return {Array.<module:zrender/Element>} */ children: function () { return this._children.slice(); }, /** * 获取指定 index 的儿子节点 * @param {number} idx * @return {module:zrender/Element} */ childAt: function (idx) { return this._children[idx]; }, /** * 获取指定名字的儿子节点 * @param {string} name * @return {module:zrender/Element} */ childOfName: function (name) { var children = this._children; for (var i = 0; i < children.length; i++) { if (children[i].name === name) { return children[i]; } } }, /** * @return {number} */ childCount: function () { return this._children.length; }, /** * 添加子节点到最后 * @param {module:zrender/Element} child */ add: function (child) { if (child && child !== this && child.parent !== this) { this._children.push(child); this._doAdd(child); } return this; }, /** * 添加子节点在 nextSibling 之前 * @param {module:zrender/Element} child * @param {module:zrender/Element} nextSibling */ addBefore: function (child, nextSibling) { if (child && child !== this && child.parent !== this && nextSibling && nextSibling.parent === this) { var children = this._children; var idx = children.indexOf(nextSibling); if (idx >= 0) { children.splice(idx, 0, child); this._doAdd(child); } } return this; }, _doAdd: function (child) { if (child.parent) { child.parent.remove(child); } child.parent = this; var storage = this.__storage; var zr = this.__zr; if (storage && storage !== child.__storage) { storage.addToStorage(child); if (child instanceof Group) { child.addChildrenToStorage(storage); } } zr && zr.refresh(); }, /** * 移除子节点 * @param {module:zrender/Element} child */ remove: function (child) { var zr = this.__zr; var storage = this.__storage; var children = this._children; var idx = zrUtil.indexOf(children, child); if (idx < 0) { return this; } children.splice(idx, 1); child.parent = null; if (storage) { storage.delFromStorage(child); if (child instanceof Group) { child.delChildrenFromStorage(storage); } } zr && zr.refresh(); return this; }, /** * 移除所有子节点 */ removeAll: function () { var children = this._children; var storage = this.__storage; var child; var i; for (i = 0; i < children.length; i++) { child = children[i]; if (storage) { storage.delFromStorage(child); if (child instanceof Group) { child.delChildrenFromStorage(storage); } } child.parent = null; } children.length = 0; return this; }, /** * 遍历所有子节点 * @param {Function} cb * @param {} context */ eachChild: function (cb, context) { var children = this._children; for (var i = 0; i < children.length; i++) { var child = children[i]; cb.call(context, child, i); } return this; }, /** * 深度优先遍历所有子孙节点 * @param {Function} cb * @param {} context */ traverse: function (cb, context) { for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; cb.call(context, child); if (child.type === 'group') { child.traverse(cb, context); } } return this; }, addChildrenToStorage: function (storage) { for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; storage.addToStorage(child); if (child instanceof Group) { child.addChildrenToStorage(storage); } } }, delChildrenFromStorage: function (storage) { for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; storage.delFromStorage(child); if (child instanceof Group) { child.delChildrenFromStorage(storage); } } }, dirty: function () { this.__dirty = true; this.__zr && this.__zr.refresh(); return this; }, /** * @return {module:zrender/core/BoundingRect} */ getBoundingRect: function (includeChildren) { // TODO Caching var rect = null; var tmpRect = new BoundingRect(0, 0, 0, 0); var children = includeChildren || this._children; var tmpMat = []; for (var i = 0; i < children.length; i++) { var child = children[i]; if (child.ignore || child.invisible) { continue; } var childRect = child.getBoundingRect(); var transform = child.getLocalTransform(tmpMat); // TODO // The boundingRect cacluated by transforming original // rect may be bigger than the actual bundingRect when rotation // is used. (Consider a circle rotated aginst its center, where // the actual boundingRect should be the same as that not be // rotated.) But we can not find better approach to calculate // actual boundingRect yet, considering performance. if (transform) { tmpRect.copy(childRect); tmpRect.applyTransform(transform); rect = rect || tmpRect.clone(); rect.union(tmpRect); } else { rect = rect || childRect.clone(); rect.union(childRect); } } return rect || tmpRect; } }; zrUtil.inherits(Group, Element); var _default = Group; module.exports = _default; /***/ }, /* 56 */ /*!*************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/Text.js ***! \*************************************************/ /***/ function(module, exports, __webpack_require__) { var Displayable = __webpack_require__(/*! ./Displayable */ 19); var zrUtil = __webpack_require__(/*! ../core/util */ 5); var textContain = __webpack_require__(/*! ../contain/text */ 38); var textHelper = __webpack_require__(/*! ./helper/text */ 37); /** * @alias zrender/graphic/Text * @extends module:zrender/graphic/Displayable * @constructor * @param {Object} opts */ var Text = function (opts) { // jshint ignore:line Displayable.call(this, opts); }; Text.prototype = { constructor: Text, type: 'text', brush: function (ctx, prevEl) { var style = this.style; // Optimize, avoid normalize every time. this.__dirty && textHelper.normalizeTextStyle(style, true); // Use props with prefix 'text'. style.fill = style.stroke = style.shadowBlur = style.shadowColor = style.shadowOffsetX = style.shadowOffsetY = null; var text = style.text; // Convert to string text != null && (text += ''); // Always bind style style.bind(ctx, this, prevEl); if (!textHelper.needDrawText(text, style)) { return; } this.setTransform(ctx); textHelper.renderText(this, ctx, text, style); this.restoreTransform(ctx); }, getBoundingRect: function () { var style = this.style; // Optimize, avoid normalize every time. this.__dirty && textHelper.normalizeTextStyle(style, true); if (!this._rect) { var text = style.text; text != null ? text += '' : text = ''; var rect = textContain.getBoundingRect(style.text + '', style.font, style.textAlign, style.textVerticalAlign, style.textPadding, style.rich); rect.x += style.x || 0; rect.y += style.y || 0; if (textHelper.getStroke(style.textStroke, style.textStrokeWidth)) { var w = style.textStrokeWidth; rect.x -= w / 2; rect.y -= w / 2; rect.width += w; rect.height += w; } this._rect = rect; } return this._rect; } }; zrUtil.inherits(Text, Displayable); var _default = Text; module.exports = _default; /***/ }, /* 57 */ /*!*********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/shape/Circle.js ***! \*********************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../Path */ 18); /** * 圆形 * @module zrender/shape/Circle */ var _default = Path.extend({ type: 'circle', shape: { cx: 0, cy: 0, r: 0 }, buildPath: function (ctx, shape, inBundle) { // Better stroking in ShapeBundle // Always do it may have performence issue ( fill may be 2x more cost) if (inBundle) { ctx.moveTo(shape.cx + shape.r, shape.cy); } // else { // if (ctx.allocate && !ctx.data.length) { // ctx.allocate(ctx.CMD_MEM_SIZE.A); // } // } // Better stroking in ShapeBundle // ctx.moveTo(shape.cx + shape.r, shape.cy); ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true); } }); module.exports = _default; /***/ }, /* 58 */ /*!*********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/shape/Sector.js ***! \*********************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../Path */ 18); var fixClipWithShadow = __webpack_require__(/*! ../helper/fixClipWithShadow */ 59); /** * 扇形 * @module zrender/graphic/shape/Sector */ var _default = Path.extend({ type: 'sector', shape: { cx: 0, cy: 0, r0: 0, r: 0, startAngle: 0, endAngle: Math.PI * 2, clockwise: true }, brush: fixClipWithShadow(Path.prototype.brush), buildPath: function (ctx, shape) { var x = shape.cx; var y = shape.cy; var r0 = Math.max(shape.r0 || 0, 0); var r = Math.max(shape.r, 0); var startAngle = shape.startAngle; var endAngle = shape.endAngle; var clockwise = shape.clockwise; var unitX = Math.cos(startAngle); var unitY = Math.sin(startAngle); ctx.moveTo(unitX * r0 + x, unitY * r0 + y); ctx.lineTo(unitX * r + x, unitY * r + y); ctx.arc(x, y, r, startAngle, endAngle, !clockwise); ctx.lineTo(Math.cos(endAngle) * r0 + x, Math.sin(endAngle) * r0 + y); if (r0 !== 0) { ctx.arc(x, y, r0, endAngle, startAngle, clockwise); } ctx.closePath(); } }); module.exports = _default; /***/ }, /* 59 */ /*!*********************************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/helper/fixClipWithShadow.js ***! \*********************************************************************/ /***/ function(module, exports, __webpack_require__) { var env = __webpack_require__(/*! ../../core/env */ 60); // Fix weird bug in some version of IE11 (like 11.0.9600.178**), // where exception "unexpected call to method or property access" // might be thrown when calling ctx.fill or ctx.stroke after a path // whose area size is zero is drawn and ctx.clip() is called and // shadowBlur is set. See #4572, #3112, #5777. // (e.g., // ctx.moveTo(10, 10); // ctx.lineTo(20, 10); // ctx.closePath(); // ctx.clip(); // ctx.shadowBlur = 10; // ... // ctx.fill(); // ) var shadowTemp = [['shadowBlur', 0], ['shadowColor', '#000'], ['shadowOffsetX', 0], ['shadowOffsetY', 0]]; function _default(orignalBrush) { // version string can be: '11.0' return env.browser.ie && env.browser.version >= 11 ? function () { var clipPaths = this.__clipPaths; var style = this.style; var modified; if (clipPaths) { for (var i = 0; i < clipPaths.length; i++) { var clipPath = clipPaths[i]; var shape = clipPath && clipPath.shape; var type = clipPath && clipPath.type; if (shape && (type === 'sector' && shape.startAngle === shape.endAngle || type === 'rect' && (!shape.width || !shape.height))) { for (var j = 0; j < shadowTemp.length; j++) { // It is save to put shadowTemp static, because shadowTemp // will be all modified each item brush called. shadowTemp[j][2] = style[shadowTemp[j][0]]; style[shadowTemp[j][0]] = shadowTemp[j][1]; } modified = true; break; } } } orignalBrush.apply(this, arguments); if (modified) { for (var j = 0; j < shadowTemp.length; j++) { style[shadowTemp[j][0]] = shadowTemp[j][2]; } } } : orignalBrush; } module.exports = _default; /***/ }, /* 60 */ /*!*********************************************!*\ !*** ./~/echarts/~/zrender/lib/core/env.js ***! \*********************************************/ /***/ function(module, exports) { /** * echarts设备环境识别 * * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 * @author firede[[email protected]] * @desc thanks zepto. */ var env = {}; if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') { // In Weixin Application env = { browser: {}, os: {}, node: false, wxa: true, // Weixin Application canvasSupported: true, svgSupported: false, touchEventsSupported: true }; } else if (typeof document === 'undefined' && typeof self !== 'undefined') { // In worker env = { browser: {}, os: {}, node: false, worker: true, canvasSupported: true }; } else if (typeof navigator === 'undefined') { // In node env = { browser: {}, os: {}, node: true, worker: false, // Assume canvas is supported canvasSupported: true, svgSupported: true }; } else { env = detect(navigator.userAgent); } var _default = env; // Zepto.js // (c) 2010-2013 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. function detect(ua) { var os = {}; var browser = {}; // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/); // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/); // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/); // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/); // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/); // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/); // var touchpad = webos && ua.match(/TouchPad/); // var kindle = ua.match(/Kindle\/([\d.]+)/); // var silk = ua.match(/Silk\/([\d._]+)/); // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/); // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/); // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/); // var playbook = ua.match(/PlayBook/); // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/); var firefox = ua.match(/Firefox\/([\d.]+)/); // var safari = webkit && ua.match(/Mobile\//) && !chrome; // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome; var ie = ua.match(/MSIE\s([\d.]+)/) // IE 11 Trident/7.0; rv:11.0 || ua.match(/Trident\/.+?rv:(([\d.]+))/); var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+ var weChat = /micromessenger/i.test(ua); // Todo: clean this up with a better OS/browser seperation: // - discern (more) between multiple browsers on android // - decide if kindle fire in silk mode is android or not // - Firefox on Android doesn't specify the Android version // - possibly devide in os, device and browser hashes // if (browser.webkit = !!webkit) browser.version = webkit[1]; // if (android) os.android = true, os.version = android[2]; // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.'); // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.'); // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null; // if (webos) os.webos = true, os.version = webos[2]; // if (touchpad) os.touchpad = true; // if (blackberry) os.blackberry = true, os.version = blackberry[2]; // if (bb10) os.bb10 = true, os.version = bb10[2]; // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2]; // if (playbook) browser.playbook = true; // if (kindle) os.kindle = true, os.version = kindle[1]; // if (silk) browser.silk = true, browser.version = silk[1]; // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true; // if (chrome) browser.chrome = true, browser.version = chrome[1]; if (firefox) { browser.firefox = true; browser.version = firefox[1]; } // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true; // if (webview) browser.webview = true; if (ie) { browser.ie = true; browser.version = ie[1]; } if (edge) { browser.edge = true; browser.version = edge[1]; } // It is difficult to detect WeChat in Win Phone precisely, because ua can // not be set on win phone. So we do not consider Win Phone. if (weChat) { browser.weChat = true; } // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) || // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/))); // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos || // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) || // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/)))); return { browser: browser, os: os, node: false, // 原生canvas支持,改极端点了 // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9) canvasSupported: !!document.createElement('canvas').getContext, svgSupported: typeof SVGRect !== 'undefined', // works on most browsers // IE10/11 does not support touch event, and MS Edge supports them but not by // default, so we dont check navigator.maxTouchPoints for them here. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge, // <http://caniuse.com/#search=pointer%20event>. pointerEventsSupported: 'onpointerdown' in window // Firefox supports pointer but not by default, only MS browsers are reliable on pointer // events currently. So we dont use that on other browsers unless tested sufficiently. // Although IE 10 supports pointer event, it use old style and is different from the // standard. So we exclude that. (IE 10 is hardly used on touch device) && (browser.edge || browser.ie && browser.version >= 11) // passiveSupported: detectPassiveSupport() }; } // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection // function detectPassiveSupport() { // // Test via a getter in the options object to see if the passive property is accessed // var supportsPassive = false; // try { // var opts = Object.defineProperty({}, 'passive', { // get: function() { // supportsPassive = true; // } // }); // window.addEventListener('testPassive', function() {}, opts); // } catch (e) { // } // return supportsPassive; // } module.exports = _default; /***/ }, /* 61 */ /*!*******************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/shape/Ring.js ***! \*******************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../Path */ 18); /** * 圆环 * @module zrender/graphic/shape/Ring */ var _default = Path.extend({ type: 'ring', shape: { cx: 0, cy: 0, r: 0, r0: 0 }, buildPath: function (ctx, shape) { var x = shape.cx; var y = shape.cy; var PI2 = Math.PI * 2; ctx.moveTo(x + shape.r, y); ctx.arc(x, y, shape.r, 0, PI2, false); ctx.moveTo(x + shape.r0, y); ctx.arc(x, y, shape.r0, 0, PI2, true); } }); module.exports = _default; /***/ }, /* 62 */ /*!**********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/shape/Polygon.js ***! \**********************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../Path */ 18); var polyHelper = __webpack_require__(/*! ../helper/poly */ 63); /** * 多边形 * @module zrender/shape/Polygon */ var _default = Path.extend({ type: 'polygon', shape: { points: null, smooth: false, smoothConstraint: null }, buildPath: function (ctx, shape) { polyHelper.buildPath(ctx, shape, true); } }); module.exports = _default; /***/ }, /* 63 */ /*!********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/helper/poly.js ***! \********************************************************/ /***/ function(module, exports, __webpack_require__) { var smoothSpline = __webpack_require__(/*! ./smoothSpline */ 64); var smoothBezier = __webpack_require__(/*! ./smoothBezier */ 65); function buildPath(ctx, shape, closePath) { var points = shape.points; var smooth = shape.smooth; if (points && points.length >= 2) { if (smooth && smooth !== 'spline') { var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint); ctx.moveTo(points[0][0], points[0][1]); var len = points.length; for (var i = 0; i < (closePath ? len : len - 1); i++) { var cp1 = controlPoints[i * 2]; var cp2 = controlPoints[i * 2 + 1]; var p = points[(i + 1) % len]; ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]); } } else { if (smooth === 'spline') { points = smoothSpline(points, closePath); } ctx.moveTo(points[0][0], points[0][1]); for (var i = 1, l = points.length; i < l; i++) { ctx.lineTo(points[i][0], points[i][1]); } } closePath && ctx.closePath(); } } exports.buildPath = buildPath; /***/ }, /* 64 */ /*!****************************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/helper/smoothSpline.js ***! \****************************************************************/ /***/ function(module, exports, __webpack_require__) { var _vector = __webpack_require__(/*! ../../core/vector */ 27); var v2Distance = _vector.distance; /** * Catmull-Rom spline 插值折线 * @module zrender/shape/util/smoothSpline * @author pissang (https://www.github.com/pissang) * Kener (@Kener-林峰, [email protected]) * errorrik ([email protected]) */ /** * @inner */ function interpolate(p0, p1, p2, p3, t, t2, t3) { var v0 = (p2 - p0) * 0.5; var v1 = (p3 - p1) * 0.5; return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1; } /** * @alias module:zrender/shape/util/smoothSpline * @param {Array} points 线段顶点数组 * @param {boolean} isLoop * @return {Array} */ function _default(points, isLoop) { var len = points.length; var ret = []; var distance = 0; for (var i = 1; i < len; i++) { distance += v2Distance(points[i - 1], points[i]); } var segs = distance / 2; segs = segs < len ? len : segs; for (var i = 0; i < segs; i++) { var pos = i / (segs - 1) * (isLoop ? len : len - 1); var idx = Math.floor(pos); var w = pos - idx; var p0; var p1 = points[idx % len]; var p2; var p3; if (!isLoop) { p0 = points[idx === 0 ? idx : idx - 1]; p2 = points[idx > len - 2 ? len - 1 : idx + 1]; p3 = points[idx > len - 3 ? len - 1 : idx + 2]; } else { p0 = points[(idx - 1 + len) % len]; p2 = points[(idx + 1) % len]; p3 = points[(idx + 2) % len]; } var w2 = w * w; var w3 = w * w2; ret.push([interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3), interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)]); } return ret; } module.exports = _default; /***/ }, /* 65 */ /*!****************************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/helper/smoothBezier.js ***! \****************************************************************/ /***/ function(module, exports, __webpack_require__) { var _vector = __webpack_require__(/*! ../../core/vector */ 27); var v2Min = _vector.min; var v2Max = _vector.max; var v2Scale = _vector.scale; var v2Distance = _vector.distance; var v2Add = _vector.add; var v2Clone = _vector.clone; var v2Sub = _vector.sub; /** * 贝塞尔平滑曲线 * @module zrender/shape/util/smoothBezier * @author pissang (https://www.github.com/pissang) * Kener (@Kener-林峰, [email protected]) * errorrik ([email protected]) */ /** * 贝塞尔平滑曲线 * @alias module:zrender/shape/util/smoothBezier * @param {Array} points 线段顶点数组 * @param {number} smooth 平滑等级, 0-1 * @param {boolean} isLoop * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内 * 比如 [[0, 0], [100, 100]], 这个包围盒会与 * 整个折线的包围盒做一个并集用来约束控制点。 * @param {Array} 计算出来的控制点数组 */ function _default(points, smooth, isLoop, constraint) { var cps = []; var v = []; var v1 = []; var v2 = []; var prevPoint; var nextPoint; var min, max; if (constraint) { min = [Infinity, Infinity]; max = [-Infinity, -Infinity]; for (var i = 0, len = points.length; i < len; i++) { v2Min(min, min, points[i]); v2Max(max, max, points[i]); } // 与指定的包围盒做并集 v2Min(min, min, constraint[0]); v2Max(max, max, constraint[1]); } for (var i = 0, len = points.length; i < len; i++) { var point = points[i]; if (isLoop) { prevPoint = points[i ? i - 1 : len - 1]; nextPoint = points[(i + 1) % len]; } else { if (i === 0 || i === len - 1) { cps.push(v2Clone(points[i])); continue; } else { prevPoint = points[i - 1]; nextPoint = points[i + 1]; } } v2Sub(v, nextPoint, prevPoint); // use degree to scale the handle length v2Scale(v, v, smooth); var d0 = v2Distance(point, prevPoint); var d1 = v2Distance(point, nextPoint); var sum = d0 + d1; if (sum !== 0) { d0 /= sum; d1 /= sum; } v2Scale(v1, v, -d0); v2Scale(v2, v, d1); var cp0 = v2Add([], point, v1); var cp1 = v2Add([], point, v2); if (constraint) { v2Max(cp0, cp0, min); v2Min(cp0, cp0, max); v2Max(cp1, cp1, min); v2Min(cp1, cp1, max); } cps.push(cp0); cps.push(cp1); } if (isLoop) { cps.push(cps.shift()); } return cps; } module.exports = _default; /***/ }, /* 66 */ /*!***********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/shape/Polyline.js ***! \***********************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../Path */ 18); var polyHelper = __webpack_require__(/*! ../helper/poly */ 63); /** * @module zrender/graphic/shape/Polyline */ var _default = Path.extend({ type: 'polyline', shape: { points: null, smooth: false, smoothConstraint: null }, style: { stroke: '#000', fill: null }, buildPath: function (ctx, shape) { polyHelper.buildPath(ctx, shape, false); } }); module.exports = _default; /***/ }, /* 67 */ /*!*******************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/shape/Rect.js ***! \*******************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../Path */ 18); var roundRectHelper = __webpack_require__(/*! ../helper/roundRect */ 41); /** * 矩形 * @module zrender/graphic/shape/Rect */ var _default = Path.extend({ type: 'rect', shape: { // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4 // r缩写为1 相当于 [1, 1, 1, 1] // r缩写为[1] 相当于 [1, 1, 1, 1] // r缩写为[1, 2] 相当于 [1, 2, 1, 2] // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2] r: 0, x: 0, y: 0, width: 0, height: 0 }, buildPath: function (ctx, shape) { var x = shape.x; var y = shape.y; var width = shape.width; var height = shape.height; if (!shape.r) { ctx.rect(x, y, width, height); } else { roundRectHelper.buildPath(ctx, shape); } ctx.closePath(); return; } }); module.exports = _default; /***/ }, /* 68 */ /*!*******************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/shape/Line.js ***! \*******************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../Path */ 18); /** * 直线 * @module zrender/graphic/shape/Line */ var _default = Path.extend({ type: 'line', shape: { // Start point x1: 0, y1: 0, // End point x2: 0, y2: 0, percent: 1 }, style: { stroke: '#000', fill: null }, buildPath: function (ctx, shape) { var x1 = shape.x1; var y1 = shape.y1; var x2 = shape.x2; var y2 = shape.y2; var percent = shape.percent; if (percent === 0) { return; } ctx.moveTo(x1, y1); if (percent < 1) { x2 = x1 * (1 - percent) + x2 * percent; y2 = y1 * (1 - percent) + y2 * percent; } ctx.lineTo(x2, y2); }, /** * Get point at percent * @param {number} percent * @return {Array.<number>} */ pointAt: function (p) { var shape = this.shape; return [shape.x1 * (1 - p) + shape.x2 * p, shape.y1 * (1 - p) + shape.y2 * p]; } }); module.exports = _default; /***/ }, /* 69 */ /*!**************************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/shape/BezierCurve.js ***! \**************************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../Path */ 18); var vec2 = __webpack_require__(/*! ../../core/vector */ 27); var _curve = __webpack_require__(/*! ../../core/curve */ 43); var quadraticSubdivide = _curve.quadraticSubdivide; var cubicSubdivide = _curve.cubicSubdivide; var quadraticAt = _curve.quadraticAt; var cubicAt = _curve.cubicAt; var quadraticDerivativeAt = _curve.quadraticDerivativeAt; var cubicDerivativeAt = _curve.cubicDerivativeAt; /** * 贝塞尔曲线 * @module zrender/shape/BezierCurve */ var out = []; function someVectorAt(shape, t, isTangent) { var cpx2 = shape.cpx2; var cpy2 = shape.cpy2; if (cpx2 === null || cpy2 === null) { return [(isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t), (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)]; } else { return [(isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t), (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)]; } } var _default = Path.extend({ type: 'bezier-curve', shape: { x1: 0, y1: 0, x2: 0, y2: 0, cpx1: 0, cpy1: 0, // cpx2: 0, // cpy2: 0 // Curve show percent, for animating percent: 1 }, style: { stroke: '#000', fill: null }, buildPath: function (ctx, shape) { var x1 = shape.x1; var y1 = shape.y1; var x2 = shape.x2; var y2 = shape.y2; var cpx1 = shape.cpx1; var cpy1 = shape.cpy1; var cpx2 = shape.cpx2; var cpy2 = shape.cpy2; var percent = shape.percent; if (percent === 0) { return; } ctx.moveTo(x1, y1); if (cpx2 == null || cpy2 == null) { if (percent < 1) { quadraticSubdivide(x1, cpx1, x2, percent, out); cpx1 = out[1]; x2 = out[2]; quadraticSubdivide(y1, cpy1, y2, percent, out); cpy1 = out[1]; y2 = out[2]; } ctx.quadraticCurveTo(cpx1, cpy1, x2, y2); } else { if (percent < 1) { cubicSubdivide(x1, cpx1, cpx2, x2, percent, out); cpx1 = out[1]; cpx2 = out[2]; x2 = out[3]; cubicSubdivide(y1, cpy1, cpy2, y2, percent, out); cpy1 = out[1]; cpy2 = out[2]; y2 = out[3]; } ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2); } }, /** * Get point at percent * @param {number} t * @return {Array.<number>} */ pointAt: function (t) { return someVectorAt(this.shape, t, false); }, /** * Get tangent at percent * @param {number} t * @return {Array.<number>} */ tangentAt: function (t) { var p = someVectorAt(this.shape, t, true); return vec2.normalize(p, p); } }); module.exports = _default; /***/ }, /* 70 */ /*!******************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/shape/Arc.js ***! \******************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ../Path */ 18); /** * 圆弧 * @module zrender/graphic/shape/Arc */ var _default = Path.extend({ type: 'arc', shape: { cx: 0, cy: 0, r: 0, startAngle: 0, endAngle: Math.PI * 2, clockwise: true }, style: { stroke: '#000', fill: null }, buildPath: function (ctx, shape) { var x = shape.cx; var y = shape.cy; var r = Math.max(shape.r, 0); var startAngle = shape.startAngle; var endAngle = shape.endAngle; var clockwise = shape.clockwise; var unitX = Math.cos(startAngle); var unitY = Math.sin(startAngle); ctx.moveTo(unitX * r + x, unitY * r + y); ctx.arc(x, y, r, startAngle, endAngle, !clockwise); } }); module.exports = _default; /***/ }, /* 71 */ /*!*********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/CompoundPath.js ***! \*********************************************************/ /***/ function(module, exports, __webpack_require__) { var Path = __webpack_require__(/*! ./Path */ 18); // CompoundPath to improve performance var _default = Path.extend({ type: 'compound', shape: { paths: null }, _updatePathDirty: function () { var dirtyPath = this.__dirtyPath; var paths = this.shape.paths; for (var i = 0; i < paths.length; i++) { // Mark as dirty if any subpath is dirty dirtyPath = dirtyPath || paths[i].__dirtyPath; } this.__dirtyPath = dirtyPath; this.__dirty = this.__dirty || dirtyPath; }, beforeBrush: function () { this._updatePathDirty(); var paths = this.shape.paths || []; var scale = this.getGlobalScale(); // Update path scale for (var i = 0; i < paths.length; i++) { if (!paths[i].path) { paths[i].createPathProxy(); } paths[i].path.setScale(scale[0], scale[1]); } }, buildPath: function (ctx, shape) { var paths = shape.paths || []; for (var i = 0; i < paths.length; i++) { paths[i].buildPath(ctx, paths[i].shape, true); } }, afterBrush: function () { var paths = this.shape.paths || []; for (var i = 0; i < paths.length; i++) { paths[i].__dirtyPath = false; } }, getBoundingRect: function () { this._updatePathDirty(); return Path.prototype.getBoundingRect.call(this); } }); module.exports = _default; /***/ }, /* 72 */ /*!***********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/LinearGradient.js ***! \***********************************************************/ /***/ function(module, exports, __webpack_require__) { var zrUtil = __webpack_require__(/*! ../core/util */ 5); var Gradient = __webpack_require__(/*! ./Gradient */ 73); /** * x, y, x2, y2 are all percent from 0 to 1 * @param {number} [x=0] * @param {number} [y=0] * @param {number} [x2=1] * @param {number} [y2=0] * @param {Array.<Object>} colorStops * @param {boolean} [globalCoord=false] */ var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) { // Should do nothing more in this constructor. Because gradient can be // declard by `color: {type: 'linear', colorStops: ...}`, where // this constructor will not be called. this.x = x == null ? 0 : x; this.y = y == null ? 0 : y; this.x2 = x2 == null ? 1 : x2; this.y2 = y2 == null ? 0 : y2; // Can be cloned this.type = 'linear'; // If use global coord this.global = globalCoord || false; Gradient.call(this, colorStops); }; LinearGradient.prototype = { constructor: LinearGradient }; zrUtil.inherits(LinearGradient, Gradient); var _default = LinearGradient; module.exports = _default; /***/ }, /* 73 */ /*!*****************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/Gradient.js ***! \*****************************************************/ /***/ function(module, exports) { /** * @param {Array.<Object>} colorStops */ var Gradient = function (colorStops) { this.colorStops = colorStops || []; }; Gradient.prototype = { constructor: Gradient, addColorStop: function (offset, color) { this.colorStops.push({ offset: offset, color: color }); } }; var _default = Gradient; module.exports = _default; /***/ }, /* 74 */ /*!***********************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/RadialGradient.js ***! \***********************************************************/ /***/ function(module, exports, __webpack_require__) { var zrUtil = __webpack_require__(/*! ../core/util */ 5); var Gradient = __webpack_require__(/*! ./Gradient */ 73); /** * x, y, r are all percent from 0 to 1 * @param {number} [x=0.5] * @param {number} [y=0.5] * @param {number} [r=0.5] * @param {Array.<Object>} [colorStops] * @param {boolean} [globalCoord=false] */ var RadialGradient = function (x, y, r, colorStops, globalCoord) { // Should do nothing more in this constructor. Because gradient can be // declard by `color: {type: 'radial', colorStops: ...}`, where // this constructor will not be called. this.x = x == null ? 0.5 : x; this.y = y == null ? 0.5 : y; this.r = r == null ? 0.5 : r; // Can be cloned this.type = 'radial'; // If use global coord this.global = globalCoord || false; Gradient.call(this, colorStops); }; RadialGradient.prototype = { constructor: RadialGradient }; zrUtil.inherits(RadialGradient, Gradient); var _default = RadialGradient; module.exports = _default; /***/ }, /* 75 */ /*!*******************************************************************!*\ !*** ./~/echarts/~/zrender/lib/graphic/IncrementalDisplayable.js ***! \*******************************************************************/ /***/ function(module, exports, __webpack_require__) { var _util = __webpack_require__(/*! ../core/util */ 5); var inherits = _util.inherits; var Displayble = __webpack_require__(/*! ./Displayable */ 19); var BoundingRect = __webpack_require__(/*! ../core/BoundingRect */ 39); /** * Displayable for incremental rendering. It will be rendered in a separate layer * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables` * addDisplayables will render the added displayables incremetally. * * It use a not clearFlag to tell the painter don't clear the layer if it's the first element. */ // TODO Style override ? function IncrementalDisplayble(opts) { Displayble.call(this, opts); this._displayables = []; this._temporaryDisplayables = []; this._cursor = 0; this.notClear = true; } IncrementalDisplayble.prototype.incremental = true; IncrementalDisplayble.prototype.clearDisplaybles = function () { this._displayables = []; this._temporaryDisplayables = []; this._cursor = 0; this.dirty(); this.notClear = false; }; IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) { if (notPersistent) { this._temporaryDisplayables.push(displayable); } else { this._displayables.push(displayable); } this.dirty(); }; IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) { notPersistent = notPersistent || false; for (var i = 0; i < displayables.length; i++) { this.addDisplayable(displayables[i], notPersistent); } }; IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) { for (var i = this._cursor; i < this._displayables.length; i++) { cb && cb(this._displayables[i]); } for (var i = 0; i < this._temporaryDisplayables.length; i++) { cb && cb(this._temporaryDisplayables[i]); } }; IncrementalDisplayble.prototype.update = function () { this.updateTransform(); for (var i = this._cursor; i < this._displayables.length; i++) { var displayable = this._displayables[i]; // PENDING displayable.parent = this; displayable.update(); displayable.parent = null; } for (var i = 0; i < this._temporaryDisplayables.length; i++) { var displayable = this._temporaryDisplayables[i]; // PENDING displayable.parent = this; displayable.update(); displayable.parent = null; } }; IncrementalDisplayble.prototype.brush = function (ctx, prevEl) { // Render persistant displayables. for (var i = this._cursor; i < this._displayables.length; i++) { var displayable = this._displayables[i]; displayable.beforeBrush && displayable.beforeBrush(ctx); displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]); displayable.afterBrush && displayable.afterBrush(ctx); } this._cursor = i; // Render temporary displayables. for (var i = 0; i < this._temporaryDisplayables.length; i++) { var displayable = this._temporaryDisplayables[i]; displayable.beforeBrush && displayable.beforeBrush(ctx); displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]); displayable.afterBrush && displayable.afterBrush(ctx); } this._temporaryDisplayables = []; this.notClear = true; }; var m = []; IncrementalDisplayble.prototype.getBoundingRect = function () { if (!this._rect) { var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity); for (var i = 0; i < this._displayables.length; i++) { var displayable = this._displayables[i]; var childRect = displayable.getBoundingRect().clone(); if (displayable.needLocalTransform()) { childRect.applyTransform(displayable.getLocalTransform(m)); } rect.union(childRect); } this._rect = rect; } return this._rect; }; IncrementalDisplayble.prototype.contain = function (x, y) { var localPos = this.transformCoordToLocal(x, y); var rect = this.getBoundingRect(); if (rect.contain(localPos[0], localPos[1])) { for (var i = 0; i < this._displayables.length; i++) { var displayable = this._displayables[i]; if (displayable.contain(x, y)) { return true; } } } return false; }; inherits(IncrementalDisplayble, Displayble); var _default = IncrementalDisplayble; module.exports = _default; /***/ }, /* 76 */ /*!*********************************!*\ !*** ./src/liquidFillLayout.js ***! \*********************************/ /***/ function(module, exports, __webpack_require__) { var echarts = __webpack_require__(/*! echarts/lib/echarts */ 2); module.exports = echarts.graphic.extendShape({ type: 'ec-liquid-fill', shape: { waveLength: 0, radius: 0, cx: 0, cy: 0, waterLevel: 0, amplitude: 0, phase: 0, inverse: false }, buildPath: function (ctx, shape) { /** * We define a sine wave having 4 waves, and make sure at least 8 curves * is drawn. Otherwise, it may cause blank area for some waves when * wave length is large enough. */ var curves = Math.max( Math.ceil(2 * shape.radius / shape.waveLength * 4) * 2, 8 ); // map phase to [-Math.PI * 2, 0] while (shape.phase < -Math.PI * 2) { shape.phase += Math.PI * 2; } while (shape.phase > 0) { shape.phase -= Math.PI * 2; } var phase = shape.phase / Math.PI / 2 * shape.waveLength; var left = shape.cx - shape.radius + phase - shape.radius * 2; /** * top-left corner as start point * * draws this point * | * \|/ * ~~~~~~~~ * | | * +------+ */ ctx.moveTo(left, shape.waterLevel); /** * top wave * * ~~~~~~~~ <- draws this sine wave * | | * +------+ */ var waveRight = 0; for (var c = 0; c < curves; ++c) { var stage = c % 4; var pos = getWaterPositions(c * shape.waveLength / 4, stage, shape.waveLength, shape.amplitude); ctx.bezierCurveTo(pos[0][0] + left, -pos[0][1] + shape.waterLevel, pos[1][0] + left, -pos[1][1] + shape.waterLevel, pos[2][0] + left, -pos[2][1] + shape.waterLevel); if (c === curves - 1) { waveRight = pos[2][0]; } } if (shape.inverse) { /** * top-right corner * 2. draws this line * | * +------+ * 3. draws this line -> | | <- 1. draws this line * ~~~~~~~~ */ ctx.lineTo(waveRight + left, shape.cy - shape.radius); ctx.lineTo(left, shape.cy - shape.radius); ctx.lineTo(left, shape.waterLevel); } else { /** * top-right corner * * ~~~~~~~~ * 3. draws this line -> | | <- 1. draws this line * +------+ * ^ * | * 2. draws this line */ ctx.lineTo(waveRight + left, shape.cy + shape.radius); ctx.lineTo(left, shape.cy + shape.radius); ctx.lineTo(left, shape.waterLevel); } ctx.closePath(); } }); /** * Using Bezier curves to fit sine wave. * There is 4 control points for each curve of wave, * which is at 1/4 wave length of the sine wave. * * The control points for a wave from (a) to (d) are a-b-c-d: * c *----* d * b * * | * ... a * .................. * * whose positions are a: (0, 0), b: (0.5, 0.5), c: (1, 1), d: (PI / 2, 1) * * @param {number} x x position of the left-most point (a) * @param {number} stage 0-3, stating which part of the wave it is * @param {number} waveLength wave length of the sine wave * @param {number} amplitude wave amplitude */ function getWaterPositions(x, stage, waveLength, amplitude) { if (stage === 0) { return [ [x + 1 / 2 * waveLength / Math.PI / 2, amplitude / 2], [x + 1 / 2 * waveLength / Math.PI, amplitude], [x + waveLength / 4, amplitude] ]; } else if (stage === 1) { return [ [x + 1 / 2 * waveLength / Math.PI / 2 * (Math.PI - 2), amplitude], [x + 1 / 2 * waveLength / Math.PI / 2 * (Math.PI - 1), amplitude / 2], [x + waveLength / 4, 0] ] } else if (stage === 2) { return [ [x + 1 / 2 * waveLength / Math.PI / 2, -amplitude / 2], [x + 1 / 2 * waveLength / Math.PI, -amplitude], [x + waveLength / 4, -amplitude] ] } else { return [ [x + 1 / 2 * waveLength / Math.PI / 2 * (Math.PI - 2), -amplitude], [x + 1 / 2 * waveLength / Math.PI / 2 * (Math.PI - 1), -amplitude / 2], [x + waveLength / 4, 0] ] } } /***/ }, /* 77 */ /*!*******************************************!*\ !*** ./~/echarts/lib/visual/dataColor.js ***! \*******************************************/ /***/ function(module, exports, __webpack_require__) { var _util = __webpack_require__(/*! zrender/lib/core/util */ 5); var createHashMap = _util.createHashMap; /* * 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. */ // Pick color from palette for each data item. // Applicable for charts that require applying color palette // in data level (like pie, funnel, chord). function _default(seriesType) { return { getTargetSeries: function (ecModel) { // Pie and funnel may use diferrent scope var paletteScope = {}; var seiresModelMap = createHashMap(); ecModel.eachSeriesByType(seriesType, function (seriesModel) { seriesModel.__paletteScope = paletteScope; seiresModelMap.set(seriesModel.uid, seriesModel); }); return seiresModelMap; }, reset: function (seriesModel, ecModel) { var dataAll = seriesModel.getRawData(); var idxMap = {}; var data = seriesModel.getData(); data.each(function (idx) { var rawIdx = data.getRawIndex(idx); idxMap[rawIdx] = idx; }); dataAll.each(function (rawIdx) { var filteredIdx = idxMap[rawIdx]; // If series.itemStyle.normal.color is a function. itemVisual may be encoded var singleDataColor = filteredIdx != null && data.getItemVisual(filteredIdx, 'color', true); if (!singleDataColor) { // FIXME Performance var itemModel = dataAll.getItemModel(rawIdx); var color = itemModel.get('itemStyle.color') || seriesModel.getColorFromPalette(dataAll.getName(rawIdx) || rawIdx + '', seriesModel.__paletteScope, dataAll.count()); // Legend may use the visual info in data before processed dataAll.setItemVisual(rawIdx, 'color', color); // Data is not filtered if (filteredIdx != null) { data.setItemVisual(filteredIdx, 'color', color); } } else { // Set data all color for legend dataAll.setItemVisual(rawIdx, 'color', singleDataColor); } }); } }; } module.exports = _default; /***/ } /******/ ]) }); ; //# sourceMappingURL=echarts-liquidfill.js.map
thisMa
bitmap_test.go
package bitmap_test import ( "image" "image/color" "image/png" "io/ioutil" "os" "testing" // Modules gopi "github.com/djthorpe/gopi/v3" bitmap "github.com/djthorpe/gopi/v3/pkg/graphics/bitmap" tool "github.com/djthorpe/gopi/v3/pkg/tool" // Dependencies _ "github.com/djthorpe/gopi/v3/pkg/graphics/bitmap/rgba32" _ "github.com/djthorpe/gopi/v3/pkg/graphics/bitmap/rgba32dx" _ "github.com/djthorpe/gopi/v3/pkg/hw/platform" ) type App struct { gopi.Unit *bitmap.Bitmaps } const ( PNG_FILEPATH = "../../../etc/images/gopi-800x388.png" ) func Test_Bitmap_001(t *testing.T) { tool.Test(t, nil, new(App), func(app *App) { app.Require(app.Bitmaps) if bitmap, err := app.NewBitmap(gopi.SURFACE_FMT_RGBA32, 10, 10); err != nil { t.Error(err) } else { t.Log(bitmap) } }) } func Test_Bitmap_002(t *testing.T) { tool.Test(t, nil, new(App), func(app *App) { app.Require(app.Bitmaps) bitmap, err := app.NewBitmap(gopi.SURFACE_FMT_RGBA32, 100, 100) if err != nil { t.Fatal(err) } bitmap.ClearToColor(color.RGBA{0xFF, 0x00, 0x00, 0xFF}) if writer, err := ioutil.TempFile("", "png"); err != nil { t.Error(err) } else if err := png.Encode(writer, bitmap); err != nil { t.Error(err) } else { writer.Close() t.Log(writer.Name()) } }) } func Test_Bitmap_003(t *testing.T) { tool.Test(t, nil, new(App), func(app *App) { app.Require(app.Bitmaps) reader, err := os.Open(PNG_FILEPATH) if err != nil { t.Fatal(err) } defer reader.Close() if bitmap, _, err := image.Decode(reader); err != nil { t.Error(err) } else if dest, err := app.NewBitmap(gopi.SURFACE_FMT_RGBA32, uint32(bitmap.Bounds().Dx()), uint32(bitmap.Bounds().Dy())); err != nil { t.Error(err) } else { bounds := bitmap.Bounds() for y := bounds.Min.Y; y <= bounds.Max.Y; y++ { for x := bounds.Min.X; x <= bounds.Max.X; x++ { c := bitmap.At(x, y) dest.SetAt(c, x, y)
t.Error(err) } else if err := png.Encode(writer, dest); err != nil { t.Error(err) } else { writer.Close() t.Log(writer.Name()) } } }) }
} } if writer, err := ioutil.TempFile("", "png"); err != nil {
participant.py
import copy from pathlib import Path from typing import Dict, List, Optional, Union import torch from pytorch_lightning.metrics import Accuracy from torch import Tensor, optim from torch.utils import data import pytorch_lightning as pl from pytorch_lightning.loggers import LightningLoggerBase from pytorch_lightning.callbacks.base import Callback from mlmi.structs import OptimizerArgs, TrainArgs, ModelArgs from mlmi.log import getLogger from mlmi.settings import CHECKPOINT_DIR logger = getLogger(__name__) def optimizer_state_dict_to_cpu(optimizer_state_dict): c = copy.deepcopy(optimizer_state_dict) o = {} state_dict = c.get('state') r = {} for key, state in state_dict.items(): s = {} for k, v in state.items(): if torch.is_tensor(v): s[k] = v.cpu() else: s[k] = v r[key] = s o['state'] = r o['param_groups'] = c.get('param_groups') return o class BaseParticipant(object): def __init__(self, participant_name: str, model_args: ModelArgs, context): assert participant_name is not None, 'A participant name is required to load and save logs' assert model_args is not None, 'Model args are required to initialize a model for the participant' assert context is not None, 'Experiment context is required for participant' self._name = participant_name self._cluster_id = None self._experiment_context = context participant_model_kwargs = self.get_model_kwargs() if participant_model_kwargs is not None: self._model = model_args(participant_name=participant_name, **participant_model_kwargs) else: self._model = model_args(participant_name=participant_name) self._model_args = model_args def get_model_kwargs(self) -> Optional[Dict]: return None @property def model(self) -> Union[pl.LightningModule, 'BaseParticipantModel']: """ The model to train :return: The model """ return self._model @property def cluster_id(self) -> str: return self._cluster_id @cluster_id.setter def cluster_id(self, value: str): self._cluster_id = value def overwrite_model_state(self, model_state: Dict[str, Tensor]): """ Loads the model state into the current model instance :param model_state: The model state to load """ self._model.load_state_dict(model_state, strict=False) def load_model_state_from_checkpoint(self): """ Load the model state from an existing saved checkpoint """ self._model = self._model_args.model_class.load_from_checkpoint( checkpoint_path=str(self.get_checkpoint_path().absolute())) def get_checkpoint_path(self, suffix: Union[str, None] = None) -> Path: """ Constructs a checkpoint path based on :return: """ str_suffix = '' if suffix is None else '_' + suffix filename = (self._name + str_suffix + '.ckpt') return CHECKPOINT_DIR / self._experiment_context.name / filename def save_model_state(self): """ Saves the model state of the aggregated model :param target_path: The path to save the model at :return: """ path = self.get_checkpoint_path() path.parent.mkdir(parents=True, exist_ok=True) torch.save(self._model.state_dict(), path) class BaseTrainingParticipant(BaseParticipant): def __init__(self, client_id: str, model_args: ModelArgs, context, train_dataloader: data.DataLoader, num_train_samples: int, test_dataloader: data.DataLoader, num_test_samples: int, lightning_logger: LightningLoggerBase, *args, **kwargs): self._train_dataloader = train_dataloader self._test_dataloader = test_dataloader self._num_train_samples = sum([len(y) for x, y in train_dataloader]) self._num_test_samples = num_test_samples self._lightning_logger = lightning_logger self._callbacks = None self._model_state = None self._trainer = None super().__init__(client_id, model_args, context) def create_trainer(self, enable_logging=True, **kwargs) -> pl.Trainer: """ Creates a new trainer instance for each training round. :param kwargs: additional keyword arguments to send to the trainer for configuration :return: a pytorch lightning trainer instance """ _kwargs = kwargs.copy() _kwargs['logger'] = self.logger _kwargs['checkpoint_callback'] = False if torch.cuda.is_available(): _kwargs['gpus'] = 1 return pl.Trainer(callbacks=self._callbacks, limit_val_batches=0.0, **_kwargs) def set_trainer_callbacks(self, callbacks: List[Callback]): self._callbacks = callbacks @property def logger(self) -> LightningLoggerBase: """ Gets the logger to use for the training in later stage. :return: The lightning logger to use """ return self._lightning_logger @property def train_data_loader(self) -> data.DataLoader: return self._train_dataloader @property def test_data_loader(self) -> data.DataLoader: return self._test_dataloader @property def num_train_samples(self) -> int: return self._num_train_samples @property def num_test_samples(self) -> int: return self._num_test_samples def train(self, training_args: TrainArgs, *args, **kwargs): """ Implement the training routine. :param training_args: :param args: :param kwargs: :return: """ trainer = self.create_trainer(enable_logging=False, **training_args.kwargs) train_dataloader = self.train_data_loader trainer.fit(self.model, train_dataloader) del self.model.trainer def test(self, model: Optional[torch.nn.Module] = None, use_local_model: bool = False): """ Test the model state on this clients data. :param :param model_state: The model state to evaluate :return: The output loss """ assert use_local_model or model is not None trainer = self.create_trainer(enable_logging=False, progress_bar_refresh_rate=0) if use_local_model: result = trainer.test(model=self.model, test_dataloaders=self.test_data_loader, verbose=False) self._model = self._model.cpu() del self._model.trainer else: result = trainer.test(model=model, test_dataloaders=self.test_data_loader, verbose=False) return result class BaseAggregatorParticipant(BaseParticipant): def __init__(self, participant_name: str, model_args: ModelArgs, context): super().__init__(participant_name, model_args, context) def aggregate(self, participants: List['BaseTrainingParticipant'], *args, **kwargs): """ Aggregate the models of other participants with their models. :param participants: Participants to apply the model changes from :return: """ raise NotImplementedError() class BaseParticipantModel(object): def __init__(self, *args, participant_name=None, optimizer_args: Optional[OptimizerArgs]=None, model=None, **kwargs): assert participant_name is not None, 'Please provide a participant name parameter in model args to identify' \ 'your model in logging' assert optimizer_args is not None, 'Optimizer args not set!' assert model is not None, 'Model not passed!' self.participant_name = participant_name self.optimizer_args = optimizer_args super().__init__(*args, **kwargs) self.model = model self._optimizer_state = None @property def optimizer_state(self): return self._optimizer_state @optimizer_state.setter def optimizer_state(self, value):
def configure_optimizers(self): return self.optimizer_args(self.model.parameters()) """ Do not restore state if self.optimizer_state is not None: optimizer.load_state_dict(self.optimizer_state) return optimizer """
self._optimizer_state = value
(8 kyu) Even or Odd.rs
fn even_or_odd(i: i32) -> &'static str
{ // #1 // if i % 2 == 0 { // return "Even"; // } else { // return "Odd"; // } // #2 // return if i % 2 == 0 { "Even" } else { "Odd" }; // #3 // if i % 2 == 0 { "Even" } else { "Odd" } // #4 if i & 1 == 0 { "Even" } else { "Odd" } }
proto3.go
// Copyright 2015, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package logutil import ( "time" logutilpb "github.com/gitql/vitess/go/vt/proto/logutil" ) // This file contains a few functions to help with proto3. // ProtoToTime converts a logutilpb.Time to a time.Time. // proto3 will eventually support timestamps, at which point we'll retire // this. // // A nil pointer is like the empty timestamp. func ProtoToTime(ts *logutilpb.Time) time.Time { if ts == nil { // treat nil like the empty Timestamp return time.Unix(0, 0).UTC() } return time.Unix(ts.Seconds, int64(ts.Nanoseconds)).UTC() } // TimeToProto converts the time.Time to a logutilpb.Time. func
(t time.Time) *logutilpb.Time { seconds := t.Unix() nanos := int64(t.Sub(time.Unix(seconds, 0))) return &logutilpb.Time{ Seconds: seconds, Nanoseconds: int32(nanos), } } // EventStream is an interface used by RPC clients when the streaming // RPC returns a stream of log events. type EventStream interface { // Recv returns the next event in the logs. // If there are no more, it will return io.EOF. Recv() (*logutilpb.Event, error) }
TimeToProto
send_batch.rs
use super::{Batch, PacketError, BATCH_SIZE}; use native::mbuf_free_bulk; use native::mbuf::MBuf; use packets::Packet; use scheduler::Executable; use interface::PacketTx; /// Send operator /// /// Marks the end of a pipeline. pub struct SendBatch<B: Batch, Tx: PacketTx> { source: B, port: Tx, transmit_q: Vec<*mut MBuf>, drop_q: Vec<*mut MBuf>, } impl<B: Batch, Tx: PacketTx> SendBatch<B, Tx> { #[inline] pub fn new(source: B, port: Tx) -> Self { SendBatch { source, port, transmit_q: Vec::with_capacity(BATCH_SIZE), drop_q: Vec::with_capacity(BATCH_SIZE), } } } impl<B: Batch, Tx: PacketTx> Executable for SendBatch<B, Tx> { fn
(&mut self) -> usize { self.source.receive(); let transmit_q = &mut self.transmit_q; let drop_q = &mut self.drop_q; while let Some(item) = self.source.next() { match item { Ok(packet) => { transmit_q.push(packet.mbuf()); } Err(PacketError::Emit(mbuf)) => { transmit_q.push(mbuf); } Err(PacketError::Drop(mbuf)) => { drop_q.push(mbuf); } Err(PacketError::Abort(mbuf, err)) => { error_chain!(&err); drop_q.push(mbuf); } } } let pkt_sents = transmit_q.len(); if !transmit_q.is_empty() { let mut to_send = transmit_q.len(); while to_send > 0 { match self.port.send(transmit_q.as_mut_slice()) { Ok(sent) => { let sent = sent as usize; to_send -= sent; if to_send > 0 { transmit_q.drain(..sent); } } // the underlying DPDK method `rte_eth_tx_burst` will // never return an error. The error arm is unreachable _ => unreachable!(), } } unsafe { transmit_q.set_len(0); } } if !drop_q.is_empty() { let len = drop_q.len(); let ptr = drop_q.as_mut_ptr(); unsafe { // never have a non-zero return mbuf_free_bulk(ptr, len as i32); drop_q.set_len(0); } } pkt_sents } #[inline] fn dependencies(&mut self) -> Vec<usize> { vec![] } }
execute
eviction.rs
// Generated from definition io.k8s.api.policy.v1beta1.Eviction /// Eviction evicts a pod from its node subject to certain policies and safety constraints. This is a subresource of Pod. A request to cause such an eviction is created by POSTing to .../pods/\<pod name\>/evictions. #[derive(Clone, Debug, Default, PartialEq)] pub struct
{ /// DeleteOptions may be provided pub delete_options: Option<crate::v1_11::apimachinery::pkg::apis::meta::v1::DeleteOptions>, /// ObjectMeta describes the pod that is being evicted. pub metadata: Option<crate::v1_11::apimachinery::pkg::apis::meta::v1::ObjectMeta>, } // Begin policy/v1beta1/Eviction // Generated from operation createCoreV1NamespacedPodEviction impl Eviction { /// create eviction of a Pod /// /// Use the returned [`crate::ResponseBody`]`<`[`CreateNamespacedPodEvictionResponse`]`>` constructor, or [`CreateNamespacedPodEvictionResponse`] directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Eviction /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `body` /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn create_namespaced_pod_eviction( name: &str, namespace: &str, body: &crate::v1_11::api::policy::v1beta1::Eviction, optional: CreateNamespacedPodEvictionOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<CreateNamespacedPodEvictionResponse>), crate::RequestError> { let CreateNamespacedPodEvictionOptional { pretty, } = optional; let __url = format!("/api/v1/namespaces/{namespace}/pods/{name}/eviction?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); if let Some(pretty) = pretty { __query_pairs.append_pair("pretty", pretty); } let __url = __query_pairs.finish(); let mut __request = http::Request::post(__url); let __body = serde_json::to_vec(body).map_err(crate::RequestError::Json)?; __request.header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static("application/json")); match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } /// Optional parameters of [`Eviction::create_namespaced_pod_eviction`] #[cfg(feature = "api")] #[derive(Clone, Copy, Debug, Default)] pub struct CreateNamespacedPodEvictionOptional<'a> { /// If 'true', then the output is pretty printed. pub pretty: Option<&'a str>, } /// Use `<CreateNamespacedPodEvictionResponse as Response>::try_from_parts` to parse the HTTP response body of [`Eviction::create_namespaced_pod_eviction`] #[cfg(feature = "api")] #[derive(Debug)] pub enum CreateNamespacedPodEvictionResponse { Ok(crate::v1_11::api::policy::v1beta1::Eviction), Created(crate::v1_11::api::policy::v1beta1::Eviction), Accepted(crate::v1_11::api::policy::v1beta1::Eviction), Other(Result<Option<serde_json::Value>, serde_json::Error>), } #[cfg(feature = "api")] impl crate::Response for CreateNamespacedPodEvictionResponse { fn try_from_parts(status_code: http::StatusCode, buf: &[u8]) -> Result<(Self, usize), crate::ResponseError> { match status_code { http::StatusCode::OK => { let result = match serde_json::from_slice(buf) { Ok(value) => value, Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => return Err(crate::ResponseError::Json(err)), }; Ok((CreateNamespacedPodEvictionResponse::Ok(result), buf.len())) }, http::StatusCode::CREATED => { let result = match serde_json::from_slice(buf) { Ok(value) => value, Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => return Err(crate::ResponseError::Json(err)), }; Ok((CreateNamespacedPodEvictionResponse::Created(result), buf.len())) }, http::StatusCode::ACCEPTED => { let result = match serde_json::from_slice(buf) { Ok(value) => value, Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => return Err(crate::ResponseError::Json(err)), }; Ok((CreateNamespacedPodEvictionResponse::Accepted(result), buf.len())) }, _ => { let (result, read) = if buf.is_empty() { (Ok(None), 0) } else { match serde_json::from_slice(buf) { Ok(value) => (Ok(Some(value)), buf.len()), Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => (Err(err), 0), } }; Ok((CreateNamespacedPodEvictionResponse::Other(result), read)) }, } } } // End policy/v1beta1/Eviction impl crate::Resource for Eviction { fn api_version() -> &'static str { "policy/v1beta1" } fn group() -> &'static str { "policy" } fn kind() -> &'static str { "Eviction" } fn version() -> &'static str { "v1beta1" } } impl crate::Metadata for Eviction { type Ty = crate::v1_11::apimachinery::pkg::apis::meta::v1::ObjectMeta; fn metadata(&self) -> Option<&<Self as crate::Metadata>::Ty> { self.metadata.as_ref() } } impl<'de> serde::Deserialize<'de> for Eviction { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { #[allow(non_camel_case_types)] enum Field { Key_api_version, Key_kind, Key_delete_options, Key_metadata, Other, } impl<'de> serde::Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Field; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "field identifier") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error { Ok(match v { "apiVersion" => Field::Key_api_version, "kind" => Field::Key_kind, "deleteOptions" => Field::Key_delete_options, "metadata" => Field::Key_metadata, _ => Field::Other, }) } } deserializer.deserialize_identifier(Visitor) } } struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Eviction; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "struct Eviction") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> { let mut value_delete_options: Option<crate::v1_11::apimachinery::pkg::apis::meta::v1::DeleteOptions> = None; let mut value_metadata: Option<crate::v1_11::apimachinery::pkg::apis::meta::v1::ObjectMeta> = None; while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? { match key { Field::Key_api_version => { let value_api_version: String = serde::de::MapAccess::next_value(&mut map)?; if value_api_version != <Self::Value as crate::Resource>::api_version() { return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(&value_api_version), &<Self::Value as crate::Resource>::api_version())); } }, Field::Key_kind => { let value_kind: String = serde::de::MapAccess::next_value(&mut map)?; if value_kind != <Self::Value as crate::Resource>::kind() { return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(&value_kind), &<Self::Value as crate::Resource>::kind())); } }, Field::Key_delete_options => value_delete_options = serde::de::MapAccess::next_value(&mut map)?, Field::Key_metadata => value_metadata = serde::de::MapAccess::next_value(&mut map)?, Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(Eviction { delete_options: value_delete_options, metadata: value_metadata, }) } } deserializer.deserialize_struct( "Eviction", &[ "apiVersion", "kind", "deleteOptions", "metadata", ], Visitor, ) } } impl serde::Serialize for Eviction { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state = serializer.serialize_struct( "Eviction", 2 + self.delete_options.as_ref().map_or(0, |_| 1) + self.metadata.as_ref().map_or(0, |_| 1), )?; serde::ser::SerializeStruct::serialize_field(&mut state, "apiVersion", <Self as crate::Resource>::api_version())?; serde::ser::SerializeStruct::serialize_field(&mut state, "kind", <Self as crate::Resource>::kind())?; if let Some(value) = &self.delete_options { serde::ser::SerializeStruct::serialize_field(&mut state, "deleteOptions", value)?; } if let Some(value) = &self.metadata { serde::ser::SerializeStruct::serialize_field(&mut state, "metadata", value)?; } serde::ser::SerializeStruct::end(state) } }
Eviction
read.ts
import extractComments from "extract-comments"; import { Either, Entry, Entries, Left, Right, isLeft } from "./types"; import { START_TAG, END_TAG, TAG_PREFIX } from "./syntax"; import { r } from "./common"; const REGEX_START_TAG = new RegExp(r`^\s*` + START_TAG + r`\s*$`); const REGEX_END_TAG = new RegExp(r`^\s*` + END_TAG + r`\s*$`); export const enum ExtractionError { NO_LINE_COMMENTS = "NO_LINE_COMMENTS", NO_START_TAG = "NO_START_TAG", NO_END_TAG = "NO_END_TAG", END_TAG_BEFORE_START_TAG = "END_TAG_BEFORE_START_TAG", } export type ExtractionResult = Either<ExtractionError, string> export type BlockParseResult = Either<ReadonlyArray<string>, Entries> type LineParseResult = Either<string, Entry> export function extractBlock(userscript: string): ExtractionResult { const lineComments = ( extractComments(userscript) .filter(c => c.type === "LineComment") .map(c => c.raw) ); if (lineComments.length === 0) { return Left(ExtractionError.NO_LINE_COMMENTS); } else { const startTagIndex = lineComments.findIndex(x => REGEX_START_TAG.test(x)); const endTagIndex = lineComments.findIndex(x => REGEX_END_TAG.test(x)); if (startTagIndex < 0) { return Left(ExtractionError.NO_START_TAG); } else if (endTagIndex < 0) { return Left(ExtractionError.NO_END_TAG); } else if (endTagIndex < startTagIndex) { return Left(ExtractionError.END_TAG_BEFORE_START_TAG); } else { return Right(lineComments.slice(startTagIndex+1, endTagIndex).join("\n")); } } } export function parseBlock(block: string): BlockParseResult { const lines = block.split("\n").filter(line => /\S/.test(line)); const validEntries: Entry[] = []; const invalidLines: string[] = []; lines.map(parseLine).forEach(result => { if (isLeft(result)) { invalidLines.push(result.Left); } else { validEntries.push(result.Right);
}); return invalidLines.length > 0 ? Left(invalidLines) : Right(validEntries); } // `line` is expected to be a line without any comment prefix, but leading whitespace is OK. export function parseLine(line: string): LineParseResult { const match = line.match(new RegExp( r`^\s*` + TAG_PREFIX + r`([a-z\-]+)` + r`(?:\s*|\s+(\S.*))$`, "i", )); if (match === null) { return Left(line); } else { const key = match[1]; const value = match[2]; return Right({ key, value: value ? value.trimEnd() : true } as Entry); } }
}
_util.ts
// --------------------------------------------------------------------------------------------------------------------- // node-kisl | Copyright (C) 2020 eth-p | MIT License // https://github.com/eth-p/node-kisl // --------------------------------------------------------------------------------------------------------------------- /**
* @param debug The debug pattern to compile. * * @return A function that checks module names against the compiled pattern. */ export function compileDebugMatcher(debug: string): (module: string) => boolean { function formatRegex(char: string) { switch (char) { case "*": return '[^:]*'; case "**": return ".*"; default: return `\\u{${char.charCodeAt(0).toString(16)}}`; } } const patterns: [RegExp, boolean][] = debug.split(",") .map(p => p.trim()) .map(p => (p.startsWith('-') ? [p.substring(1), false] : [p, true]) as [string, boolean]) .map(([p, type]) => [ new RegExp(`^${Array.from(p).map(formatRegex).join('')}$`, 'u'), type ]); return function(module: string) { let result = false; patterns.forEach(([pattern, type]) => { if (pattern.test(module)) { result = type; } }); return result; } }
* Compiles a function that checks if a `DEBUG=...` environment variable matches a module name. *
methods.go
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: LGPL-3.0-only package utils // An available method on the substrate chain type Method string var AddRelayerMethod Method = BridgePalletName + ".add_relayer" var SetResourceMethod Method = BridgePalletName + ".set_resource" var SetThresholdMethod Method = BridgePalletName + ".set_threshold" var WhitelistChainMethod Method = BridgePalletName + ".whitelist_chain" var ExampleTransferNativeMethod Method = "Example.transfer_native" var ExampleTransferErc721Method Method = "Example.transfer_erc721"
var ExampleMintErc721Method Method = "Example.mint_erc721" var ExampleTransferMethod Method = "Example.transfer" var ExampleRemarkMethod Method = "Example.remark" var Erc721MintMethod Method = "Erc721.mint" var SudoMethod Method = "Sudo.sudo" var BalancesTransferMethod Method = "Balances.transfer" var BalancesTransferKeepAliveMethod Method = "Balances.transfer_keep_alive" var SystemRemark Method = "System.remark" var UtilityBatch Method = "Utility.batch" var UtilityBatchAll Method = "Utility.batchall" var MultisigAsMulti Method = "Multisig.as_multi" /// ChainX Method var XAssetsTransferMethod Method = "XAssets.transfer"
var ExampleTransferHashMethod Method = "Example.transfer_hash"
CalendarPage.tsx
import * as React from 'react'; import { ExampleCard, ComponentPage, PropertiesTableSet, PageMarkdown } from '@uifabric/example-app-base'; import { DateRangeType, DayOfWeek } from '../Calendar/Calendar.types'; import { CalendarButtonExample } from '../Calendar/examples/Calendar.Button.Example'; import { CalendarInlineExample } from '../Calendar/examples/Calendar.Inline.Example'; import { addMonths, addYears, addDays } from 'office-ui-fabric-react/lib/utilities/dateMath/DateMath'; const CalendarButtonExampleCode = require('!raw-loader!@uifabric/date-time/src/components/Calendar/examples/Calendar.Button.Example.tsx') as string; const CalendarButtonExampleCodepen = require('!@uifabric/codepen-loader!@uifabric/date-time/src/components/Calendar/examples/Calendar.Button.Example.tsx') as string; const CalendarInlineExampleCode = require('!raw-loader!@uifabric/date-time/src/components/Calendar/examples/Calendar.Inline.Example.tsx') as string; const CalendarInlineExampleCodepen = require('!@uifabric/codepen-loader!@uifabric/date-time/src/components/Calendar/examples/Calendar.Inline.Example.tsx') as string; const today = new Date(Date.now()); export class CalendarPage extends React.Component<{}, {}> { public render(): JSX.Element { return ( <ComponentPage title="Calendar" componentName="Calendar" exampleCards={ <div> <ExampleCard title="Inline Calendar" code={CalendarInlineExampleCode} codepenJS={CalendarInlineExampleCodepen}> <CalendarInlineExample isMonthPickerVisible={false} dateRangeType={DateRangeType.Day} autoNavigateOnSelection={false} showGoToToday={true} /> </ExampleCard> <ExampleCard title="Inline Calendar with overlayed month picker when header is clicked" code={CalendarInlineExampleCode}> <CalendarInlineExample showMonthPickerAsOverlay={true} highlightCurrentMonth={false} highlightSelectedMonth={true} dateRangeType={DateRangeType.Day} autoNavigateOnSelection={false} showGoToToday={false} /> </ExampleCard> <ExampleCard title="Inline Calendar with month picker" code={CalendarInlineExampleCode}> <CalendarInlineExample dateRangeType={DateRangeType.Day} autoNavigateOnSelection={false} highlightCurrentMonth={false} highlightSelectedMonth={true} showGoToToday={true} /> </ExampleCard> <ExampleCard title="Inline Calendar with week selection" code={CalendarInlineExampleCode}> <CalendarInlineExample dateRangeType={DateRangeType.Week} autoNavigateOnSelection={true} highlightCurrentMonth={false} highlightSelectedMonth={true} showGoToToday={true} showNavigateButtons={true} /> </ExampleCard> <ExampleCard title="Inline Calendar with month selection" code={CalendarInlineExampleCode}> <CalendarInlineExample dateRangeType={DateRangeType.Month} autoNavigateOnSelection={true} highlightCurrentMonth={false} highlightSelectedMonth={true} showGoToToday={true} showNavigateButtons={true} /> </ExampleCard> <ExampleCard title="Inline Calendar with week numbers" code={CalendarInlineExampleCode}> <CalendarInlineExample isMonthPickerVisible={false} dateRangeType={DateRangeType.Day} autoNavigateOnSelection={false} showGoToToday={true} showWeekNumbers={true} /> </ExampleCard> <ExampleCard title="Inline Calendar with 6 weeks display by default" code={CalendarInlineExampleCode}> <CalendarInlineExample isMonthPickerVisible={false} dateRangeType={DateRangeType.Day} autoNavigateOnSelection={false} showGoToToday={true} showSixWeeksByDefault={true} />
</ExampleCard> <ExampleCard title="Inline Calendar with month picker and no day picker" code={CalendarInlineExampleCode}> <CalendarInlineExample dateRangeType={DateRangeType.Month} autoNavigateOnSelection={false} showGoToToday={true} highlightCurrentMonth={false} highlightSelectedMonth={true} isDayPickerVisible={false} /> </ExampleCard> <ExampleCard title="Inline Calendar with date boundary (minDate, maxDate) and disabled dates (restrictedDates)" code={CalendarInlineExampleCode} > <CalendarInlineExample dateRangeType={DateRangeType.Day} autoNavigateOnSelection={true} highlightCurrentMonth={false} highlightSelectedMonth={true} showGoToToday={false} minDate={addMonths(today, -1)} maxDate={addYears(today, 1)} restrictedDates={[addDays(today, -2), addDays(today, -8), addDays(today, 2), addDays(today, 8)]} /> </ExampleCard> <ExampleCard title="Calendar with selectableDays = [Tuesday, Wednesday, Friday, Saturday] provided, first day of week = Monday" code={CalendarInlineExampleCode} > <CalendarInlineExample dateRangeType={DateRangeType.WorkWeek} firstDayOfWeek={DayOfWeek.Monday} autoNavigateOnSelection={true} highlightCurrentMonth={false} highlightSelectedMonth={true} showGoToToday={true} workWeekDays={[DayOfWeek.Tuesday, DayOfWeek.Saturday, DayOfWeek.Wednesday, DayOfWeek.Friday]} /> </ExampleCard> <ExampleCard title="Calendar launched from a button" code={CalendarButtonExampleCode} codepenJS={CalendarButtonExampleCodepen}> <CalendarButtonExample highlightCurrentMonth={true} /> </ExampleCard> <ExampleCard title="Month picker launched from a button" code={CalendarButtonExampleCode}> <CalendarButtonExample isDayPickerVisible={false} highlightCurrentMonth={false} highlightSelectedMonth={true} buttonString={'Click for Month Picker'} /> </ExampleCard> <ExampleCard title="Calendar with overlayed month picker launched from a button" code={CalendarButtonExampleCode}> <CalendarButtonExample showMonthPickerAsOverlay={true} highlightCurrentMonth={false} highlightSelectedMonth={true} buttonString={'Click for Overlayed Day Picker and Month Picker'} /> </ExampleCard> <ExampleCard title="Calendar with overlayed month picker launched from a button without show go to today button" code={CalendarButtonExampleCode} > <CalendarButtonExample showMonthPickerAsOverlay={true} showGoToToday={false} highlightCurrentMonth={false} highlightSelectedMonth={true} buttonString={'Click for Overlayed Day Picker and Month Picker without go to today button'} /> </ExampleCard> </div> } propertiesTables={ <PropertiesTableSet sources={[require<string>('!raw-loader!@uifabric/date-time/src/components/Calendar/Calendar.types.ts')]} /> } // tslint:disable:deprecation overview={ <PageMarkdown>{require<string>('!raw-loader!@uifabric/date-time/src/components/Calendar/docs/CalendarOverview.md')}</PageMarkdown> } bestPractices={<div />} dos={<PageMarkdown>{require<string>('!raw-loader!@uifabric/date-time/src/components/Calendar/docs/CalendarDos.md')}</PageMarkdown>} donts={ <PageMarkdown>{require<string>('!raw-loader!@uifabric/date-time/src/components/Calendar/docs/CalendarDonts.md')}</PageMarkdown> } /> ); } }
model_search.py
import torch import torch.nn as nn import torch.nn.functional as F from operations import * from torch.autograd import Variable from genotypes import PRIMITIVES from genotypes import Genotype class MixedOp(nn.Module): def __init__(self, C, stride): super(MixedOp, self).__init__() self._ops = nn.ModuleList() for primitive in PRIMITIVES: op = OPS[primitive](C, stride, False) if 'pool' in primitive: op = nn.Sequential(op, nn.BatchNorm2d(C, affine=False)) self._ops.append(op) def forward(self, x, weights): return sum(w * op(x) for w, op in zip(weights, self._ops)) class Cell(nn.Module): def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev): super(Cell, self).__init__() self.reduction = reduction if reduction_prev: self.preprocess0 = FactorizedReduce(C_prev_prev, C, affine=False) else: self.preprocess0 = ReLUConvBN(C_prev_prev, C, 1, 1, 0, affine=False) self.preprocess1 = ReLUConvBN(C_prev, C, 1, 1, 0, affine=False) self._steps = steps self._multiplier = multiplier self._ops = nn.ModuleList() self._bns = nn.ModuleList() for i in range(self._steps): for j in range(2+i): stride = 2 if reduction and j < 2 else 1 op = MixedOp(C, stride) self._ops.append(op) def forward(self, s0, s1, weights): s0 = self.preprocess0(s0) s1 = self.preprocess1(s1) states = [s0, s1] offset = 0 for i in range(self._steps): s = sum(self._ops[offset+j](h, weights[offset+j]) for j, h in enumerate(states)) offset += len(states) states.append(s) return torch.cat(states[-self._multiplier:], dim=1) class Network(nn.Module): def __init__(self, C, num_classes, layers, criterion, steps=4, multiplier=4, stem_multiplier=3): super(Network, self).__init__() self._C = C self._num_classes = num_classes self._layers = layers self._criterion = criterion self._steps = steps self._multiplier = multiplier C_curr = stem_multiplier*C self.stem = nn.Sequential( nn.Conv2d(1, C_curr, 3, padding=1, bias=False), nn.BatchNorm2d(C_curr) ) C_prev_prev, C_prev, C_curr = C_curr, C_curr, C self.cells = nn.ModuleList() reduction_prev = False for i in range(layers): if i in [layers//3, 2*layers//3]: C_curr *= 2 reduction = True else: reduction = False cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction, reduction_prev) reduction_prev = reduction self.cells += [cell] C_prev_prev, C_prev = C_prev, multiplier*C_curr self.global_pooling = nn.AdaptiveAvgPool2d(1) self.classifier = nn.Linear(C_prev, num_classes) self._initialize_alphas() def new(self): model_new = Network(self._C, self._num_classes, self._layers, self._criterion).cuda() for x, y in zip(model_new.arch_parameters(), self.arch_parameters()): x.data.copy_(y.data) return model_new def forward(self, input): s0 = s1 = self.stem(input) for i, cell in enumerate(self.cells): if cell.reduction: weights = F.softmax(self.alphas_reduce, dim=-1) else: weights = F.softmax(self.alphas_normal, dim=-1) s0, s1 = s1, cell(s0, s1, weights) out = self.global_pooling(s1) logits = self.classifier(out.view(out.size(0),-1)) return logits def _loss(self, input, target): logits = self(input) return self._criterion(logits, target) def _initialize_alphas(self): k = sum(1 for i in range(self._steps) for n in range(2+i)) num_ops = len(PRIMITIVES) self.alphas_normal = Variable(1e-3*torch.randn(k, num_ops).cuda(), requires_grad=True) self.alphas_reduce = Variable(1e-3*torch.randn(k, num_ops).cuda(), requires_grad=True) self._arch_parameters = [ self.alphas_normal, self.alphas_reduce, ] def
(self): return self._arch_parameters def genotype(self): def _parse(weights): gene = [] n = 2 start = 0 for i in range(self._steps): end = start + n W = weights[start:end].copy() edges = sorted(range(i + 2), key=lambda x: -max(W[x][k] for k in range(len(W[x])) if k != PRIMITIVES.index('none')))[:2] for j in edges: k_best = None for k in range(len(W[j])): if k != PRIMITIVES.index('none'): if k_best is None or W[j][k] > W[j][k_best]: k_best = k gene.append((PRIMITIVES[k_best], j)) start = end n += 1 return gene gene_normal = _parse(F.softmax(self.alphas_normal, dim=-1).data.cpu().numpy()) gene_reduce = _parse(F.softmax(self.alphas_reduce, dim=-1).data.cpu().numpy()) concat = range(2+self._steps-self._multiplier, self._steps+2) genotype = Genotype( normal=gene_normal, normal_concat=concat, reduce=gene_reduce, reduce_concat=concat ) return genotype
arch_parameters
shuf.rs
// * This file is part of the uutils coreutils package. // * // * (c) Alex Lyon <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. // spell-checker:ignore (ToDO) cmdline evec seps rvec fdata use clap::{crate_version, App, AppSettings, Arg}; use rand::distributions::Uniform; use rand::Rng; use std::fs::File; use std::io::{stdin, stdout, BufReader, BufWriter, Read, Write}; use uucore::display::Quotable; use uucore::error::{FromIo, UResult, USimpleError}; use uucore::InvalidEncodingHandling; mod rand_read_adapter; enum Mode { Default(String), Echo(Vec<String>), InputRange((usize, usize)), } static NAME: &str = "shuf"; static USAGE: &str = r#"shuf [OPTION]... [FILE] or: shuf -e [OPTION]... [ARG]... or: shuf -i LO-HI [OPTION]... Write a random permutation of the input lines to standard output. With no FILE, or when FILE is -, read standard input. "#; static ABOUT: &str = "Shuffle the input by outputting a random permutation of input lines. Each output permutation is equally likely."; static TEMPLATE: &str = "Usage: {usage}\nMandatory arguments to long options are mandatory for short options too.\n{options}"; struct Options { head_count: usize, output: Option<String>, random_source: Option<String>, repeat: bool, sep: u8, } mod options { pub static ECHO: &str = "echo"; pub static INPUT_RANGE: &str = "input-range"; pub static HEAD_COUNT: &str = "head-count"; pub static OUTPUT: &str = "output"; pub static RANDOM_SOURCE: &str = "random-source"; pub static REPEAT: &str = "repeat"; pub static ZERO_TERMINATED: &str = "zero-terminated"; pub static FILE: &str = "file"; } #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let args = args .collect_str(InvalidEncodingHandling::ConvertLossy) .accept_any(); let matches = uu_app().get_matches_from(args); let mode = if let Some(args) = matches.values_of(options::ECHO) { Mode::Echo(args.map(String::from).collect()) } else if let Some(range) = matches.value_of(options::INPUT_RANGE) { match parse_range(range) { Ok(m) => Mode::InputRange(m), Err(msg) => { return Err(USimpleError::new(1, msg)); } } } else { Mode::Default(matches.value_of(options::FILE).unwrap_or("-").to_string()) }; let options = Options { head_count: match matches.value_of(options::HEAD_COUNT) { Some(count) => match count.parse::<usize>() { Ok(val) => val, Err(_) => { return Err(USimpleError::new( 1, format!("invalid line count: {}", count.quote()), )); } }, None => std::usize::MAX, }, output: matches.value_of(options::OUTPUT).map(String::from), random_source: matches.value_of(options::RANDOM_SOURCE).map(String::from), repeat: matches.is_present(options::REPEAT), sep: if matches.is_present(options::ZERO_TERMINATED) { 0x00_u8 } else { 0x0a_u8 }, }; match mode { Mode::Echo(args) => { let mut evec = args.iter().map(String::as_bytes).collect::<Vec<_>>(); find_seps(&mut evec, options.sep); shuf_bytes(&mut evec, options)?; } Mode::InputRange((b, e)) => { let rvec = (b..e).map(|x| format!("{}", x)).collect::<Vec<String>>(); let mut rvec = rvec.iter().map(String::as_bytes).collect::<Vec<&[u8]>>(); shuf_bytes(&mut rvec, options)?; } Mode::Default(filename) => { let fdata = read_input_file(&filename)?; let mut fdata = vec![&fdata[..]]; find_seps(&mut fdata, options.sep); shuf_bytes(&mut fdata, options)?; } } Ok(()) } pub fn uu_app<'a>() -> App<'a> { App::new(uucore::util_name()) .name(NAME) .about(ABOUT) .version(crate_version!()) .help_template(TEMPLATE) .override_usage(USAGE) .setting(AppSettings::InferLongArgs) .arg( Arg::new(options::ECHO) .short('e') .long(options::ECHO) .takes_value(true) .value_name("ARG") .help("treat each ARG as an input line") .multiple_occurrences(true) .use_delimiter(false) .min_values(0) .conflicts_with(options::INPUT_RANGE), ) .arg( Arg::new(options::INPUT_RANGE) .short('i') .long(options::INPUT_RANGE) .takes_value(true) .value_name("LO-HI") .help("treat each number LO through HI as an input line") .conflicts_with(options::FILE), ) .arg( Arg::new(options::HEAD_COUNT) .short('n') .long(options::HEAD_COUNT) .takes_value(true) .value_name("COUNT") .help("output at most COUNT lines"), ) .arg( Arg::new(options::OUTPUT) .short('o') .long(options::OUTPUT) .takes_value(true) .value_name("FILE") .help("write result to FILE instead of standard output"), ) .arg( Arg::new(options::RANDOM_SOURCE) .long(options::RANDOM_SOURCE) .takes_value(true) .value_name("FILE") .help("get random bytes from FILE"), ) .arg( Arg::new(options::REPEAT) .short('r') .long(options::REPEAT) .help("output lines can be repeated"), ) .arg( Arg::new(options::ZERO_TERMINATED) .short('z') .long(options::ZERO_TERMINATED) .help("line delimiter is NUL, not newline"), ) .arg(Arg::new(options::FILE).takes_value(true)) } fn read_input_file(filename: &str) -> UResult<Vec<u8>> { let mut file = BufReader::new(if filename == "-" { Box::new(stdin()) as Box<dyn Read> } else { let file = File::open(filename) .map_err_context(|| format!("failed to open {}", filename.quote()))?; Box::new(file) as Box<dyn Read> }); let mut data = Vec::new(); file.read_to_end(&mut data) .map_err_context(|| format!("failed reading {}", filename.quote()))?; Ok(data) } fn find_seps(data: &mut Vec<&[u8]>, sep: u8) { // need to use for loop so we don't borrow the vector as we modify it in place // basic idea: // * We don't care about the order of the result. This lets us slice the slices // without making a new vector. // * Starting from the end of the vector, we examine each element. // * If that element contains the separator, we remove it from the vector, // and then sub-slice it into slices that do not contain the separator. // * We maintain the invariant throughout that each element in the vector past // the ith element does not have any separators remaining. for i in (0..data.len()).rev() { if data[i].contains(&sep) { let this = data.swap_remove(i); let mut p = 0; let mut i = 1; loop { if i == this.len() { break; } if this[i] == sep { data.push(&this[p..i]); p = i + 1; } i += 1; } if p < this.len() { data.push(&this[p..i]); } } } } fn
(input: &mut Vec<&[u8]>, opts: Options) -> UResult<()> { let mut output = BufWriter::new(match opts.output { None => Box::new(stdout()) as Box<dyn Write>, Some(s) => { let file = File::create(&s[..]) .map_err_context(|| format!("failed to open {} for writing", s.quote()))?; Box::new(file) as Box<dyn Write> } }); let mut rng = match opts.random_source { Some(r) => { let file = File::open(&r[..]) .map_err_context(|| format!("failed to open random source {}", r.quote()))?; WrappedRng::RngFile(rand_read_adapter::ReadRng::new(file)) } None => WrappedRng::RngDefault(rand::thread_rng()), }; let mut dist = Uniform::new(0, input.len()); let mut count = opts.head_count; while count > 0 && !input.is_empty() { let r = rng.sample(dist); // write the randomly chosen value and the separator output .write_all(input[r]) .map_err_context(|| "write failed".to_string())?; output .write_all(&[opts.sep]) .map_err_context(|| "write failed".to_string())?; // if we do not allow repeats, remove the chosen value from the input vector if !opts.repeat { input.swap_remove(r); if !input.is_empty() { dist = Uniform::new(0, input.len()); } } count -= 1; } Ok(()) } fn parse_range(input_range: &str) -> Result<(usize, usize), String> { let split: Vec<&str> = input_range.split('-').collect(); if split.len() != 2 { Err(format!("invalid input range: {}", input_range.quote())) } else { let begin = split[0] .parse::<usize>() .map_err(|_| format!("invalid input range: {}", split[0].quote()))?; let end = split[1] .parse::<usize>() .map_err(|_| format!("invalid input range: {}", split[1].quote()))?; Ok((begin, end + 1)) } } enum WrappedRng { RngFile(rand_read_adapter::ReadRng<File>), RngDefault(rand::rngs::ThreadRng), } impl WrappedRng { fn sample(&mut self, dist: Uniform<usize>) -> usize { match *self { WrappedRng::RngFile(ref mut r) => r.sample(dist), WrappedRng::RngDefault(ref mut r) => r.sample(dist), } } }
shuf_bytes
mnscoin_vi.ts
<TS language="vi" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Ấn chuột phải để sửa địa chỉ hoặc tên</translation> </message> <message> <source>Create a new address</source> <translation>Tạo địa chỉ mới </translation> </message> <message> <source>&amp;New</source> <translation>Mới</translation> </message> <message> <source>&amp;Copy</source> <translation>Sao chép</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Xóa các địa chỉ được chọn khỏi danh sách</translation> </message> <message> <source>&amp;Delete</source> <translation>Xóa</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Xuất dữ liệu của tab hiện tại sang file</translation> </message> <message> <source>&amp;Export</source> <translation>Xuất</translation> </message> <message> <source>C&amp;lose</source> <translation>Đóng</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Chọn địa chỉ để gửi coin đi</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Chọn địa chỉ để nhận coin về</translation> </message> <message> <source>C&amp;hoose</source> <translation>Chọn</translation> </message> <message> <source>Sending addresses</source>
<translation>Địa chỉ nhận</translation> </message> <message> <source>Receiving addresses</source> <translation>Địa chỉ gửi </translation> </message> <message> <source>These are your MNS addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Đây là địa chỉ ví MNS của bạn để gửi đi. Luôn luôn kiểm tra số lượng và địa chỉ ví nhận trước khi gửi.</translation> </message> <message> <source>These are your MNS addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Đây là địa chỉ ví MNS của bạn để nhận. Bạn nên sử dụng địa chỉ ví nhận mới cho mỗi giao dịch</translation> </message> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Unlock wallet</source> <translation>Mở khóa ví</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>Bip38ToolDialog</name> </context> <context> <name>BitcoinGUI</name> <message> <source>Unlock wallet</source> <translation>Mở khóa ví</translation> </message> </context> <context> <name>BlockExplorer</name> </context> <context> <name>ClientModel</name> </context> <context> <name>CoinControlDialog</name> </context> <context> <name>EditAddressDialog</name> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> </context> <context> <name>Intro</name> </context> <context> <name>MasternodeList</name> </context> <context> <name>MultiSendDialog</name> </context> <context> <name>MultisigDialog</name> </context> <context> <name>ObfuscationConfig</name> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> </context> <context> <name>OverviewPage</name> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>PrivacyDialog</name> </context> <context> <name>QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> </context> <context> <name>ReceiveCoinsDialog</name> </context> <context> <name>ReceiveRequestDialog</name> </context> <context> <name>RecentRequestsTableModel</name> </context> <context> <name>SendCoinsDialog</name> </context> <context> <name>SendCoinsEntry</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> </context> <context> <name>TransactionView</name> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>Xuất</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Xuất dữ liệu của tab hiện tại sang file</translation> </message> </context> <context> <name>mnscoin-core</name> </context> </TS>
0062_auto_20210511_2322.py
# Generated by Django 3.1.7 on 2021-05-11 21:22 from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('MatchApp', '0061_apadrinamiento'), ] operations = [ migrations.AlterField( model_name='apadrinamiento', name='tipo_ingreso', field=models.CharField(blank=True, choices=[('Combinado', 'Combinado'), ('Unico', 'Unico'), ('Directo Albergue', 'Directo Albergue')], max_length=20, null=True, verbose_name='Tipo de Ingreso'), ), ]
crossref.py
import argparse import asyncio import html import json import logging import os import textwrap import time import xmltodict from aiohttp import ClientSession, ClientConnectorError, ServerDisconnectedError, ContentTypeError from articlemeta.client import RestfulClient from datetime import datetime from json import JSONDecodeError from pyexpat import ExpatError from pymongo import errors, MongoClient, uri_parser from utils.string_processor import preprocess_author_name, preprocess_doi, preprocess_journal_title from xylose.scielodocument import Article, Citation DIR_DATA = os.environ.get('DIR_DATA', '/opt/data') MONGO_STDCITS_COLLECTION = os.environ.get('MONGO_STDCITS_COLLECTION', 'standardized') CROSSREF_URL_WORKS = os.environ.get('CROSSREF_URL_WORKS', 'https://api.crossref.org/works/{}') CROSSREF_URL_OPENURL = os.environ.get('CROSSREF_URL_OPENURL', 'https://doi.crossref.org/openurl?') CROSSREF_SEMAPHORE_LIMIT = int(os.environ.get('CROSSREF_SEMAPHORE_LIMIT', '20')) class CrossrefAsyncCollector(object): logging.basicConfig(level=logging.INFO) def __init__(self, email: None, mongo_uri_std_cits=None): self.email = email if mongo_uri_std_cits: try: self.persist_mode = 'mongo' mongo_col = uri_parser.parse_uri(mongo_uri_std_cits).get('collection') if not mongo_col: mongo_col = MONGO_STDCITS_COLLECTION self.standardizer = MongoClient(mongo_uri_std_cits).get_database().get_collection(mongo_col) total_docs = self.standardizer.count_documents({}) logging.info('There are {0} documents in the collection {1}'.format(total_docs, mongo_col)) except ConnectionError as e: logging.error('ConnectionError %s' % mongo_uri_std_cits) logging.error(e) else: self.persist_mode = 'json' file_name_results = 'crossref-results-' + str(time.time()) + '.json' self.path_results = os.path.join(DIR_DATA, file_name_results) def extract_attrs(self, article: Article): """ Extrai os atributos de todas as referências citadas de um documento. :param article: documento do qual serão extraídos os atributos das referências citadas :return: dicionário de ids de citações e respectivos atributos """ cit_id_to_attrs = {} if article.citations: for cit in article.citations: if cit.publication_type == 'article': cit_id = self.mount_id(cit, article.collection_acronym) cit_attrs = {} if self.persist_mode == 'json': cit_attrs = self._extract_cit_attrs(cit) elif self.persist_mode == 'mongo': cit_data = self.standardizer.find_one({'_id': cit_id}) if not cit_data or not cit_data.get('crossref'): cit_attrs = self._extract_cit_attrs(cit) if cit_attrs: cit_id_to_attrs[cit_id] = cit_attrs return cit_id_to_attrs def _extract_cit_attrs(self, cit: Citation): """ Extrai os atributos de uma referência citada necessários para requisitar metadados CrossRef. :param cit: referência citada :return: dicionário de atributos para consulta no serviço CrossRef """ if cit.doi: valid_doi = preprocess_doi(cit.doi) if valid_doi: return {'doi': valid_doi} attrs = {} if cit.first_author: first_author_surname = cit.first_author.get('surname', '') cleaned_author_surname = preprocess_author_name(first_author_surname) if cleaned_author_surname: attrs.update({'aulast': cleaned_author_surname}) journal_title = cit.source if journal_title: cleaned_journal_title = preprocess_journal_title(journal_title) if cleaned_journal_title: attrs.update({'title': cleaned_journal_title}) publication_date = html.unescape(cit.publication_date) if cit.publication_date else None if publication_date and len(publication_date) >= 4: publication_year = publication_date[:4] if publication_year.isdigit(): attrs.update({'data': publication_year}) volume = html.unescape(cit.volume) if cit.volume else None if volume: attrs.update({'volume': volume}) issue = html.unescape(cit.issue) if cit.issue else None if issue: attrs.update({'issue': issue}) first_page = html.unescape(cit.first_page) if cit.first_page else None if first_page: attrs.update({'spage': first_page}) if attrs: return attrs def parse_crossref_openurl_result(self, text): """ Converte response.text para JSON com metadados obtidos do endpoint OPENURL. :param response: resposta de requisição em formato de texto :return: JSON com metadados obtidos do serviço CrossRef """ try: raw = xmltodict.parse(text) for v in raw.get('doi_records', {}).values(): metadata = v.get('crossref') if metadata and 'error' not in metadata.keys(): owner = v.get('@owner') if owner: metadata.update({'owner': owner}) timestamp = v.get('@timestamp') if timestamp: metadata.update({'timestamp': timestamp}) journal_article = metadata.get('journal', {}).get('journal_article', {}) if 'citation_list' in journal_article: journal_article.__delitem__('citation_list') return metadata except ExpatError as e: logging.warning("ExpatError {0}".format(text)) logging.warning(e) def parse_crossref_works_result(self, raw_metadata): """ Limpa dicionário de metadados obtidos do endpoint WORKS. Remove campo de referências :param raw_metadata: resposta de requisição em formato de dicionário :return: JSON com metadados obtidos do serviço Crossref """ raw_status = raw_metadata.get('status', '') if raw_status == 'ok': metadata = raw_metadata.get('message') if metadata: if 'reference' in metadata: metadata.__delitem__('reference') return metadata def mount_id(self, cit: Citation, collection: str): """ Monta o identificador de uma referência citada. :param cit: referência citada :param collection: coleção em que a referência foi citada :return: código identificador da citação """ cit_id = cit.data['v880'][0]['_'] return '{0}-{1}'.format(cit_id, collection) def save_crossref_metadata(self, id_to_metadata: dict): """ Persiste os metadados da referência citada. :param id_to_metadata: dicionário com id da referência citada e seus respectivos metadados Crossref """ if self.persist_mode == 'json': with open(self.path_results, 'a') as f: json.dump(id_to_metadata, f) f.write('\n') elif self.persist_mode == 'mongo': self.standardizer.update_one(filter={'_id': id_to_metadata['_id']}, update={'$set': { 'crossref': id_to_metadata['crossref'], 'update-date': datetime.now().strftime('%Y-%m-%d') }}, upsert=True) async def run(self, citations_attrs: dict): sem = asyncio.Semaphore(CROSSREF_SEMAPHORE_LIMIT) tasks = [] async with ClientSession(headers={'mailto:': self.email}) as session: for cit_id, attrs in citations_attrs.items(): if 'doi' in attrs: url = CROSSREF_URL_WORKS.format(attrs['doi']) mode = 'doi' else: url = CROSSREF_URL_OPENURL for k, v in attrs.items(): if k != 'doi': url += '&' + k + '=' + v url += '&pid=' + self.email url += '&format=unixref' url += '&multihit=false' mode = 'attrs' task = asyncio.ensure_future(self.bound_fetch(cit_id, url, sem, session, mode)) tasks.append(task) responses = asyncio.gather(*tasks) await responses async def bound_fetch(self, cit_id, url, semaphore, session, mode): async with semaphore: await self.fetch(cit_id, url, session, mode) async def fetch(self, cit_id, url, session, mode): try: async with session.get(url) as response: try: logging.info('Collecting metadata for %s' % cit_id) if mode == 'doi': raw_metadata = await response.json(content_type=None) if raw_metadata: metadata = self.parse_crossref_works_result(raw_metadata) else: raw_metadata = await response.text() if raw_metadata: metadata = self.parse_crossref_openurl_result(raw_metadata) if metadata: id_to_metadata = {'_id': cit_id, 'crossref': metadata} self.save_crossref_metadata(id_to_metadata) except JSONDecodeError as e: logging.warning('JSONDecodeError: %s' % cit_id) logging.warning(e) except TimeoutError as e: logging.warning('TimeoutError [INNER]: %s' % cit_id) logging.warning(e) except ContentTypeError as e: logging.warning('ContentTypeError: %s' % cit_id) logging.warning(e) except ServerDisconnectedError as e: logging.warning('ServerDisconnectedError: %s' % cit_id) logging.warning(e) except TimeoutError as e: logging.warning('TimeoutError [OUTER]: %s' % cit_id) logging.warning(e) except ClientConnectorError as e: logging.warning('ClientConectorError: %s' % cit_id) logging.warning(e) def format_date(date: datetime): if not date: return None
ect metadata from the Crossref Service" parser = argparse.ArgumentParser(textwrap.dedent(usage)) parser.add_argument( '-c', '--col', default=None, dest='col', help='normalize cited references in an entire collection' ) parser.add_argument( '-f', '--from_date', type=lambda x: datetime.strptime(x, '%Y-%m-%d'), nargs='?', help='collect metadata for cited references in documents published from a date (YYYY-MM-DD)' ) parser.add_argument( '-u', '--until_date', type=lambda x: datetime.strptime(x, '%Y-%m-%d'), nargs='?', default=datetime.now(), help='collect metadata for cited references in documents published until a date (YYYY-MM-DD)' ) parser.add_argument( '-i', '--document_id', default=None, dest='pid', help='collect metadata for cited for the cited references in a PID (document)' ) parser.add_argument( '--mongo_uri', default=None, dest='mongo_uri_std_cits', help='mongo uri string in the format mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]' ) parser.add_argument( '-e', '--email', required=True, default=None, dest='email', help='an e-mail registered in the Crossref service' ) args = parser.parse_args() try: art_meta = RestfulClient() cac = CrossrefAsyncCollector(email=args.email, mongo_uri_std_cits=args.mongo_uri_std_cits) cit_ids_to_attrs = {} start_time = time.time() if args.pid: logging.info('Running in one PID mode') document = art_meta.document(collection=args.col, code=args.pid) if document: logging.info('Extracting info from cited references in %s ' % document.publisher_id) cit_ids_to_attrs = cac.extract_attrs(document) else: logging.info('Running in many PIDs mode') for document in art_meta.documents(collection=args.col, from_date=format_date(args.from_date), until_date=format_date(args.until_date)): logging.info('Extracting info from cited references in %s ' % document.publisher_id) cit_ids_to_attrs.update(cac.extract_attrs(document)) loop = asyncio.get_event_loop() future = asyncio.ensure_future(cac.run(cit_ids_to_attrs)) loop.run_until_complete(future) end_time = time.time() logging.info('Duration {0} seconds.'.format(end_time - start_time)) except KeyboardInterrupt: print("Interrupt by user")
return date.strftime('%Y-%m-%d') def main(): usage = "coll
analysis.py
from conding_htm import * fileuh = "markdown.md" fichier = "markdown.md" # The fonction read...just read the file def readeuh(fileuh): with open(fileuh , "r") as markdown: global contents contents = markdown.readlines() return contents # The function say the level of the title def a_title(): readeuh(fichier) for element in contents: counter = 0 for cara in element: if cara == "#": counter += 1 # Title level 1 if counter == 1: h1(element) print("TITRE DE NIV 1") # Title level 2 elif counter == 2: h2(element) print("TITRE DE NIV 2") # Title level 3 elif counter == 3: h3(element) print("TITRE DE NIV 3") # Title level 4 elif counter == 4: h4(element) print("TITRE DE NIV 4") # Title level 5 elif counter == 5: h5(element) print("TITRE DE NIV 5") # Title level 6 elif counter == 6: h6(element) print("TITRE DE NIV 6") # The function say if their is an important part text and the type of the program def a_italic_bold(): readeuh(fichier) for element in contents: counter_star = 0 counter_under = 0 for cara in element: if cara == "*": counter_star += 1 elif cara == "_": counter_under += 1 # *Italique* word
if counter_star == 2: italic(element , "*") print("C'est un mot italique") # **Bold** word elif counter_star == 4: bold(element , "**") print("C'est un mot gras") # _italique_ word if counter_under == 2: italic(element , "_") print("Italique aussi") # __bold__ word elif counter_under == 4: bold(element , "__") print("Gras aussi") # The function say if their is a link def a_link(): readeuh(fichier) for element in contents: counter = 0 for cara in element: if cara =="[": counter += 1 if cara == "]": counter += 1 if cara == "(": counter += 1 if cara == ")": counter += 1 # link if counter == 4: link(element) print("C'EST UN LIEN") # The function say if their is a list def a_list(): readeuh(fichier) for element in contents: counter = 0 # print(element) # print(contents) for cara in element: if cara == "-": counter += 1 if counter == 2: ul_li(contents) print("Y'A UNE LISTE ICI") # if element != "-": # print(element) # ul_li(contents) a_title() a_italic_bold() a_link() a_list()
__init__.py
from .utils import *
from .defaults import get_cfg_defaults
declarationEmitExpressionInExtends6.js
//// [tests/cases/compiler/declarationEmitExpressionInExtends6.ts] //// //// [index.d.ts]
declare const require: any; //// [a.ts] export class Foo {} //// [b.ts] const { Foo } = require("./a"); export default class extends Foo {} //// [b.js] "use strict"; 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 __()); }; })(); exports.__esModule = true; var Foo = require("./a").Foo; var default_1 = /** @class */ (function (_super) { __extends(default_1, _super); function default_1() { return _super !== null && _super.apply(this, arguments) || this; } return default_1; }(Foo)); exports["default"] = default_1;
sys_casbin.go
package types type CasbinInReceive struct { AuthorityId string `json:"authorityId"` // 权限id CasbinInfos []CasbinInfo `json:"casbinInfos"` } type CasbinSearch struct { AuthorityId string `json:"authorityId"` // 权限id } type PolicyPathResponse struct { Paths []CasbinInfo `json:"paths"` } func DefaultC
binInfo { return []CasbinInfo{ {Path: "/menu/getMenu", Method: "POST"}, {Path: "/jwt/jsonInBlacklist", Method: "POST"}, {Path: "/base/login", Method: "POST"}, {Path: "/user/register", Method: "POST"}, {Path: "/user/changePassword", Method: "POST"}, {Path: "/user/setUserAuthority", Method: "POST"}, {Path: "/user/setUserInfo", Method: "PUT"}, {Path: "/user/getUserInfo", Method: "GET"}, } }
asbin() []Cas
toggle-quotes.js
'use babel' export const toggleQuotes = (editor) => { editor.transact(() => { for (let cursor of editor.getCursors()) { let position = cursor.getBufferPosition() toggleQuoteAtPosition(editor, position) cursor.setBufferPosition(position) } }) } const getNextQuoteCharacter = (quoteCharacter, allQuoteCharacters) => { let index = allQuoteCharacters.indexOf(quoteCharacter) if (index === -1) { return null
} else { return allQuoteCharacters[(index + 1) % allQuoteCharacters.length] } } const escapePattern = (s) => { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') } // Using the quote characters configured by the user, build a pattern that can // be used to filter the syntax nodes in tree-sitter mode. const makePredicate = (quoteChars) => { // We want text that begins and ends with the same quote character (and // _might_ start with one of Python's string format prefixes). let pattern = new RegExp(`^[uUr]?([${escapePattern(quoteChars)}])[\\s\\S]*(\\1)$`, 'g') return ({ text }) => pattern.test(text) } const toggleQuoteAtPosition = (editor, position) => { let quoteChars = atom.config.get('toggle-quotes.quoteCharacters', { scope: editor.getRootScopeDescriptor() }) let range if (editor.languageMode.getSyntaxNodeAtPosition) { const node = editor.languageMode.getSyntaxNodeAtPosition(position, makePredicate(quoteChars)) range = node && node.range } else { range = editor.bufferRangeForScopeAtPosition('.string.quoted', position) } if (!range) { // Attempt to match the current invalid region if it is wrapped in quotes // This is useful for languages where changing the quotes makes the range // invalid and so toggling again should properly restore the valid quotes range = editor.bufferRangeForScopeAtPosition('.invalid.illegal', position) if (range) { let inner = quoteChars.split('').map(character => `${character}.*${character}`).join('|') if (!RegExp(`^(${inner})$`, 'g').test(editor.getTextInBufferRange(range))) { return } } } if (range == null) { return } let text = editor.getTextInBufferRange(range) let [quoteCharacter] = text // In Python a string can have a prefix specifying its format. The Python // grammar includes this prefix in the string, and thus we need to exclude // it when toggling quotes let prefix = '' if (/[uUr]/.test(quoteCharacter)) { [prefix, quoteCharacter] = text } let nextQuoteCharacter = getNextQuoteCharacter(quoteCharacter, quoteChars) if (!nextQuoteCharacter) { return } const locateEscapesAndQuotesRegex = new RegExp(`\\\\.|${escapePattern(nextQuoteCharacter)}`, 'g') let newText = text .replace(locateEscapesAndQuotesRegex, m => { if (m[0] === nextQuoteCharacter) { return '\\' + nextQuoteCharacter } else { return m[1] === quoteCharacter ? quoteCharacter : m } }) newText = prefix + nextQuoteCharacter + newText.slice(1 + prefix.length, -1) + nextQuoteCharacter editor.setTextInBufferRange(range, newText) }
AuthWrapper.js
import React from "react"; //Styles import styled from "styled-components"; const AuthWrapper = props => { return ( <div className={`container ${props.className}`}> <form className="form-signin"> <h2 className="form-signin-heading">{props.title}</h2> {props.children} </form> </div> ); }; const authWrapperWithStyles = styled(AuthWrapper)` .form-signin { max-width: 330px; padding: 15px; margin: 0 auto; } .form-signin .form-signin-heading, .form-signin .checkbox { margin-bottom: 10px; } .form-signin .checkbox { font-weight: 400; } .form-signin .form-control { position: relative; box-sizing: border-box; height: auto; padding: 10px; font-size: 16px; } .form-signin .form-control:focus {
border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .form-signin input[type="password"] { margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0; } `; export default authWrapperWithStyles;
z-index: 2; } .form-signin input[type="email"] { margin-bottom: -1px;
benchmark_client.go
/* * * Copyright 2016 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package main import ( "context" "flag" "math" "runtime" "sync" "time" "google.golang.org/grpc" "google.golang.org/grpc/benchmark" "google.golang.org/grpc/benchmark/stats" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/syscall" testpb "google.golang.org/grpc/interop/grpc_testing" "google.golang.org/grpc/status" "google.golang.org/grpc/testdata" ) var caFile = flag.String("ca_file", "", "The file containing the CA root cert file") type lockingHistogram struct { mu sync.Mutex histogram *stats.Histogram } func (h *lockingHistogram) add(value int64) { h.mu.Lock() defer h.mu.Unlock() h.histogram.Add(value) } // swap sets h.histogram to o and returns its old value. func (h *lockingHistogram) swap(o *stats.Histogram) *stats.Histogram { h.mu.Lock() defer h.mu.Unlock() old := h.histogram h.histogram = o return old } func (h *lockingHistogram) mergeInto(merged *stats.Histogram) { h.mu.Lock() defer h.mu.Unlock() merged.Merge(h.histogram) } type benchmarkClient struct { closeConns func() stop chan bool lastResetTime time.Time histogramOptions stats.HistogramOptions lockingHistograms []lockingHistogram rusageLastReset *syscall.Rusage } func printClientConfig(config *testpb.ClientConfig) { // Some config options are ignored: // - client type: // will always create sync client // - async client threads. // - core list logger.Infof(" * client type: %v (ignored, always creates sync client)", config.ClientType) logger.Infof(" * async client threads: %v (ignored)", config.AsyncClientThreads) // TODO: use cores specified by CoreList when setting list of cores is supported in go. logger.Infof(" * core list: %v (ignored)", config.CoreList) logger.Infof(" - security params: %v", config.SecurityParams) logger.Infof(" - core limit: %v", config.CoreLimit) logger.Infof(" - payload config: %v", config.PayloadConfig) logger.Infof(" - rpcs per chann: %v", config.OutstandingRpcsPerChannel) logger.Infof(" - channel number: %v", config.ClientChannels) logger.Infof(" - load params: %v", config.LoadParams) logger.Infof(" - rpc type: %v", config.RpcType) logger.Infof(" - histogram params: %v", config.HistogramParams) logger.Infof(" - server targets: %v", config.ServerTargets) } func setupClientEnv(config *testpb.ClientConfig) { // Use all cpu cores available on machine by default. // TODO: Revisit this for the optimal default setup. if config.CoreLimit > 0 { runtime.GOMAXPROCS(int(config.CoreLimit)) } else { runtime.GOMAXPROCS(runtime.NumCPU()) } } // createConns creates connections according to given config. // It returns the connections and corresponding function to close them. // It returns non-nil error if there is anything wrong. func createConns(config *testpb.ClientConfig) ([]*grpc.ClientConn, func(), error) { var opts []grpc.DialOption // Sanity check for client type. switch config.ClientType { case testpb.ClientType_SYNC_CLIENT: case testpb.ClientType_ASYNC_CLIENT: default: return nil, nil, status.Errorf(codes.InvalidArgument, "unknown client type: %v", config.ClientType) } // Check and set security options. if config.SecurityParams != nil { if *caFile == "" { *caFile = testdata.Path("ca.pem") } creds, err := credentials.NewClientTLSFromFile(*caFile, config.SecurityParams.ServerHostOverride) if err != nil { return nil, nil, status.Errorf(codes.InvalidArgument, "failed to create TLS credentials %v", err) } opts = append(opts, grpc.WithTransportCredentials(creds)) } else { opts = append(opts, grpc.WithInsecure()) } // Use byteBufCodec if it is required. if config.PayloadConfig != nil { switch config.PayloadConfig.Payload.(type) { case *testpb.PayloadConfig_BytebufParams: opts = append(opts, grpc.WithDefaultCallOptions(grpc.CallCustomCodec(byteBufCodec{}))) case *testpb.PayloadConfig_SimpleParams: default: return nil, nil, status.Errorf(codes.InvalidArgument, "unknown payload config: %v", config.PayloadConfig) } } // Create connections. connCount := int(config.ClientChannels) conns := make([]*grpc.ClientConn, connCount) for connIndex := 0; connIndex < connCount; connIndex++ { conns[connIndex] = benchmark.NewClientConn(config.ServerTargets[connIndex%len(config.ServerTargets)], opts...) } return conns, func() { for _, conn := range conns { conn.Close() } }, nil } func
(config *testpb.ClientConfig, conns []*grpc.ClientConn, bc *benchmarkClient) error { // Read payload size and type from config. var ( payloadReqSize, payloadRespSize int payloadType string ) if config.PayloadConfig != nil { switch c := config.PayloadConfig.Payload.(type) { case *testpb.PayloadConfig_BytebufParams: payloadReqSize = int(c.BytebufParams.ReqSize) payloadRespSize = int(c.BytebufParams.RespSize) payloadType = "bytebuf" case *testpb.PayloadConfig_SimpleParams: payloadReqSize = int(c.SimpleParams.ReqSize) payloadRespSize = int(c.SimpleParams.RespSize) payloadType = "protobuf" default: return status.Errorf(codes.InvalidArgument, "unknown payload config: %v", config.PayloadConfig) } } // TODO add open loop distribution. switch config.LoadParams.Load.(type) { case *testpb.LoadParams_ClosedLoop: case *testpb.LoadParams_Poisson: return status.Errorf(codes.Unimplemented, "unsupported load params: %v", config.LoadParams) default: return status.Errorf(codes.InvalidArgument, "unknown load params: %v", config.LoadParams) } rpcCountPerConn := int(config.OutstandingRpcsPerChannel) switch config.RpcType { case testpb.RpcType_UNARY: bc.doCloseLoopUnary(conns, rpcCountPerConn, payloadReqSize, payloadRespSize) // TODO open loop. case testpb.RpcType_STREAMING: bc.doCloseLoopStreaming(conns, rpcCountPerConn, payloadReqSize, payloadRespSize, payloadType) // TODO open loop. default: return status.Errorf(codes.InvalidArgument, "unknown rpc type: %v", config.RpcType) } return nil } func startBenchmarkClient(config *testpb.ClientConfig) (*benchmarkClient, error) { printClientConfig(config) // Set running environment like how many cores to use. setupClientEnv(config) conns, closeConns, err := createConns(config) if err != nil { return nil, err } rpcCountPerConn := int(config.OutstandingRpcsPerChannel) bc := &benchmarkClient{ histogramOptions: stats.HistogramOptions{ NumBuckets: int(math.Log(config.HistogramParams.MaxPossible)/math.Log(1+config.HistogramParams.Resolution)) + 1, GrowthFactor: config.HistogramParams.Resolution, BaseBucketSize: (1 + config.HistogramParams.Resolution), MinValue: 0, }, lockingHistograms: make([]lockingHistogram, rpcCountPerConn*len(conns)), stop: make(chan bool), lastResetTime: time.Now(), closeConns: closeConns, rusageLastReset: syscall.GetRusage(), } if err = performRPCs(config, conns, bc); err != nil { // Close all connections if performRPCs failed. closeConns() return nil, err } return bc, nil } func (bc *benchmarkClient) doCloseLoopUnary(conns []*grpc.ClientConn, rpcCountPerConn int, reqSize int, respSize int) { for ic, conn := range conns { client := testpb.NewBenchmarkServiceClient(conn) // For each connection, create rpcCountPerConn goroutines to do rpc. for j := 0; j < rpcCountPerConn; j++ { // Create histogram for each goroutine. idx := ic*rpcCountPerConn + j bc.lockingHistograms[idx].histogram = stats.NewHistogram(bc.histogramOptions) // Start goroutine on the created mutex and histogram. go func(idx int) { // TODO: do warm up if necessary. // Now relying on worker client to reserve time to do warm up. // The worker client needs to wait for some time after client is created, // before starting benchmark. done := make(chan bool) for { go func() { start := time.Now() if err := benchmark.DoUnaryCall(client, reqSize, respSize); err != nil { select { case <-bc.stop: case done <- false: } return } elapse := time.Since(start) bc.lockingHistograms[idx].add(int64(elapse)) select { case <-bc.stop: case done <- true: } }() select { case <-bc.stop: return case <-done: } } }(idx) } } } func (bc *benchmarkClient) doCloseLoopStreaming(conns []*grpc.ClientConn, rpcCountPerConn int, reqSize int, respSize int, payloadType string) { var doRPC func(testpb.BenchmarkService_StreamingCallClient, int, int) error if payloadType == "bytebuf" { doRPC = benchmark.DoByteBufStreamingRoundTrip } else { doRPC = benchmark.DoStreamingRoundTrip } for ic, conn := range conns { // For each connection, create rpcCountPerConn goroutines to do rpc. for j := 0; j < rpcCountPerConn; j++ { c := testpb.NewBenchmarkServiceClient(conn) stream, err := c.StreamingCall(context.Background()) if err != nil { logger.Fatalf("%v.StreamingCall(_) = _, %v", c, err) } // Create histogram for each goroutine. idx := ic*rpcCountPerConn + j bc.lockingHistograms[idx].histogram = stats.NewHistogram(bc.histogramOptions) // Start goroutine on the created mutex and histogram. go func(idx int) { // TODO: do warm up if necessary. // Now relying on worker client to reserve time to do warm up. // The worker client needs to wait for some time after client is created, // before starting benchmark. for { start := time.Now() if err := doRPC(stream, reqSize, respSize); err != nil { return } elapse := time.Since(start) bc.lockingHistograms[idx].add(int64(elapse)) select { case <-bc.stop: return default: } } }(idx) } } } // getStats returns the stats for benchmark client. // It resets lastResetTime and all histograms if argument reset is true. func (bc *benchmarkClient) getStats(reset bool) *testpb.ClientStats { var wallTimeElapsed, uTimeElapsed, sTimeElapsed float64 mergedHistogram := stats.NewHistogram(bc.histogramOptions) if reset { // Merging histogram may take some time. // Put all histograms aside and merge later. toMerge := make([]*stats.Histogram, len(bc.lockingHistograms)) for i := range bc.lockingHistograms { toMerge[i] = bc.lockingHistograms[i].swap(stats.NewHistogram(bc.histogramOptions)) } for i := 0; i < len(toMerge); i++ { mergedHistogram.Merge(toMerge[i]) } wallTimeElapsed = time.Since(bc.lastResetTime).Seconds() latestRusage := syscall.GetRusage() uTimeElapsed, sTimeElapsed = syscall.CPUTimeDiff(bc.rusageLastReset, latestRusage) bc.rusageLastReset = latestRusage bc.lastResetTime = time.Now() } else { // Merge only, not reset. for i := range bc.lockingHistograms { bc.lockingHistograms[i].mergeInto(mergedHistogram) } wallTimeElapsed = time.Since(bc.lastResetTime).Seconds() uTimeElapsed, sTimeElapsed = syscall.CPUTimeDiff(bc.rusageLastReset, syscall.GetRusage()) } b := make([]uint32, len(mergedHistogram.Buckets)) for i, v := range mergedHistogram.Buckets { b[i] = uint32(v.Count) } return &testpb.ClientStats{ Latencies: &testpb.HistogramData{ Bucket: b, MinSeen: float64(mergedHistogram.Min), MaxSeen: float64(mergedHistogram.Max), Sum: float64(mergedHistogram.Sum), SumOfSquares: float64(mergedHistogram.SumOfSquares), Count: float64(mergedHistogram.Count), }, TimeElapsed: wallTimeElapsed, TimeUser: uTimeElapsed, TimeSystem: sTimeElapsed, } } func (bc *benchmarkClient) shutdown() { close(bc.stop) bc.closeConns() }
performRPCs