file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
batsky_sim.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import zmq import click import logging BATSIM_PORT = 28000 @click.command() @click.option('-d', '--debug', is_flag=True, help='Debug flag.') @click.option('-l', '--logfile', type=click.STRING, help='Specify log file.') @click.option('-c', '--controller', type=click.STRING, help='Specify which hostname is the controller.') @click.option('-f', '--workload-file', type=click.STRING, help='Specify workload file.') @click.option('-s', '--start-time', type=click.float, default=0.0, help='Specify start time of simulation') def cli(debug, logfile, controller, workload_file):
if __name__ == '__main__': cli()
if debug: logger.setLevel(logging.DEBUG) if logfile: fh = logging.FileHandler(logfile) fh.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(levelname)-6s %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) else: handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(levelname)-6s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.info('Simple delay job only bat-simulator') context = zmq.Context() batsim_sock = context.socket(zmq.PAIR) batsim_sock.bind("tcp://*:{}".format(BATSIM_PORT)) #controller_sock.send_json({'wjid': int(workload_jobid), 'nodeset': str(nodeset), # 'port': int(finalize_port)})
util.tsx
/* eslint-disable no-lonely-if */ /** * Legacy code. Should avoid to use if you are new to import these code. */ import React from 'react'; import warning from 'rc-util/lib/warning'; import TreeNode, { TreeNodeProps } from './TreeNode'; import { NodeElement, Key, DataNode, DataEntity, NodeInstance, FlattenNode, Direction } from './interface'; import { TreeProps, AllowDrop } from './Tree'; export function arrDel(list: Key[], value: Key) { const clone = list.slice(); const index = clone.indexOf(value); if (index >= 0) { clone.splice(index, 1); } return clone; } export function arrAdd(list: Key[], value: Key) { const clone = list.slice(); if (clone.indexOf(value) === -1) { clone.push(value); } return clone; } export function posToArr(pos: string) { return pos.split('-'); } export function getPosition(level: string | number, index: number) { return `${level}-${index}`; } export function isTreeNode(node: NodeElement) { return node && node.type && node.type.isTreeNode; } export function getDragChildrenKeys(dragNodeKey: Key, keyEntities: Record<Key, DataEntity>): Key[] { // not contains self // self for left or right drag const dragChildrenKeys = []; const entity = keyEntities[dragNodeKey]; function dig(list: DataEntity[] = []) { list.forEach(({ key, children }) => { dragChildrenKeys.push(key); dig(children); }); } dig(entity.children); return dragChildrenKeys; } export function isLastChild (treeNodeEntity: DataEntity) { if (treeNodeEntity.parent) { const posArr = posToArr(treeNodeEntity.pos); return Number(posArr[posArr.length - 1]) === treeNodeEntity.parent.children.length - 1; } return false; } export function isFirstChild (treeNodeEntity: DataEntity) { const posArr = posToArr(treeNodeEntity.pos); return Number(posArr[posArr.length - 1]) === 0; } // Only used when drag, not affect SSR. export function calcDropPosition( event: React.MouseEvent, targetNode: NodeInstance, indent: number, startMousePosition: { x: number, y: number, }, allowDrop: AllowDrop, flattenedNodes: FlattenNode[], keyEntities: Record<Key, DataEntity>, expandKeys: Key[], direction: Direction, ) : { dropPosition: -1 | 0 | 1, dropLevelOffset: number, dropTargetKey: Key, dropTargetPos: string, dropContainerKey: Key, dragOverNodeKey: Key, dropAllowed: boolean, } { const { clientX, clientY } = event; const { top, height } = (event.target as HTMLElement).getBoundingClientRect(); // optional chain for testing const horizontalMouseOffset = (direction === 'rtl' ? -1 : 1) * ((startMousePosition?.x || 0) - clientX); const rawDropLevelOffset = (horizontalMouseOffset - 12) / indent; // find abstract drop node by horizontal offset let abstractDropNodeEntity: DataEntity = keyEntities[targetNode.props.eventKey]; if (clientY < top + height / 2) { // first half, set abstract drop node to previous node const nodeIndex = flattenedNodes.findIndex( flattenedNode => flattenedNode.data.key === abstractDropNodeEntity.key, ); const prevNodeIndex = nodeIndex <= 0 ? 0 : nodeIndex - 1; const prevNodeKey = flattenedNodes[prevNodeIndex].data.key; abstractDropNodeEntity = keyEntities[prevNodeKey]; } const abstractDragOverEntity = abstractDropNodeEntity; const dragOverNodeKey = abstractDropNodeEntity.key; let dropPosition: -1 | 0 | 1 = 0; let dropLevelOffset = 0; for (let i = 0; i < rawDropLevelOffset; i += 1) { if ( isLastChild(abstractDropNodeEntity) ) { abstractDropNodeEntity = abstractDropNodeEntity.parent; dropLevelOffset += 1; } else { break; } } const abstractDropDataNode = abstractDropNodeEntity.node let dropAllowed = true; if ( isFirstChild(abstractDropNodeEntity) && abstractDropNodeEntity.level === 0 && clientY < top + height / 2 && allowDrop({ dropNode: abstractDropDataNode, dropPosition: -1, }) && abstractDropNodeEntity.key === targetNode.props.eventKey ) { // first half of first node in first level dropPosition = -1 } else if ( (abstractDragOverEntity.children || []).length && expandKeys.includes(dragOverNodeKey) ) { // drop on expanded node // only allow drop inside if (allowDrop({ dropNode: abstractDropDataNode, dropPosition: 0, })) { dropPosition = 0; } else { dropAllowed = false } } else if ( dropLevelOffset === 0 ) { if (rawDropLevelOffset > -1.5) { // | Node | <- abstractDropNode // | -^-===== | <- mousePosition // 1. try drop after // 2. do not allow drop if (allowDrop({ dropNode: abstractDropDataNode, dropPosition: 1, })) { dropPosition = 1; } else { dropAllowed = false; } } else { // | Node | <- abstractDropNode // | ---==^== | <- mousePosition // whether it has children or doesn't has children // always // 1. try drop inside // 2. try drop after // 3. do not allow drop if (allowDrop({ dropNode: abstractDropDataNode, dropPosition: 0, })) { dropPosition = 0; } else if (allowDrop({ dropNode: abstractDropDataNode, dropPosition: 1, })) { dropPosition = 1; } else { dropAllowed = false; } } } else { // | Node1 | <- abstractDropNode // | Node2 | // --^--|----=====| <- mousePosition // 1. try insert after Node1 // 2. do not allow drop if (allowDrop({ dropNode: abstractDropDataNode, dropPosition: 1, })) { dropPosition = 1; } else { dropAllowed = false; } } return { dropPosition, dropLevelOffset, dropTargetKey: abstractDropNodeEntity.key, dropTargetPos: abstractDropNodeEntity.pos, dragOverNodeKey, dropContainerKey: dropPosition === 0 ? null : (abstractDropNodeEntity.parent?.key || null), dropAllowed, }; } /** * Return selectedKeys according with multiple prop * @param selectedKeys * @param props * @returns [string] */ export function calcSelectedKeys(selectedKeys: Key[], props: TreeProps) { if (!selectedKeys) return undefined; const { multiple } = props; if (multiple) { return selectedKeys.slice(); } if (selectedKeys.length) { return [selectedKeys[0]]; } return selectedKeys; } const internalProcessProps = (props: DataNode): Partial<TreeNodeProps> => props; export function convertDataToTree( treeData: DataNode[], processor?: { processProps: (prop: DataNode) => any }, ): NodeElement[] { if (!treeData) return []; const { processProps = internalProcessProps } = processor || {}; const list = Array.isArray(treeData) ? treeData : [treeData]; return list.map( ({ children, ...props }): NodeElement => { const childrenNodes = convertDataToTree(children, processor); return <TreeNode {...processProps(props)}>{childrenNodes}</TreeNode>; }, ); } /** * Parse `checkedKeys` to { checkedKeys, halfCheckedKeys } style */ export function
(keys: Key[] | { checked: Key[]; halfChecked: Key[] }) { if (!keys) { return null; } // Convert keys to object format let keyProps; if (Array.isArray(keys)) { // [Legacy] Follow the api doc keyProps = { checkedKeys: keys, halfCheckedKeys: undefined, }; } else if (typeof keys === 'object') { keyProps = { checkedKeys: keys.checked || undefined, halfCheckedKeys: keys.halfChecked || undefined, }; } else { warning(false, '`checkedKeys` is not an array or an object'); return null; } return keyProps; } /** * If user use `autoExpandParent` we should get the list of parent node * @param keyList * @param keyEntities */ export function conductExpandParent(keyList: Key[], keyEntities: Record<Key, DataEntity>): Key[] { const expandedKeys = new Set<Key>(); function conductUp(key: Key) { if (expandedKeys.has(key)) return; const entity = keyEntities[key]; if (!entity) return; expandedKeys.add(key); const { parent, node } = entity; if (node.disabled) return; if (parent) { conductUp(parent.key); } } (keyList || []).forEach(key => { conductUp(key); }); return [...expandedKeys]; } /** * Returns only the data- and aria- key/value pairs */ export function getDataAndAria(props: Partial<TreeProps | TreeNodeProps>) { const omitProps: Record<string, string> = {}; Object.keys(props).forEach(key => { if (key.startsWith('data-') || key.startsWith('aria-')) { omitProps[key] = props[key]; } }); return omitProps; }
parseCheckedKeys
LightningBolt16.tsx
/* eslint-disable react/jsx-sort-props */ import * as React from 'react'; import * as vars from '../../styles/variables'; import AccessibleSVG, { SVGProps } from '../../components/accessible-svg/AccessibleSVG'; /** * This is an auto-generated component and should not be edited * manually in contributor pull requests. * * If you have problems with this component: * - https://github.com/box/box-ui-elements/issues/new?template=Bug_report.md * * If there are missing features in this component: * - https://github.com/box/box-ui-elements/issues/new?template=Feature_request.md */ const LightningBolt16 = (props: SVGProps) => ( <AccessibleSVG width={16} height={16} viewBox="0 0 16 16" {...props}> <path fill={vars.bdlGray50} d="M11.503 1a.496.496 0 01.447.712L9.302 6.998h2.193a.5.5 0 01.423.766L6.91 14.792a.5.5 0 01-.902-.365L6.836 9H4.493a.496.496 0 01-.483-.602l1.516-7A.495.495 0 016.008 1h5.495z" /> </AccessibleSVG> );
export default LightningBolt16;
HouseHomePageParser.py
import re from HouseMarketTracker.parser.ImagesParser import ImagesParser from HouseMarketTracker.parser.ParseUtil import ParseUtil class HouseHomePageParser():
def parse(self, response): meta = response.meta item = meta['item'] item['house_layout'] = self.parse_layout(response) images_url = meta['root_url'] + 'xiangce/' yield from ParseUtil.start_request(images_url, ImagesParser().parse, meta) def parse_layout(self, response): layout_list = [] layout_ul_s = response.xpath('//ul[@class="clear house-det"]') for layout_ul in layout_ul_s: layout_dict = {} img_src = layout_ul.xpath('child::*/img/@src').extract_first() img_src = re.sub(r'\d+?x\d*', '1000x', img_src) layout_dict['img_src'] = img_src layout_dict['layout_type_name'] = layout_ul.xpath('child::*/span/text()').extract_first() info_li = layout_ul.xpath('li[@class="info-li"]') p1 = info_li.xpath('p[@class="p1"]') layout_dict['layout_type'] = p1.xpath('text()').extract_first() layout_dict['construction_area'] = p1.xpath('span[not(@class)]/text()').extract_first() layout_dict['sales_status'] = p1.xpath('span[contains(@class,"p1-state")]/text()').extract_first() p2 = info_li.xpath('p[@class="p2"]') layout_dict['layout_price'] = re.sub(r'\n.+', '', info_li.xpath('string(p[@class="p2"])').extract_first()) layout_dict['last_update_time'] = p2.xpath('span[contains(@class,"p2-time")]/text()').extract_first() p3 = info_li.xpath('p[@class="p3"]') key = p3.xpath('text()').extract_first() value = p3.xpath('span/text()').extract_first() layout_dict[key] = value layout_dict['tags'] = info_li.xpath('p[@class="p4"]/span/text()').extract() layout_list.append(layout_dict) return layout_list def parse_unit_info(self, response): return
args.rs
//! Global initialization and retrieval of command line arguments. //! //! On some platforms these are stored during runtime startup, //! and on some they are retrieved from the system on demand. #![allow(dead_code)] // runtime init functions not used during testing use crate::ffi::OsString; use crate::fmt; use crate::vec; /// One-time global initialization. pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) } /// Returns the command line arguments pub fn args() -> Args { imp::args() } pub struct Args { iter: vec::IntoIter<OsString>, } impl !Send for Args {} impl !Sync for Args {} impl fmt::Debug for Args { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.iter.as_slice().fmt(f) } } impl Iterator for Args { type Item = OsString; fn next(&mut self) -> Option<OsString> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl ExactSizeIterator for Args { fn len(&self) -> usize { self.iter.len() } } impl DoubleEndedIterator for Args { fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() } } #[cfg(any( target_os = "linux", target_os = "android", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", target_os = "solaris", target_os = "illumos", target_os = "emscripten", target_os = "haiku", target_os = "l4re", target_os = "fuchsia", target_os = "redox", target_os = "vxworks", target_os = "horizon" ))] mod imp { use super::Args; use crate::ffi::{CStr, OsString}; use crate::os::unix::prelude::*; use crate::ptr; use crate::sync::atomic::{AtomicIsize, AtomicPtr, Ordering}; // The system-provided argc and argv, which we store in static memory // here so that we can defer the work of parsing them until its actually // needed. // // Note that we never mutate argv/argc, the argv array, or the argv // strings, which allows the code in this file to be very simple. static ARGC: AtomicIsize = AtomicIsize::new(0); static ARGV: AtomicPtr<*const u8> = AtomicPtr::new(ptr::null_mut()); unsafe fn really_init(argc: isize, argv: *const *const u8) { // These don't need to be ordered with each other or other stores, // because they only hold the unmodified system-provide argv/argc. ARGC.store(argc, Ordering::Relaxed); ARGV.store(argv as *mut _, Ordering::Relaxed); } #[inline(always)] pub unsafe fn init(_argc: isize, _argv: *const *const u8) { // On Linux-GNU, we rely on `ARGV_INIT_ARRAY` below to initialize // `ARGC` and `ARGV`. But in Miri that does not actually happen so we // still initialize here. #[cfg(any(miri, not(all(target_os = "linux", target_env = "gnu"))))] really_init(_argc, _argv); } /// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension. /// This allows `std::env::args` to work even in a `cdylib`, as it does on macOS and Windows. #[cfg(all(target_os = "linux", target_env = "gnu"))] #[used] #[link_section = ".init_array.00099"] static ARGV_INIT_ARRAY: extern "C" fn( crate::os::raw::c_int,
*const *const u8, ) = { extern "C" fn init_wrapper( argc: crate::os::raw::c_int, argv: *const *const u8, _envp: *const *const u8, ) { unsafe { really_init(argc as isize, argv); } } init_wrapper }; pub fn args() -> Args { Args { iter: clone().into_iter() } } fn clone() -> Vec<OsString> { unsafe { // Load ARGC and ARGV, which hold the unmodified system-provided // argc/argv, so we can read the pointed-to memory without atomics // or synchronization. // // If either ARGC or ARGV is still zero or null, then either there // really are no arguments, or someone is asking for `args()` // before initialization has completed, and we return an empty // list. let argv = ARGV.load(Ordering::Relaxed); let argc = if argv.is_null() { 0 } else { ARGC.load(Ordering::Relaxed) }; (0..argc) .map(|i| { let cstr = CStr::from_ptr(*argv.offset(i) as *const libc::c_char); OsStringExt::from_vec(cstr.to_bytes().to_vec()) }) .collect() } } } #[cfg(any(target_os = "macos", target_os = "ios"))] mod imp { use super::Args; use crate::ffi::CStr; pub unsafe fn init(_argc: isize, _argv: *const *const u8) {} #[cfg(target_os = "macos")] pub fn args() -> Args { use crate::os::unix::prelude::*; extern "C" { // These functions are in crt_externs.h. fn _NSGetArgc() -> *mut libc::c_int; fn _NSGetArgv() -> *mut *mut *mut libc::c_char; } let vec = unsafe { let (argc, argv) = (*_NSGetArgc() as isize, *_NSGetArgv() as *const *const libc::c_char); (0..argc as isize) .map(|i| { let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec(); OsStringExt::from_vec(bytes) }) .collect::<Vec<_>>() }; Args { iter: vec.into_iter() } } // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs // and use underscores in their names - they're most probably // are considered private and therefore should be avoided // Here is another way to get arguments using Objective C // runtime // // In general it looks like: // res = Vec::new() // let args = [[NSProcessInfo processInfo] arguments] // for i in (0..[args count]) // res.push([args objectAtIndex:i]) // res #[cfg(target_os = "ios")] pub fn args() -> Args { use crate::ffi::OsString; use crate::mem; use crate::str; extern "C" { fn sel_registerName(name: *const libc::c_uchar) -> Sel; fn objc_getClass(class_name: *const libc::c_uchar) -> NsId; } #[cfg(target_arch = "aarch64")] extern "C" { fn objc_msgSend(obj: NsId, sel: Sel) -> NsId; #[allow(clashing_extern_declarations)] #[link_name = "objc_msgSend"] fn objc_msgSend_ul(obj: NsId, sel: Sel, i: libc::c_ulong) -> NsId; } #[cfg(not(target_arch = "aarch64"))] extern "C" { fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId; #[allow(clashing_extern_declarations)] #[link_name = "objc_msgSend"] fn objc_msgSend_ul(obj: NsId, sel: Sel, ...) -> NsId; } type Sel = *const libc::c_void; type NsId = *const libc::c_void; let mut res = Vec::new(); unsafe { let process_info_sel = sel_registerName("processInfo\0".as_ptr()); let arguments_sel = sel_registerName("arguments\0".as_ptr()); let utf8_sel = sel_registerName("UTF8String\0".as_ptr()); let count_sel = sel_registerName("count\0".as_ptr()); let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr()); let klass = objc_getClass("NSProcessInfo\0".as_ptr()); let info = objc_msgSend(klass, process_info_sel); let args = objc_msgSend(info, arguments_sel); let cnt: usize = mem::transmute(objc_msgSend(args, count_sel)); for i in 0..cnt { let tmp = objc_msgSend_ul(args, object_at_sel, i as libc::c_ulong); let utf_c_str: *const libc::c_char = mem::transmute(objc_msgSend(tmp, utf8_sel)); let bytes = CStr::from_ptr(utf_c_str).to_bytes(); res.push(OsString::from(str::from_utf8(bytes).unwrap())) } } Args { iter: res.into_iter() } } } #[cfg(target_os = "espidf")] mod imp { use super::Args; #[inline(always)] pub unsafe fn init(_argc: isize, _argv: *const *const u8) {} pub fn args() -> Args { Args { iter: Vec::new().into_iter() } } }
*const *const u8,
definitionProvider.ts
import { IConnection, Location, LocationLink, Position, Range, TextDocumentPositionParams, } from "vscode-languageserver"; import { URI } from "vscode-uri"; import { SyntaxNode, Tree } from "web-tree-sitter"; import { ElmWorkspace } from "../elmWorkspace"; import { ElmWorkspaceMatcher } from "../util/elmWorkspaceMatcher"; import { TreeUtils } from "../util/treeUtils"; type DefinitionResult = | Location | Location[] | LocationLink[] | null | undefined; export class
{ constructor(private connection: IConnection, elmWorkspaces: ElmWorkspace[]) { this.connection.onDefinition( new ElmWorkspaceMatcher( elmWorkspaces, (param: TextDocumentPositionParams) => URI.parse(param.textDocument.uri), ).handlerForWorkspace(this.handleDefinitionRequest), ); } protected handleDefinitionRequest = async ( param: TextDocumentPositionParams, elmWorkspace: ElmWorkspace, // tslint:disable-next-line: max-union-size ): Promise<DefinitionResult> => { this.connection.console.info(`A definition was requested`); const forest = elmWorkspace.getForest(); const tree: Tree | undefined = forest.getTree(param.textDocument.uri); if (tree) { const nodeAtPosition = TreeUtils.getNamedDescendantForPosition( tree.rootNode, param.position, ); const definitionNode = TreeUtils.findDefinitionNodeByReferencingNode( nodeAtPosition, param.textDocument.uri, tree, elmWorkspace.getImports(), forest, ); if (definitionNode) { return this.createLocationFromDefinition( definitionNode.node, definitionNode.uri, ); } } }; private createLocationFromDefinition( definitionNode: SyntaxNode | undefined, uri: string, ): Location | undefined { if (definitionNode) { return Location.create( uri, Range.create( Position.create( definitionNode.startPosition.row, definitionNode.startPosition.column, ), Position.create( definitionNode.endPosition.row, definitionNode.endPosition.column, ), ), ); } } }
DefinitionProvider
grpc.component.ts
// Copyright IBM Corp. 2017,2019. All Rights Reserved. // Node module: @loopback/grpc // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT import { Component, ProviderMap, Server, CoreBindings, Application, } from '@loopback/core'; import {inject, Constructor} from '@loopback/context'; import {GrpcBindings} from './keys'; import {ServerProvider} from './providers/server.provider'; import {GrpcServer} from './grpc.server'; import {GrpcSequence} from './grpc.sequence'; import {GeneratorProvider} from './providers/generator.provider'; import {GrpcService} from './types'; /** * Grpc Component for LoopBack 4. */ export class
implements Component { /** * Export GrpcProviders */ providers: ProviderMap = { [GrpcBindings.GRPC_SERVER.toString()]: ServerProvider, [GrpcBindings.GRPC_GENERATOR]: GeneratorProvider, }; /** * Export Grpc Server */ servers: {[name: string]: Constructor<Server>} = { GrpcServer, }; constructor( @inject(CoreBindings.APPLICATION_INSTANCE) app: Application, @inject(GrpcBindings.CONFIG) config: GrpcService, ) { // Set default configuration for this component config = Object.assign( { host: '127.0.0.1', port: 3000, }, config, ); // Bind host, port, proto path, package and sequence app.bind(GrpcBindings.HOST).to(config.host); app.bind(GrpcBindings.PORT).to(config.port); app .bind(GrpcBindings.GRPC_SEQUENCE) .toClass(config.sequence ?? GrpcSequence); } }
GrpcComponent
filesystem.go
// Copyright 2019 The gVisor 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 tmpfs import ( "fmt" "sync/atomic" "gvisor.dev/gvisor/pkg/abi/linux" "gvisor.dev/gvisor/pkg/context" "gvisor.dev/gvisor/pkg/fspath" "gvisor.dev/gvisor/pkg/sentry/kernel/auth" "gvisor.dev/gvisor/pkg/sentry/socket/unix/transport" "gvisor.dev/gvisor/pkg/sentry/vfs" "gvisor.dev/gvisor/pkg/syserror" "gvisor.dev/gvisor/pkg/usermem" ) // Sync implements vfs.FilesystemImpl.Sync. func (fs *filesystem) Sync(ctx context.Context) error { // All filesystem state is in-memory. return nil } // stepLocked resolves rp.Component() to an existing file, starting from the // given directory. // // stepLocked is loosely analogous to fs/namei.c:walk_component(). // // Preconditions: filesystem.mu must be locked. !rp.Done(). func stepLocked(rp *vfs.ResolvingPath, d *dentry) (*dentry, error) { dir, ok := d.inode.impl.(*directory) if !ok { return nil, syserror.ENOTDIR } if err := d.inode.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil { return nil, err } afterSymlink: name := rp.Component() if name == "." { rp.Advance() return d, nil } if name == ".." { if isRoot, err := rp.CheckRoot(&d.vfsd); err != nil { return nil, err } else if isRoot || d.parent == nil { rp.Advance() return d, nil } if err := rp.CheckMount(&d.parent.vfsd); err != nil { return nil, err } rp.Advance() return d.parent, nil } if len(name) > linux.NAME_MAX { return nil, syserror.ENAMETOOLONG } child, ok := dir.childMap[name] if !ok { return nil, syserror.ENOENT } if err := rp.CheckMount(&child.vfsd); err != nil { return nil, err } if symlink, ok := child.inode.impl.(*symlink); ok && rp.ShouldFollowSymlink() { // Symlink traversal updates access time. child.inode.touchAtime(rp.Mount()) if err := rp.HandleSymlink(symlink.target); err != nil { return nil, err } goto afterSymlink // don't check the current directory again } rp.Advance() return child, nil } // walkParentDirLocked resolves all but the last path component of rp to an // existing directory, starting from the given directory (which is usually // rp.Start().Impl().(*dentry)). It does not check that the returned directory // is searchable by the provider of rp. // // walkParentDirLocked is loosely analogous to Linux's // fs/namei.c:path_parentat(). // // Preconditions: filesystem.mu must be locked. !rp.Done(). func walkParentDirLocked(rp *vfs.ResolvingPath, d *dentry) (*directory, error) { for !rp.Final() { next, err := stepLocked(rp, d) if err != nil { return nil, err } d = next } dir, ok := d.inode.impl.(*directory) if !ok { return nil, syserror.ENOTDIR } return dir, nil } // resolveLocked resolves rp to an existing file. // // resolveLocked is loosely analogous to Linux's fs/namei.c:path_lookupat(). // // Preconditions: filesystem.mu must be locked. func
(rp *vfs.ResolvingPath) (*dentry, error) { d := rp.Start().Impl().(*dentry) for !rp.Done() { next, err := stepLocked(rp, d) if err != nil { return nil, err } d = next } if rp.MustBeDir() && !d.inode.isDir() { return nil, syserror.ENOTDIR } return d, nil } // doCreateAt checks that creating a file at rp is permitted, then invokes // create to do so. // // doCreateAt is loosely analogous to a conjunction of Linux's // fs/namei.c:filename_create() and done_path_create(). // // Preconditions: !rp.Done(). For the final path component in rp, // !rp.ShouldFollowSymlink(). func (fs *filesystem) doCreateAt(rp *vfs.ResolvingPath, dir bool, create func(parentDir *directory, name string) error) error { fs.mu.Lock() defer fs.mu.Unlock() parentDir, err := walkParentDirLocked(rp, rp.Start().Impl().(*dentry)) if err != nil { return err } if err := parentDir.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil { return err } name := rp.Component() if name == "." || name == ".." { return syserror.EEXIST } if len(name) > linux.NAME_MAX { return syserror.ENAMETOOLONG } if _, ok := parentDir.childMap[name]; ok { return syserror.EEXIST } if !dir && rp.MustBeDir() { return syserror.ENOENT } // tmpfs never calls VFS.InvalidateDentry(), so parentDir.dentry can only // be dead if it was deleted. if parentDir.dentry.vfsd.IsDead() { return syserror.ENOENT } mnt := rp.Mount() if err := mnt.CheckBeginWrite(); err != nil { return err } defer mnt.EndWrite() if err := create(parentDir, name); err != nil { return err } ev := linux.IN_CREATE if dir { ev |= linux.IN_ISDIR } parentDir.inode.watches.Notify(name, uint32(ev), 0, vfs.InodeEvent, false /* unlinked */) parentDir.inode.touchCMtime() return nil } // AccessAt implements vfs.Filesystem.Impl.AccessAt. func (fs *filesystem) AccessAt(ctx context.Context, rp *vfs.ResolvingPath, creds *auth.Credentials, ats vfs.AccessTypes) error { fs.mu.RLock() defer fs.mu.RUnlock() d, err := resolveLocked(rp) if err != nil { return err } return d.inode.checkPermissions(creds, ats) } // GetDentryAt implements vfs.FilesystemImpl.GetDentryAt. func (fs *filesystem) GetDentryAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.GetDentryOptions) (*vfs.Dentry, error) { fs.mu.RLock() defer fs.mu.RUnlock() d, err := resolveLocked(rp) if err != nil { return nil, err } if opts.CheckSearchable { if !d.inode.isDir() { return nil, syserror.ENOTDIR } if err := d.inode.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil { return nil, err } } d.IncRef() return &d.vfsd, nil } // GetParentDentryAt implements vfs.FilesystemImpl.GetParentDentryAt. func (fs *filesystem) GetParentDentryAt(ctx context.Context, rp *vfs.ResolvingPath) (*vfs.Dentry, error) { fs.mu.RLock() defer fs.mu.RUnlock() dir, err := walkParentDirLocked(rp, rp.Start().Impl().(*dentry)) if err != nil { return nil, err } dir.dentry.IncRef() return &dir.dentry.vfsd, nil } // LinkAt implements vfs.FilesystemImpl.LinkAt. func (fs *filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.VirtualDentry) error { return fs.doCreateAt(rp, false /* dir */, func(parentDir *directory, name string) error { if rp.Mount() != vd.Mount() { return syserror.EXDEV } d := vd.Dentry().Impl().(*dentry) i := d.inode if i.isDir() { return syserror.EPERM } if err := vfs.MayLink(auth.CredentialsFromContext(ctx), linux.FileMode(atomic.LoadUint32(&i.mode)), auth.KUID(atomic.LoadUint32(&i.uid)), auth.KGID(atomic.LoadUint32(&i.gid))); err != nil { return err } if i.nlink == 0 { return syserror.ENOENT } if i.nlink == maxLinks { return syserror.EMLINK } i.incLinksLocked() i.watches.Notify("", linux.IN_ATTRIB, 0, vfs.InodeEvent, false /* unlinked */) parentDir.insertChildLocked(fs.newDentry(i), name) return nil }) } // MkdirAt implements vfs.FilesystemImpl.MkdirAt. func (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MkdirOptions) error { return fs.doCreateAt(rp, true /* dir */, func(parentDir *directory, name string) error { creds := rp.Credentials() if parentDir.inode.nlink == maxLinks { return syserror.EMLINK } parentDir.inode.incLinksLocked() // from child's ".." childDir := fs.newDirectory(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode) parentDir.insertChildLocked(&childDir.dentry, name) return nil }) } // MknodAt implements vfs.FilesystemImpl.MknodAt. func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MknodOptions) error { return fs.doCreateAt(rp, false /* dir */, func(parentDir *directory, name string) error { creds := rp.Credentials() var childInode *inode switch opts.Mode.FileType() { case 0, linux.S_IFREG: childInode = fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode) case linux.S_IFIFO: childInode = fs.newNamedPipe(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode) case linux.S_IFBLK: childInode = fs.newDeviceFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, vfs.BlockDevice, opts.DevMajor, opts.DevMinor) case linux.S_IFCHR: childInode = fs.newDeviceFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, vfs.CharDevice, opts.DevMajor, opts.DevMinor) case linux.S_IFSOCK: childInode = fs.newSocketFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, opts.Endpoint) default: return syserror.EINVAL } child := fs.newDentry(childInode) parentDir.insertChildLocked(child, name) return nil }) } // OpenAt implements vfs.FilesystemImpl.OpenAt. func (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.OpenOptions) (*vfs.FileDescription, error) { if opts.Flags&linux.O_TMPFILE != 0 { // Not yet supported. return nil, syserror.EOPNOTSUPP } // Handle O_CREAT and !O_CREAT separately, since in the latter case we // don't need fs.mu for writing. if opts.Flags&linux.O_CREAT == 0 { fs.mu.RLock() defer fs.mu.RUnlock() d, err := resolveLocked(rp) if err != nil { return nil, err } return d.open(ctx, rp, &opts, false /* afterCreate */) } mustCreate := opts.Flags&linux.O_EXCL != 0 start := rp.Start().Impl().(*dentry) fs.mu.Lock() defer fs.mu.Unlock() if rp.Done() { // Reject attempts to open directories with O_CREAT. if rp.MustBeDir() { return nil, syserror.EISDIR } if mustCreate { return nil, syserror.EEXIST } return start.open(ctx, rp, &opts, false /* afterCreate */) } afterTrailingSymlink: parentDir, err := walkParentDirLocked(rp, start) if err != nil { return nil, err } // Check for search permission in the parent directory. if err := parentDir.inode.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil { return nil, err } // Reject attempts to open directories with O_CREAT. if rp.MustBeDir() { return nil, syserror.EISDIR } name := rp.Component() if name == "." || name == ".." { return nil, syserror.EISDIR } if len(name) > linux.NAME_MAX { return nil, syserror.ENAMETOOLONG } // Determine whether or not we need to create a file. child, ok := parentDir.childMap[name] if !ok { // Already checked for searchability above; now check for writability. if err := parentDir.inode.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil { return nil, err } if err := rp.Mount().CheckBeginWrite(); err != nil { return nil, err } defer rp.Mount().EndWrite() // Create and open the child. creds := rp.Credentials() child := fs.newDentry(fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode)) parentDir.insertChildLocked(child, name) fd, err := child.open(ctx, rp, &opts, true) if err != nil { return nil, err } parentDir.inode.watches.Notify(name, linux.IN_CREATE, 0, vfs.PathEvent, false /* unlinked */) parentDir.inode.touchCMtime() return fd, nil } if mustCreate { return nil, syserror.EEXIST } // Is the file mounted over? if err := rp.CheckMount(&child.vfsd); err != nil { return nil, err } // Do we need to resolve a trailing symlink? if symlink, ok := child.inode.impl.(*symlink); ok && rp.ShouldFollowSymlink() { // Symlink traversal updates access time. child.inode.touchAtime(rp.Mount()) if err := rp.HandleSymlink(symlink.target); err != nil { return nil, err } start = &parentDir.dentry goto afterTrailingSymlink } // Open existing file. if mustCreate { return nil, syserror.EEXIST } return child.open(ctx, rp, &opts, false) } func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.OpenOptions, afterCreate bool) (*vfs.FileDescription, error) { ats := vfs.AccessTypesForOpenFlags(opts) if !afterCreate { if err := d.inode.checkPermissions(rp.Credentials(), ats); err != nil { return nil, err } } switch impl := d.inode.impl.(type) { case *regularFile: var fd regularFileFD fd.LockFD.Init(&d.inode.locks) if err := fd.vfsfd.Init(&fd, opts.Flags, rp.Mount(), &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil { return nil, err } if opts.Flags&linux.O_TRUNC != 0 { if _, err := impl.truncate(0); err != nil { return nil, err } } return &fd.vfsfd, nil case *directory: // Can't open directories writably. if ats&vfs.MayWrite != 0 { return nil, syserror.EISDIR } var fd directoryFD fd.LockFD.Init(&d.inode.locks) if err := fd.vfsfd.Init(&fd, opts.Flags, rp.Mount(), &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil { return nil, err } return &fd.vfsfd, nil case *symlink: // TODO(gvisor.dev/issue/2782): Can't open symlinks without O_PATH. return nil, syserror.ELOOP case *namedPipe: return impl.pipe.Open(ctx, rp.Mount(), &d.vfsd, opts.Flags, &d.inode.locks) case *deviceFile: return rp.VirtualFilesystem().OpenDeviceSpecialFile(ctx, rp.Mount(), &d.vfsd, impl.kind, impl.major, impl.minor, opts) case *socketFile: return nil, syserror.ENXIO default: panic(fmt.Sprintf("unknown inode type: %T", d.inode.impl)) } } // ReadlinkAt implements vfs.FilesystemImpl.ReadlinkAt. func (fs *filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (string, error) { fs.mu.RLock() defer fs.mu.RUnlock() d, err := resolveLocked(rp) if err != nil { return "", err } symlink, ok := d.inode.impl.(*symlink) if !ok { return "", syserror.EINVAL } symlink.inode.touchAtime(rp.Mount()) return symlink.target, nil } // RenameAt implements vfs.FilesystemImpl.RenameAt. func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldParentVD vfs.VirtualDentry, oldName string, opts vfs.RenameOptions) error { if opts.Flags != 0 { // TODO(b/145974740): Support renameat2 flags. return syserror.EINVAL } // Resolve newParent first to verify that it's on this Mount. fs.mu.Lock() defer fs.mu.Unlock() newParentDir, err := walkParentDirLocked(rp, rp.Start().Impl().(*dentry)) if err != nil { return err } newName := rp.Component() if newName == "." || newName == ".." { return syserror.EBUSY } mnt := rp.Mount() if mnt != oldParentVD.Mount() { return syserror.EXDEV } if err := mnt.CheckBeginWrite(); err != nil { return err } defer mnt.EndWrite() oldParentDir := oldParentVD.Dentry().Impl().(*dentry).inode.impl.(*directory) if err := oldParentDir.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil { return err } renamed, ok := oldParentDir.childMap[oldName] if !ok { return syserror.ENOENT } // Note that we don't need to call rp.CheckMount(), since if renamed is a // mount point then we want to rename the mount point, not anything in the // mounted filesystem. if renamed.inode.isDir() { if renamed == &newParentDir.dentry || genericIsAncestorDentry(renamed, &newParentDir.dentry) { return syserror.EINVAL } if oldParentDir != newParentDir { // Writability is needed to change renamed's "..". if err := renamed.inode.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil { return err } } } else { if opts.MustBeDir || rp.MustBeDir() { return syserror.ENOTDIR } } if err := newParentDir.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil { return err } replaced, ok := newParentDir.childMap[newName] if ok { replacedDir, ok := replaced.inode.impl.(*directory) if ok { if !renamed.inode.isDir() { return syserror.EISDIR } if len(replacedDir.childMap) != 0 { return syserror.ENOTEMPTY } } else { if rp.MustBeDir() { return syserror.ENOTDIR } if renamed.inode.isDir() { return syserror.ENOTDIR } } } else { if renamed.inode.isDir() && newParentDir.inode.nlink == maxLinks { return syserror.EMLINK } } // tmpfs never calls VFS.InvalidateDentry(), so newParentDir.dentry can // only be dead if it was deleted. if newParentDir.dentry.vfsd.IsDead() { return syserror.ENOENT } // Linux places this check before some of those above; we do it here for // simplicity, under the assumption that applications are not intentionally // doing noop renames expecting them to succeed where non-noop renames // would fail. if renamed == replaced { return nil } vfsObj := rp.VirtualFilesystem() mntns := vfs.MountNamespaceFromContext(ctx) defer mntns.DecRef() var replacedVFSD *vfs.Dentry if replaced != nil { replacedVFSD = &replaced.vfsd } if err := vfsObj.PrepareRenameDentry(mntns, &renamed.vfsd, replacedVFSD); err != nil { return err } if replaced != nil { newParentDir.removeChildLocked(replaced) if replaced.inode.isDir() { newParentDir.inode.decLinksLocked() // from replaced's ".." } replaced.inode.decLinksLocked() } oldParentDir.removeChildLocked(renamed) newParentDir.insertChildLocked(renamed, newName) vfsObj.CommitRenameReplaceDentry(&renamed.vfsd, replacedVFSD) oldParentDir.inode.touchCMtime() if oldParentDir != newParentDir { if renamed.inode.isDir() { oldParentDir.inode.decLinksLocked() newParentDir.inode.incLinksLocked() } newParentDir.inode.touchCMtime() } renamed.inode.touchCtime() vfs.InotifyRename(ctx, &renamed.inode.watches, &oldParentDir.inode.watches, &newParentDir.inode.watches, oldName, newName, renamed.inode.isDir()) return nil } // RmdirAt implements vfs.FilesystemImpl.RmdirAt. func (fs *filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error { fs.mu.Lock() defer fs.mu.Unlock() parentDir, err := walkParentDirLocked(rp, rp.Start().Impl().(*dentry)) if err != nil { return err } if err := parentDir.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil { return err } name := rp.Component() if name == "." { return syserror.EINVAL } if name == ".." { return syserror.ENOTEMPTY } child, ok := parentDir.childMap[name] if !ok { return syserror.ENOENT } childDir, ok := child.inode.impl.(*directory) if !ok { return syserror.ENOTDIR } if len(childDir.childMap) != 0 { return syserror.ENOTEMPTY } mnt := rp.Mount() if err := mnt.CheckBeginWrite(); err != nil { return err } defer mnt.EndWrite() vfsObj := rp.VirtualFilesystem() mntns := vfs.MountNamespaceFromContext(ctx) defer mntns.DecRef() if err := vfsObj.PrepareDeleteDentry(mntns, &child.vfsd); err != nil { return err } parentDir.removeChildLocked(child) parentDir.inode.watches.Notify(name, linux.IN_DELETE|linux.IN_ISDIR, 0, vfs.InodeEvent, true /* unlinked */) // Remove links for child, child/., and child/.. child.inode.decLinksLocked() child.inode.decLinksLocked() parentDir.inode.decLinksLocked() vfsObj.CommitDeleteDentry(&child.vfsd) parentDir.inode.touchCMtime() return nil } // SetStatAt implements vfs.FilesystemImpl.SetStatAt. func (fs *filesystem) SetStatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.SetStatOptions) error { fs.mu.RLock() d, err := resolveLocked(rp) if err != nil { fs.mu.RUnlock() return err } if err := d.inode.setStat(ctx, rp.Credentials(), &opts.Stat); err != nil { fs.mu.RUnlock() return err } fs.mu.RUnlock() if ev := vfs.InotifyEventFromStatMask(opts.Stat.Mask); ev != 0 { d.InotifyWithParent(ev, 0, vfs.InodeEvent) } return nil } // StatAt implements vfs.FilesystemImpl.StatAt. func (fs *filesystem) StatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.StatOptions) (linux.Statx, error) { fs.mu.RLock() defer fs.mu.RUnlock() d, err := resolveLocked(rp) if err != nil { return linux.Statx{}, err } var stat linux.Statx d.inode.statTo(&stat) return stat, nil } // StatFSAt implements vfs.FilesystemImpl.StatFSAt. func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linux.Statfs, error) { fs.mu.RLock() defer fs.mu.RUnlock() if _, err := resolveLocked(rp); err != nil { return linux.Statfs{}, err } statfs := linux.Statfs{ Type: linux.TMPFS_MAGIC, BlockSize: usermem.PageSize, FragmentSize: usermem.PageSize, NameLength: linux.NAME_MAX, // TODO(b/29637826): Allow configuring a tmpfs size and enforce it. Blocks: 0, BlocksFree: 0, } return statfs, nil } // SymlinkAt implements vfs.FilesystemImpl.SymlinkAt. func (fs *filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, target string) error { return fs.doCreateAt(rp, false /* dir */, func(parentDir *directory, name string) error { creds := rp.Credentials() child := fs.newDentry(fs.newSymlink(creds.EffectiveKUID, creds.EffectiveKGID, 0777, target)) parentDir.insertChildLocked(child, name) return nil }) } // UnlinkAt implements vfs.FilesystemImpl.UnlinkAt. func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error { fs.mu.Lock() defer fs.mu.Unlock() parentDir, err := walkParentDirLocked(rp, rp.Start().Impl().(*dentry)) if err != nil { return err } if err := parentDir.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil { return err } name := rp.Component() if name == "." || name == ".." { return syserror.EISDIR } child, ok := parentDir.childMap[name] if !ok { return syserror.ENOENT } if child.inode.isDir() { return syserror.EISDIR } if rp.MustBeDir() { return syserror.ENOTDIR } mnt := rp.Mount() if err := mnt.CheckBeginWrite(); err != nil { return err } defer mnt.EndWrite() vfsObj := rp.VirtualFilesystem() mntns := vfs.MountNamespaceFromContext(ctx) defer mntns.DecRef() if err := vfsObj.PrepareDeleteDentry(mntns, &child.vfsd); err != nil { return err } // Generate inotify events. Note that this must take place before the link // count of the child is decremented, or else the watches may be dropped // before these events are added. vfs.InotifyRemoveChild(&child.inode.watches, &parentDir.inode.watches, name) parentDir.removeChildLocked(child) child.inode.decLinksLocked() vfsObj.CommitDeleteDentry(&child.vfsd) parentDir.inode.touchCMtime() return nil } // BoundEndpointAt implements FilesystemImpl.BoundEndpointAt. func (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.BoundEndpointOptions) (transport.BoundEndpoint, error) { fs.mu.RLock() defer fs.mu.RUnlock() d, err := resolveLocked(rp) if err != nil { return nil, err } if err := d.inode.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil { return nil, err } switch impl := d.inode.impl.(type) { case *socketFile: return impl.ep, nil default: return nil, syserror.ECONNREFUSED } } // ListxattrAt implements vfs.FilesystemImpl.ListxattrAt. func (fs *filesystem) ListxattrAt(ctx context.Context, rp *vfs.ResolvingPath, size uint64) ([]string, error) { fs.mu.RLock() defer fs.mu.RUnlock() d, err := resolveLocked(rp) if err != nil { return nil, err } return d.inode.listxattr(size) } // GetxattrAt implements vfs.FilesystemImpl.GetxattrAt. func (fs *filesystem) GetxattrAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.GetxattrOptions) (string, error) { fs.mu.RLock() defer fs.mu.RUnlock() d, err := resolveLocked(rp) if err != nil { return "", err } return d.inode.getxattr(rp.Credentials(), &opts) } // SetxattrAt implements vfs.FilesystemImpl.SetxattrAt. func (fs *filesystem) SetxattrAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.SetxattrOptions) error { fs.mu.RLock() d, err := resolveLocked(rp) if err != nil { fs.mu.RUnlock() return err } if err := d.inode.setxattr(rp.Credentials(), &opts); err != nil { fs.mu.RUnlock() return err } fs.mu.RUnlock() d.InotifyWithParent(linux.IN_ATTRIB, 0, vfs.InodeEvent) return nil } // RemovexattrAt implements vfs.FilesystemImpl.RemovexattrAt. func (fs *filesystem) RemovexattrAt(ctx context.Context, rp *vfs.ResolvingPath, name string) error { fs.mu.RLock() d, err := resolveLocked(rp) if err != nil { fs.mu.RUnlock() return err } if err := d.inode.removexattr(rp.Credentials(), name); err != nil { fs.mu.RUnlock() return err } fs.mu.RUnlock() d.InotifyWithParent(linux.IN_ATTRIB, 0, vfs.InodeEvent) return nil } // PrependPath implements vfs.FilesystemImpl.PrependPath. func (fs *filesystem) PrependPath(ctx context.Context, vfsroot, vd vfs.VirtualDentry, b *fspath.Builder) error { fs.mu.RLock() defer fs.mu.RUnlock() mnt := vd.Mount() d := vd.Dentry().Impl().(*dentry) for { if mnt == vfsroot.Mount() && &d.vfsd == vfsroot.Dentry() { return vfs.PrependPathAtVFSRootError{} } if &d.vfsd == mnt.Root() { return nil } if d.parent == nil { if d.name != "" { // This must be an anonymous memfd file. b.PrependComponent("/" + d.name) return vfs.PrependPathSyntheticError{} } return vfs.PrependPathAtNonMountRootError{} } b.PrependComponent(d.name) d = d.parent } }
resolveLocked
textdocument_highlight.go
package langserver import ( "context" "luahelper-lsp/langserver/check/common" "luahelper-lsp/langserver/log" "luahelper-lsp/langserver/lspcommon" lsp "luahelper-lsp/langserver/protocol" ) // TextDocumentHighlight 对变量单击选中着色 func (l *LspServer) TextDocumentHighlight(ctx context.Context, vs lsp.TextDocumentPositionParams) (retVec []lsp.DocumentHighlight, err error) { l.requestMutex.Lock() defer l.requestMutex.Unlock() if !l.isCanHighlight() { log.Error("IsCanHighlight is false") return } comResult := l.beginFileRequest(vs.TextDocument.URI, vs.Position) if !comResult.result { return } if len(comResult.contents) == 0 || comResult.offset >= len(comResult.contents) { return } project := l.getAllProject() varStruct := getVarStruct(comResult.contents, comResult.offset, comResult.pos.Line, comResult.pos.Character, comResult.strFile) if !varStruct.ValidFlag { log.Error("Tex
ferenVecs := project.FindReferences(comResult.strFile, &varStruct, common.CRSHighlight) retVec = make([]lsp.DocumentHighlight, 0, len(referenVecs)) for _, referVarInfo := range referenVecs { retVec = append(retVec, lsp.DocumentHighlight{ Range: lspcommon.LocToRange(&referVarInfo.Loc), Kind: lsp.Write, }) } return }
tDocumentHighlight varStruct.ValidFlag not valid") return } // 去掉前缀后的名字 re
mod.rs
mod actions; mod image; mod input; mod section; pub use crate::blocks::actions::*; pub use crate::blocks::image::*; pub use crate::blocks::input::*; pub use crate::blocks::section::*; use crate::objects::Text; use serde::{Serialize, Serializer}; #[derive(Serialize)] pub struct Actions { elements: Vec<ActionsElement>, block_id: Option<String>, } impl Actions { pub fn new(elements: Vec<ActionsElement>) -> Self { Actions { elements, block_id: None, } } pub fn new_with_id<S: Into<String>>(block_id: S, elements: Vec<ActionsElement>) -> Self { Self { elements, block_id: Some(block_id.into()), } } } #[derive(Serialize)] pub struct Context { pub elements: Vec<ContextElement>, pub block_id: Option<String>, } impl Context { pub fn new(elements: Vec<ContextElement>) -> Self { Context { elements, block_id: None, } } pub fn new_with_id<S: Into<String>>(block_id: S, elements: Vec<ContextElement>) -> Self { Self { elements, block_id: Some(block_id.into()), } } } #[derive(Default, Serialize)] pub struct Divider { pub block_id: Option<String>, } impl Divider { pub fn new() -> Self { Divider::default() } pub fn new_with_id<S: Into<String>>(block_id: S) -> Self { Self { block_id: Some(block_id.into()), } } } #[derive(Serialize)] pub struct File { external_id: String, block_id: Option<String>, } impl File { pub fn new<S: Into<String>>(external_id: S) -> Self { File { external_id: external_id.into(), block_id: None, } } pub fn new_with_id<S: Into<String>, T: Into<String>>(block_id: S, external_id: T) -> Self { Self { external_id: external_id.into(), block_id: Some(block_id.into()), } } } impl Into<ContextElement> for Image { fn
(self) -> ContextElement { ContextElement::Image(self) } } impl Into<ContextElement> for Text { fn into(self) -> ContextElement { ContextElement::Text(self) } } pub enum ContextElement { Image(Image), Text(Text), } impl Serialize for ContextElement { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { ContextElement::Image(e) => e.serialize(serializer), ContextElement::Text(e) => e.serialize(serializer), } } }
into
interface.go
package types import ( "github.com/gin-gonic/gin" "github.com/jinzhu/gorm" "github.com/jiwoniy/otmk-kipris-collector/nice/schema" "github.com/jiwoniy/otmk-kipris-collector/utils" )
type RestMethod struct { Path string Handler RestHandler } type Result struct { Data interface{} `json:"data,omitempty"` } type Storage struct { DB *gorm.DB } type ImportClient interface { GetStorage() *Storage ImportNiceCsv(folderPath string, db *gorm.DB) GetNiceList(result *[]schema.NiceClassification) } type Client interface { GetStorage() *Storage GetMethods() ([]RestMethod, error) } type QueryClient interface { Client SearchSimilarGroups(text string, classificationCode string, size int, page int) (*utils.Paginator, error) GetSimilarCodeText(id string) (string, error) }
type RestHandler func(ctx *gin.Context)
odr_test.go
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package light import ( "bytes" "context" "errors" "math/big" "testing" "time" "github.com/ethereum-optimism/optimism/l2geth/common" "github.com/ethereum-optimism/optimism/l2geth/common/math" "github.com/ethereum-optimism/optimism/l2geth/consensus/ethash" "github.com/ethereum-optimism/optimism/l2geth/core" "github.com/ethereum-optimism/optimism/l2geth/core/rawdb" "github.com/ethereum-optimism/optimism/l2geth/core/state" "github.com/ethereum-optimism/optimism/l2geth/core/types" "github.com/ethereum-optimism/optimism/l2geth/core/vm" "github.com/ethereum-optimism/optimism/l2geth/crypto" "github.com/ethereum-optimism/optimism/l2geth/ethdb" "github.com/ethereum-optimism/optimism/l2geth/params" "github.com/ethereum-optimism/optimism/l2geth/rlp" "github.com/ethereum-optimism/optimism/l2geth/trie" ) var ( testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey) testBankFunds = big.NewInt(100000000) acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a") acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee") acc1Addr = crypto.PubkeyToAddress(acc1Key.PublicKey) acc2Addr = crypto.PubkeyToAddress(acc2Key.PublicKey) testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056") testContractAddr common.Address ) type testOdr struct { OdrBackend indexerConfig *IndexerConfig sdb, ldb ethdb.Database disable bool } func (odr *testOdr) Database() ethdb.Database { return odr.ldb } var ErrOdrDisabled = errors.New("ODR disabled") func (odr *testOdr) Retrieve(ctx context.Context, req OdrRequest) error { if odr.disable { return ErrOdrDisabled } switch req := req.(type) { case *BlockRequest: number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash) if number != nil { req.Rlp = rawdb.ReadBodyRLP(odr.sdb, req.Hash, *number) } case *ReceiptsRequest: number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash) if number != nil { req.Receipts = rawdb.ReadRawReceipts(odr.sdb, req.Hash, *number) } case *TrieRequest: t, _ := trie.New(req.Id.Root, trie.NewDatabase(odr.sdb)) nodes := NewNodeSet() t.Prove(req.Key, 0, nodes) req.Proof = nodes case *CodeRequest: req.Data, _ = odr.sdb.Get(req.Hash[:]) } req.StoreResult(odr.ldb) return nil } func (odr *testOdr) IndexerConfig() *IndexerConfig { return odr.indexerConfig } type odrTestFn func(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) func TestOdrGetBlockLes2(t *testing.T) { testChainOdr(t, 1, odrGetBlock) } func
(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) { var block *types.Block if bc != nil { block = bc.GetBlockByHash(bhash) } else { block, _ = lc.GetBlockByHash(ctx, bhash) } if block == nil { return nil, nil } rlp, _ := rlp.EncodeToBytes(block) return rlp, nil } func TestOdrGetReceiptsLes2(t *testing.T) { testChainOdr(t, 1, odrGetReceipts) } func odrGetReceipts(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) { var receipts types.Receipts if bc != nil { number := rawdb.ReadHeaderNumber(db, bhash) if number != nil { receipts = rawdb.ReadReceipts(db, bhash, *number, bc.Config()) } } else { number := rawdb.ReadHeaderNumber(db, bhash) if number != nil { receipts, _ = GetBlockReceipts(ctx, lc.Odr(), bhash, *number) } } if receipts == nil { return nil, nil } rlp, _ := rlp.EncodeToBytes(receipts) return rlp, nil } func TestOdrAccountsLes2(t *testing.T) { testChainOdr(t, 1, odrAccounts) } func odrAccounts(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) { dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678") acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr} var st *state.StateDB if bc == nil { header := lc.GetHeaderByHash(bhash) st = NewState(ctx, header, lc.Odr()) } else { header := bc.GetHeaderByHash(bhash) st, _ = state.New(header.Root, state.NewDatabase(db)) } var res []byte for _, addr := range acc { bal := st.GetBalance(addr) rlp, _ := rlp.EncodeToBytes(bal) res = append(res, rlp...) } return res, st.Error() } func TestOdrContractCallLes2(t *testing.T) { testChainOdr(t, 1, odrContractCall) } type callmsg struct { types.Message } func (callmsg) CheckNonce() bool { return false } func odrContractCall(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) { data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000") config := params.TestChainConfig var res []byte for i := 0; i < 3; i++ { data[35] = byte(i) var ( st *state.StateDB header *types.Header chain core.ChainContext ) if bc == nil { chain = lc header = lc.GetHeaderByHash(bhash) st = NewState(ctx, header, lc.Odr()) } else { chain = bc header = bc.GetHeaderByHash(bhash) st, _ = state.New(header.Root, state.NewDatabase(db)) } // Perform read-only call. st.SetBalance(testBankAddress, math.MaxBig256) msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 1000000, new(big.Int), data, false, nil, 0, []byte{0}, types.QueueOriginSequencer)} context := core.NewEVMContext(msg, header, chain, nil) vmenv := vm.NewEVM(context, st, config, vm.Config{}) gp := new(core.GasPool).AddGas(math.MaxUint64) ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp) res = append(res, ret...) if st.Error() != nil { return res, st.Error() } } return res, nil } func testChainGen(i int, block *core.BlockGen) { signer := types.HomesteadSigner{} switch i { case 0: // In block 1, the test bank sends account #1 some ether. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey) block.AddTx(tx) case 1: // In block 2, the test bank sends some more ether to account #1. // acc1Addr passes it on to account #2. // acc1Addr creates a test contract. tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey) nonce := block.TxNonce(acc1Addr) tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key) nonce++ tx3, _ := types.SignTx(types.NewContractCreation(nonce, big.NewInt(0), 1000000, big.NewInt(0), testContractCode), signer, acc1Key) testContractAddr = crypto.CreateAddress(acc1Addr, nonce) block.AddTx(tx1) block.AddTx(tx2) block.AddTx(tx3) case 2: // Block 3 is empty but was mined by account #2. block.SetCoinbase(acc2Addr) block.SetExtra([]byte("yeehaw")) data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001") tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey) block.AddTx(tx) case 3: // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data). b2 := block.PrevBlock(1).Header() b2.Extra = []byte("foo") block.AddUncle(b2) b3 := block.PrevBlock(2).Header() b3.Extra = []byte("foo") block.AddUncle(b3) data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002") tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey) block.AddTx(tx) } } func testChainOdr(t *testing.T, protocol int, fn odrTestFn) { var ( sdb = rawdb.NewMemoryDatabase() ldb = rawdb.NewMemoryDatabase() gspec = core.Genesis{Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}} genesis = gspec.MustCommit(sdb) ) gspec.MustCommit(ldb) // Assemble the test environment blockchain, _ := core.NewBlockChain(sdb, nil, params.TestChainConfig, ethash.NewFullFaker(), vm.Config{}, nil) gchain, _ := core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), sdb, 4, testChainGen) if _, err := blockchain.InsertChain(gchain); err != nil { t.Fatal(err) } odr := &testOdr{sdb: sdb, ldb: ldb, indexerConfig: TestClientIndexerConfig} lightchain, err := NewLightChain(odr, params.TestChainConfig, ethash.NewFullFaker(), nil) if err != nil { t.Fatal(err) } headers := make([]*types.Header, len(gchain)) for i, block := range gchain { headers[i] = block.Header() } if _, err := lightchain.InsertHeaderChain(headers, 1); err != nil { t.Fatal(err) } test := func(expFail int) { for i := uint64(0); i <= blockchain.CurrentHeader().Number.Uint64(); i++ { bhash := rawdb.ReadCanonicalHash(sdb, i) b1, err := fn(NoOdr, sdb, blockchain, nil, bhash) if err != nil { t.Fatalf("error in full-node test for block %d: %v", i, err) } ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() exp := i < uint64(expFail) b2, err := fn(ctx, ldb, nil, lightchain, bhash) if err != nil && exp { t.Errorf("error in ODR test for block %d: %v", i, err) } eq := bytes.Equal(b1, b2) if exp && !eq { t.Errorf("ODR test output for block %d doesn't match full node", i) } } } // expect retrievals to fail (except genesis block) without a les peer t.Log("checking without ODR") odr.disable = true test(1) // expect all retrievals to pass with ODR enabled t.Log("checking with ODR") odr.disable = false test(len(gchain)) // still expect all retrievals to pass, now data should be cached locally t.Log("checking without ODR, should be cached") odr.disable = true test(len(gchain)) }
odrGetBlock
test_training_data.py
import asyncio from pathlib import Path from typing import Text import pytest import rasa.shared.utils.io from rasa.core.domain import Domain from rasa.core.events import UserUttered, ActionExecuted from rasa.core.training.structures import StoryStep, StoryGraph from rasa.importers.importer import E2EImporter, TrainingDataImporter from rasa.shared.nlu.constants import TEXT, INTENT_RESPONSE_KEY from rasa.nlu.convert import convert_training_data from rasa.nlu.extractors.mitie_entity_extractor import MitieEntityExtractor from rasa.nlu.tokenizers.whitespace_tokenizer import WhitespaceTokenizer from rasa.shared.nlu.training_data.training_data import TrainingData from rasa.shared.nlu.training_data.loading import ( guess_format, UNK, RASA_YAML, JSON, MARKDOWN, load_data, ) from rasa.shared.nlu.training_data.util import get_file_format def test_luis_data(): td = load_data("data/examples/luis/demo-restaurants_v5.json") assert not td.is_empty() assert len(td.entity_examples) == 8 assert len(td.intent_examples) == 28 assert len(td.training_examples) == 28 assert td.entity_synonyms == {} assert td.intents == {"affirm", "goodbye", "greet", "inform"} assert td.entities == {"location", "cuisine"} def test_wit_data(): td = load_data("data/examples/wit/demo-flights.json") assert not td.is_empty() assert len(td.entity_examples) == 4 assert len(td.intent_examples) == 1 assert len(td.training_examples) == 4 assert td.entity_synonyms == {} assert td.intents == {"flight_booking"} assert td.entities == {"location", "datetime"} def test_dialogflow_data(): td = load_data("data/examples/dialogflow/") assert not td.is_empty() assert len(td.entity_examples) == 5 assert len(td.intent_examples) == 24 assert len(td.training_examples) == 24 assert len(td.lookup_tables) == 2 assert td.intents == {"affirm", "goodbye", "hi", "inform"} assert td.entities == {"cuisine", "location"} non_trivial_synonyms = {k: v for k, v in td.entity_synonyms.items() if k != v} assert non_trivial_synonyms == { "mexico": "mexican", "china": "chinese", "india": "indian", } # The order changes based on different computers hence the grouping assert {td.lookup_tables[0]["name"], td.lookup_tables[1]["name"]} == { "location", "cuisine", } assert { len(td.lookup_tables[0]["elements"]), len(td.lookup_tables[1]["elements"]), } == {4, 6} def test_lookup_table_json(): lookup_fname = "data/test/lookup_tables/plates.txt" td_lookup = load_data("data/test/lookup_tables/lookup_table.json") assert not td_lookup.is_empty() assert len(td_lookup.lookup_tables) == 1 assert td_lookup.lookup_tables[0]["name"] == "plates" assert td_lookup.lookup_tables[0]["elements"] == lookup_fname def test_lookup_table_md(): lookup_fname = "data/test/lookup_tables/plates.txt" td_lookup = load_data("data/test/lookup_tables/lookup_table.md") assert not td_lookup.is_empty() assert len(td_lookup.lookup_tables) == 1 assert td_lookup.lookup_tables[0]["name"] == "plates" assert td_lookup.lookup_tables[0]["elements"] == lookup_fname def test_composite_entities_data(): td = load_data("data/test/demo-rasa-composite-entities.md") assert not td.is_empty() assert len(td.entity_examples) == 11 assert len(td.intent_examples) == 45 assert len(td.training_examples) == 45 assert td.entity_synonyms == {"SF": "San Fransisco"} assert td.intents == { "order_pizza", "book_flight", "chitchat", "greet", "goodbye", "affirm", } assert td.entities == {"location", "topping", "size"} assert td.entity_groups == {"1", "2"} assert td.entity_roles == {"to", "from"} assert td.number_of_examples_per_entity["entity 'location'"] == 8 assert td.number_of_examples_per_entity["group '1'"] == 9 assert td.number_of_examples_per_entity["role 'from'"] == 3 @pytest.mark.parametrize( "files", [ [ "data/examples/rasa/demo-rasa.json", "data/examples/rasa/demo-rasa-responses.md", ], [ "data/examples/rasa/demo-rasa.md", "data/examples/rasa/demo-rasa-responses.md", ], ], ) def test_demo_data(files): from rasa.importers.utils import training_data_from_paths td = training_data_from_paths(files, language="en") assert td.intents == {"affirm", "greet", "restaurant_search", "goodbye", "chitchat"} assert td.entities == {"location", "cuisine"} assert set(td.responses.keys()) == {"chitchat/ask_name", "chitchat/ask_weather"} assert len(td.training_examples) == 46 assert len(td.intent_examples) == 46 assert len(td.response_examples) == 4 assert len(td.entity_examples) == 11 assert len(td.responses) == 2 assert td.entity_synonyms == { "Chines": "chinese", "Chinese": "chinese", "chines": "chinese", "vegg": "vegetarian", "veggie": "vegetarian", } assert td.regex_features == [ {"name": "greet", "pattern": r"hey[^\s]*"}, {"name": "zipcode", "pattern": r"[0-9]{5}"}, ] @pytest.mark.parametrize( "files", [ [ "data/examples/rasa/demo-rasa.json", "data/examples/rasa/demo-rasa-responses.md", ], [ "data/examples/rasa/demo-rasa.md", "data/examples/rasa/demo-rasa-responses.md", ], ], ) def test_demo_data_filter_out_retrieval_intents(files): from rasa.importers.utils import training_data_from_paths training_data = training_data_from_paths(files, language="en") assert len(training_data.training_examples) == 46 training_data_filtered = training_data.filter_training_examples( lambda ex: ex.get(INTENT_RESPONSE_KEY) is None ) assert len(training_data_filtered.training_examples) == 42 training_data_filtered_2 = training_data.filter_training_examples( lambda ex: ex.get(INTENT_RESPONSE_KEY) is not None ) assert len(training_data_filtered_2.training_examples) == 4 # make sure filtering operation doesn't mutate the source training data assert len(training_data.training_examples) == 46 @pytest.mark.parametrize( "filepaths", [["data/examples/rasa/demo-rasa.md", "data/examples/rasa/demo-rasa-responses.md"]], ) def test_train_test_split(filepaths): from rasa.importers.utils import training_data_from_paths td = training_data_from_paths(filepaths, language="en") assert td.intents == {"affirm", "greet", "restaurant_search", "goodbye", "chitchat"} assert td.entities == {"location", "cuisine"} assert set(td.responses.keys()) == {"chitchat/ask_name", "chitchat/ask_weather"} assert len(td.training_examples) == 46 assert len(td.intent_examples) == 46 assert len(td.response_examples) == 4 td_train, td_test = td.train_test_split(train_frac=0.8) assert len(td_test.training_examples) + len(td_train.training_examples) == 46 assert len(td_train.training_examples) == 34 assert len(td_test.training_examples) == 12 assert len(td.number_of_examples_per_intent.keys()) == len( td_test.number_of_examples_per_intent.keys() ) assert len(td.number_of_examples_per_intent.keys()) == len( td_train.number_of_examples_per_intent.keys() ) assert len(td.number_of_examples_per_response.keys()) == len( td_test.number_of_examples_per_response.keys() ) assert len(td.number_of_examples_per_response.keys()) == len( td_train.number_of_examples_per_response.keys() ) @pytest.mark.parametrize( "filepaths", [["data/examples/rasa/demo-rasa.md", "data/examples/rasa/demo-rasa-responses.md"]], ) def test_train_test_split_with_random_seed(filepaths): from rasa.importers.utils import training_data_from_paths td = training_data_from_paths(filepaths, language="en") td_train_1, td_test_1 = td.train_test_split(train_frac=0.8, random_seed=1) td_train_2, td_test_2 = td.train_test_split(train_frac=0.8, random_seed=1) train_1_intent_examples = [e.get(TEXT) for e in td_train_1.intent_examples] train_2_intent_examples = [e.get(TEXT) for e in td_train_2.intent_examples] test_1_intent_examples = [e.get(TEXT) for e in td_test_1.intent_examples] test_2_intent_examples = [e.get(TEXT) for e in td_test_2.intent_examples] assert train_1_intent_examples == train_2_intent_examples assert test_1_intent_examples == test_2_intent_examples @pytest.mark.parametrize( "files", [ ("data/examples/rasa/demo-rasa.json", "data/test/multiple_files_json"), ("data/examples/rasa/demo-rasa.md", "data/test/multiple_files_markdown"), ("data/examples/rasa/demo-rasa.md", "data/test/duplicate_intents_markdown"), ], ) def test_data_merging(files): td_reference = load_data(files[0]) td = load_data(files[1]) assert len(td.entity_examples) == len(td_reference.entity_examples) assert len(td.intent_examples) == len(td_reference.intent_examples) assert len(td.training_examples) == len(td_reference.training_examples) assert td.intents == td_reference.intents assert td.entities == td_reference.entities assert td.entity_synonyms == td_reference.entity_synonyms assert td.regex_features == td_reference.regex_features def test_markdown_single_sections(): td_regex_only = load_data("data/test/markdown_single_sections/regex_only.md") assert td_regex_only.regex_features == [{"name": "greet", "pattern": r"hey[^\s]*"}] td_syn_only = load_data("data/test/markdown_single_sections/synonyms_only.md") assert td_syn_only.entity_synonyms == {"Chines": "chinese", "Chinese": "chinese"} def test_repeated_entities(tmp_path): data = """ { "rasa_nlu_data": { "common_examples" : [ { "text": "book a table today from 3 to 6 for 3 people", "intent": "unk", "entities": [ { "entity": "description", "start": 35, "end": 36, "value": "3" } ] } ] } }""" f = tmp_path / "tmp_training_data.json" f.write_text(data, rasa.shared.utils.io.DEFAULT_ENCODING) td = load_data(str(f)) assert len(td.entity_examples) == 1 example = td.entity_examples[0] entities = example.get("entities") assert len(entities) == 1 tokens = WhitespaceTokenizer().tokenize(example, attribute=TEXT) start, end = MitieEntityExtractor.find_entity( entities[0], example.get(TEXT), tokens ) assert start == 9 assert end == 10 def test_multiword_entities(tmp_path): data = """ { "rasa_nlu_data": { "common_examples" : [ { "text": "show me flights to New York City", "intent": "unk", "entities": [ { "entity": "destination", "start": 19, "end": 32, "value": "New York City" } ] } ] } }""" f = tmp_path / "tmp_training_data.json" f.write_text(data, rasa.shared.utils.io.DEFAULT_ENCODING) td = load_data(str(f)) assert len(td.entity_examples) == 1 example = td.entity_examples[0] entities = example.get("entities") assert len(entities) == 1 tokens = WhitespaceTokenizer().tokenize(example, attribute=TEXT) start, end = MitieEntityExtractor.find_entity( entities[0], example.get(TEXT), tokens ) assert start == 4 assert end == 7 def test_nonascii_entities(tmp_path): data = """ { "luis_schema_version": "5.0", "utterances" : [ { "text": "I am looking for a ßäæ ?€ö) item", "intent": "unk", "entities": [ { "entity": "description", "startPos": 19, "endPos": 26 } ] } ] }""" f = tmp_path / "tmp_training_data.json" f.write_text(data, rasa.shared.utils.io.DEFAULT_ENCODING) td = load_data(str(f)) assert len(td.entity_examples) == 1 example = td.entity_examples[0] entities = example.get("entities") assert len(entities) == 1 entity = entities[0] assert entity["value"] == "ßäæ ?€ö)" assert entity["start"] == 19 assert entity["end"] == 27 assert entity["entity"] == "description" def test_entities_synonyms(tmp_path): data = """ { "rasa_nlu_data": { "entity_synonyms": [ { "value": "nyc", "synonyms": ["New York City", "nyc", "the big apple"] } ], "common_examples" : [ { "text": "show me flights to New York City", "intent": "unk", "entities": [ { "entity": "destination", "start": 19, "end": 32, "value": "NYC" } ] }, { "text": "show me flights to nyc", "intent": "unk", "entities": [ { "entity": "destination", "start": 19, "end": 22, "value": "nyc" } ] } ] } }""" f = tmp_path / "tmp_training_data.json" f.write_text(data, rasa.shared.utils.io.DEFAULT_ENCODING) td = load_data(str(f)) assert td.entity_synonyms["New York City"] == "nyc" def cmp_message_list(firsts, seconds): assert len(firsts) == len(seconds), "Message lists have unequal length" def cmp_dict_list(firsts, seconds): if len(firsts) != len(seconds): return False for a in firsts: for idx, b in enumerate(seconds): if hash(a) == hash(b): del seconds[idx] break else: others = ", ".join(e.text for e in seconds) assert False, f"Failed to find message {a.text} in {others}" return not seconds @pytest.mark.parametrize( "data_file,gold_standard_file,output_format,language", [ ( "data/examples/wit/demo-flights.json", "data/test/wit_converted_to_rasa.json", "json", None, ), ( "data/examples/luis/demo-restaurants_v5.json", "data/test/luis_converted_to_rasa.json", "json", None, ), ( "data/examples/dialogflow/", "data/test/dialogflow_en_converted_to_rasa.json", "json", "en", ), ( "data/examples/dialogflow/", "data/test/dialogflow_es_converted_to_rasa.json", "json", "es", ), ( "data/examples/rasa/demo-rasa.md", "data/test/md_converted_to_json.json", "json", None, ), ( "data/examples/rasa/demo-rasa.json", "data/test/json_converted_to_md.md", "md", None, ), ( "data/test/training_data_containing_special_chars.json", "data/test/json_with_special_chars_convered_to_md.md", "md", None, ), ], ) def test_training_data_conversion( tmpdir, data_file, gold_standard_file, output_format, language ): out_path = t
ark.parametrize( "data_file,expected_format", [ ("data/examples/luis/demo-restaurants_v5.json", JSON), ("data/examples", JSON), ("data/examples/rasa/demo-rasa.md", MARKDOWN), ("data/rasa_yaml_examples", RASA_YAML), ], ) def test_get_supported_file_format(data_file: Text, expected_format: Text): fformat = get_file_format(data_file) assert fformat == expected_format @pytest.mark.parametrize("data_file", ["path-does-not-exists", None]) def test_get_non_existing_file_format_raises(data_file: Text): with pytest.raises(AttributeError): get_file_format(data_file) def test_guess_format_from_non_existing_file_path(): assert guess_format("not existing path") == UNK def test_is_empty(): assert TrainingData().is_empty() def test_custom_attributes(tmp_path): data = """ { "rasa_nlu_data": { "common_examples" : [ { "intent": "happy", "text": "I'm happy.", "sentiment": 0.8 } ] } }""" f = tmp_path / "tmp_training_data.json" f.write_text(data, rasa.shared.utils.io.DEFAULT_ENCODING) td = load_data(str(f)) assert len(td.training_examples) == 1 example = td.training_examples[0] assert example.get("sentiment") == 0.8 async def test_without_additional_e2e_examples(tmp_path: Path): domain_path = tmp_path / "domain.yml" domain_path.write_text(Domain.empty().as_yaml()) config_path = tmp_path / "config.yml" config_path.touch() existing = TrainingDataImporter.load_from_dict( {}, str(config_path), str(domain_path), [] ) stories = StoryGraph( [ StoryStep( events=[ UserUttered("greet_from_stories", {"name": "greet_from_stories"}), ActionExecuted("utter_greet_from_stories"), ] ) ] ) # Patch to return our test stories existing.get_stories = asyncio.coroutine(lambda *args: stories) importer = E2EImporter(existing) training_data = await importer.get_nlu_data() assert training_data.training_examples assert training_data.is_empty() assert not training_data.without_empty_e2e_examples().training_examples
mpdir.join("rasa_nlu_data.json") convert_training_data(data_file, out_path.strpath, output_format, language) td = load_data(out_path.strpath, language) assert td.entity_examples != [] assert td.intent_examples != [] gold_standard = load_data(gold_standard_file, language) cmp_message_list(td.entity_examples, gold_standard.entity_examples) cmp_message_list(td.intent_examples, gold_standard.intent_examples) assert td.entity_synonyms == gold_standard.entity_synonyms # converting the converted file back to original # file format and performing the same tests rto_path = tmpdir.join("data_in_original_format.txt") convert_training_data(out_path.strpath, rto_path.strpath, "json", language) rto = load_data(rto_path.strpath, language) cmp_message_list(gold_standard.entity_examples, rto.entity_examples) cmp_message_list(gold_standard.intent_examples, rto.intent_examples) assert gold_standard.entity_synonyms == rto.entity_synonyms # If the above assert fails - this can be used # to dump to the file and diff using git # with io.open(gold_standard_file) as f: # f.write(td.as_json(indent=2)) @pytest.m
cli.rs
use assert_cmd::prelude::*; use predicates::prelude::*; use std::process::Command; #[test] fn test_version_argument() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = Command::cargo_bin("git-mob")?; cmd.arg("--version"); cmd.assert().stdout(predicate::str::contains("git-mob 0.1"));
Ok(()) } #[test] fn test_help_argument() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = Command::cargo_bin("git-mob")?; cmd.arg("--help"); cmd.assert() .stdout(predicate::str::contains("git-mob 0.1")) .stdout(predicate::str::contains( "James Thompson <[email protected]>", )) .stdout(predicate::str::contains( "makes mob programming easier with Git", )); Ok(()) }
multithread.rs
use rhook::*; use std::process::Command; // return fake data for read fn multithread() { macro_rules! command { ($msg: expr) => { Command::new("cat") .arg("Cargo.toml") .add_hook(Hook::read(stringify!(|| { let buf = buf as *mut u8; use std::io::Write; let mut buf = ManuallyDrop::new(std::slice::from_raw_parts_mut(buf, count)); let msg = $msg; let msg = msg.as_bytes(); buf.write_all(msg).unwrap(); COUNTER += 1; if COUNTER % 2 != 0 { Some(msg.len() as isize) } else { Some(0) } }))) .set_hooks() .unwrap() .spawn() .unwrap()
} let t1 = std::thread::spawn(|| command!("hello")); let t2 = std::thread::spawn(|| command!("bye")); t1.join().unwrap(); t2.join().unwrap(); } fn main() { multithread(); }
.wait() .unwrap(); };
replace_nested_conditional_with_guard_clauses.py
# by Kami Bigdely # Replace nested conditional with guard clauses def
(line): if line is not None and "x:" in line: start_index = line.find("x:") + 2 pos = line[start_index:] # from start_index to the end. else: pos = None return pos if __name__ == "__main__": result1 = extract_position("|error| numerical calculations could not converge.") print(result1) result2 = extract_position( "|update| the positron location in the particle accelerator is x:21.432" ) print(result2)
extract_position
container_stop_responses.go
// Code generated by go-swagger; DO NOT EDIT. package container // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "net/http" "github.com/go-openapi/runtime" "github.com/migueleliasweb/d2k/src/openapi/gen/models" ) // ContainerStopNoContentCode is the HTTP code returned for type ContainerStopNoContent const ContainerStopNoContentCode int = 204 /*ContainerStopNoContent no error swagger:response containerStopNoContent */ type ContainerStopNoContent struct { } // NewContainerStopNoContent creates ContainerStopNoContent with default headers values func NewContainerStopNoContent() *ContainerStopNoContent { return &ContainerStopNoContent{} } // WriteResponse to the client func (o *ContainerStopNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses rw.WriteHeader(204) } // ContainerStopNotModifiedCode is the HTTP code returned for type ContainerStopNotModified const ContainerStopNotModifiedCode int = 304 /*ContainerStopNotModified container already stopped swagger:response containerStopNotModified */ type ContainerStopNotModified struct { } // NewContainerStopNotModified creates ContainerStopNotModified with default headers values func NewContainerStopNotModified() *ContainerStopNotModified { return &ContainerStopNotModified{} } // WriteResponse to the client func (o *ContainerStopNotModified) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses rw.WriteHeader(304) } // ContainerStopNotFoundCode is the HTTP code returned for type ContainerStopNotFound const ContainerStopNotFoundCode int = 404 /*ContainerStopNotFound no such container swagger:response containerStopNotFound */ type ContainerStopNotFound struct { /* In: Body */ Payload *models.ErrorResponse `json:"body,omitempty"` } // NewContainerStopNotFound creates ContainerStopNotFound with default headers values func NewContainerStopNotFound() *ContainerStopNotFound { return &ContainerStopNotFound{} } // WithPayload adds the payload to the container stop not found response func (o *ContainerStopNotFound) WithPayload(payload *models.ErrorResponse) *ContainerStopNotFound { o.Payload = payload return o } // SetPayload sets the payload to the container stop not found response func (o *ContainerStopNotFound) SetPayload(payload *models.ErrorResponse) { o.Payload = payload } // WriteResponse to the client func (o *ContainerStopNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(404) if o.Payload != nil { payload := o.Payload if err := producer.Produce(rw, payload); err != nil { panic(err) // let the recovery middleware deal with this } } } // ContainerStopInternalServerErrorCode is the HTTP code returned for type ContainerStopInternalServerError const ContainerStopInternalServerErrorCode int = 500 /*ContainerStopInternalServerError server error swagger:response containerStopInternalServerError */ type ContainerStopInternalServerError struct { /* In: Body */ Payload *models.ErrorResponse `json:"body,omitempty"` } // NewContainerStopInternalServerError creates ContainerStopInternalServerError with default headers values func NewContainerStopInternalServerError() *ContainerStopInternalServerError { return &ContainerStopInternalServerError{} } // WithPayload adds the payload to the container stop internal server error response func (o *ContainerStopInternalServerError) WithPayload(payload *models.ErrorResponse) *ContainerStopInternalServerError { o.Payload = payload return o } // SetPayload sets the payload to the container stop internal server error response func (o *ContainerStopInternalServerError) SetPayload(payload *models.ErrorResponse) { o.Payload = payload } // WriteResponse to the client func (o *ContainerStopInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(500) if o.Payload != nil
}
{ payload := o.Payload if err := producer.Produce(rw, payload); err != nil { panic(err) // let the recovery middleware deal with this } }
arraylist.go
package basics // ArrayList implements array resizing type ArrayList interface { Empty() bool Size() int Items() []int Add(item int) Get(i int) (int, bool) Set(i int, item int) Del(i int) Swap(i, j int) } // NewArrayList creates a new ArrayList func
() ArrayList { return &list{ items: make([]int, 2), size: 0, } } type list struct { items []int size int } func (l *list) Empty() bool { return l.size == 0 } func (l *list) Size() int { return l.size } func (l *list) Items() []int { return l.items[:l.size] } func (l *list) Get(i int) (int, bool) { if !l.inRange(i) { return 0, false } return l.items[i], true } func (l *list) Set(i int, item int) { if !l.inRange(i) { return } l.items[i] = item } func (l *list) Del(i int) { if l.Empty() || !l.inRange(i) { return } l.size-- l.items[i] = l.items[l.size] l.items[l.size] = 0 l.shrink() } func (l *list) Add(item int) { l.grow() l.items[l.size] = item l.size++ } func (l *list) Swap(i, j int) { if l.Empty() { return } if !l.inRange(i) || !l.inRange(j) || i == j { return } l.items[i], l.items[j] = l.items[j], l.items[i] } func (l *list) inRange(i int) bool { return i >= 0 && i < l.size } func (l *list) shrink() { if l.size > cap(l.items)/4 { return } l.resize(cap(l.items) / 2) } func (l *list) grow() { if l.size+1 <= cap(l.items) { return } l.resize((cap(l.items) + 1) * 2) } func (l *list) resize(capacity int) { items := make([]int, capacity) i := 0 for i < l.size { items[i] = l.items[i] i++ } l.items = items }
NewArrayList
config.rs
//! Contains infrastructure for configuring the compiler, including parsing //! command-line options. pub use crate::options::*; use crate::lint; use crate::search_paths::SearchPath; use crate::utils::NativeLibKind; use crate::{early_error, early_warn, Session}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::impl_stable_hash_via_hash; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_target::spec::{Target, TargetTriple}; use crate::parse::CrateConfig; use rustc_feature::UnstableFeatures; use rustc_span::edition::{Edition, DEFAULT_EDITION, EDITION_NAME_LIST}; use rustc_span::source_map::{FileName, FilePathMapping}; use rustc_span::symbol::{sym, Symbol}; use rustc_span::SourceFileHashAlgorithm; use rustc_errors::emitter::HumanReadableErrorType; use rustc_errors::{ColorConfig, HandlerFlags}; use std::collections::btree_map::{ Iter as BTreeMapIter, Keys as BTreeMapKeysIter, Values as BTreeMapValuesIter, }; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use std::iter::{self, FromIterator}; use std::path::{Path, PathBuf}; use std::str::{self, FromStr}; pub struct Config { pub target: Target, pub ptr_width: u32, } bitflags! { #[derive(Default, RustcEncodable, RustcDecodable)] pub struct SanitizerSet: u8 { const ADDRESS = 1 << 0; const LEAK = 1 << 1; const MEMORY = 1 << 2; const THREAD = 1 << 3; } } /// Formats a sanitizer set as a comma separated list of sanitizers' names. impl fmt::Display for SanitizerSet { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut first = true; for s in *self { let name = match s { SanitizerSet::ADDRESS => "address", SanitizerSet::LEAK => "leak", SanitizerSet::MEMORY => "memory", SanitizerSet::THREAD => "thread", _ => panic!("unrecognized sanitizer {:?}", s), }; if !first { f.write_str(",")?; } f.write_str(name)?; first = false; } Ok(()) } } impl IntoIterator for SanitizerSet { type Item = SanitizerSet; type IntoIter = std::vec::IntoIter<SanitizerSet>; fn
(self) -> Self::IntoIter { [SanitizerSet::ADDRESS, SanitizerSet::LEAK, SanitizerSet::MEMORY, SanitizerSet::THREAD] .iter() .copied() .filter(|&s| self.contains(s)) .collect::<Vec<_>>() .into_iter() } } impl<CTX> HashStable<CTX> for SanitizerSet { fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { self.bits().hash_stable(ctx, hasher); } } /// The different settings that the `-Z strip` flag can have. #[derive(Clone, Copy, PartialEq, Hash, Debug)] pub enum Strip { /// Do not strip at all. None, /// Strip debuginfo. Debuginfo, /// Strip all symbols. Symbols, } /// The different settings that the `-Z control-flow-guard` flag can have. #[derive(Clone, Copy, PartialEq, Hash, Debug)] pub enum CFGuard { /// Do not emit Control Flow Guard metadata or checks. Disabled, /// Emit Control Flow Guard metadata but no checks. NoChecks, /// Emit Control Flow Guard metadata and checks. Checks, } #[derive(Clone, Copy, Debug, PartialEq, Hash)] pub enum OptLevel { No, // -O0 Less, // -O1 Default, // -O2 Aggressive, // -O3 Size, // -Os SizeMin, // -Oz } impl_stable_hash_via_hash!(OptLevel); /// This is what the `LtoCli` values get mapped to after resolving defaults and /// and taking other command line options into account. #[derive(Clone, PartialEq)] pub enum Lto { /// Don't do any LTO whatsoever No, /// Do a full crate graph LTO with ThinLTO Thin, /// Do a local graph LTO with ThinLTO (only relevant for multiple codegen /// units). ThinLocal, /// Do a full crate graph LTO with "fat" LTO Fat, } /// The different settings that the `-C lto` flag can have. #[derive(Clone, Copy, PartialEq, Hash, Debug)] pub enum LtoCli { /// `-C lto=no` No, /// `-C lto=yes` Yes, /// `-C lto` NoParam, /// `-C lto=thin` Thin, /// `-C lto=fat` Fat, /// No `-C lto` flag passed Unspecified, } #[derive(Clone, PartialEq, Hash)] pub enum LinkerPluginLto { LinkerPlugin(PathBuf), LinkerPluginAuto, Disabled, } impl LinkerPluginLto { pub fn enabled(&self) -> bool { match *self { LinkerPluginLto::LinkerPlugin(_) | LinkerPluginLto::LinkerPluginAuto => true, LinkerPluginLto::Disabled => false, } } } #[derive(Clone, PartialEq, Hash)] pub enum SwitchWithOptPath { Enabled(Option<PathBuf>), Disabled, } impl SwitchWithOptPath { pub fn enabled(&self) -> bool { match *self { SwitchWithOptPath::Enabled(_) => true, SwitchWithOptPath::Disabled => false, } } } #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] pub enum SymbolManglingVersion { Legacy, V0, } impl_stable_hash_via_hash!(SymbolManglingVersion); #[derive(Clone, Copy, PartialEq, Hash)] pub enum DebugInfo { None, Limited, Full, } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)] pub enum OutputType { Bitcode, Assembly, LlvmAssembly, Mir, Metadata, Object, Exe, DepInfo, } impl_stable_hash_via_hash!(OutputType); impl OutputType { fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool { match *self { OutputType::Exe | OutputType::DepInfo | OutputType::Metadata => true, OutputType::Bitcode | OutputType::Assembly | OutputType::LlvmAssembly | OutputType::Mir | OutputType::Object => false, } } fn shorthand(&self) -> &'static str { match *self { OutputType::Bitcode => "llvm-bc", OutputType::Assembly => "asm", OutputType::LlvmAssembly => "llvm-ir", OutputType::Mir => "mir", OutputType::Object => "obj", OutputType::Metadata => "metadata", OutputType::Exe => "link", OutputType::DepInfo => "dep-info", } } fn from_shorthand(shorthand: &str) -> Option<Self> { Some(match shorthand { "asm" => OutputType::Assembly, "llvm-ir" => OutputType::LlvmAssembly, "mir" => OutputType::Mir, "llvm-bc" => OutputType::Bitcode, "obj" => OutputType::Object, "metadata" => OutputType::Metadata, "link" => OutputType::Exe, "dep-info" => OutputType::DepInfo, _ => return None, }) } fn shorthands_display() -> String { format!( "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`", OutputType::Bitcode.shorthand(), OutputType::Assembly.shorthand(), OutputType::LlvmAssembly.shorthand(), OutputType::Mir.shorthand(), OutputType::Object.shorthand(), OutputType::Metadata.shorthand(), OutputType::Exe.shorthand(), OutputType::DepInfo.shorthand(), ) } pub fn extension(&self) -> &'static str { match *self { OutputType::Bitcode => "bc", OutputType::Assembly => "s", OutputType::LlvmAssembly => "ll", OutputType::Mir => "mir", OutputType::Object => "o", OutputType::Metadata => "rmeta", OutputType::DepInfo => "d", OutputType::Exe => "", } } } /// The type of diagnostics output to generate. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ErrorOutputType { /// Output meant for the consumption of humans. HumanReadable(HumanReadableErrorType), /// Output that's consumed by other tools such as `rustfix` or the `RLS`. Json { /// Render the JSON in a human readable way (with indents and newlines). pretty: bool, /// The JSON output includes a `rendered` field that includes the rendered /// human output. json_rendered: HumanReadableErrorType, }, } impl Default for ErrorOutputType { fn default() -> Self { Self::HumanReadable(HumanReadableErrorType::Default(ColorConfig::Auto)) } } /// Use tree-based collections to cheaply get a deterministic `Hash` implementation. /// *Do not* switch `BTreeMap` out for an unsorted container type! That would break /// dependency tracking for command-line arguments. #[derive(Clone, Hash)] pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>); impl_stable_hash_via_hash!(OutputTypes); impl OutputTypes { pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes { OutputTypes(BTreeMap::from_iter(entries.iter().map(|&(k, ref v)| (k, v.clone())))) } pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> { self.0.get(key) } pub fn contains_key(&self, key: &OutputType) -> bool { self.0.contains_key(key) } pub fn keys(&self) -> BTreeMapKeysIter<'_, OutputType, Option<PathBuf>> { self.0.keys() } pub fn values(&self) -> BTreeMapValuesIter<'_, OutputType, Option<PathBuf>> { self.0.values() } pub fn len(&self) -> usize { self.0.len() } // Returns `true` if any of the output types require codegen or linking. pub fn should_codegen(&self) -> bool { self.0.keys().any(|k| match *k { OutputType::Bitcode | OutputType::Assembly | OutputType::LlvmAssembly | OutputType::Mir | OutputType::Object | OutputType::Exe => true, OutputType::Metadata | OutputType::DepInfo => false, }) } } /// Use tree-based collections to cheaply get a deterministic `Hash` implementation. /// *Do not* switch `BTreeMap` or `BTreeSet` out for an unsorted container type! That /// would break dependency tracking for command-line arguments. #[derive(Clone)] pub struct Externs(BTreeMap<String, ExternEntry>); #[derive(Clone, Debug)] pub struct ExternEntry { pub location: ExternLocation, /// Indicates this is a "private" dependency for the /// `exported_private_dependencies` lint. /// /// This can be set with the `priv` option like /// `--extern priv:name=foo.rlib`. pub is_private_dep: bool, /// Add the extern entry to the extern prelude. /// /// This can be disabled with the `noprelude` option like /// `--extern noprelude:name`. pub add_prelude: bool, } #[derive(Clone, Debug)] pub enum ExternLocation { /// Indicates to look for the library in the search paths. /// /// Added via `--extern name`. FoundInLibrarySearchDirectories, /// The locations where this extern entry must be found. /// /// The `CrateLoader` is responsible for loading these and figuring out /// which one to use. /// /// Added via `--extern prelude_name=some_file.rlib` ExactPaths(BTreeSet<String>), } impl Externs { pub fn new(data: BTreeMap<String, ExternEntry>) -> Externs { Externs(data) } pub fn get(&self, key: &str) -> Option<&ExternEntry> { self.0.get(key) } pub fn iter(&self) -> BTreeMapIter<'_, String, ExternEntry> { self.0.iter() } } impl ExternEntry { fn new(location: ExternLocation) -> ExternEntry { ExternEntry { location, is_private_dep: false, add_prelude: false } } pub fn files(&self) -> Option<impl Iterator<Item = &String>> { match &self.location { ExternLocation::ExactPaths(set) => Some(set.iter()), _ => None, } } } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum PrintRequest { FileNames, Sysroot, TargetLibdir, CrateName, Cfg, TargetList, TargetCPUs, TargetFeatures, RelocationModels, CodeModels, TlsModels, TargetSpec, NativeStaticLibs, } #[derive(Copy, Clone)] pub enum BorrowckMode { Mir, Migrate, } impl BorrowckMode { /// Returns whether we should run the MIR-based borrow check, but also fall back /// on the AST borrow check if the MIR-based one errors. pub fn migrate(self) -> bool { match self { BorrowckMode::Mir => false, BorrowckMode::Migrate => true, } } } pub enum Input { /// Load source code from a file. File(PathBuf), /// Load source code from a string. Str { /// A string that is shown in place of a filename. name: FileName, /// An anonymous string containing the source code. input: String, }, } impl Input { pub fn filestem(&self) -> &str { match *self { Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap(), Input::Str { .. } => "rust_out", } } pub fn get_input(&mut self) -> Option<&mut String> { match *self { Input::File(_) => None, Input::Str { ref mut input, .. } => Some(input), } } pub fn source_name(&self) -> FileName { match *self { Input::File(ref ifile) => ifile.clone().into(), Input::Str { ref name, .. } => name.clone(), } } } #[derive(Clone, Hash)] pub struct OutputFilenames { pub out_directory: PathBuf, filestem: String, pub single_output_file: Option<PathBuf>, pub outputs: OutputTypes, } impl_stable_hash_via_hash!(OutputFilenames); pub const RLINK_EXT: &str = "rlink"; pub const RUST_CGU_EXT: &str = "rcgu"; impl OutputFilenames { pub fn new( out_directory: PathBuf, out_filestem: String, single_output_file: Option<PathBuf>, extra: String, outputs: OutputTypes, ) -> Self { OutputFilenames { out_directory, single_output_file, outputs, filestem: format!("{}{}", out_filestem, extra), } } pub fn path(&self, flavor: OutputType) -> PathBuf { self.outputs .get(&flavor) .and_then(|p| p.to_owned()) .or_else(|| self.single_output_file.clone()) .unwrap_or_else(|| self.temp_path(flavor, None)) } /// Gets the path where a compilation artifact of the given type for the /// given codegen unit should be placed on disk. If codegen_unit_name is /// None, a path distinct from those of any codegen unit will be generated. pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf { let extension = flavor.extension(); self.temp_path_ext(extension, codegen_unit_name) } /// Like temp_path, but also supports things where there is no corresponding /// OutputType, like noopt-bitcode or lto-bitcode. pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf { let mut extension = String::new(); if let Some(codegen_unit_name) = codegen_unit_name { extension.push_str(codegen_unit_name); } if !ext.is_empty() { if !extension.is_empty() { extension.push_str("."); extension.push_str(RUST_CGU_EXT); extension.push_str("."); } extension.push_str(ext); } self.with_extension(&extension) } pub fn with_extension(&self, extension: &str) -> PathBuf { let mut path = self.out_directory.join(&self.filestem); path.set_extension(extension); path } } pub fn host_triple() -> &'static str { // Get the host triple out of the build environment. This ensures that our // idea of the host triple is the same as for the set of libraries we've // actually built. We can't just take LLVM's host triple because they // normalize all ix86 architectures to i386. // // Instead of grabbing the host triple (for the current host), we grab (at // compile time) the target triple that this rustc is built with and // calling that (at runtime) the host triple. (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE") } impl Default for Options { fn default() -> Options { Options { crate_types: Vec::new(), optimize: OptLevel::No, debuginfo: DebugInfo::None, lint_opts: Vec::new(), lint_cap: None, describe_lints: false, output_types: OutputTypes(BTreeMap::new()), search_paths: vec![], maybe_sysroot: None, target_triple: TargetTriple::from_triple(host_triple()), test: false, incremental: None, debugging_opts: basic_debugging_options(), prints: Vec::new(), borrowck_mode: BorrowckMode::Migrate, cg: basic_codegen_options(), error_format: ErrorOutputType::default(), externs: Externs(BTreeMap::new()), crate_name: None, alt_std_name: None, libs: Vec::new(), unstable_features: UnstableFeatures::Disallow, debug_assertions: true, actually_rustdoc: false, cli_forced_codegen_units: None, cli_forced_thinlto_off: false, remap_path_prefix: Vec::new(), edition: DEFAULT_EDITION, json_artifact_notifications: false, pretty: None, } } } impl Options { /// Returns `true` if there is a reason to build the dep graph. pub fn build_dep_graph(&self) -> bool { self.incremental.is_some() || self.debugging_opts.dump_dep_graph || self.debugging_opts.query_dep_graph } #[inline(always)] pub fn enable_dep_node_debug_strs(&self) -> bool { cfg!(debug_assertions) && (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info) } pub fn file_path_mapping(&self) -> FilePathMapping { FilePathMapping::new(self.remap_path_prefix.clone()) } /// Returns `true` if there will be an output file generated. pub fn will_create_output_file(&self) -> bool { !self.debugging_opts.parse_only && // The file is just being parsed !self.debugging_opts.ls // The file is just being queried } #[inline] pub fn share_generics(&self) -> bool { match self.debugging_opts.share_generics { Some(setting) => setting, None => match self.optimize { OptLevel::No | OptLevel::Less | OptLevel::Size | OptLevel::SizeMin => true, OptLevel::Default | OptLevel::Aggressive => false, }, } } } impl DebuggingOptions { pub fn diagnostic_handler_flags(&self, can_emit_warnings: bool) -> HandlerFlags { HandlerFlags { can_emit_warnings, treat_err_as_bug: self.treat_err_as_bug, dont_buffer_diagnostics: self.dont_buffer_diagnostics, report_delayed_bugs: self.report_delayed_bugs, macro_backtrace: self.macro_backtrace, deduplicate_diagnostics: self.deduplicate_diagnostics, } } } // The type of entry function, so users can have their own entry functions #[derive(Copy, Clone, PartialEq, Hash, Debug)] pub enum EntryFnType { Main, Start, } impl_stable_hash_via_hash!(EntryFnType); #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug, RustcEncodable, RustcDecodable)] pub enum CrateType { Executable, Dylib, Rlib, Staticlib, Cdylib, ProcMacro, } impl_stable_hash_via_hash!(CrateType); #[derive(Clone, Hash)] pub enum Passes { Some(Vec<String>), All, } impl Passes { pub fn is_empty(&self) -> bool { match *self { Passes::Some(ref v) => v.is_empty(), Passes::All => false, } } } pub const fn default_lib_output() -> CrateType { CrateType::Rlib } pub fn default_configuration(sess: &Session) -> CrateConfig { let end = &sess.target.target.target_endian; let arch = &sess.target.target.arch; let wordsz = &sess.target.target.target_pointer_width; let os = &sess.target.target.target_os; let env = &sess.target.target.target_env; let vendor = &sess.target.target.target_vendor; let min_atomic_width = sess.target.target.min_atomic_width(); let max_atomic_width = sess.target.target.max_atomic_width(); let atomic_cas = sess.target.target.options.atomic_cas; let mut ret = FxHashSet::default(); ret.reserve(6); // the minimum number of insertions // Target bindings. ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os)))); if let Some(ref fam) = sess.target.target.options.target_family { ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam)))); if fam == "windows" || fam == "unix" { ret.insert((Symbol::intern(fam), None)); } } ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch)))); ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end)))); ret.insert((Symbol::intern("target_pointer_width"), Some(Symbol::intern(wordsz)))); ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env)))); ret.insert((Symbol::intern("target_vendor"), Some(Symbol::intern(vendor)))); if sess.target.target.options.has_elf_tls { ret.insert((sym::target_thread_local, None)); } for &i in &[8, 16, 32, 64, 128] { if i >= min_atomic_width && i <= max_atomic_width { let mut insert_atomic = |s| { ret.insert((sym::target_has_atomic_load_store, Some(Symbol::intern(s)))); if atomic_cas { ret.insert((sym::target_has_atomic, Some(Symbol::intern(s)))); } }; let s = i.to_string(); insert_atomic(&s); if &s == wordsz { insert_atomic("ptr"); } } } for s in sess.opts.debugging_opts.sanitizer { let symbol = Symbol::intern(&s.to_string()); ret.insert((sym::sanitize, Some(symbol))); } if sess.opts.debug_assertions { ret.insert((Symbol::intern("debug_assertions"), None)); } if sess.opts.crate_types.contains(&CrateType::ProcMacro) { ret.insert((sym::proc_macro, None)); } ret } /// Converts the crate `cfg!` configuration from `String` to `Symbol`. /// `rustc_interface::interface::Config` accepts this in the compiler configuration, /// but the symbol interner is not yet set up then, so we must convert it later. pub fn to_crate_config(cfg: FxHashSet<(String, Option<String>)>) -> CrateConfig { cfg.into_iter().map(|(a, b)| (Symbol::intern(&a), b.map(|b| Symbol::intern(&b)))).collect() } pub fn build_configuration(sess: &Session, mut user_cfg: CrateConfig) -> CrateConfig { // Combine the configuration requested by the session (command line) with // some default and generated configuration items. let default_cfg = default_configuration(sess); // If the user wants a test runner, then add the test cfg. if sess.opts.test { user_cfg.insert((sym::test, None)); } user_cfg.extend(default_cfg.iter().cloned()); user_cfg } pub fn build_target_config(opts: &Options, error_format: ErrorOutputType) -> Config { let target = Target::search(&opts.target_triple).unwrap_or_else(|e| { early_error( error_format, &format!( "Error loading target specification: {}. \ Use `--print target-list` for a list of built-in targets", e ), ) }); let ptr_width = match &target.target_pointer_width[..] { "16" => 16, "32" => 32, "64" => 64, w => early_error( error_format, &format!( "target specification was invalid: \ unrecognized target-pointer-width {}", w ), ), }; Config { target, ptr_width } } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum OptionStability { Stable, Unstable, } pub struct RustcOptGroup { pub apply: Box<dyn Fn(&mut getopts::Options) -> &mut getopts::Options>, pub name: &'static str, pub stability: OptionStability, } impl RustcOptGroup { pub fn is_stable(&self) -> bool { self.stability == OptionStability::Stable } pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static, { RustcOptGroup { name, apply: Box::new(f), stability: OptionStability::Stable } } pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static, { RustcOptGroup { name, apply: Box::new(f), stability: OptionStability::Unstable } } } // The `opt` local module holds wrappers around the `getopts` API that // adds extra rustc-specific metadata to each option; such metadata // is exposed by . The public // functions below ending with `_u` are the functions that return // *unstable* options, i.e., options that are only enabled when the // user also passes the `-Z unstable-options` debugging flag. mod opt { // The `fn flag*` etc below are written so that we can use them // in the future; do not warn about them not being used right now. #![allow(dead_code)] use super::RustcOptGroup; pub type R = RustcOptGroup; pub type S = &'static str; fn stable<F>(name: S, f: F) -> R where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static, { RustcOptGroup::stable(name, f) } fn unstable<F>(name: S, f: F) -> R where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static, { RustcOptGroup::unstable(name, f) } fn longer(a: S, b: S) -> S { if a.len() > b.len() { a } else { b } } pub fn opt_s(a: S, b: S, c: S, d: S) -> R { stable(longer(a, b), move |opts| opts.optopt(a, b, c, d)) } pub fn multi_s(a: S, b: S, c: S, d: S) -> R { stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d)) } pub fn flag_s(a: S, b: S, c: S) -> R { stable(longer(a, b), move |opts| opts.optflag(a, b, c)) } pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R { stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d)) } pub fn flagmulti_s(a: S, b: S, c: S) -> R { stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c)) } pub fn opt(a: S, b: S, c: S, d: S) -> R { unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d)) } pub fn multi(a: S, b: S, c: S, d: S) -> R { unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d)) } pub fn flag(a: S, b: S, c: S) -> R { unstable(longer(a, b), move |opts| opts.optflag(a, b, c)) } pub fn flagopt(a: S, b: S, c: S, d: S) -> R { unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d)) } pub fn flagmulti(a: S, b: S, c: S) -> R { unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c)) } } /// Returns the "short" subset of the rustc command line options, /// including metadata for each option, such as whether the option is /// part of the stable long-term interface for rustc. pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> { vec![ opt::flag_s("h", "help", "Display this message"), opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"), opt::multi_s( "L", "", "Add a directory to the library search path. The optional KIND can be one of dependency, crate, native, framework, or all (the default).", "[KIND=]PATH", ), opt::multi_s( "l", "", "Link the generated crate(s) to the specified native library NAME. The optional KIND can be one of static, framework, or dylib (the default).", "[KIND=]NAME", ), make_crate_type_option(), opt::opt_s("", "crate-name", "Specify the name of the crate being built", "NAME"), opt::opt_s( "", "edition", "Specify which edition of the compiler to use when compiling code.", EDITION_NAME_LIST, ), opt::multi_s( "", "emit", "Comma separated list of types of output for \ the compiler to emit", "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]", ), opt::multi_s( "", "print", "Compiler information to print on stdout", "[crate-name|file-names|sysroot|target-libdir|cfg|target-list|\ target-cpus|target-features|relocation-models|\ code-models|tls-models|target-spec-json|native-static-libs]", ), opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"), opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"), opt::opt_s("o", "", "Write output to <filename>", "FILENAME"), opt::opt_s( "", "out-dir", "Write output to compiler-chosen filename \ in <dir>", "DIR", ), opt::opt_s( "", "explain", "Provide a detailed explanation of an error \ message", "OPT", ), opt::flag_s("", "test", "Build a test harness"), opt::opt_s("", "target", "Target triple for which the code is compiled", "TARGET"), opt::multi_s("W", "warn", "Set lint warnings", "OPT"), opt::multi_s("A", "allow", "Set lint allowed", "OPT"), opt::multi_s("D", "deny", "Set lint denied", "OPT"), opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"), opt::multi_s( "", "cap-lints", "Set the most restrictive lint level. \ More restrictive lints are capped at this \ level", "LEVEL", ), opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"), opt::flag_s("V", "version", "Print version info and exit"), opt::flag_s("v", "verbose", "Use verbose output"), ] } /// Returns all rustc command line options, including metadata for /// each option, such as whether the option is part of the stable /// long-term interface for rustc. pub fn rustc_optgroups() -> Vec<RustcOptGroup> { let mut opts = rustc_short_optgroups(); opts.extend(vec![ opt::multi_s( "", "extern", "Specify where an external rust library is located", "NAME[=PATH]", ), opt::opt_s("", "sysroot", "Override the system root", "PATH"), opt::multi("Z", "", "Set internal debugging options", "FLAG"), opt::opt_s( "", "error-format", "How errors and other messages are produced", "human|json|short", ), opt::multi_s("", "json", "Configure the JSON output of the compiler", "CONFIG"), opt::opt_s( "", "color", "Configure coloring of output: auto = colorize, if output goes to a tty (default); always = always colorize output; never = never colorize output", "auto|always|never", ), opt::opt( "", "pretty", "Pretty-print the input instead of compiling; valid types are: `normal` (un-annotated source), `expanded` (crates expanded), or `expanded,identified` (fully parenthesized, AST nodes with IDs).", "TYPE", ), opt::multi_s( "", "remap-path-prefix", "Remap source names in all output (compiler messages and output files)", "FROM=TO", ), ]); opts } pub fn get_cmd_lint_options( matches: &getopts::Matches, error_format: ErrorOutputType, ) -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) { let mut lint_opts_with_position = vec![]; let mut describe_lints = false; for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] { for (passed_arg_pos, lint_name) in matches.opt_strs_pos(level.as_str()) { let arg_pos = if let lint::Forbid = level { // HACK: forbid is always specified last, so it can't be overridden. // FIXME: remove this once <https://github.com/rust-lang/rust/issues/70819> is // fixed and `forbid` works as expected. usize::MAX } else { passed_arg_pos }; if lint_name == "help" { describe_lints = true; } else { lint_opts_with_position.push((arg_pos, lint_name.replace("-", "_"), level)); } } } lint_opts_with_position.sort_by_key(|x| x.0); let lint_opts = lint_opts_with_position .iter() .cloned() .map(|(_, lint_name, level)| (lint_name, level)) .collect(); let lint_cap = matches.opt_str("cap-lints").map(|cap| { lint::Level::from_str(&cap) .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap))) }); (lint_opts, describe_lints, lint_cap) } /// Parses the `--color` flag. pub fn parse_color(matches: &getopts::Matches) -> ColorConfig { match matches.opt_str("color").as_ref().map(|s| &s[..]) { Some("auto") => ColorConfig::Auto, Some("always") => ColorConfig::Always, Some("never") => ColorConfig::Never, None => ColorConfig::Auto, Some(arg) => early_error( ErrorOutputType::default(), &format!( "argument for `--color` must be auto, \ always or never (instead was `{}`)", arg ), ), } } /// Parse the `--json` flag. /// /// The first value returned is how to render JSON diagnostics, and the second /// is whether or not artifact notifications are enabled. pub fn parse_json(matches: &getopts::Matches) -> (HumanReadableErrorType, bool) { let mut json_rendered: fn(ColorConfig) -> HumanReadableErrorType = HumanReadableErrorType::Default; let mut json_color = ColorConfig::Never; let mut json_artifact_notifications = false; for option in matches.opt_strs("json") { // For now conservatively forbid `--color` with `--json` since `--json` // won't actually be emitting any colors and anything colorized is // embedded in a diagnostic message anyway. if matches.opt_str("color").is_some() { early_error( ErrorOutputType::default(), "cannot specify the `--color` option with `--json`", ); } for sub_option in option.split(',') { match sub_option { "diagnostic-short" => json_rendered = HumanReadableErrorType::Short, "diagnostic-rendered-ansi" => json_color = ColorConfig::Always, "artifacts" => json_artifact_notifications = true, s => early_error( ErrorOutputType::default(), &format!("unknown `--json` option `{}`", s), ), } } } (json_rendered(json_color), json_artifact_notifications) } /// Parses the `--error-format` flag. pub fn parse_error_format( matches: &getopts::Matches, color: ColorConfig, json_rendered: HumanReadableErrorType, ) -> ErrorOutputType { // We need the `opts_present` check because the driver will send us Matches // with only stable options if no unstable options are used. Since error-format // is unstable, it will not be present. We have to use `opts_present` not // `opt_present` because the latter will panic. let error_format = if matches.opts_present(&["error-format".to_owned()]) { match matches.opt_str("error-format").as_ref().map(|s| &s[..]) { None | Some("human") => { ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)) } Some("human-annotate-rs") => { ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateSnippet(color)) } Some("json") => ErrorOutputType::Json { pretty: false, json_rendered }, Some("pretty-json") => ErrorOutputType::Json { pretty: true, json_rendered }, Some("short") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Short(color)), Some(arg) => early_error( ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)), &format!( "argument for `--error-format` must be `human`, `json` or \ `short` (instead was `{}`)", arg ), ), } } else { ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)) }; match error_format { ErrorOutputType::Json { .. } => {} // Conservatively require that the `--json` argument is coupled with // `--error-format=json`. This means that `--json` is specified we // should actually be emitting JSON blobs. _ if !matches.opt_strs("json").is_empty() => { early_error( ErrorOutputType::default(), "using `--json` requires also using `--error-format=json`", ); } _ => {} } error_format } fn parse_crate_edition(matches: &getopts::Matches) -> Edition { let edition = match matches.opt_str("edition") { Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_| { early_error( ErrorOutputType::default(), &format!( "argument for `--edition` must be one of: \ {}. (instead was `{}`)", EDITION_NAME_LIST, arg ), ) }), None => DEFAULT_EDITION, }; if !edition.is_stable() && !nightly_options::is_nightly_build() { early_error( ErrorOutputType::default(), &format!( "edition {} is unstable and only \ available for nightly builds of rustc.", edition, ), ) } edition } fn check_debug_option_stability( debugging_opts: &DebuggingOptions, error_format: ErrorOutputType, json_rendered: HumanReadableErrorType, ) { if !debugging_opts.unstable_options { if let ErrorOutputType::Json { pretty: true, json_rendered } = error_format { early_error( ErrorOutputType::Json { pretty: false, json_rendered }, "`--error-format=pretty-json` is unstable", ); } if let ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateSnippet(_)) = error_format { early_error( ErrorOutputType::Json { pretty: false, json_rendered }, "`--error-format=human-annotate-rs` is unstable", ); } } } fn parse_output_types( debugging_opts: &DebuggingOptions, matches: &getopts::Matches, error_format: ErrorOutputType, ) -> OutputTypes { let mut output_types = BTreeMap::new(); if !debugging_opts.parse_only { for list in matches.opt_strs("emit") { for output_type in list.split(',') { let mut parts = output_type.splitn(2, '='); let shorthand = parts.next().unwrap(); let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(|| { early_error( error_format, &format!( "unknown emission type: `{}` - expected one of: {}", shorthand, OutputType::shorthands_display(), ), ) }); let path = parts.next().map(PathBuf::from); output_types.insert(output_type, path); } } }; if output_types.is_empty() { output_types.insert(OutputType::Exe, None); } OutputTypes(output_types) } fn should_override_cgus_and_disable_thinlto( output_types: &OutputTypes, matches: &getopts::Matches, error_format: ErrorOutputType, mut codegen_units: Option<usize>, ) -> (bool, Option<usize>) { let mut disable_thinlto = false; // Issue #30063: if user requests LLVM-related output to one // particular path, disable codegen-units. let incompatible: Vec<_> = output_types .0 .iter() .map(|ot_path| ot_path.0) .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file()) .map(|ot| ot.shorthand()) .collect(); if !incompatible.is_empty() { match codegen_units { Some(n) if n > 1 => { if matches.opt_present("o") { for ot in &incompatible { early_warn( error_format, &format!( "`--emit={}` with `-o` incompatible with \ `-C codegen-units=N` for N > 1", ot ), ); } early_warn(error_format, "resetting to default -C codegen-units=1"); codegen_units = Some(1); disable_thinlto = true; } } _ => { codegen_units = Some(1); disable_thinlto = true; } } } if codegen_units == Some(0) { early_error(error_format, "value for codegen units must be a positive non-zero integer"); } (disable_thinlto, codegen_units) } fn check_thread_count(debugging_opts: &DebuggingOptions, error_format: ErrorOutputType) { if debugging_opts.threads == 0 { early_error(error_format, "value for threads must be a positive non-zero integer"); } if debugging_opts.threads > 1 && debugging_opts.fuel.is_some() { early_error(error_format, "optimization fuel is incompatible with multiple threads"); } } fn collect_print_requests( cg: &mut CodegenOptions, dopts: &mut DebuggingOptions, matches: &getopts::Matches, error_format: ErrorOutputType, ) -> Vec<PrintRequest> { let mut prints = Vec::<PrintRequest>::new(); if cg.target_cpu.as_ref().map_or(false, |s| s == "help") { prints.push(PrintRequest::TargetCPUs); cg.target_cpu = None; }; if cg.target_feature == "help" { prints.push(PrintRequest::TargetFeatures); cg.target_feature = String::new(); } prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s { "crate-name" => PrintRequest::CrateName, "file-names" => PrintRequest::FileNames, "sysroot" => PrintRequest::Sysroot, "target-libdir" => PrintRequest::TargetLibdir, "cfg" => PrintRequest::Cfg, "target-list" => PrintRequest::TargetList, "target-cpus" => PrintRequest::TargetCPUs, "target-features" => PrintRequest::TargetFeatures, "relocation-models" => PrintRequest::RelocationModels, "code-models" => PrintRequest::CodeModels, "tls-models" => PrintRequest::TlsModels, "native-static-libs" => PrintRequest::NativeStaticLibs, "target-spec-json" => { if dopts.unstable_options { PrintRequest::TargetSpec } else { early_error( error_format, "the `-Z unstable-options` flag must also be passed to \ enable the target-spec-json print option", ); } } req => early_error(error_format, &format!("unknown print request `{}`", req)), })); prints } fn parse_target_triple(matches: &getopts::Matches, error_format: ErrorOutputType) -> TargetTriple { match matches.opt_str("target") { Some(target) if target.ends_with(".json") => { let path = Path::new(&target); TargetTriple::from_path(&path).unwrap_or_else(|_| { early_error(error_format, &format!("target file {:?} does not exist", path)) }) } Some(target) => TargetTriple::TargetTriple(target), _ => TargetTriple::from_triple(host_triple()), } } fn parse_opt_level( matches: &getopts::Matches, cg: &CodegenOptions, error_format: ErrorOutputType, ) -> OptLevel { // The `-O` and `-C opt-level` flags specify the same setting, so we want to be able // to use them interchangeably. However, because they're technically different flags, // we need to work out manually which should take precedence if both are supplied (i.e. // the rightmost flag). We do this by finding the (rightmost) position of both flags and // comparing them. Note that if a flag is not found, its position will be `None`, which // always compared less than `Some(_)`. let max_o = matches.opt_positions("O").into_iter().max(); let max_c = matches .opt_strs_pos("C") .into_iter() .flat_map( |(i, s)| { if let Some("opt-level") = s.splitn(2, '=').next() { Some(i) } else { None } }, ) .max(); if max_o > max_c { OptLevel::Default } else { match cg.opt_level.as_ref() { "0" => OptLevel::No, "1" => OptLevel::Less, "2" => OptLevel::Default, "3" => OptLevel::Aggressive, "s" => OptLevel::Size, "z" => OptLevel::SizeMin, arg => { early_error( error_format, &format!( "optimization level needs to be \ between 0-3, s or z (instead was `{}`)", arg ), ); } } } } fn select_debuginfo( matches: &getopts::Matches, cg: &CodegenOptions, error_format: ErrorOutputType, ) -> DebugInfo { let max_g = matches.opt_positions("g").into_iter().max(); let max_c = matches .opt_strs_pos("C") .into_iter() .flat_map( |(i, s)| { if let Some("debuginfo") = s.splitn(2, '=').next() { Some(i) } else { None } }, ) .max(); if max_g > max_c { DebugInfo::Full } else { match cg.debuginfo { 0 => DebugInfo::None, 1 => DebugInfo::Limited, 2 => DebugInfo::Full, arg => { early_error( error_format, &format!( "debug info level needs to be between \ 0-2 (instead was `{}`)", arg ), ); } } } } fn parse_libs( matches: &getopts::Matches, error_format: ErrorOutputType, ) -> Vec<(String, Option<String>, NativeLibKind)> { matches .opt_strs("l") .into_iter() .map(|s| { // Parse string of the form "[KIND=]lib[:new_name]", // where KIND is one of "dylib", "framework", "static". let mut parts = s.splitn(2, '='); let kind = parts.next().unwrap(); let (name, kind) = match (parts.next(), kind) { (None, name) => (name, NativeLibKind::Unspecified), (Some(name), "dylib") => (name, NativeLibKind::Dylib), (Some(name), "framework") => (name, NativeLibKind::Framework), (Some(name), "static") => (name, NativeLibKind::StaticBundle), (Some(name), "static-nobundle") => (name, NativeLibKind::StaticNoBundle), (_, s) => { early_error( error_format, &format!( "unknown library kind `{}`, expected \ one of dylib, framework, or static", s ), ); } }; if kind == NativeLibKind::StaticNoBundle && !nightly_options::is_nightly_build() { early_error( error_format, "the library kind 'static-nobundle' is only \ accepted on the nightly compiler", ); } let mut name_parts = name.splitn(2, ':'); let name = name_parts.next().unwrap(); let new_name = name_parts.next(); (name.to_owned(), new_name.map(|n| n.to_owned()), kind) }) .collect() } fn parse_borrowck_mode(dopts: &DebuggingOptions, error_format: ErrorOutputType) -> BorrowckMode { match dopts.borrowck.as_ref() { "migrate" => BorrowckMode::Migrate, "mir" => BorrowckMode::Mir, m => early_error(error_format, &format!("unknown borrowck mode `{}`", m)), } } pub fn parse_externs( matches: &getopts::Matches, debugging_opts: &DebuggingOptions, error_format: ErrorOutputType, ) -> Externs { let is_unstable_enabled = debugging_opts.unstable_options; let mut externs: BTreeMap<String, ExternEntry> = BTreeMap::new(); for arg in matches.opt_strs("extern") { let mut parts = arg.splitn(2, '='); let name = parts .next() .unwrap_or_else(|| early_error(error_format, "--extern value must not be empty")); let path = parts.next().map(|s| s.to_string()); let mut name_parts = name.splitn(2, ':'); let first_part = name_parts.next(); let second_part = name_parts.next(); let (options, name) = match (first_part, second_part) { (Some(opts), Some(name)) => (Some(opts), name), (Some(name), None) => (None, name), (None, None) => early_error(error_format, "--extern name must not be empty"), _ => unreachable!(), }; let entry = externs.entry(name.to_owned()); use std::collections::btree_map::Entry; let entry = if let Some(path) = path { // --extern prelude_name=some_file.rlib match entry { Entry::Vacant(vacant) => { let files = BTreeSet::from_iter(iter::once(path)); vacant.insert(ExternEntry::new(ExternLocation::ExactPaths(files))) } Entry::Occupied(occupied) => { let ext_ent = occupied.into_mut(); match ext_ent { ExternEntry { location: ExternLocation::ExactPaths(files), .. } => { files.insert(path); } ExternEntry { location: location @ ExternLocation::FoundInLibrarySearchDirectories, .. } => { // Exact paths take precedence over search directories. let files = BTreeSet::from_iter(iter::once(path)); *location = ExternLocation::ExactPaths(files); } } ext_ent } } } else { // --extern prelude_name match entry { Entry::Vacant(vacant) => { vacant.insert(ExternEntry::new(ExternLocation::FoundInLibrarySearchDirectories)) } Entry::Occupied(occupied) => { // Ignore if already specified. occupied.into_mut() } } }; let mut is_private_dep = false; let mut add_prelude = true; if let Some(opts) = options { if !is_unstable_enabled { early_error( error_format, "the `-Z unstable-options` flag must also be passed to \ enable `--extern options", ); } for opt in opts.split(',') { match opt { "priv" => is_private_dep = true, "noprelude" => { if let ExternLocation::ExactPaths(_) = &entry.location { add_prelude = false; } else { early_error( error_format, "the `noprelude` --extern option requires a file path", ); } } _ => early_error(error_format, &format!("unknown --extern option `{}`", opt)), } } } // Crates start out being not private, and go to being private `priv` // is specified. entry.is_private_dep |= is_private_dep; // If any flag is missing `noprelude`, then add to the prelude. entry.add_prelude |= add_prelude; } Externs(externs) } fn parse_remap_path_prefix( matches: &getopts::Matches, error_format: ErrorOutputType, ) -> Vec<(PathBuf, PathBuf)> { matches .opt_strs("remap-path-prefix") .into_iter() .map(|remap| { let mut parts = remap.rsplitn(2, '='); // reverse iterator let to = parts.next(); let from = parts.next(); match (from, to) { (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)), _ => early_error( error_format, "--remap-path-prefix must contain '=' between FROM and TO", ), } }) .collect() } pub fn build_session_options(matches: &getopts::Matches) -> Options { let color = parse_color(matches); let edition = parse_crate_edition(matches); let (json_rendered, json_artifact_notifications) = parse_json(matches); let error_format = parse_error_format(matches, color, json_rendered); let unparsed_crate_types = matches.opt_strs("crate-type"); let crate_types = parse_crate_types_from_list(unparsed_crate_types) .unwrap_or_else(|e| early_error(error_format, &e[..])); let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format); let mut debugging_opts = build_debugging_options(matches, error_format); check_debug_option_stability(&debugging_opts, error_format, json_rendered); let output_types = parse_output_types(&debugging_opts, matches, error_format); let mut cg = build_codegen_options(matches, error_format); let (disable_thinlto, mut codegen_units) = should_override_cgus_and_disable_thinlto( &output_types, matches, error_format, cg.codegen_units, ); check_thread_count(&debugging_opts, error_format); let incremental = cg.incremental.as_ref().map(PathBuf::from); if debugging_opts.profile && incremental.is_some() { early_error( error_format, "can't instrument with gcov profiling when compiling incrementally", ); } if debugging_opts.profile { match codegen_units { Some(1) => {} None => codegen_units = Some(1), Some(_) => early_error( error_format, "can't instrument with gcov profiling with multiple codegen units", ), } } if cg.profile_generate.enabled() && cg.profile_use.is_some() { early_error( error_format, "options `-C profile-generate` and `-C profile-use` are exclusive", ); } if !cg.embed_bitcode { match cg.lto { LtoCli::No | LtoCli::Unspecified => {} LtoCli::Yes | LtoCli::NoParam | LtoCli::Thin | LtoCli::Fat => early_error( error_format, "options `-C embed-bitcode=no` and `-C lto` are incompatible", ), } } let prints = collect_print_requests(&mut cg, &mut debugging_opts, matches, error_format); let cg = cg; let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m)); let target_triple = parse_target_triple(matches, error_format); let opt_level = parse_opt_level(matches, &cg, error_format); // The `-g` and `-C debuginfo` flags specify the same setting, so we want to be able // to use them interchangeably. See the note above (regarding `-O` and `-C opt-level`) // for more details. let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No); let debuginfo = select_debuginfo(matches, &cg, error_format); let mut search_paths = vec![]; for s in &matches.opt_strs("L") { search_paths.push(SearchPath::from_cli_opt(&s[..], error_format)); } let libs = parse_libs(matches, error_format); let test = matches.opt_present("test"); let borrowck_mode = parse_borrowck_mode(&debugging_opts, error_format); if !cg.remark.is_empty() && debuginfo == DebugInfo::None { early_warn(error_format, "-C remark requires \"-C debuginfo=n\" to show source locations"); } let externs = parse_externs(matches, &debugging_opts, error_format); let crate_name = matches.opt_str("crate-name"); let remap_path_prefix = parse_remap_path_prefix(matches, error_format); let pretty = parse_pretty(matches, &debugging_opts, error_format); Options { crate_types, optimize: opt_level, debuginfo, lint_opts, lint_cap, describe_lints, output_types, search_paths, maybe_sysroot: sysroot_opt, target_triple, test, incremental, debugging_opts, prints, borrowck_mode, cg, error_format, externs, crate_name, alt_std_name: None, libs, unstable_features: UnstableFeatures::from_environment(), debug_assertions, actually_rustdoc: false, cli_forced_codegen_units: codegen_units, cli_forced_thinlto_off: disable_thinlto, remap_path_prefix, edition, json_artifact_notifications, pretty, } } fn parse_pretty( matches: &getopts::Matches, debugging_opts: &DebuggingOptions, efmt: ErrorOutputType, ) -> Option<PpMode> { let pretty = if debugging_opts.unstable_options { matches.opt_default("pretty", "normal").map(|a| { // stable pretty-print variants only parse_pretty_inner(efmt, &a, false) }) } else { None }; return if pretty.is_none() { debugging_opts.unpretty.as_ref().map(|a| { // extended with unstable pretty-print variants parse_pretty_inner(efmt, &a, true) }) } else { pretty }; fn parse_pretty_inner(efmt: ErrorOutputType, name: &str, extended: bool) -> PpMode { use PpMode::*; use PpSourceMode::*; let first = match (name, extended) { ("normal", _) => PpmSource(PpmNormal), ("identified", _) => PpmSource(PpmIdentified), ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops), ("expanded", _) => PpmSource(PpmExpanded), ("expanded,identified", _) => PpmSource(PpmExpandedIdentified), ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene), ("hir", true) => PpmHir(PpmNormal), ("hir,identified", true) => PpmHir(PpmIdentified), ("hir,typed", true) => PpmHir(PpmTyped), ("hir-tree", true) => PpmHirTree(PpmNormal), ("mir", true) => PpmMir, ("mir-cfg", true) => PpmMirCFG, _ => { if extended { early_error( efmt, &format!( "argument to `unpretty` must be one of `normal`, \ `expanded`, `identified`, `expanded,identified`, \ `expanded,hygiene`, `everybody_loops`, \ `hir`, `hir,identified`, `hir,typed`, `hir-tree`, \ `mir` or `mir-cfg`; got {}", name ), ); } else { early_error( efmt, &format!( "argument to `pretty` must be one of `normal`, \ `expanded`, `identified`, or `expanded,identified`; got {}", name ), ); } } }; first } } pub fn make_crate_type_option() -> RustcOptGroup { opt::multi_s( "", "crate-type", "Comma separated list of types of crates for the compiler to emit", "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]", ) } pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> { let mut crate_types: Vec<CrateType> = Vec::new(); for unparsed_crate_type in &list_list { for part in unparsed_crate_type.split(',') { let new_part = match part { "lib" => default_lib_output(), "rlib" => CrateType::Rlib, "staticlib" => CrateType::Staticlib, "dylib" => CrateType::Dylib, "cdylib" => CrateType::Cdylib, "bin" => CrateType::Executable, "proc-macro" => CrateType::ProcMacro, _ => return Err(format!("unknown crate type: `{}`", part)), }; if !crate_types.contains(&new_part) { crate_types.push(new_part) } } } Ok(crate_types) } pub mod nightly_options { use super::{ErrorOutputType, OptionStability, RustcOptGroup}; use crate::early_error; use rustc_feature::UnstableFeatures; pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool { is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options") } pub fn is_nightly_build() -> bool { UnstableFeatures::from_environment().is_nightly_build() } pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) { let has_z_unstable_option = matches.opt_strs("Z").iter().any(|x| *x == "unstable-options"); let really_allows_unstable_options = UnstableFeatures::from_environment().is_nightly_build(); for opt in flags.iter() { if opt.stability == OptionStability::Stable { continue; } if !matches.opt_present(opt.name) { continue; } if opt.name != "Z" && !has_z_unstable_option { early_error( ErrorOutputType::default(), &format!( "the `-Z unstable-options` flag must also be passed to enable \ the flag `{}`", opt.name ), ); } if really_allows_unstable_options { continue; } match opt.stability { OptionStability::Unstable => { let msg = format!( "the option `{}` is only accepted on the \ nightly compiler", opt.name ); early_error(ErrorOutputType::default(), &msg); } OptionStability::Stable => {} } } } } impl fmt::Display for CrateType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { CrateType::Executable => "bin".fmt(f), CrateType::Dylib => "dylib".fmt(f), CrateType::Rlib => "rlib".fmt(f), CrateType::Staticlib => "staticlib".fmt(f), CrateType::Cdylib => "cdylib".fmt(f), CrateType::ProcMacro => "proc-macro".fmt(f), } } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum PpSourceMode { PpmNormal, PpmEveryBodyLoops, PpmExpanded, PpmIdentified, PpmExpandedIdentified, PpmExpandedHygiene, PpmTyped, } #[derive(Copy, Clone, PartialEq, Debug)] pub enum PpMode { PpmSource(PpSourceMode), PpmHir(PpSourceMode), PpmHirTree(PpSourceMode), PpmMir, PpmMirCFG, } impl PpMode { pub fn needs_ast_map(&self) -> bool { use PpMode::*; use PpSourceMode::*; match *self { PpmSource(PpmNormal | PpmEveryBodyLoops | PpmIdentified) => false, PpmSource(PpmExpanded | PpmExpandedIdentified | PpmExpandedHygiene) | PpmHir(_) | PpmHirTree(_) | PpmMir | PpmMirCFG => true, PpmSource(PpmTyped) => panic!("invalid state"), } } pub fn needs_analysis(&self) -> bool { use PpMode::*; match *self { PpmMir | PpmMirCFG => true, _ => false, } } } /// Command-line arguments passed to the compiler have to be incorporated with /// the dependency tracking system for incremental compilation. This module /// provides some utilities to make this more convenient. /// /// The values of all command-line arguments that are relevant for dependency /// tracking are hashed into a single value that determines whether the /// incremental compilation cache can be re-used or not. This hashing is done /// via the `DepTrackingHash` trait defined below, since the standard `Hash` /// implementation might not be suitable (e.g., arguments are stored in a `Vec`, /// the hash of which is order dependent, but we might not want the order of /// arguments to make a difference for the hash). /// /// However, since the value provided by `Hash::hash` often *is* suitable, /// especially for primitive types, there is the /// `impl_dep_tracking_hash_via_hash!()` macro that allows to simply reuse the /// `Hash` implementation for `DepTrackingHash`. It's important though that /// we have an opt-in scheme here, so one is hopefully forced to think about /// how the hash should be calculated when adding a new command-line argument. crate mod dep_tracking { use super::{ CFGuard, CrateType, DebugInfo, ErrorOutputType, LinkerPluginLto, LtoCli, OptLevel, OutputTypes, Passes, SanitizerSet, SourceFileHashAlgorithm, SwitchWithOptPath, SymbolManglingVersion, }; use crate::lint; use crate::utils::NativeLibKind; use rustc_feature::UnstableFeatures; use rustc_span::edition::Edition; use rustc_target::spec::{CodeModel, MergeFunctions, PanicStrategy, RelocModel}; use rustc_target::spec::{RelroLevel, TargetTriple, TlsModel}; use std::collections::hash_map::DefaultHasher; use std::collections::BTreeMap; use std::hash::Hash; use std::path::PathBuf; pub trait DepTrackingHash { fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType); } macro_rules! impl_dep_tracking_hash_via_hash { ($t:ty) => { impl DepTrackingHash for $t { fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) { Hash::hash(self, hasher); } } }; } macro_rules! impl_dep_tracking_hash_for_sortable_vec_of { ($t:ty) => { impl DepTrackingHash for Vec<$t> { fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) { let mut elems: Vec<&$t> = self.iter().collect(); elems.sort(); Hash::hash(&elems.len(), hasher); for (index, elem) in elems.iter().enumerate() { Hash::hash(&index, hasher); DepTrackingHash::hash(*elem, hasher, error_format); } } } }; } impl_dep_tracking_hash_via_hash!(bool); impl_dep_tracking_hash_via_hash!(usize); impl_dep_tracking_hash_via_hash!(u64); impl_dep_tracking_hash_via_hash!(String); impl_dep_tracking_hash_via_hash!(PathBuf); impl_dep_tracking_hash_via_hash!(lint::Level); impl_dep_tracking_hash_via_hash!(Option<bool>); impl_dep_tracking_hash_via_hash!(Option<usize>); impl_dep_tracking_hash_via_hash!(Option<String>); impl_dep_tracking_hash_via_hash!(Option<(String, u64)>); impl_dep_tracking_hash_via_hash!(Option<Vec<String>>); impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>); impl_dep_tracking_hash_via_hash!(Option<RelocModel>); impl_dep_tracking_hash_via_hash!(Option<CodeModel>); impl_dep_tracking_hash_via_hash!(Option<TlsModel>); impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>); impl_dep_tracking_hash_via_hash!(Option<RelroLevel>); impl_dep_tracking_hash_via_hash!(Option<lint::Level>); impl_dep_tracking_hash_via_hash!(Option<PathBuf>); impl_dep_tracking_hash_via_hash!(CrateType); impl_dep_tracking_hash_via_hash!(MergeFunctions); impl_dep_tracking_hash_via_hash!(PanicStrategy); impl_dep_tracking_hash_via_hash!(RelroLevel); impl_dep_tracking_hash_via_hash!(Passes); impl_dep_tracking_hash_via_hash!(OptLevel); impl_dep_tracking_hash_via_hash!(LtoCli); impl_dep_tracking_hash_via_hash!(DebugInfo); impl_dep_tracking_hash_via_hash!(UnstableFeatures); impl_dep_tracking_hash_via_hash!(OutputTypes); impl_dep_tracking_hash_via_hash!(NativeLibKind); impl_dep_tracking_hash_via_hash!(SanitizerSet); impl_dep_tracking_hash_via_hash!(CFGuard); impl_dep_tracking_hash_via_hash!(TargetTriple); impl_dep_tracking_hash_via_hash!(Edition); impl_dep_tracking_hash_via_hash!(LinkerPluginLto); impl_dep_tracking_hash_via_hash!(SwitchWithOptPath); impl_dep_tracking_hash_via_hash!(SymbolManglingVersion); impl_dep_tracking_hash_via_hash!(Option<SourceFileHashAlgorithm>); impl_dep_tracking_hash_for_sortable_vec_of!(String); impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf); impl_dep_tracking_hash_for_sortable_vec_of!(CrateType); impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level)); impl_dep_tracking_hash_for_sortable_vec_of!((String, Option<String>, NativeLibKind)); impl_dep_tracking_hash_for_sortable_vec_of!((String, u64)); impl<T1, T2> DepTrackingHash for (T1, T2) where T1: DepTrackingHash, T2: DepTrackingHash, { fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) { Hash::hash(&0, hasher); DepTrackingHash::hash(&self.0, hasher, error_format); Hash::hash(&1, hasher); DepTrackingHash::hash(&self.1, hasher, error_format); } } impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3) where T1: DepTrackingHash, T2: DepTrackingHash, T3: DepTrackingHash, { fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) { Hash::hash(&0, hasher); DepTrackingHash::hash(&self.0, hasher, error_format); Hash::hash(&1, hasher); DepTrackingHash::hash(&self.1, hasher, error_format); Hash::hash(&2, hasher); DepTrackingHash::hash(&self.2, hasher, error_format); } } // This is a stable hash because BTreeMap is a sorted container pub fn stable_hash( sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>, hasher: &mut DefaultHasher, error_format: ErrorOutputType, ) { for (key, sub_hash) in sub_hashes { // Using Hash::hash() instead of DepTrackingHash::hash() is fine for // the keys, as they are just plain strings Hash::hash(&key.len(), hasher); Hash::hash(key, hasher); sub_hash.hash(hasher, error_format); } } }
into_iter
example0.py
print(sum([i for i in range(1_000_000)]))
errorHandle.go
package utils import "github.com/hashload/boss/msg" func HandleError(err error) { if err != nil
}
{ msg.Err(err.Error()) }
test_ghebbrish_converter.py
from unittest import TestCase from ..gib2u import GhebbrishConverter class TestGhebbrishConverter(TestCase): gib = GhebbrishConverter('') def test_gibberish_to_utf8_converter(self):
original_string = "ùìåí çðåê" expected_output = "שלום חנוך" self.assertEqual(self.gib.convert_gibberish_to_utf8(original_string), expected_output)
index.tsx
import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; import { MdAddCircleOutline } from 'react-icons/md'; import { parseISO, format } from 'date-fns'; import pt from 'date-fns/locale/pt'; import api from 'services/api'; import { Container } from './styles'; interface Meetup { id: number; title: string; date: string; formatedDate?: string; } export default function SingIn() { const [meetups, setMeetups] = useState<Meetup[]>([]); useEffect(() => { async function
() { try { const response = await api.get('/meetups'); const data: Meetup[] = response.data.map((item: Meetup) => { return { id: item.id, title: item.title, formatedDate: format( parseISO(item.date), "dd 'de' MMMM', às' HH'h' ", { locale: pt } ), }; }); setMeetups(data); } catch (err) { setMeetups([]); } } loadMeetups(); }, []); return ( <Container> <div className="header"> <strong>Meus Meetups</strong> <Link to="/editmeetup"> <button type="button" data-testid="new-meetup"> <MdAddCircleOutline /> Novo Meetup </button> </Link> </div> <ul> {meetups.length === 0 ? ( <> <strong>Não existe meetup cadastrado, crie um novo meetup</strong> </> ) : ( <> {meetups.map(meetup => ( <Link to={`/meetup/${encodeURIComponent(meetup.id)}`} key={meetup.id} > <li> <strong>{meetup.title}</strong> <p>{meetup.formatedDate}</p> </li> </Link> ))} </> )} </ul> </Container> ); }
loadMeetups
SideBarComponent.tsx
import React, {useContext, useEffect, useState} from 'react'; import AuthContext from '../../components/auth/AuthContext'; import API from '../../api/API'; import sidebarStyles from '../../css/profile/SideBarComponent.module.css'; import commonStyles from '../../css/Common.module.css'; const SideBarComponent = (props: any) => { const { user } = useContext(AuthContext); const [ img, setImg ] = useState(); const [ name, setName ] = useState(); const [ lastName, setLastName ] = useState(); const [ admin, setAdmin ] = useState(); const [ email, setEmail ] = useState(); useEffect(() =>{ getFromServer(); // Get image from server }) async function
(){ try { let response = await API.user(5); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! CHANGE USER ID if (response.status === 200) { console.log(response.data); setImg(response.data.image); setName(response.data.name); setLastName(response.data.lastName); setAdmin(response.data.isAdmin); setEmail(response.data.email); } } catch (error) { if (error.response.status === 401 || error.response.status === 504) { console.log(error); } // If TwoFactorAuthentication if (error.response.status === 418) { } } } return ( <div className={sidebarStyles.SideBarWrapper}> <h1>{name} {lastName}</h1> <h3>{(admin == '1') ? "Admin":"user"}</h3> <div className={sidebarStyles.imageWrapper}><img src={img} alt="profilepicture"/></div> <div className={sidebarStyles.text}> {/* <label className={commonStyles.label}>Telephone <input type="tel"></input>{tel}</label> */} <label className={commonStyles.label} htmlFor="email">email</label> <input className={commonStyles.input} name="email" type="tel" value={email}/> </div> </div> ) } export default SideBarComponent;
getFromServer
Populating Next Right Pointers in Each Node 116.py
# 116. Populating Next Right Pointers in Each Node # 117. Populating Next Right Pointers in Each Node II # [email protected] # Given a binary tree # struct TreeLinkNode { # TreeLinkNode *left; # TreeLinkNode *right; # TreeLinkNode *next; # } # Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. # Initially, all next pointers are set to NULL. # Note: # You may only use constant extra space. # You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). # For example, # Given the following perfect binary tree, # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 # After calling your function, the tree should look like: # 1 -> NULL # / \ # 2 -> 3 -> NULL # / \ / \ # 4->5->6->7 -> NULL # Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): while root: node = tem = TreeLinkNode(0) while root: if root.left: node.next = node = root.left if root.right:
root = root.next root = tem.next
node.next = node = root.right
planar_2d.rs
//! 2D Planar Mapping use super::*; use crate::pbrt::*; /// Implements 2D planar mapping by projecting points onto a plane. pub struct PlanarMapping2D {
vt: Vector3f, /// Offset in `s` direction. ds: Float, /// Offset in `t` direction. dt: Float, } impl PlanarMapping2D { /// Create a new `PlanarMapping2D`. /// /// * `vs` - Direction in `s` direction. /// * `vt` - Direction in `t` direction (not parallel to `vs`). /// * `ds` - Offset in `s` direction. /// * `dt` - Offset in `t` direction. pub fn new(vs: Vector3f, vt: Vector3f, ds: Float, dt: Float) -> Self { Self { vs, vt, ds, dt } } } impl TextureMapping2D for PlanarMapping2D { /// Returns the (s, t) texture coordinates and texture differentials. /// /// * `hit` - Surface interaction hit. /// * `uv` - Surface interaction uv. /// * `der` - Surface interaction derivatives. fn map(&self, hit: &Hit, _uv: &Point2f, der: &Derivatives) -> TextureMap2DResult { let vec = Vector3f::from(hit.p); let dstdx = Vector2f::new(der.dpdx.dot(&self.vs), der.dpdx.dot(&self.vt)); let dstdy = Vector2f::new(der.dpdy.dot(&self.vs), der.dpdy.dot(&self.vt)); let p = Point2f::new(self.ds + vec.dot(&self.vs), self.dt + vec.dot(&self.vt)); TextureMap2DResult::new(p, dstdx, dstdy) } }
/// Direction in `s` direction. vs: Vector3f, /// Direction in `t` direction (not parallel to `vs`).
i18n.js
import * as ls from './localStorage'; import i18n from 'i18next'; import { reactI18nextModule } from 'react-i18next'; import backend from 'i18next-xhr-backend'; let _defaultLanguage = 'en'; let _currentLanguage; function
() { if (_currentLanguage) return _currentLanguage; _currentLanguage = ls.get('setting.language'); return _currentLanguage || _defaultLanguage; } function setCurrentLanguage(lang) { _currentLanguage = lang; ls.set('setting.language', lang); } i18n .use(backend) .use(reactI18nextModule) .init({ lng: getCurrentLanguage(), fallbackLng: _defaultLanguage, backend: { loadPath: '/static/locales/{{lng}}/{{ns}}.json', }, keySeparator: false, interpolation: { escapeValue: false }, react: { wait: true } }); i18n.getCurrentLanguage = getCurrentLanguage; i18n.setCurrentLanguage = setCurrentLanguage; export default i18n;
getCurrentLanguage
team.go
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package api4 import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "regexp" "strconv" "strings" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/model" ) const ( MaxAddMembersBatch = 256 MaximumBulkImportSize = 10 * 1024 * 1024 groupIDsParamPattern = "[^a-zA-Z0-9,]*" ) var groupIDsQueryParamRegex *regexp.Regexp func init() { groupIDsQueryParamRegex = regexp.MustCompile(groupIDsParamPattern) } func (api *API) InitTeam() { api.BaseRoutes.Teams.Handle("", api.ApiSessionRequired(createTeam)).Methods("POST") api.BaseRoutes.Teams.Handle("", api.ApiSessionRequired(getAllTeams)).Methods("GET") api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/scheme", api.ApiSessionRequired(updateTeamScheme)).Methods("PUT") api.BaseRoutes.Teams.Handle("/search", api.ApiSessionRequiredDisableWhenBusy(searchTeams)).Methods("POST") api.BaseRoutes.TeamsForUser.Handle("", api.ApiSessionRequired(getTeamsForUser)).Methods("GET") api.BaseRoutes.TeamsForUser.Handle("/unread", api.ApiSessionRequired(getTeamsUnreadForUser)).Methods("GET") api.BaseRoutes.Team.Handle("", api.ApiSessionRequired(getTeam)).Methods("GET") api.BaseRoutes.Team.Handle("", api.ApiSessionRequired(updateTeam)).Methods("PUT") api.BaseRoutes.Team.Handle("", api.ApiSessionRequired(deleteTeam)).Methods("DELETE") api.BaseRoutes.Team.Handle("/patch", api.ApiSessionRequired(patchTeam)).Methods("PUT") api.BaseRoutes.Team.Handle("/restore", api.ApiSessionRequired(restoreTeam)).Methods("POST") api.BaseRoutes.Team.Handle("/privacy", api.ApiSessionRequired(updateTeamPrivacy)).Methods("PUT") api.BaseRoutes.Team.Handle("/stats", api.ApiSessionRequired(getTeamStats)).Methods("GET") api.BaseRoutes.Team.Handle("/regenerate_invite_id", api.ApiSessionRequired(regenerateTeamInviteId)).Methods("POST") api.BaseRoutes.Team.Handle("/image", api.ApiSessionRequiredTrustRequester(getTeamIcon)).Methods("GET") api.BaseRoutes.Team.Handle("/image", api.ApiSessionRequired(setTeamIcon)).Methods("POST") api.BaseRoutes.Team.Handle("/image", api.ApiSessionRequired(removeTeamIcon)).Methods("DELETE") api.BaseRoutes.TeamMembers.Handle("", api.ApiSessionRequired(getTeamMembers)).Methods("GET") api.BaseRoutes.TeamMembers.Handle("/ids", api.ApiSessionRequired(getTeamMembersByIds)).Methods("POST") api.BaseRoutes.TeamMembersForUser.Handle("", api.ApiSessionRequired(getTeamMembersForUser)).Methods("GET") api.BaseRoutes.TeamMembers.Handle("", api.ApiSessionRequired(addTeamMember)).Methods("POST") api.BaseRoutes.Teams.Handle("/members/invite", api.ApiSessionRequired(addUserToTeamFromInvite)).Methods("POST") api.BaseRoutes.TeamMembers.Handle("/batch", api.ApiSessionRequired(addTeamMembers)).Methods("POST") api.BaseRoutes.TeamMember.Handle("", api.ApiSessionRequired(removeTeamMember)).Methods("DELETE") api.BaseRoutes.TeamForUser.Handle("/unread", api.ApiSessionRequired(getTeamUnread)).Methods("GET") api.BaseRoutes.TeamByName.Handle("", api.ApiSessionRequired(getTeamByName)).Methods("GET") api.BaseRoutes.TeamMember.Handle("", api.ApiSessionRequired(getTeamMember)).Methods("GET") api.BaseRoutes.TeamByName.Handle("/exists", api.ApiSessionRequired(teamExists)).Methods("GET") api.BaseRoutes.TeamMember.Handle("/roles", api.ApiSessionRequired(updateTeamMemberRoles)).Methods("PUT") api.BaseRoutes.TeamMember.Handle("/schemeRoles", api.ApiSessionRequired(updateTeamMemberSchemeRoles)).Methods("PUT") api.BaseRoutes.Team.Handle("/import", api.ApiSessionRequired(importTeam)).Methods("POST") api.BaseRoutes.Team.Handle("/invite/email", api.ApiSessionRequired(inviteUsersToTeam)).Methods("POST") api.BaseRoutes.Team.Handle("/invite-guests/email", api.ApiSessionRequired(inviteGuestsToChannels)).Methods("POST") api.BaseRoutes.Teams.Handle("/invites/email", api.ApiSessionRequired(invalidateAllEmailInvites)).Methods("DELETE") api.BaseRoutes.Teams.Handle("/invite/{invite_id:[A-Za-z0-9]+}", api.ApiHandler(getInviteInfo)).Methods("GET") api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/members_minus_group_members", api.ApiSessionRequired(teamMembersMinusGroupMembers)).Methods("GET") } func createTeam(c *Context, w http.ResponseWriter, r *http.Request) { team := model.TeamFromJson(r.Body) if team == nil { c.SetInvalidParam("team") return } team.Email = strings.ToLower(team.Email) auditRec := c.MakeAuditRecord("createTeam", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team", team) if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_TEAM) { c.Err = model.NewAppError("createTeam", "api.team.is_team_creation_allowed.disabled.app_error", nil, "", http.StatusForbidden) return } rteam, err := c.App.CreateTeamWithUser(team, c.App.Session().UserId) if err != nil { c.Err = err return } // Don't sanitize the team here since the user will be a team admin and their session won't reflect that yet auditRec.Success() auditRec.AddMeta("team", team) // overwrite meta w.WriteHeader(http.StatusCreated) w.Write([]byte(rteam.ToJson())) } func getTeam(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } team, err := c.App.GetTeam(c.Params.TeamId) if err != nil { c.Err = err return } if (!team.AllowOpenInvite || team.Type != model.TEAM_OPEN) && !c.App.SessionHasPermissionToTeam(*c.App.Session(), team.Id, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } c.App.SanitizeTeam(*c.App.Session(), team) w.Write([]byte(team.ToJson())) } func getTeamByName(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamName() if c.Err != nil { return } team, err := c.App.GetTeamByName(c.Params.TeamName) if err != nil { c.Err = err return } if (!team.AllowOpenInvite || team.Type != model.TEAM_OPEN) && !c.App.SessionHasPermissionToTeam(*c.App.Session(), team.Id, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } c.App.SanitizeTeam(*c.App.Session(), team) w.Write([]byte(team.ToJson())) } func updateTeam(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } team := model.TeamFromJson(r.Body) if team == nil { c.SetInvalidParam("team") return } team.Email = strings.ToLower(team.Email) // The team being updated in the payload must be the same one as indicated in the URL. if team.Id != c.Params.TeamId { c.SetInvalidParam("id") return } auditRec := c.MakeAuditRecord("updateTeam", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team", team) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } updatedTeam, err := c.App.UpdateTeam(team) if err != nil { c.Err = err return } auditRec.Success() auditRec.AddMeta("update", updatedTeam) c.App.SanitizeTeam(*c.App.Session(), updatedTeam) w.Write([]byte(updatedTeam.ToJson())) } func patchTeam(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } team := model.TeamPatchFromJson(r.Body) if team == nil { c.SetInvalidParam("team") return } auditRec := c.MakeAuditRecord("patchTeam", audit.Fail) defer c.LogAuditRec(auditRec) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } if oldTeam, err := c.App.GetTeam(c.Params.TeamId); err == nil { auditRec.AddMeta("team", oldTeam) } patchedTeam, err := c.App.PatchTeam(c.Params.TeamId, team) if err != nil { c.Err = err return } c.App.SanitizeTeam(*c.App.Session(), patchedTeam) auditRec.Success() auditRec.AddMeta("patched", patchedTeam) c.LogAudit("") w.Write([]byte(patchedTeam.ToJson())) } func restoreTeam(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } auditRec := c.MakeAuditRecord("restoreTeam", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } err := c.App.RestoreTeam(c.Params.TeamId) if err != nil { c.Err = err return } // Return the restored team to be consistent with RestoreChannel. team, err := c.App.GetTeam(c.Params.TeamId) if err != nil { c.Err = err return } auditRec.AddMeta("team", team) auditRec.Success() w.Write([]byte(team.ToJson())) } func updateTeamPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } props := model.StringInterfaceFromJson(r.Body) privacy, ok := props["privacy"].(string) if !ok { c.SetInvalidParam("privacy") return } var openInvite bool switch privacy { case model.TEAM_OPEN: openInvite = true case model.TEAM_INVITE: openInvite = false default: c.SetInvalidParam("privacy") return } auditRec := c.MakeAuditRecord("updateTeamPrivacy", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("privacy", privacy) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { auditRec.AddMeta("team_id", c.Params.TeamId) c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } if err := c.App.UpdateTeamPrivacy(c.Params.TeamId, privacy, openInvite); err != nil { c.Err = err return } // Return the updated team to be consistent with UpdateChannelPrivacy team, err := c.App.GetTeam(c.Params.TeamId) if err != nil { c.Err = err return } auditRec.AddMeta("team", team) auditRec.Success() w.Write([]byte(team.ToJson())) } func regenerateTeamInviteId(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } auditRec := c.MakeAuditRecord("regenerateTeamInviteId", audit.Fail) defer c.LogAuditRec(auditRec) patchedTeam, err := c.App.RegenerateTeamInviteId(c.Params.TeamId) if err != nil { c.Err = err return } c.App.SanitizeTeam(*c.App.Session(), patchedTeam) auditRec.Success() auditRec.AddMeta("team", patchedTeam) c.LogAudit("") w.Write([]byte(patchedTeam.ToJson())) } func deleteTeam(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } auditRec := c.MakeAuditRecord("deleteTeam", audit.Fail) defer c.LogAuditRec(auditRec) if team, err := c.App.GetTeam(c.Params.TeamId); err == nil { auditRec.AddMeta("team", team) } var err *model.AppError if c.Params.Permanent { if *c.App.Config().ServiceSettings.EnableAPITeamDeletion { err = c.App.PermanentDeleteTeamId(c.Params.TeamId) } else { err = model.NewAppError("deleteTeam", "api.user.delete_team.not_enabled.app_error", nil, "teamId="+c.Params.TeamId, http.StatusUnauthorized) } } else { err = c.App.SoftDeleteTeam(c.Params.TeamId) } if err != nil { c.Err = err return } auditRec.Success() ReturnStatusOK(w) } func getTeamsForUser(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireUserId() if c.Err != nil { return } if c.App.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) return } teams, err := c.App.GetTeamsForUser(c.Params.UserId) if err != nil { c.Err = err return } c.App.SanitizeTeams(*c.App.Session(), teams) w.Write([]byte(model.TeamListToJson(teams))) } func getTeamsUnreadForUser(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireUserId() if c.Err != nil { return } if c.App.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } // optional team id to be excluded from the result teamId := r.URL.Query().Get("exclude_team") unreadTeamsList, err := c.App.GetTeamsUnreadForUser(teamId, c.Params.UserId) if err != nil { c.Err = err return } w.Write([]byte(model.TeamsUnreadToJson(unreadTeamsList))) } func getTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId().RequireUserId() if c.Err != nil { return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return } if !canSee { c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) return } team, err := c.App.GetTeamMember(c.Params.TeamId, c.Params.UserId) if err != nil { c.Err = err return } w.Write([]byte(team.ToJson())) } func getTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } sort := r.URL.Query().Get("sort") excludeDeletedUsers := r.URL.Query().Get("exclude_deleted_users") excludeDeletedUsersBool, _ := strconv.ParseBool(excludeDeletedUsers) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return } teamMembersGetOptions := &model.TeamMembersGetOptions{ Sort: sort, ExcludeDeletedUsers: excludeDeletedUsersBool, ViewRestrictions: restrictions, } members, err := c.App.GetTeamMembers(c.Params.TeamId, c.Params.Page*c.Params.PerPage, c.Params.PerPage, teamMembersGetOptions) if err != nil { c.Err = err return } w.Write([]byte(model.TeamMembersToJson(members))) } func getTeamMembersForUser(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireUserId() if c.Err != nil { return } if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_OTHER_USERS_TEAMS) { c.SetPermissionError(model.PERMISSION_READ_OTHER_USERS_TEAMS) return } canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return } if !canSee { c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) return } members, err := c.App.GetTeamMembersForUser(c.Params.UserId) if err != nil { c.Err = err return } w.Write([]byte(model.TeamMembersToJson(members))) } func getTeamMembersByIds(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } userIds := model.ArrayFromJson(r.Body) if len(userIds) == 0 { c.SetInvalidParam("user_ids") return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return } members, err := c.App.GetTeamMembersByIds(c.Params.TeamId, userIds, restrictions) if err != nil { c.Err = err return } w.Write([]byte(model.TeamMembersToJson(members))) } func addTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } var err *model.AppError member := model.TeamMemberFromJson(r.Body) if member == nil { c.Err = model.NewAppError("addTeamMember", "api.team.add_team_member.invalid_body.app_error", nil, "Error in model.TeamMemberFromJson()", http.StatusBadRequest) return } if member.TeamId != c.Params.TeamId { c.SetInvalidParam("team_id") return } if !model.IsValidId(member.UserId) { c.SetInvalidParam("user_id") return } auditRec := c.MakeAuditRecord("addTeamMember", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("member", member) if member.UserId == c.App.Session().UserId { var team *model.Team team, err = c.App.GetTeam(member.TeamId) if err != nil { c.Err = err return } if team.AllowOpenInvite && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_JOIN_PUBLIC_TEAMS) { c.SetPermissionError(model.PERMISSION_JOIN_PUBLIC_TEAMS) return } if !team.AllowOpenInvite && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_JOIN_PRIVATE_TEAMS) { c.SetPermissionError(model.PERMISSION_JOIN_PRIVATE_TEAMS) return } } else { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), member.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { c.SetPermissionError(model.PERMISSION_ADD_USER_TO_TEAM) return } } team, err := c.App.GetTeam(member.TeamId) if err != nil { c.Err = err return } auditRec.AddMeta("team", team) if team.IsGroupConstrained() { nonMembers, err := c.App.FilterNonGroupTeamMembers([]string{member.UserId}, team) if err != nil { if v, ok := err.(*model.AppError); ok { c.Err = v } else { c.Err = model.NewAppError("addTeamMember", "api.team.add_members.error", nil, err.Error(), http.StatusBadRequest) } return } if len(nonMembers) > 0 { c.Err = model.NewAppError("addTeamMember", "api.team.add_members.user_denied", map[string]interface{}{"UserIDs": nonMembers}, "", http.StatusBadRequest) return } } member, err = c.App.AddTeamMember(member.TeamId, member.UserId) if err != nil { c.Err = err return } auditRec.Success() w.WriteHeader(http.StatusCreated) w.Write([]byte(member.ToJson())) } func addUserToTeamFromInvite(c *Context, w http.ResponseWriter, r *http.Request) { tokenId := r.URL.Query().Get("token") inviteId := r.URL.Query().Get("invite_id") var member *model.TeamMember var err *model.AppError auditRec := c.MakeAuditRecord("addUserToTeamFromInvite", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("invite_id", inviteId) if len(tokenId) > 0 { member, err = c.App.AddTeamMemberByToken(c.App.Session().UserId, tokenId) } else if len(inviteId) > 0 { if c.App.Session().Props[model.SESSION_PROP_IS_GUEST] == "true" { c.Err = model.NewAppError("addUserToTeamFromInvite", "api.team.add_user_to_team_from_invite.guest.app_error", nil, "", http.StatusForbidden) return } member, err = c.App.AddTeamMemberByInviteId(inviteId, c.App.Session().UserId) } else { err = model.NewAppError("addTeamMember", "api.team.add_user_to_team.missing_parameter.app_error", nil, "", http.StatusBadRequest) } if err != nil { c.Err = err return } auditRec.Success() if member != nil { auditRec.AddMeta("member", member) } w.WriteHeader(http.StatusCreated) w.Write([]byte(member.ToJson())) } func addTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) { graceful := r.URL.Query().Get("graceful") != "" c.RequireTeamId() if c.Err != nil { return } var err *model.AppError members := model.TeamMembersFromJson(r.Body) if len(members) > MaxAddMembersBatch { c.SetInvalidParam("too many members in batch") return } if len(members) == 0 { c.SetInvalidParam("no members in batch") return } auditRec := c.MakeAuditRecord("addTeamMembers", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("count", len(members)) var memberIDs []string for _, member := range members { memberIDs = append(memberIDs, member.UserId) } auditRec.AddMeta("user_ids", memberIDs) team, err := c.App.GetTeam(c.Params.TeamId) if err != nil { c.Err = err return } auditRec.AddMeta("team", team) if team.IsGroupConstrained() { nonMembers, err := c.App.FilterNonGroupTeamMembers(memberIDs, team) if err != nil { if v, ok := err.(*model.AppError); ok { c.Err = v } else { c.Err = model.NewAppError("addTeamMembers", "api.team.add_members.error", nil, err.Error(), http.StatusBadRequest) } return } if len(nonMembers) > 0 { c.Err = model.NewAppError("addTeamMembers", "api.team.add_members.user_denied", map[string]interface{}{"UserIDs": nonMembers}, "", http.StatusBadRequest) return } } var userIds []string for _, member := range members { if member.TeamId != c.Params.TeamId { c.SetInvalidParam("team_id for member with user_id=" + member.UserId) return } if !model.IsValidId(member.UserId) { c.SetInvalidParam("user_id") return } userIds = append(userIds, member.UserId) } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { c.SetPermissionError(model.PERMISSION_ADD_USER_TO_TEAM) return } membersWithErrors, err := c.App.AddTeamMembers(c.Params.TeamId, userIds, c.App.Session().UserId, graceful) if membersWithErrors != nil { errList := make([]string, 0, len(membersWithErrors)) for _, m := range membersWithErrors { if m.Error != nil { errList = append(errList, model.TeamMemberWithErrorToString(m)) } } auditRec.AddMeta("errors", errList) } if err != nil { c.Err = err return } auditRec.Success() w.WriteHeader(http.StatusCreated) if graceful { // in 'graceful' mode we allow a different return value, notifying the client which users were not added w.Write([]byte(model.TeamMembersWithErrorToJson(membersWithErrors))) } else { w.Write([]byte(model.TeamMembersToJson(model.TeamMembersWithErrorToTeamMembers(membersWithErrors)))) } } func removeTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId().RequireUserId() if c.Err != nil { return } auditRec := c.MakeAuditRecord("removeTeamMember", audit.Fail) defer c.LogAuditRec(auditRec) if c.App.Session().UserId != c.Params.UserId { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_REMOVE_USER_FROM_TEAM) { c.SetPermissionError(model.PERMISSION_REMOVE_USER_FROM_TEAM) return } } team, err := c.App.GetTeam(c.Params.TeamId) if err != nil { c.Err = err return } auditRec.AddMeta("team", team) user, err := c.App.GetUser(c.Params.UserId) if err != nil { c.Err = err return } auditRec.AddMeta("user", user) if team.IsGroupConstrained() && (c.Params.UserId != c.App.Session().UserId) && !user.IsBot { c.Err = model.NewAppError("removeTeamMember", "api.team.remove_member.group_constrained.app_error", nil, "", http.StatusBadRequest) return } if err := c.App.RemoveUserFromTeam(c.Params.TeamId, c.Params.UserId, c.App.Session().UserId); err != nil { c.Err = err return } auditRec.Success() ReturnStatusOK(w) } func getTeamUnread(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId().RequireUserId() if c.Err != nil { return } if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } unreadTeam, err := c.App.GetTeamUnread(c.Params.TeamId, c.Params.UserId) if err != nil { c.Err = err return } w.Write([]byte(unreadTeam.ToJson())) } func getTeamStats(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return } stats, err := c.App.GetTeamStats(c.Params.TeamId, restrictions) if err != nil { c.Err = err return } w.Write([]byte(stats.ToJson())) } func updateTeamMemberRoles(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId().RequireUserId() if c.Err != nil { return } props := model.MapFromJson(r.Body) newRoles := props["roles"] if !model.IsValidUserRoles(newRoles) { c.SetInvalidParam("team_member_roles") return } auditRec := c.MakeAuditRecord("updateTeamMemberRoles", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("roles", newRoles) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM_ROLES) return } teamMember, err := c.App.UpdateTeamMemberRoles(c.Params.TeamId, c.Params.UserId, newRoles) if err != nil { c.Err = err return } auditRec.Success() auditRec.AddMeta("member", teamMember) ReturnStatusOK(w) } func updateTeamMemberSchemeRoles(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId().RequireUserId() if c.Err != nil { return } schemeRoles := model.SchemeRolesFromJson(r.Body) if schemeRoles == nil { c.SetInvalidParam("scheme_roles") return } auditRec := c.MakeAuditRecord("updateTeamMemberSchemeRoles", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("roles", schemeRoles) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM_ROLES) return } teamMember, err := c.App.UpdateTeamMemberSchemeRoles(c.Params.TeamId, c.Params.UserId, schemeRoles.SchemeGuest, schemeRoles.SchemeUser, schemeRoles.SchemeAdmin) if err != nil { c.Err = err return } auditRec.Success() auditRec.AddMeta("member", teamMember) ReturnStatusOK(w) } func getAllTeams(c *Context, w http.ResponseWriter, r *http.Request) { teams := []*model.Team{} var err *model.AppError var teamsWithCount *model.TeamsWithCount listPrivate := c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) listPublic := c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) if listPrivate && listPublic { if c.Params.IncludeTotalCount { teamsWithCount, err = c.App.GetAllTeamsPageWithCount(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } else { teams, err = c.App.GetAllTeamsPage(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } } else if listPrivate { if c.Params.IncludeTotalCount { teamsWithCount, err = c.App.GetAllPrivateTeamsPageWithCount(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } else { teams, err = c.App.GetAllPrivateTeamsPage(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } } else if listPublic { if c.Params.IncludeTotalCount { teamsWithCount, err = c.App.GetAllPublicTeamsPageWithCount(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } else { teams, err = c.App.GetAllPublicTeamsPage(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } } else { // The user doesn't have permissions to list private as well as public teams. err = model.NewAppError("getAllTeams", "api.team.get_all_teams.insufficient_permissions", nil, "", http.StatusForbidden) } if err != nil { c.Err = err return } c.App.SanitizeTeams(*c.App.Session(), teams) var resBody []byte if c.Params.IncludeTotalCount { resBody = model.TeamsWithCountToJson(teamsWithCount) } else { resBody = []byte(model.TeamListToJson(teams)) } w.Write(resBody) } func
(c *Context, w http.ResponseWriter, r *http.Request) { props := model.TeamSearchFromJson(r.Body) if props == nil { c.SetInvalidParam("team_search") return } var teams []*model.Team var totalCount int64 var err *model.AppError if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) && c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { teams, totalCount, err = c.App.SearchAllTeams(props) } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) { if props.Page != nil || props.PerPage != nil { c.Err = model.NewAppError("searchTeams", "api.team.search_teams.pagination_not_implemented.private_team_search", nil, "", http.StatusNotImplemented) return } teams, err = c.App.SearchPrivateTeams(props.Term) } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { if props.Page != nil || props.PerPage != nil { c.Err = model.NewAppError("searchTeams", "api.team.search_teams.pagination_not_implemented.public_team_search", nil, "", http.StatusNotImplemented) return } teams, err = c.App.SearchPublicTeams(props.Term) } else { teams = []*model.Team{} } if err != nil { c.Err = err return } c.App.SanitizeTeams(*c.App.Session(), teams) var payload []byte if props.Page != nil && props.PerPage != nil { twc := &model.TeamsWithCount{Teams: teams, TotalCount: totalCount} payload = model.TeamsWithCountToJson(twc) } else { payload = []byte(model.TeamListToJson(teams)) } w.Write(payload) } func teamExists(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamName() if c.Err != nil { return } team, err := c.App.GetTeamByName(c.Params.TeamName) if err != nil && err.StatusCode != http.StatusNotFound { c.Err = err return } exists := false if team != nil { var teamMember *model.TeamMember teamMember, err = c.App.GetTeamMember(team.Id, c.App.Session().UserId) if err != nil && err.StatusCode != http.StatusNotFound { c.Err = err return } // Verify that the user can see the team (be a member or have the permission to list the team) if (teamMember != nil && teamMember.DeleteAt == 0) || (team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS)) || (!team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS)) { exists = true } } resp := map[string]bool{"exists": exists} w.Write([]byte(model.MapBoolToJson(resp))) } func importTeam(c *Context, w http.ResponseWriter, r *http.Request) { if c.App.Srv().License() != nil && *c.App.Srv().License().Features.Cloud { c.Err = model.NewAppError("importTeam", "api.restricted_system_admin", nil, "", http.StatusForbidden) return } c.RequireTeamId() if c.Err != nil { return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_IMPORT_TEAM) { c.SetPermissionError(model.PERMISSION_IMPORT_TEAM) return } if err := r.ParseMultipartForm(MaximumBulkImportSize); err != nil { c.Err = model.NewAppError("importTeam", "api.team.import_team.parse.app_error", nil, err.Error(), http.StatusInternalServerError) return } importFromArray, ok := r.MultipartForm.Value["importFrom"] if !ok || len(importFromArray) < 1 { c.Err = model.NewAppError("importTeam", "api.team.import_team.no_import_from.app_error", nil, "", http.StatusBadRequest) return } importFrom := importFromArray[0] fileSizeStr, ok := r.MultipartForm.Value["filesize"] if !ok || len(fileSizeStr) < 1 { c.Err = model.NewAppError("importTeam", "api.team.import_team.unavailable.app_error", nil, "", http.StatusBadRequest) return } fileSize, err := strconv.ParseInt(fileSizeStr[0], 10, 64) if err != nil { c.Err = model.NewAppError("importTeam", "api.team.import_team.integer.app_error", nil, "", http.StatusBadRequest) return } fileInfoArray, ok := r.MultipartForm.File["file"] if !ok { c.Err = model.NewAppError("importTeam", "api.team.import_team.no_file.app_error", nil, "", http.StatusBadRequest) return } if len(fileInfoArray) <= 0 { c.Err = model.NewAppError("importTeam", "api.team.import_team.array.app_error", nil, "", http.StatusBadRequest) return } auditRec := c.MakeAuditRecord("importTeam", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) fileInfo := fileInfoArray[0] fileData, err := fileInfo.Open() if err != nil { c.Err = model.NewAppError("importTeam", "api.team.import_team.open.app_error", nil, err.Error(), http.StatusBadRequest) return } defer fileData.Close() auditRec.AddMeta("filename", fileInfo.Filename) auditRec.AddMeta("filesize", fileSize) auditRec.AddMeta("from", importFrom) var log *bytes.Buffer data := map[string]string{} switch importFrom { case "slack": var err *model.AppError if err, log = c.App.SlackImport(fileData, fileSize, c.Params.TeamId); err != nil { c.Err = err c.Err.StatusCode = http.StatusBadRequest } data["results"] = base64.StdEncoding.EncodeToString(log.Bytes()) default: c.Err = model.NewAppError("importTeam", "api.team.import_team.unknown_import_from.app_error", nil, "", http.StatusBadRequest) } if c.Err != nil { w.WriteHeader(c.Err.StatusCode) return } auditRec.Success() w.Write([]byte(model.MapToJson(data))) } func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { graceful := r.URL.Query().Get("graceful") != "" c.RequireTeamId() if c.Err != nil { return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_INVITE_USER) { c.SetPermissionError(model.PERMISSION_INVITE_USER) return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { c.SetPermissionError(model.PERMISSION_INVITE_USER) return } emailList := model.ArrayFromJson(r.Body) for i := range emailList { emailList[i] = strings.ToLower(emailList[i]) } if len(emailList) == 0 { c.SetInvalidParam("user_email") return } auditRec := c.MakeAuditRecord("inviteUsersToTeam", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) auditRec.AddMeta("count", len(emailList)) auditRec.AddMeta("emails", emailList) if graceful { cloudUserLimit := *c.App.Config().ExperimentalSettings.CloudUserLimit var invitesOverLimit []*model.EmailInviteWithError if c.App.Srv().License() != nil && *c.App.Srv().License().Features.Cloud && cloudUserLimit > 0 && c.IsSystemAdmin() { subscription, subErr := c.App.Cloud().GetSubscription() if subErr != nil { c.Err = subErr return } if subscription == nil || subscription.IsPaidTier != "true" { emailList, invitesOverLimit, _ = c.App.GetErrorListForEmailsOverLimit(emailList, cloudUserLimit) } } var invitesWithError []*model.EmailInviteWithError var err *model.AppError if emailList != nil { invitesWithError, err = c.App.InviteNewUsersToTeamGracefully(emailList, c.Params.TeamId, c.App.Session().UserId) } if len(invitesOverLimit) > 0 { invitesWithError = append(invitesWithError, invitesOverLimit...) } if invitesWithError != nil { errList := make([]string, 0, len(invitesWithError)) for _, inv := range invitesWithError { if inv.Error != nil { errList = append(errList, model.EmailInviteWithErrorToString(inv)) } } auditRec.AddMeta("errors", errList) } if err != nil { c.Err = err return } // in graceful mode we return both the successful ones and the failed ones w.Write([]byte(model.EmailInviteWithErrorToJson(invitesWithError))) } else { err := c.App.InviteNewUsersToTeam(emailList, c.Params.TeamId, c.App.Session().UserId) if err != nil { c.Err = err return } ReturnStatusOK(w) } auditRec.Success() } func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) { graceful := r.URL.Query().Get("graceful") != "" if c.App.Srv().License() == nil { c.Err = model.NewAppError("Api4.InviteGuestsToChannels", "api.team.invate_guests_to_channels.license.error", nil, "", http.StatusNotImplemented) return } if !*c.App.Config().GuestAccountsSettings.Enable { c.Err = model.NewAppError("Api4.InviteGuestsToChannels", "api.team.invate_guests_to_channels.disabled.error", nil, "", http.StatusNotImplemented) return } c.RequireTeamId() if c.Err != nil { return } auditRec := c.MakeAuditRecord("inviteGuestsToChannels", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_INVITE_GUEST) { c.SetPermissionError(model.PERMISSION_INVITE_GUEST) return } guestsInvite := model.GuestsInviteFromJson(r.Body) for i, email := range guestsInvite.Emails { guestsInvite.Emails[i] = strings.ToLower(email) } if err := guestsInvite.IsValid(); err != nil { c.Err = err return } auditRec.AddMeta("email_count", len(guestsInvite.Emails)) auditRec.AddMeta("emails", guestsInvite.Emails) auditRec.AddMeta("channel_count", len(guestsInvite.Channels)) auditRec.AddMeta("channels", guestsInvite.Channels) if graceful { cloudUserLimit := *c.App.Config().ExperimentalSettings.CloudUserLimit var invitesOverLimit []*model.EmailInviteWithError if c.App.Srv().License() != nil && *c.App.Srv().License().Features.Cloud && cloudUserLimit > 0 && c.IsSystemAdmin() { subscription, subErr := c.App.Cloud().GetSubscription() if subErr != nil { c.Err = subErr return } if subscription == nil || subscription.IsPaidTier != "true" { guestsInvite.Emails, invitesOverLimit, _ = c.App.GetErrorListForEmailsOverLimit(guestsInvite.Emails, cloudUserLimit) } } var invitesWithError []*model.EmailInviteWithError var err *model.AppError if guestsInvite.Emails != nil { invitesWithError, err = c.App.InviteGuestsToChannelsGracefully(c.Params.TeamId, guestsInvite, c.App.Session().UserId) } if len(invitesOverLimit) > 0 { invitesWithError = append(invitesWithError, invitesOverLimit...) } if err != nil { errList := make([]string, 0, len(invitesWithError)) for _, inv := range invitesWithError { errList = append(errList, model.EmailInviteWithErrorToString(inv)) } auditRec.AddMeta("errors", errList) c.Err = err return } // in graceful mode we return both the successful ones and the failed ones w.Write([]byte(model.EmailInviteWithErrorToJson(invitesWithError))) } else { err := c.App.InviteGuestsToChannels(c.Params.TeamId, guestsInvite, c.App.Session().UserId) if err != nil { c.Err = err return } ReturnStatusOK(w) } auditRec.Success() } func getInviteInfo(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireInviteId() if c.Err != nil { return } team, err := c.App.GetTeamByInviteId(c.Params.InviteId) if err != nil { c.Err = err return } if team.Type != model.TEAM_OPEN { c.Err = model.NewAppError("getInviteInfo", "api.team.get_invite_info.not_open_team", nil, "id="+c.Params.InviteId, http.StatusForbidden) return } result := map[string]string{} result["display_name"] = team.DisplayName result["description"] = team.Description result["name"] = team.Name result["id"] = team.Id w.Write([]byte(model.MapToJson(result))) } func invalidateAllEmailInvites(c *Context, w http.ResponseWriter, r *http.Request) { if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION) return } auditRec := c.MakeAuditRecord("invalidateAllEmailInvites", audit.Fail) defer c.LogAuditRec(auditRec) if err := c.App.InvalidateAllEmailInvites(); err != nil { c.Err = err return } auditRec.Success() ReturnStatusOK(w) } func getTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } team, err := c.App.GetTeam(c.Params.TeamId) if err != nil { c.Err = err return } if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) && (team.Type != model.TEAM_OPEN || !team.AllowOpenInvite) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } etag := strconv.FormatInt(team.LastTeamIconUpdate, 10) if c.HandleEtag(etag, "Get Team Icon", w, r) { return } img, err := c.App.GetTeamIcon(team) if err != nil { c.Err = err return } w.Header().Set("Content-Type", "image/png") w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%v, private", 24*60*60)) // 24 hrs w.Header().Set(model.HEADER_ETAG_SERVER, etag) w.Write(img) } func setTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { defer io.Copy(ioutil.Discard, r.Body) c.RequireTeamId() if c.Err != nil { return } auditRec := c.MakeAuditRecord("setTeamIcon", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize { c.Err = model.NewAppError("setTeamIcon", "api.team.set_team_icon.too_large.app_error", nil, "", http.StatusBadRequest) return } if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil { c.Err = model.NewAppError("setTeamIcon", "api.team.set_team_icon.parse.app_error", nil, err.Error(), http.StatusBadRequest) return } m := r.MultipartForm imageArray, ok := m.File["image"] if !ok { c.Err = model.NewAppError("setTeamIcon", "api.team.set_team_icon.no_file.app_error", nil, "", http.StatusBadRequest) return } if len(imageArray) <= 0 { c.Err = model.NewAppError("setTeamIcon", "api.team.set_team_icon.array.app_error", nil, "", http.StatusBadRequest) return } imageData := imageArray[0] if err := c.App.SetTeamIcon(c.Params.TeamId, imageData); err != nil { c.Err = err return } auditRec.Success() c.LogAudit("") ReturnStatusOK(w) } func removeTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } auditRec := c.MakeAuditRecord("removeTeamIcon", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } if err := c.App.RemoveTeamIcon(c.Params.TeamId); err != nil { c.Err = err return } auditRec.Success() c.LogAudit("") ReturnStatusOK(w) } func updateTeamScheme(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } schemeID := model.SchemeIDFromJson(r.Body) if schemeID == nil || (!model.IsValidId(*schemeID) && *schemeID != "") { c.SetInvalidParam("scheme_id") return } auditRec := c.MakeAuditRecord("updateTeamScheme", audit.Fail) defer c.LogAuditRec(auditRec) if c.App.Srv().License() == nil { c.Err = model.NewAppError("Api4.UpdateTeamScheme", "api.team.update_team_scheme.license.error", nil, "", http.StatusNotImplemented) return } if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) return } if *schemeID != "" { scheme, err := c.App.GetScheme(*schemeID) if err != nil { c.Err = err return } auditRec.AddMeta("scheme", scheme) if scheme.Scope != model.SCHEME_SCOPE_TEAM { c.Err = model.NewAppError("Api4.UpdateTeamScheme", "api.team.update_team_scheme.scheme_scope.error", nil, "", http.StatusBadRequest) return } } team, err := c.App.GetTeam(c.Params.TeamId) if err != nil { c.Err = err return } auditRec.AddMeta("team", team) team.SchemeId = schemeID _, err = c.App.UpdateTeamScheme(team) if err != nil { c.Err = err return } auditRec.Success() ReturnStatusOK(w) } func teamMembersMinusGroupMembers(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireTeamId() if c.Err != nil { return } groupIDsParam := groupIDsQueryParamRegex.ReplaceAllString(c.Params.GroupIDs, "") if len(groupIDsParam) < 26 { c.SetInvalidParam("group_ids") return } groupIDs := []string{} for _, gid := range strings.Split(c.Params.GroupIDs, ",") { if !model.IsValidId(gid) { c.SetInvalidParam("group_ids") return } groupIDs = append(groupIDs, gid) } if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) return } users, totalCount, err := c.App.TeamMembersMinusGroupMembers( c.Params.TeamId, groupIDs, c.Params.Page, c.Params.PerPage, ) if err != nil { c.Err = err return } b, marshalErr := json.Marshal(&model.UsersWithGroupsAndCount{ Users: users, Count: totalCount, }) if marshalErr != nil { c.Err = model.NewAppError("Api4.teamMembersMinusGroupMembers", "api.marshal_error", nil, marshalErr.Error(), http.StatusInternalServerError) return } w.Write(b) }
searchTeams
index.tsx
import * as React from 'react'; import { Grid } from '../index'; import { create } from 'react-test-renderer'; it('renders correctly', () => { const grid = create(<Grid blocks={[]} />).toJSON();
});
expect(grid).toMatchSnapshot();
error_meta.rs
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// All possible error types for this service. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum Error { /// <p>You do not have sufficient access to perform this action.</p> AccessDeniedException(crate::error::AccessDeniedException), /// <p>The input you provided is invalid.</p> BadRequestException(crate::error::BadRequestException), /// <p>An internal service error occurred.</p> InternalServerException(crate::error::InternalServerException), /// <p>The requested resource does not exist, or access was denied.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>You exceeded the maximum number of requests.</p> ThrottlingException(crate::error::ThrottlingException), /// An unhandled error occurred. Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::AccessDeniedException(inner) => inner.fmt(f), Error::BadRequestException(inner) => inner.fmt(f), Error::InternalServerException(inner) => inner.fmt(f), Error::ResourceNotFoundException(inner) => inner.fmt(f), Error::ThrottlingException(inner) => inner.fmt(f), Error::Unhandled(inner) => inner.fmt(f), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::AddProfileKeyError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::AddProfileKeyError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::AddProfileKeyErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::AddProfileKeyErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::AddProfileKeyErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::AddProfileKeyErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::AddProfileKeyErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::AddProfileKeyErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::CreateDomainError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::CreateDomainError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::CreateDomainErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::CreateDomainErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::CreateDomainErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::CreateDomainErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::CreateDomainErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::CreateDomainErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::CreateProfileError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::CreateProfileError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::CreateProfileErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::CreateProfileErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::CreateProfileErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::CreateProfileErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::CreateProfileErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::CreateProfileErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::DeleteDomainError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::DeleteDomainError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DeleteDomainErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::DeleteDomainErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::DeleteDomainErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::DeleteDomainErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DeleteDomainErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::DeleteDomainErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::DeleteIntegrationError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::DeleteIntegrationError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DeleteIntegrationErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::DeleteIntegrationErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::DeleteIntegrationErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::DeleteIntegrationErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DeleteIntegrationErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::DeleteIntegrationErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::DeleteProfileError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::DeleteProfileError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DeleteProfileErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::DeleteProfileErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::DeleteProfileErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::DeleteProfileErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DeleteProfileErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::DeleteProfileErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::DeleteProfileKeyError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::DeleteProfileKeyError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DeleteProfileKeyErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::DeleteProfileKeyErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::DeleteProfileKeyErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::DeleteProfileKeyErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DeleteProfileKeyErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::DeleteProfileKeyErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::DeleteProfileObjectError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::DeleteProfileObjectError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DeleteProfileObjectErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::DeleteProfileObjectErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::DeleteProfileObjectErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::DeleteProfileObjectErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DeleteProfileObjectErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::DeleteProfileObjectErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::DeleteProfileObjectTypeError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::DeleteProfileObjectTypeError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DeleteProfileObjectTypeErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::DeleteProfileObjectTypeErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::DeleteProfileObjectTypeErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::DeleteProfileObjectTypeErrorKind::ResourceNotFoundException( inner, ) => Error::ResourceNotFoundException(inner), crate::error::DeleteProfileObjectTypeErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::DeleteProfileObjectTypeErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::GetDomainError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::GetDomainError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::GetDomainErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::GetDomainErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::GetDomainErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::GetDomainErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::GetDomainErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::GetDomainErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::GetIntegrationError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::GetIntegrationError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::GetIntegrationErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::GetIntegrationErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::GetIntegrationErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::GetIntegrationErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::GetIntegrationErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::GetIntegrationErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::GetMatchesError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::GetMatchesError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::GetMatchesErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::GetMatchesErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::GetMatchesErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::GetMatchesErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::GetMatchesErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::GetMatchesErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::GetProfileObjectTypeError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::GetProfileObjectTypeError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::GetProfileObjectTypeErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::GetProfileObjectTypeErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::GetProfileObjectTypeErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::GetProfileObjectTypeErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::GetProfileObjectTypeErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::GetProfileObjectTypeErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::GetProfileObjectTypeTemplateError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::GetProfileObjectTypeTemplateError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::GetProfileObjectTypeTemplateErrorKind::AccessDeniedException( inner, ) => Error::AccessDeniedException(inner), crate::error::GetProfileObjectTypeTemplateErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::GetProfileObjectTypeTemplateErrorKind::InternalServerException( inner, ) => Error::InternalServerException(inner), crate::error::GetProfileObjectTypeTemplateErrorKind::ResourceNotFoundException( inner, ) => Error::ResourceNotFoundException(inner), crate::error::GetProfileObjectTypeTemplateErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::GetProfileObjectTypeTemplateErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::ListAccountIntegrationsError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::ListAccountIntegrationsError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListAccountIntegrationsErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::ListAccountIntegrationsErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::ListAccountIntegrationsErrorKind::InternalServerException(inner) =>
crate::error::ListAccountIntegrationsErrorKind::ResourceNotFoundException( inner, ) => Error::ResourceNotFoundException(inner), crate::error::ListAccountIntegrationsErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::ListAccountIntegrationsErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::ListDomainsError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::ListDomainsError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListDomainsErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::ListDomainsErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::ListDomainsErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::ListDomainsErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::ListDomainsErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::ListDomainsErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::ListIntegrationsError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::ListIntegrationsError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListIntegrationsErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::ListIntegrationsErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::ListIntegrationsErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::ListIntegrationsErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::ListIntegrationsErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::ListIntegrationsErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::ListProfileObjectsError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::ListProfileObjectsError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListProfileObjectsErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::ListProfileObjectsErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::ListProfileObjectsErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::ListProfileObjectsErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::ListProfileObjectsErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::ListProfileObjectsErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::ListProfileObjectTypesError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::ListProfileObjectTypesError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListProfileObjectTypesErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::ListProfileObjectTypesErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::ListProfileObjectTypesErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::ListProfileObjectTypesErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::ListProfileObjectTypesErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::ListProfileObjectTypesErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::ListProfileObjectTypeTemplatesError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError< crate::error::ListProfileObjectTypeTemplatesError, R, >, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::ListProfileObjectTypeTemplatesErrorKind::AccessDeniedException(inner) => Error::AccessDeniedException(inner), crate::error::ListProfileObjectTypeTemplatesErrorKind::BadRequestException(inner) => Error::BadRequestException(inner), crate::error::ListProfileObjectTypeTemplatesErrorKind::InternalServerException(inner) => Error::InternalServerException(inner), crate::error::ListProfileObjectTypeTemplatesErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::ListProfileObjectTypeTemplatesErrorKind::ThrottlingException(inner) => Error::ThrottlingException(inner), crate::error::ListProfileObjectTypeTemplatesErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::ListTagsForResourceError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::ListTagsForResourceError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListTagsForResourceErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::ListTagsForResourceErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::ListTagsForResourceErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::ListTagsForResourceErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::MergeProfilesError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::MergeProfilesError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::MergeProfilesErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::MergeProfilesErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::MergeProfilesErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::MergeProfilesErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::MergeProfilesErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::PutIntegrationError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::PutIntegrationError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::PutIntegrationErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::PutIntegrationErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::PutIntegrationErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::PutIntegrationErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::PutIntegrationErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::PutIntegrationErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::PutProfileObjectError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::PutProfileObjectError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::PutProfileObjectErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::PutProfileObjectErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::PutProfileObjectErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::PutProfileObjectErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::PutProfileObjectErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::PutProfileObjectErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::PutProfileObjectTypeError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from( err: aws_smithy_http::result::SdkError<crate::error::PutProfileObjectTypeError, R>, ) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::PutProfileObjectTypeErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::PutProfileObjectTypeErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::PutProfileObjectTypeErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::PutProfileObjectTypeErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::PutProfileObjectTypeErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::PutProfileObjectTypeErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::SearchProfilesError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::SearchProfilesError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::SearchProfilesErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::SearchProfilesErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::SearchProfilesErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::SearchProfilesErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::SearchProfilesErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::SearchProfilesErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::TagResourceError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::TagResourceError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::TagResourceErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::TagResourceErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::TagResourceErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::TagResourceErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::UntagResourceError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::UntagResourceError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::UntagResourceErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::UntagResourceErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::UntagResourceErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::UntagResourceErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::UpdateDomainError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::UpdateDomainError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::UpdateDomainErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::UpdateDomainErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::UpdateDomainErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::UpdateDomainErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::UpdateDomainErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::UpdateDomainErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl<R> From<aws_smithy_http::result::SdkError<crate::error::UpdateProfileError, R>> for Error where R: Send + Sync + std::fmt::Debug + 'static, { fn from(err: aws_smithy_http::result::SdkError<crate::error::UpdateProfileError, R>) -> Self { match err { aws_smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::UpdateProfileErrorKind::AccessDeniedException(inner) => { Error::AccessDeniedException(inner) } crate::error::UpdateProfileErrorKind::BadRequestException(inner) => { Error::BadRequestException(inner) } crate::error::UpdateProfileErrorKind::InternalServerException(inner) => { Error::InternalServerException(inner) } crate::error::UpdateProfileErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::UpdateProfileErrorKind::ThrottlingException(inner) => { Error::ThrottlingException(inner) } crate::error::UpdateProfileErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl std::error::Error for Error {}
{ Error::InternalServerException(inner) }
test_payment_chargebacks.py
from mollie.api.objects.chargeback import Chargeback from .utils import assert_list_object PAYMENT_ID = 'tr_7UhSN1zuXS' CHARGEBACK_ID = 'chb_n9z0tp' def test_get_payment_chargebacks_by_payment_id(client, response): """Get chargebacks relevant to payment by payment id.""" response.get('https://api.mollie.com/v2/payments/%s/chargebacks' % PAYMENT_ID, 'chargebacks_list') chargebacks = client.payment_chargebacks.with_parent_id(PAYMENT_ID).list() assert_list_object(chargebacks, Chargeback) def test_get_single_payment_chargeback(client, response): """Get a single chargeback relevant to payment by payment id.""" response.get('https://api.mollie.com/v2/payments/%s/chargebacks/%s' % (PAYMENT_ID, CHARGEBACK_ID), 'chargeback_single') chargeback = client.payment_chargebacks.with_parent_id(PAYMENT_ID).get(CHARGEBACK_ID) assert isinstance(chargeback, Chargeback) assert chargeback.id == CHARGEBACK_ID assert chargeback.amount == {'currency': 'USD', 'value': '43.38'}
def test_list_payment_chargebacks_by_payment_object(client, response): """Get a list of chargebacks relevant to payment object.""" response.get('https://api.mollie.com/v2/payments/%s/chargebacks' % PAYMENT_ID, 'chargebacks_list') response.get('https://api.mollie.com/v2/payments/%s' % PAYMENT_ID, 'payment_single') payment = client.payments.get(PAYMENT_ID) chargebacks = client.payment_chargebacks.on(payment).list() assert_list_object(chargebacks, Chargeback) def test_get_single_payment_chargeback_by_payment_object(client, response): """Get a single chargeback relevant to payment object.""" response.get('https://api.mollie.com/v2/payments/%s/chargebacks/%s' % (PAYMENT_ID, CHARGEBACK_ID), 'chargeback_single') response.get('https://api.mollie.com/v2/payments/%s' % PAYMENT_ID, 'payment_single') payment = client.payments.get(PAYMENT_ID) chargeback = client.payment_chargebacks.on(payment).get(CHARGEBACK_ID) assert isinstance(chargeback, Chargeback) assert chargeback.payment_id == PAYMENT_ID
assert chargeback.settlement_amount == {'currency': 'EUR', 'value': '-35.07'} assert chargeback.created_at == '2018-03-14T17:00:52.0Z' assert chargeback.reversed_at == '2018-03-14T17:00:55.0Z' assert chargeback.payment_id == PAYMENT_ID
conn_test.go
// Copyright 2019-present Facebook Inc. All rights reserved. // This source code is licensed under the Apache 2.0 license found // in the LICENSE file in the root directory of this source tree. package ws import ( "context" "net/http" "net/http/httptest" "strconv" "sync" "testing" "entgo.io/ent/dialect/gremlin" "entgo.io/ent/dialect/gremlin/encoding/graphson" "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type conn struct{ *websocket.Conn } func (c conn) ReadRequest() (*gremlin.Request, error) { _, data, err := c.ReadMessage() if err != nil { return nil, err } var req gremlin.Request if err := graphson.Unmarshal(data[data[0]+1:], &req); err != nil { return nil, err } return &req, nil } func (c conn) WriteResponse(rsp *gremlin.Response) error { data, err := graphson.Marshal(rsp) if err != nil { return err } return c.WriteMessage(websocket.BinaryMessage, data) } func serve(handler func(conn)) *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { upgrader := websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024} c, _ := upgrader.Upgrade(w, r, nil) defer c.Close() handler(conn{c}) for { _, _, err := c.ReadMessage() if err != nil { break } } })) } func TestConnectClosure(t *testing.T) { var wg sync.WaitGroup wg.Add(1) defer wg.Wait() srv := serve(func(conn conn) { defer wg.Done() _, _, err := conn.ReadMessage() assert.True(t, websocket.IsCloseError(err, websocket.CloseNormalClosure)) }) defer srv.Close() conn, err := DefaultDialer.Dial("ws://" + srv.Listener.Addr().String()) require.NoError(t, err) err = conn.Close() assert.NoError(t, err) _, err = conn.Execute(context.Background(), gremlin.NewEvalRequest("g.V()")) assert.EqualError(t, err, ErrConnClosed.Error()) } func TestSimpleQuery(t *testing.T) { srv := serve(func(conn conn) { typ, data, err := conn.ReadMessage() require.NoError(t, err) assert.Equal(t, websocket.BinaryMessage, typ) var req gremlin.Request err = graphson.Unmarshal(data[data[0]+1:], &req) require.NoError(t, err) assert.Equal(t, "g.V()", req.Arguments["gremlin"]) rsp := gremlin.Response{RequestID: req.RequestID} rsp.Status.Code = gremlin.StatusNoContent err = conn.WriteResponse(&rsp) require.NoError(t, err) }) defer srv.Close() conn, err := DefaultDialer.Dial("ws://" + srv.Listener.Addr().String()) require.NoError(t, err) defer assert.Condition(t, func() bool { return assert.NoError(t, conn.Close()) }) rsp, err := conn.Execute(context.Background(), gremlin.NewEvalRequest("g.V()")) assert.NoError(t, err) require.NotNil(t, rsp) assert.Equal(t, gremlin.StatusNoContent, rsp.Status.Code) } func TestDuplicateRequest(t *testing.T) { // skip until flakiness will be fixed. t.SkipNow() srv := serve(func(conn conn) { req, err := conn.ReadRequest() require.NoError(t, err) rsp := gremlin.Response{RequestID: req.RequestID} rsp.Status.Code = gremlin.StatusNoContent err = conn.WriteResponse(&rsp) require.NoError(t, err) }) defer srv.Close() conn, err := DefaultDialer.Dial("ws://" + srv.Listener.Addr().String()) require.NoError(t, err) defer conn.Close() var errors [2]error req := gremlin.NewEvalRequest("g.V()") var wg sync.WaitGroup wg.Add(len(errors)) for i := range errors { go func(i int) { _, errors[i] = conn.Execute(context.Background(), req) wg.Done() }(i) } wg.Wait() err = errors[0] if err == nil { err = errors[1] } assert.EqualError(t, err, ErrDuplicateRequest.Error()) } func TestConnectCancellation(t *testing.T) { srv := serve(func(conn) {}) defer srv.Close() ctx, cancel := context.WithCancel(context.Background()) cancel() conn, err := DefaultDialer.DialContext(ctx, "ws://"+srv.Listener.Addr().String()) assert.Error(t, err) assert.Nil(t, conn) } func TestQueryCancellation(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) srv := serve(func(conn conn) { if _, _, err := conn.ReadMessage(); err == nil { cancel() } }) defer srv.Close() conn, err := DefaultDialer.Dial("ws://" + srv.Listener.Addr().String()) require.NoError(t, err) defer conn.Close() _, err = conn.Execute(ctx, gremlin.NewEvalRequest("g.E()")) assert.EqualError(t, err, context.Canceled.Error()) } func TestBadResponse(t *testing.T) { tests := []struct { name string mangle func(*gremlin.Response) *gremlin.Response }{ { name: "NoStatus", mangle: func(rsp *gremlin.Response) *gremlin.Response { return rsp }, }, { name: "Malformed", mangle: func(rsp *gremlin.Response) *gremlin.Response { rsp.Status.Code = gremlin.StatusMalformedRequest rsp.Status.Message = "bad request" return rsp }, }, { name: "Unknown", mangle: func(rsp *gremlin.Response) *gremlin.Response { rsp.Status.Code = 424242 return rsp }, }, } srv := serve(func(conn conn) { for { req, err := conn.ReadRequest() if err != nil { break } idx, err := strconv.ParseInt(req.Arguments["gremlin"].(string), 10, 0) require.NoError(t, err) err = conn.WriteResponse(tests[idx].mangle(&gremlin.Response{RequestID: req.RequestID})) require.NoError(t, err) } }) defer srv.Close() conn, err := DefaultDialer.Dial("ws://" + srv.Listener.Addr().String()) require.NoError(t, err) defer conn.Close() var wg sync.WaitGroup wg.Add(len(tests)) ctx := context.Background() for i, tc := range tests { i, tc := i, tc t.Run(tc.name, func(t *testing.T) { defer wg.Done() rsp, err := conn.Execute(ctx, gremlin.NewEvalRequest(strconv.FormatInt(int64(i), 10))) assert.NoError(t, err) assert.True(t, rsp.IsErr()) }) } wg.Wait() } func TestServerHangup(t *testing.T) { // skip until flakiness will be fixed. t.SkipNow() srv := serve(func(conn conn) { _ = conn.Close() }) defer srv.Close() conn, err := DefaultDialer.Dial("ws://" + srv.Listener.Addr().String()) require.NoError(t, err) defer conn.Close() _, err = conn.Execute(context.Background(), gremlin.NewEvalRequest("g.V()")) assert.EqualError(t, err, ErrConnClosed.Error()) assert.Error(t, conn.ctx.Err()) } func TestCanceledLongRequest(t *testing.T) { // skip until flakiness will be fixed. t.SkipNow() ctx, cancel := context.WithCancel(context.Background()) srv := serve(func(conn conn) { var responses [3]*gremlin.Response for i := 0; i < len(responses); i++ { req, err := conn.ReadRequest() require.NoError(t, err) rsp := gremlin.Response{RequestID: req.RequestID} rsp.Status.Code = gremlin.StatusSuccess rsp.Result.Data = graphson.RawMessage(`"ok"`) responses[i] = &rsp } cancel() responses[0], responses[2] = responses[2], responses[0] for i := 0; i < len(responses); i++ { err := conn.WriteResponse(responses[i]) require.NoError(t, err) } }) defer srv.Close() conn, err := DefaultDialer.Dial("ws://" + srv.Listener.Addr().String()) require.NoError(t, err) defer conn.Close() var wg sync.WaitGroup wg.Add(3) defer wg.Wait() for i := 0; i < 3; i++ { go func(ctx context.Context, idx int) { defer wg.Done() rsp, err := conn.Execute(ctx, gremlin.NewEvalRequest("g.V()")) if idx > 0
else { assert.EqualError(t, err, context.Canceled.Error()) } }(ctx, i) ctx = context.Background() } } func TestPartialResponse(t *testing.T) { type kv struct { Key string Value int } kvs := []kv{ {"one", 1}, {"two", 2}, {"three", 3}, } srv := serve(func(conn conn) { req, err := conn.ReadRequest() require.NoError(t, err) for i := range kvs { data, err := graphson.Marshal([]kv{kvs[i]}) require.NoError(t, err) rsp := gremlin.Response{RequestID: req.RequestID} rsp.Result.Data = graphson.RawMessage(data) if i != len(kvs)-1 { rsp.Status.Code = gremlin.StatusPartialContent } else { rsp.Status.Code = gremlin.StatusSuccess } err = conn.WriteResponse(&rsp) require.NoError(t, err) } }) defer srv.Close() conn, err := DefaultDialer.Dial("ws://" + srv.Listener.Addr().String()) require.NoError(t, err) defer conn.Close() rsp, err := conn.Execute(context.Background(), gremlin.NewEvalRequest("g.E()")) assert.NoError(t, err) var result []kv err = graphson.Unmarshal(rsp.Result.Data, &result) require.NoError(t, err) assert.Equal(t, kvs, result) } func TestAuthentication(t *testing.T) { user, pass := "username", "password" srv := serve(func(conn conn) { req, err := conn.ReadRequest() require.NoError(t, err) rsp := gremlin.Response{RequestID: req.RequestID} rsp.Status.Code = gremlin.StatusAuthenticate err = conn.WriteResponse(&rsp) require.NoError(t, err) areq, err := conn.ReadRequest() require.NoError(t, err) var acreds gremlin.Credentials err = acreds.UnmarshalText([]byte(areq.Arguments["sasl"].(string))) assert.NoError(t, err) areq.Arguments["sasl"] = acreds assert.Equal(t, gremlin.NewAuthRequest(req.RequestID, user, pass), areq) rsp = gremlin.Response{RequestID: req.RequestID} rsp.Status.Code = gremlin.StatusNoContent err = conn.WriteResponse(&rsp) require.NoError(t, err) }) defer srv.Close() dialer := *DefaultDialer dialer.user = user dialer.pass = pass client, err := dialer.Dial("ws://" + srv.Listener.Addr().String()) require.NoError(t, err) defer client.Close() _, err = client.Execute(context.Background(), gremlin.NewEvalRequest("g.E().drop()")) assert.NoError(t, err) }
{ assert.NoError(t, err) assert.EqualValues(t, []byte(`"ok"`), rsp.Result.Data) }
test_hostname.py
import util def run_hostname(stack, value, value2): name = util.rioRun(stack, value, value2, 'nginx')
def rio_chk(stack, sname): fullName = (f"{stack}/{sname}") inspect = util.rioInspect(fullName) return inspect['hostname'] def kube_chk(stack, service): fullName = "%s/%s" % (stack, service) id = util.rioInspect(fullName, "id") namespace = id.split(":")[0] obj = util.kubectl(namespace, "deployment", service) cnt = obj['spec']['template']['spec'] results = cnt['hostname'] return results def test_hostname1(stack): value = "--hostname" value2 = "chost" service_name = run_hostname(stack, value, value2) rio_got = rio_chk(stack, service_name) assert rio_got == "chost" kube_got = kube_chk(stack, service_name) assert kube_got == "chost"
return name
uiFunctions.js
/** * @file uiFunctions.js * * Copyright (c) 2018 Pedro Sequeira ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @version 1.0 * @author Pedro Sequeira ([email protected]) * @updated 05/17/2018 * @link https://github.com/pedrodbs/DendrogramViewer * */ // #region Json file loading /** * Reads the json dendrogram data from the given file. * @param {Array} files The files retrieved from the input-file control. The first file is loaded. */ function loadFile(files) { // checks file if (files.length > 0) { const file = files[0]; console.info(`Reading Json dendrogram data from file ${file.name}...`); window.fileName = file.name; // reads file as json const reader = new FileReader(); reader.onload = function (event) { // reads data and loads tree const clusterJsonObj = JSON.parse(event.target.result); window.readData(clusterJsonObj); return true; }; reader.readAsText(file); } return false; } /** * Reads the json dendrogram data from the file provided in the URL parameter. */ function loadFromUrl() { console.info(`Reading Json dendrogram data from file ${window.fileName}...`); d3.json(window.fileName, function (error, clusterJsonObj) { if (error) { console.error(error); return false; } // reads root element from json window.root = clusterJsonObj; // reads data and loads dendrogram window.readData(clusterJsonObj); return true; }); } // #endregion // #region Initialization methods /** * Initializes the whole user interface for the dendrogram area by creating all the SVG elements. */ function initUI() { // creates d3 cluster layout window.cluster = d3.layout.cluster() .size([window.height, window.width - 2 * window.treeMargin]); // adds main svg window.topSvg = d3.select("#container").append("svg") .attr("id", "topSvg"); // adds overall svg window.svg = window.topSvg.append("svg:svg") .attr("id", "innerSvg"); // adds a rectangle as a background window.backgRect = window.svg.append("rect") .attr("id", "backgRect") .attr("width", "100%") .attr("height", "100%") .style("fill", "none"); document.getElementById("color-picker").value = "FFF"; document.getElementById("pick-color-btn").style.color = "black"; // adds threshold line window.threshLine = window.svg.append("line") .attr("class", "threshLine") .attr("id", "threshLine"); // adds scale axis window.scaleSvg = window.svg.append("svg:g") .attr("id", "scaleSvg"); window.scaleLine = window.scaleSvg.append("line") .attr("id", "scaleLine"); // adds color options to select const select = document.getElementById("color-scheme-select"); for (let key in window.colorPaletteOptions) { select.options[select.options.length] = new Option(window.colorPaletteOptions[key], key); } //reads data and initializes graph loadFromUrl(); } /** * Reads all dendrogram / clustering information from the given Json object. * @param {object} clusterJsonObj The Json object containing all the dendrogram / clustering information. */ function readData(clusterJsonObj) { if (window.isNull(clusterJsonObj)) { window.update(); return false; } else { // resets variables window.resetVars(); // sets root window.root = clusterJsonObj; // reads children data window.numClusterLeafs = 0; getChildrenData(clusterJsonObj); // gets min and max dissimilarity/distance window.nodes = window.cluster.nodes(window.root); window.links = window.cluster.links(window.nodes); window.nodes.forEach(function (nd) { if (!isNull(nd.d)) { nd.y = nd.d; if (nd.d > window.dMax) window.dMax = nd.d; if (nd.d < window.dMin) window.dMin = nd.d; } }); window.clusterDistThreshold = window.dMax; console.info(`Dissimilarity in [${window.dMin},${window.dMax}]`); console.info(`Num. cluster leafs: ${window.numClusterLeafs}`); // changes title document.title = `Clustering Dendrogram Visualizer - ${window.fileName}`; // changes sliders ranges document.getElementById("threshold-slider").min = window.dMin; document.getElementById("threshold-slider").max = window.dMax; document.getElementById("threshold-slider").step = (window.dMax - window.dMin) / window.numRangeSteps; document.getElementById("num-clusters-slider").min = 1; document.getElementById("num-clusters-slider").max = window.numClusterLeafs; document.getElementById("num-clusters-slider").step = 1; // define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents var zoomListener = d3.behavior.zoom() .scaleExtent([window.minZoom, Math.max(window.minZoom + 1, window.numClusterLeafs / window.maxZoomFactor)]) .on("zoom", window.onZoom); window.topSvg.call(zoomListener); // sets link data window.svg.selectAll(".link") .data(window.links) .enter().append("path") .attr("class", "link"); // sets node data and translate nodes window.svg.selectAll(".node").remove(); var node = window.svg.selectAll(".node") .data(window.nodes) .enter().append("g") .attr("class", "node"); // adds node's circle and text node.append("circle") .attr("r", window.nodeRadius); node.append("text"); // updates visual elements update(); return true; } } /** * Simply converts the node structural information and that of its children so to be compatible with D3. * @param {object} node The D3 node from which to update the data based on the json information. */ function getChildrenData(node) { // just replace children data from attribute 'c' node.children = node.c; node.c = null; if (!isNull(node.children)) { // iterate over children for (let j in node.children) { getChildrenData(node.children[j]); } // if no chilren, cluster is leaf if (node.children.length === 0) window.numClusterLeafs++; } } // #endregion // #region Update html/ui methods /** * Updates the whole interface. */ function update() { //console.info("Updating elements"); //updates variables based on UI updateVariables(); //updates UI elements dimensions updatePageElements(); //updates tree window.updateDendrogram(); } /** * Updates the variables according to the html UI control values. */ function updateVariables() { //reads all options from the html elements window.showLabels = document.getElementById("labels-chkbox").checked; window.vertLayout = document.getElementById("vert-layout-chkbox").checked; window.grayscale = document.getElementById("grayscale-chkbox").checked; window.straightLinks = document.getElementById("straight-chkbox").checked; window.zoomDragable = document.getElementById("zoom-chkbox").checked; window.labelColor = document.getElementById("pick-color-btn").style.color; } /** * Updates the html UI elements according to the variables. */ function updatePageElements() { // calculates max dimensions const windowDiscount = 20; const optionsWidth = document.getElementById("save-button").offsetWidth + 20; window.width = window.innerWidth - optionsWidth - windowDiscount; window.height = window.innerHeight - windowDiscount; //modifies divs dimensions document.getElementById("options-column").style.width = optionsWidth + "px"; document.getElementById("container").style.width = window.width + "px"; document.getElementById("container").style.height = window.height + "px"; //updates d3 elements window.topSvg.attr("width", window.width).attr("height", window.height); window.svg.attr("width", window.width).attr("height", window.height); window.cluster.size(window.vertLayout ? [window.width - window.treeMargin, window.height] : [window.height - window.treeMargin, window.width]); window.backgRect.style("fill", `#${document.getElementById("color-picker").value}`); window.backgRect.attr("width", window.width) window.backgRect.attr("height", window.height) //updates threshold slider text and value document.getElementById("threshold-slider-value").innerHTML = window.clusterDistThreshold.toFixed(1); document.getElementById("threshold-slider").value = window.clusterDistThreshold; // counts num threshold clusters and update slider window.numThresholdClusters = countThresholdNodes(window.root); document.getElementById("num-clusters-slider-value").innerHTML = window.numThresholdClusters; document.getElementById("num-clusters-slider").value = window.numThresholdClusters; // reads selected palette and create colors const select = document.getElementById("color-scheme-select"); const selectedPalette = select.options[select.selectedIndex].value; window.clusterColors = palette(selectedPalette, Math.max(1, window.numThresholdClusters)).reverse(); } /** * Counts the number of nodes / clusters under the given node whose dissimilarity is below the defined threshold. * @param {object} node The node from which to count the number of chidren. * @returns {Number} The number of nodes / clusters under the given node whose dissimilarity is below the defined threshold. */ function countThresholdNodes(node) { // checks whether cluster is below distance threshold, stops search if (node.d <= window.clusterDistThreshold || isNull(node.children)) { return 1; } var count = 0; for (let j in node.children) { count += countThresholdNodes(node.children[j]); } return count; } // #endregion // #region Update dendrogram methods /** * Updates the dendrogram by first updating the positions, then the tree links, then the colors and finally the node * labels. */ function updateDendrogram() { window.updateAllPositions(); window.updateAllLinks(); window.updateAllColors(); window.updateAllLabels(); } /** * Updates the D3 tree links. */ function updateAllLinks() { if (!window.updateLinks) return; const thirdMargin = window.treeMargin / 3; var twoThirdMargin = thirdMargin * 2; var halfMargin = window.treeMargin / 2; // a line function for the tree's links var line = d3.svg.line() .x(function (point) { return window.vertLayout ? (twoThirdMargin + point.lx) : (halfMargin + point.ly); }) .y(function (point) { return window.vertLayout ? (halfMargin + point.ly) : (twoThirdMargin + point.lx); }); //creates tree diagonal (for children link plotting) const diagonal = window.straightLinks ? function (d) { // vertical layout, build dendrogram lines const points = [ { lx: d.source.x, ly: d.source.y }, { lx: d.target.x, ly: d.source.y }, { lx: d.target.x, ly: d.target.y } ]; return line(points); } : d3.svg.diagonal().projection(function (d) { return window.vertLayout ? [twoThirdMargin + d.x, halfMargin + d.y] : [halfMargin + d.y, twoThirdMargin + d.x]; }); // updates links positions window.svg.selectAll(".link") .attr("d", diagonal) .attr("fill", "none"); window.updateLinks = false; } /** * Updates the positions of the D3 tree nodes, the dissimilarity scale and the threshold line. */ function updateAllPositions() { if (!window.updatePositions) return; var thirdMargin = window.treeMargin / 3; var twoThirdMargin = thirdMargin * 2; var halfMargin = window.treeMargin / 2; // creates the scale range functions used to position the nodes according to dissimilarity / distance window.distScale = d3.scale.linear().domain([window.dMin, window.dMax]).range( [0, (window.vertLayout ? window.height : window.width) - window.treeMargin]); window.invDistScale = d3.scale.linear().domain([window.dMax, window.dMin]).range( [0, (window.vertLayout ? window.height : window.width) - window.treeMargin]); // updates node's relative distances window.nodes = window.cluster.nodes(window.root); window.nodes.forEach(function (nd) { if (!isNull(nd.d)) { nd.y = window.vertLayout ? window.invDistScale(nd.d) : window.distScale(nd.d); } }); //window.updateAllLinks(); // update nodes positions window.svg.selectAll(".node") .attr("transform", function (d) { return `translate(${window .vertLayout ? (twoThirdMargin + d.x) : (halfMargin + d.y)},${window.vertLayout ? (halfMargin + d.y) : (twoThirdMargin + d.x)})`; }); // changes scale axis window.scaleSvg.attr("transform", `translate(${window.vertLayout ? thirdMargin : halfMargin},${window.vertLayout ? halfMargin : thirdMargin})`); window.scaleLine .attr("x1", vertLayout ? 0 : window.invDistScale(window.dMin)) .attr("y1", vertLayout ? window.invDistScale(window.dMin) : 0) .attr("x2", vertLayout ? 0 : window.invDistScale(window.dMax)) .attr("y2", vertLayout ? window.invDistScale(window.dMax) : 0); var tickShift = 5; window.scaleSvg.selectAll(".ticks").remove(); window.scaleSvg.selectAll(".ticks") .data(window.distScale.ticks(window.numScaleTicks)) .enter().append("line") .attr("class", "ticks") .style("stroke", window.labelColor) .attr("x1", function (d) { return vertLayout ? -tickShift : window.distScale(d); }) .attr("y1", function (d) { return vertLayout ? window.invDistScale(d) : -tickShift; }) .attr("x2", function (d) { return vertLayout ? tickShift : window.distScale(d); }) .attr("y2", function (d) { return vertLayout ? window.invDistScale(d) : tickShift; }); var scaleLabelShift = 5; window.scaleSvg.selectAll(".label").remove(); window.scaleSvg.selectAll(".label") .data(window.distScale.ticks(window.numScaleTicks)) .enter().append("text") .attr("class", "label") .style("fill", window.labelColor) .text(String) .attr("x", function (d) { return window.vertLayout ? -2 * scaleLabelShift : window.distScale(d); }) .attr("y", function (d) { return window.vertLayout ? window.invDistScale(d) : -scaleLabelShift; }) .style("text-anchor", vertLayout ? "end" : "middle") .style("dominant-baseline", vertLayout ? "middle" : "ideographic"); // updates threshold line window.updateThreshLine(); window.updatePositions = false; } /** * Updates the dissimilarity threshold line position according to the defined variable. */ function updateThreshLine() { const thirdMargin = window.treeMargin / 3; const halfMargin = window.treeMargin / 2; // changes threshold indicative line window.threshLine .style("stroke", window.labelColor) .attr("x1", vertLayout ? thirdMargin : halfMargin + window.distScale(window.clusterDistThreshold)) .attr("y1", vertLayout ? halfMargin + window.invDistScale(window.clusterDistThreshold) : thirdMargin) .attr("x2", vertLayout ? window.width - thirdMargin : halfMargin + window.distScale(window.clusterDistThreshold)) .attr("y2", vertLayout ? halfMargin + window.invDistScale(window.clusterDistThreshold) : window.height - thirdMargin); } /** * Updates the D3 tree links and nodes, the scale, and dissmilarity threshold line colors. */ function updateAllColors() { if (!window.updateColors) return; // updates nodes color recursively window.clusterColorIdx = 0; updateNodeColor(window.root, window.strokeColor, true); window.svg.selectAll(".link") .style("stroke", function (d) { return getColor(d.target.color); }); // adds node's circle window.svg.selectAll(".node") .select("circle") .style("stroke", function (d) { return getColor(d.color); }) .style("fill", function (d) { return getColor(d.color); }); // updates scale axis colors window.scaleLine .style("stroke", window.labelColor); window.scaleSvg.selectAll(".ticks") .style("stroke", window.labelColor); window.scaleSvg.selectAll(".label") .style("fill", window.labelColor); // updates threshold line window.updateThreshLine(); window.updateColors = false; } /** * Gets the color value according to whether grayscale option is active or not. * @param {string} colorValue The color value in html hexadecimal format. * @returns The color value according to whether grayscale option is active or not. */ function getColor(colorValue) { return `#${window.grayscale ? getGrayscale(colorValue) : colorValue}`; } /** * Changes the color of the given D3 node and all of its children recursively. * @param {object} node The D3 node to be updated. * @param {string} color The color of the node in html hexadecimal format. * @param {boolean} changeColor Whether to change all colors. */ function updateNodeColor(node, color, changeColor) { // checks whether cluster is below distance threshold, change color if (changeColor && node.d <= window.clusterDistThreshold) { changeColor = false; color = window.clusterColors[window.clusterColorIdx]; window.clusterColorIdx++; } node.color = color; // sets color of children recursively if (!isNull(node.children)) { for (let j in node.children) { updateNodeColor(node.children[j], color, changeColor); } } } /** * Updates the nodes labels text and its relative position. */ function updateAllLabels() { if (!window.showLabels) { window.svg.selectAll(".node") .select("text").text(""); return; } // positions label according to vertical layout and nodes' num. children var labelShift = window.nodeRadius * 2; window.svg.selectAll(".node") .select("text") .style("fill", window.labelColor) .attr("dx", function (d) { return (d.children ? labelShift : -labelShift); }) .attr("dy", function (d) { return window.vertLayout ? (d.children ? -2 * labelShift : 0) : (d.children ? -labelShift : 0); }) .attr("transform", function (d) { return `rotate(${window.vertLayout && !d.children ? 290 : 0})`; }) .style("text-anchor", function (d) { return (d.children ? "start" : "end"); }) .style("dominant-baseline", function (d) { return window.vertLayout ? "central" : (d.children ? "alphabetic" : "middle"); }) .style("font-size", Math.max(3, (98 / window.numClusterLeafs)) + "px") .text(function (d) { return d.n; }); } // #endregion // #region Event handlers window.onresize = function () { // resets internal variables for a refresh window.updatePositions = true; window.updateLinks = true; window.update(); }; /** * Resets the drag position and zoom level. */ function onResetDragZoom() { //resets translate and scale values window.svg.attr("transform", "translate(0,0)scale(1)"); } /** * Toggles node label visibility and triggers an interface refresh. */ function onShowLabels() { window.showLabels = true; window.update(); } /** * Toggles dendrogram grayscale / colors and triggers an interface refresh. */ function onGrayscale() { window.updateColors = true; window.update(); } /** * Toggles vertical / horizontal layout and triggers an interface refresh. */ function onVertLayout() { window.updateColors = true; window.updateLinks = true; window.updatePositions = true; window.update(); } /** * Toggles straight / round lines and triggers an interface refresh. */ function onStraightLinks() { window.updateLinks = true; window.update(); } /** * Changes the color scheme used and triggers an interface refresh. */ function onColorSchemeChanged() { window.updateColors = true; window.update(); } /** * Changes the dissimilarity threshold and triggers an interface refresh. */ function onThresholdChanged(value) { window.clusterDistThreshold = Number(value); window.updateColors = true; window.update(); } /** * Changes the number of clusters and triggers an interface refresh. */ function onNumClustersChanged(value) { window.clusterDistThreshold = getThresholdFromNumClusters(value); window.updateColors = true; window.update(); } /** * Gets the dissimilarity threshold value according to the number of clusters. * @param {Number} numClusters The number of clusters. * @returns {Number} The dissimilarity threshold value according to the number of clusters. */ function getThresholdFromNumClusters(numClusters) { if (numClusters < 2) { return window.root.d; } // gets all nodes and sorts them by dissimilarity/distance, descendingly const nodes = window.getAllNodes(window.root, []); nodes.sort(function (n1, n2) { return n2.d - n1.d; }); // gets distance right below the node's distance console.info(numClusters) console.info(nodes.length) return Math.max(nodes[numClusters - 2].d - 0.001, 0); } /** * Gets all nodes by searching starting from the given D3 node. * @param {object} node The current D3 tree node from which to get all nodes. * @param {Array} nodes The array containing all nodes. */ function getAllNodes(node, nodes) { if (isNull(node.children)) { return nodes; } nodes.push(node); for (let j in node.children) { getAllNodes(node.children[j], nodes); } return nodes; } /** * Changes the zoom level. */ function on
{ // define the zoom function for the zoomable tree if (!window.zoomDragable) return; const scale = d3.event.scale; const dx = Math.max((1 - scale) * window.width, Math.min(0, d3.event.translate[0])); const dy = Math.max((1 - scale) * window.height, Math.min(0, d3.event.translate[1])); window.svg.attr("transform", `translate(${dx},${dy})scale(${scale})`); } // #endregion
Zoom()
short.rs
use std::convert::TryInto; use super::super::{EccPoint, EccScalarFixedShort, FixedPoints, L_SCALAR_SHORT, NUM_WINDOWS_SHORT}; use crate::{ecc::chip::MagnitudeSign, utilities::bool_check}; use halo2_proofs::{ circuit::{Layouter, Region}, plonk::{ConstraintSystem, Constraints, Error, Expression, Selector}, poly::Rotation, }; use pasta_curves::pallas; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Config<Fixed: FixedPoints<pallas::Affine>> { // Selector used for fixed-base scalar mul with short signed exponent. q_mul_fixed_short: Selector, super_config: super::Config<Fixed>, } impl<Fixed: FixedPoints<pallas::Affine>> Config<Fixed> { pub(crate) fn configure( meta: &mut ConstraintSystem<pallas::Base>, super_config: super::Config<Fixed>, ) -> Self { let config = Self { q_mul_fixed_short: meta.selector(), super_config, }; config.create_gate(meta); config } fn create_gate(&self, meta: &mut ConstraintSystem<pallas::Base>) { // Gate contains the following constraints: // - https://p.z.cash/halo2-0.1:ecc-fixed-mul-short-msb // - https://p.z.cash/halo2-0.1:ecc-fixed-mul-short-conditional-neg meta.create_gate("Short fixed-base mul gate", |meta| { let q_mul_fixed_short = meta.query_selector(self.q_mul_fixed_short); let y_p = meta.query_advice(self.super_config.add_config.y_p, Rotation::cur()); let y_a = meta.query_advice(self.super_config.add_config.y_qr, Rotation::cur()); // z_21 = k_21 let last_window = meta.query_advice(self.super_config.u, Rotation::cur()); let sign = meta.query_advice(self.super_config.window, Rotation::cur()); let one = Expression::Constant(pallas::Base::one()); // Check that last window is either 0 or 1. let last_window_check = bool_check(last_window); // Check that sign is either 1 or -1. let sign_check = sign.clone().square() - one; // `(x_a, y_a)` is the result of `[m]B`, where `m` is the magnitude. // We conditionally negate this result using `y_p = y_a * s`, where `s` is the sign. // Check that the final `y_p = y_a` or `y_p = -y_a` // // This constraint is redundant / unnecessary, because `sign` is constrained // to -1 or 1 by `sign_check`, and `negation_check` therefore permits a strict // subset of the cases that this constraint permits. let y_check = (y_p.clone() - y_a.clone()) * (y_p.clone() + y_a.clone()); // Check that the correct sign is witnessed s.t. sign * y_p = y_a let negation_check = sign * y_p - y_a; Constraints::with_selector( q_mul_fixed_short, [ ("last_window_check", last_window_check), ("sign_check", sign_check), ("y_check", y_check), ("negation_check", negation_check), ], ) }); } /// Constraints `magnitude` to be at most 66 bits. /// /// The final window is separately constrained to be a single bit, which completes the /// 64-bit range constraint. fn decompose( &self, region: &mut Region<'_, pallas::Base>, offset: usize, magnitude_sign: MagnitudeSign, ) -> Result<EccScalarFixedShort, Error> { let (magnitude, sign) = magnitude_sign; // Decompose magnitude let running_sum = self.super_config.running_sum_config.copy_decompose( region, offset, magnitude.clone(), true, L_SCALAR_SHORT, NUM_WINDOWS_SHORT, )?; Ok(EccScalarFixedShort { magnitude, sign, running_sum: Some((*running_sum).as_slice().try_into().unwrap()), }) } pub fn assign( &self, mut layouter: impl Layouter<pallas::Base>, scalar: &EccScalarFixedShort, base: &<Fixed as FixedPoints<pallas::Affine>>::ShortScalar, ) -> Result<(EccPoint, EccScalarFixedShort), Error> where <Fixed as FixedPoints<pallas::Affine>>::ShortScalar: super::super::FixedPoint<pallas::Affine>, { let (scalar, acc, mul_b) = layouter.assign_region( || "Short fixed-base mul (incomplete addition)", |mut region| { let offset = 0; // Decompose the scalar let scalar = match scalar.running_sum { None => self.decompose( &mut region, offset, (scalar.magnitude.clone(), scalar.sign.clone()), ), Some(_) => todo!("unimplemented for halo2_gadgets v0.1.0"), }?; let (acc, mul_b) = self .super_config .assign_region_inner::<_, NUM_WINDOWS_SHORT>( &mut region, offset, &(&scalar).into(), base, self.super_config.running_sum_config.q_range_check(), )?; Ok((scalar, acc, mul_b)) }, )?; // Last window let result = layouter.assign_region( || "Short fixed-base mul (most significant word)", |mut region| { let offset = 0; // Add to the cumulative sum to get `[magnitude]B`. let magnitude_mul = self.super_config.add_config.assign_region( &mul_b.clone().into(), &acc.clone().into(), offset, &mut region, )?; // Increase offset by 1 after complete addition let offset = offset + 1; // Copy sign to `window` column let sign = scalar.sign.copy_advice( || "sign", &mut region, self.super_config.window, offset, )?; // Copy last window to `u` column. // (Although the last window is not a `u` value; we are copying it into the `u` // column because there is an available cell there.) let z_21 = scalar.running_sum.as_ref().unwrap()[21].clone(); z_21.copy_advice(|| "last_window", &mut region, self.super_config.u, offset)?; // Conditionally negate `y`-coordinate let y_val = if let Some(sign) = sign.value() { if sign == &-pallas::Base::one() { magnitude_mul.y.value().cloned().map(|y: pallas::Base| -y) } else { magnitude_mul.y.value().cloned() } } else { None }; // Enable mul_fixed_short selector on final row self.q_mul_fixed_short.enable(&mut region, offset)?; // Assign final `y` to `y_p` column and return final point let y_var = region.assign_advice( || "y_var", self.super_config.add_config.y_p, offset, || y_val.ok_or(Error::Synthesis), )?; Ok(EccPoint { x: magnitude_mul.x, y: y_var, }) }, )?; #[cfg(test)] // Check that the correct multiple is obtained. // This inlined test is only done for valid 64-bit magnitudes // and valid +/- 1 signs. // Invalid values result in constraint failures which are // tested at the circuit-level. { use super::super::FixedPoint; use group::{ff::PrimeField, Curve}; if let (Some(magnitude), Some(sign)) = (scalar.magnitude.value(), scalar.sign.value()) { let magnitude_is_valid = magnitude <= &pallas::Base::from(0xFFFF_FFFF_FFFF_FFFFu64); let sign_is_valid = sign * sign == pallas::Base::one(); if magnitude_is_valid && sign_is_valid { let scalar = scalar.magnitude.value().zip(scalar.sign.value()).map( |(magnitude, sign)| { // Move magnitude from base field into scalar field (which always fits // for Pallas). let magnitude = pallas::Scalar::from_repr(magnitude.to_repr()).unwrap(); let sign = if sign == &pallas::Base::one() { pallas::Scalar::one() } else { -pallas::Scalar::one() }; magnitude * sign }, ); let real_mul = scalar.map(|scalar| base.generator() * scalar); let result = result.point(); if let (Some(real_mul), Some(result)) = (real_mul, result) { assert_eq!(real_mul.to_affine(), result); } } } } Ok((result, scalar)) } } #[cfg(test)] pub mod tests { use group::{ff::PrimeField, Curve}; use halo2_proofs::{ arithmetic::CurveAffine, circuit::{AssignedCell, Chip, Layouter}, plonk::{Any, Error}, }; use pasta_curves::{arithmetic::FieldExt, pallas}; use crate::{ ecc::{ chip::{EccChip, FixedPoint, MagnitudeSign}, tests::{Short, TestFixedBases}, FixedPointShort, NonIdentityPoint, Point, ScalarFixedShort, }, utilities::{lookup_range_check::LookupRangeCheckConfig, UtilitiesInstructions}, }; #[allow(clippy::op_ref)] pub(crate) fn
( chip: EccChip<TestFixedBases>, mut layouter: impl Layouter<pallas::Base>, ) -> Result<(), Error> { // test_short let base_val = Short.generator(); let test_short = FixedPointShort::from_inner(chip.clone(), Short); fn load_magnitude_sign( chip: EccChip<TestFixedBases>, mut layouter: impl Layouter<pallas::Base>, magnitude: pallas::Base, sign: pallas::Base, ) -> Result<MagnitudeSign, Error> { let column = chip.config().advices[0]; let magnitude = chip.load_private(layouter.namespace(|| "magnitude"), column, Some(magnitude))?; let sign = chip.load_private(layouter.namespace(|| "sign"), column, Some(sign))?; Ok((magnitude, sign)) } fn constrain_equal_non_id( chip: EccChip<TestFixedBases>, mut layouter: impl Layouter<pallas::Base>, base_val: pallas::Affine, scalar_val: pallas::Scalar, result: Point<pallas::Affine, EccChip<TestFixedBases>>, ) -> Result<(), Error> { let expected = NonIdentityPoint::new( chip, layouter.namespace(|| "expected point"), Some((base_val * scalar_val).to_affine()), )?; result.constrain_equal(layouter.namespace(|| "constrain result"), &expected) } let magnitude_signs = [ ("random [a]B", pallas::Base::from(rand::random::<u64>()), { let mut random_sign = pallas::Base::one(); if rand::random::<bool>() { random_sign = -random_sign; } random_sign }), ( "[2^64 - 1]B", pallas::Base::from(0xFFFF_FFFF_FFFF_FFFFu64), pallas::Base::one(), ), ( "-[2^64 - 1]B", pallas::Base::from(0xFFFF_FFFF_FFFF_FFFFu64), -pallas::Base::one(), ), // There is a single canonical sequence of window values for which a doubling occurs on the last step: // 1333333333333333333334 in octal. // [0xB6DB_6DB6_DB6D_B6DC] B ( "mul_with_double", pallas::Base::from(0xB6DB_6DB6_DB6D_B6DCu64), pallas::Base::one(), ), ( "mul_with_double negative", pallas::Base::from(0xB6DB_6DB6_DB6D_B6DCu64), -pallas::Base::one(), ), ]; for (name, magnitude, sign) in magnitude_signs.iter() { let (result, _) = { let magnitude_sign = load_magnitude_sign( chip.clone(), layouter.namespace(|| *name), *magnitude, *sign, )?; let by = ScalarFixedShort::new( chip.clone(), layouter.namespace(|| "signed short scalar"), magnitude_sign, )?; test_short.mul(layouter.namespace(|| *name), by)? }; // Move from base field into scalar field let scalar = { let magnitude = pallas::Scalar::from_repr(magnitude.to_repr()).unwrap(); let sign = if *sign == pallas::Base::one() { pallas::Scalar::one() } else { -pallas::Scalar::one() }; magnitude * sign }; constrain_equal_non_id( chip.clone(), layouter.namespace(|| *name), base_val, scalar, result, )?; } let zero_magnitude_signs = [ ("mul by +zero", pallas::Base::zero(), pallas::Base::one()), ("mul by -zero", pallas::Base::zero(), -pallas::Base::one()), ]; for (name, magnitude, sign) in zero_magnitude_signs.iter() { let (result, _) = { let magnitude_sign = load_magnitude_sign( chip.clone(), layouter.namespace(|| *name), *magnitude, *sign, )?; let by = ScalarFixedShort::new( chip.clone(), layouter.namespace(|| "signed short scalar"), magnitude_sign, )?; test_short.mul(layouter.namespace(|| *name), by)? }; if let Some(is_identity) = result.inner().is_identity() { assert!(is_identity); } } Ok(()) } #[test] fn invalid_magnitude_sign() { use crate::{ ecc::chip::{EccConfig, FixedPoint}, utilities::UtilitiesInstructions, }; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner}, dev::{FailureLocation, MockProver, VerifyFailure}, plonk::{Circuit, ConstraintSystem, Error}, }; #[derive(Default)] struct MyCircuit { magnitude: Option<pallas::Base>, sign: Option<pallas::Base>, // For test checking magnitude_error: Option<pallas::Base>, } impl UtilitiesInstructions<pallas::Base> for MyCircuit { type Var = AssignedCell<pallas::Base, pallas::Base>; } impl Circuit<pallas::Base> for MyCircuit { type Config = EccConfig<TestFixedBases>; type FloorPlanner = SimpleFloorPlanner; fn without_witnesses(&self) -> Self { Self::default() } fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config { let advices = [ meta.advice_column(), meta.advice_column(), meta.advice_column(), meta.advice_column(), meta.advice_column(), meta.advice_column(), meta.advice_column(), meta.advice_column(), meta.advice_column(), meta.advice_column(), ]; let lookup_table = meta.lookup_table_column(); let lagrange_coeffs = [ meta.fixed_column(), meta.fixed_column(), meta.fixed_column(), meta.fixed_column(), meta.fixed_column(), meta.fixed_column(), meta.fixed_column(), meta.fixed_column(), ]; // Shared fixed column for loading constants let constants = meta.fixed_column(); meta.enable_constant(constants); let range_check = LookupRangeCheckConfig::configure(meta, advices[9], lookup_table); EccChip::<TestFixedBases>::configure(meta, advices, lagrange_coeffs, range_check) } fn synthesize( &self, config: Self::Config, mut layouter: impl Layouter<pallas::Base>, ) -> Result<(), Error> { let column = config.advices[0]; let short_config = config.mul_fixed_short.clone(); let magnitude_sign = { let magnitude = self.load_private( layouter.namespace(|| "load magnitude"), column, self.magnitude, )?; let sign = self.load_private(layouter.namespace(|| "load sign"), column, self.sign)?; ScalarFixedShort::new( EccChip::construct(config), layouter.namespace(|| "signed short scalar"), (magnitude, sign), )? }; short_config.assign(layouter, &magnitude_sign.inner, &Short)?; Ok(()) } } // Copied from halo2_proofs::dev::util fn format_value(v: pallas::Base) -> String { use ff::Field; if v.is_zero_vartime() { "0".into() } else if v == pallas::Base::one() { "1".into() } else if v == -pallas::Base::one() { "-1".into() } else { // Format value as hex. let s = format!("{:?}", v); // Remove leading zeroes. let s = s.strip_prefix("0x").unwrap(); let s = s.trim_start_matches('0'); format!("0x{}", s) } } // Magnitude larger than 64 bits should fail { let circuits = [ // 2^64 MyCircuit { magnitude: Some(pallas::Base::from_u128(1 << 64)), sign: Some(pallas::Base::one()), magnitude_error: Some(pallas::Base::from(1 << 1)), }, // -2^64 MyCircuit { magnitude: Some(pallas::Base::from_u128(1 << 64)), sign: Some(-pallas::Base::one()), magnitude_error: Some(pallas::Base::from(1 << 1)), }, // 2^66 MyCircuit { magnitude: Some(pallas::Base::from_u128(1 << 66)), sign: Some(pallas::Base::one()), magnitude_error: Some(pallas::Base::from(1 << 3)), }, // -2^66 MyCircuit { magnitude: Some(pallas::Base::from_u128(1 << 66)), sign: Some(-pallas::Base::one()), magnitude_error: Some(pallas::Base::from(1 << 3)), }, // 2^254 MyCircuit { magnitude: Some(pallas::Base::from_u128(1 << 127).square()), sign: Some(pallas::Base::one()), magnitude_error: Some( pallas::Base::from_u128(1 << 95).square() * pallas::Base::from(2), ), }, // -2^254 MyCircuit { magnitude: Some(pallas::Base::from_u128(1 << 127).square()), sign: Some(-pallas::Base::one()), magnitude_error: Some( pallas::Base::from_u128(1 << 95).square() * pallas::Base::from(2), ), }, ]; for circuit in circuits.iter() { let prover = MockProver::<pallas::Base>::run(11, circuit, vec![]).unwrap(); assert_eq!( prover.verify(), Err(vec![ VerifyFailure::ConstraintNotSatisfied { constraint: ( (17, "Short fixed-base mul gate").into(), 0, "last_window_check" ) .into(), location: FailureLocation::InRegion { region: (3, "Short fixed-base mul (most significant word)").into(), offset: 1, }, cell_values: vec![( ((Any::Advice, 5).into(), 0).into(), format_value(circuit.magnitude_error.unwrap()), )], }, VerifyFailure::Permutation { column: (Any::Fixed, 9).into(), location: FailureLocation::OutsideRegion { row: 0 }, }, VerifyFailure::Permutation { column: (Any::Advice, 4).into(), location: FailureLocation::InRegion { region: (2, "Short fixed-base mul (incomplete addition)").into(), offset: 22, }, } ]) ); } } // Sign that is not +/- 1 should fail { let magnitude_u64 = rand::random::<u64>(); let circuit = MyCircuit { magnitude: Some(pallas::Base::from(magnitude_u64)), sign: Some(pallas::Base::zero()), magnitude_error: None, }; let negation_check_y = { *(Short.generator() * pallas::Scalar::from(magnitude_u64)) .to_affine() .coordinates() .unwrap() .y() }; let prover = MockProver::<pallas::Base>::run(11, &circuit, vec![]).unwrap(); assert_eq!( prover.verify(), Err(vec![ VerifyFailure::ConstraintNotSatisfied { constraint: ((17, "Short fixed-base mul gate").into(), 1, "sign_check") .into(), location: FailureLocation::InRegion { region: (3, "Short fixed-base mul (most significant word)").into(), offset: 1, }, cell_values: vec![(((Any::Advice, 4).into(), 0).into(), "0".to_string())], }, VerifyFailure::ConstraintNotSatisfied { constraint: ( (17, "Short fixed-base mul gate").into(), 3, "negation_check" ) .into(), location: FailureLocation::InRegion { region: (3, "Short fixed-base mul (most significant word)").into(), offset: 1, }, cell_values: vec![ ( ((Any::Advice, 1).into(), 0).into(), format_value(negation_check_y), ), ( ((Any::Advice, 3).into(), 0).into(), format_value(negation_check_y), ), (((Any::Advice, 4).into(), 0).into(), "0".to_string()), ], } ]) ); } } }
test_mul_fixed_short
test_md019.py
""" Module to provide tests related to the MD019 rule. """ from test.markdown_scanner import MarkdownScanner import pytest # pylint: disable=too-many-lines @pytest.mark.rules def test_md019_good_single_spacing(): """ Test to make sure this rule does not trigger with a document that contains an Atx Heading with a single space before text. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md019/single_spacing.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md019_bad_multiple_spacing(): """ Test to make sure this rule does not trigger with a document that contains Atx Headings with multiple spaces before text. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md019/multiple_spacing.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md019/multiple_spacing.md:1:1: " + "MD019: Multiple spaces are present after hash character on Atx Heading. (no-multiple-space-atx)\n" "test/resources/rules/md019/multiple_spacing.md:3:1: " + "MD019: Multiple spaces are present after hash character on Atx Heading. (no-multiple-space-atx)\n" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) def test_md019_bad_multiple_spacing_with_inline(): """
""" # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md019/multiple_spacing_with_inline.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md019/multiple_spacing_with_inline.md:1:1: " + "MD019: Multiple spaces are present after hash character on Atx Heading. (no-multiple-space-atx)\n" "test/resources/rules/md019/multiple_spacing_with_inline.md:3:1: " + "MD019: Multiple spaces are present after hash character on Atx Heading. (no-multiple-space-atx)\n" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) def test_md019_bad_multiple_spacing_with_indent(): """ Test to make sure this rule does not trigger with a document that contains multiple Atx Headings with multiple spaces before text, including indets. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--disable-rules", "md023", "scan", "test/resources/rules/md019/multiple_spacing_with_indent.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md019/multiple_spacing_with_indent.md:1:2: " + "MD019: Multiple spaces are present after hash character on Atx Heading. (no-multiple-space-atx)\n" "test/resources/rules/md019/multiple_spacing_with_indent.md:3:3: " + "MD019: Multiple spaces are present after hash character on Atx Heading. (no-multiple-space-atx)\n" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) def test_md019_bad_single_space_single_tab(): """ Test to make sure this rule does not trigger with a document that contains multiple Atx Headings with tabs before text. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--disable-rules", "md010", "scan", "test/resources/rules/md019/single_space_single_tab.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code )
Test to make sure this rule does not trigger with a document that contains multiple Atx Headings with multiple spaces before text, including an inline element in the heading.
parquet.py
from functools import partial import pyarrow.parquet as pq import dask.dataframe as dd from dask.dataframe.io.parquet.arrow import ArrowEngine import cudf from cudf.core.column import build_categorical_column class CudfEngine(ArrowEngine): @staticmethod def read_metadata(*args, **kwargs): meta, stats, parts = ArrowEngine.read_metadata(*args, **kwargs) # If `strings_to_categorical==True`, convert objects to int32 strings_to_cats = kwargs.get("strings_to_categorical", False) dtypes = {} for col in meta.columns: if meta[col].dtype == "O": dtypes[col] = "int32" if strings_to_cats else "object" meta = cudf.DataFrame.from_pandas(meta) for col, dtype in dtypes.items(): meta[col] = meta[col].astype(dtype) return (meta, stats, parts) @staticmethod def read_partition( fs, piece, columns, index, categories=(), partitions=(), **kwargs ): if columns is not None: columns = [c for c in columns] if isinstance(index, list): columns += index if isinstance(piece, str): # `piece` is a file-path string piece = pq.ParquetDatasetPiece( piece, open_file_func=partial(fs.open, mode="rb") ) else: # `piece` = (path, row_group, partition_keys) (path, row_group, partition_keys) = piece piece = pq.ParquetDatasetPiece( path, row_group=row_group, partition_keys=partition_keys, open_file_func=partial(fs.open, mode="rb"), ) strings_to_cats = kwargs.get("strings_to_categorical", False) if cudf.utils.ioutils._is_local_filesystem(fs): df = cudf.read_parquet( piece.path, engine="cudf", columns=columns, row_group=piece.row_group, strings_to_categorical=strings_to_cats, **kwargs.get("read", {}), ) else: with fs.open(piece.path, mode="rb") as f: df = cudf.read_parquet( f, engine="cudf", columns=columns, row_group=piece.row_group, strings_to_categorical=strings_to_cats, **kwargs.get("read", {}), ) if index and index[0] in df.columns: df = df.set_index(index[0]) if len(piece.partition_keys) > 0: if partitions is None: raise ValueError("Must pass partition sets") for i, (name, index2) in enumerate(piece.partition_keys): categories = [ val.as_py() for val in partitions.levels[i].dictionary ] sr = cudf.Series(index2).astype(type(index2)).repeat(len(df)) df[name] = build_categorical_column( categories=categories, codes=sr._column, ordered=False ) return df @staticmethod def write_partition( df, path, fs, filename, partition_on, return_metadata, fmd=None, compression=None, index_cols=None, **kwargs, ): # TODO: Replace `pq.write_table` with gpu-accelerated # write after cudf.io.to_parquet is supported. md_list = [] preserve_index = False if index_cols: df = df.set_index(index_cols) preserve_index = True # NOTE: `to_arrow` does not accept `schema` argument t = df.to_arrow(preserve_index=preserve_index) if partition_on: pq.write_to_dataset( t, path, partition_cols=partition_on, filesystem=fs, metadata_collector=md_list, **kwargs, ) else: with fs.open(fs.sep.join([path, filename]), "wb") as fil: pq.write_table( t, fil, compression=compression, metadata_collector=md_list, **kwargs, ) if md_list: md_list[0].set_file_path(filename) # Return the schema needed to write the metadata if return_metadata: return [{"schema": t.schema, "meta": md_list[0]}] else: return [] def read_parquet( path, columns=None, split_row_groups=True, gather_statistics=None, **kwargs ):
to_parquet = partial(dd.to_parquet, engine=CudfEngine)
""" Read parquet files into a Dask DataFrame Calls ``dask.dataframe.read_parquet`` to cordinate the execution of ``cudf.read_parquet``, and ultimately read multiple partitions into a single Dask dataframe. The Dask version must supply an ``ArrowEngine`` class to support full functionality. See ``cudf.read_parquet`` and Dask documentation for further details. Examples -------- >>> import dask_cudf >>> df = dask_cudf.read_parquet("/path/to/dataset/") # doctest: +SKIP See Also -------- cudf.read_parquet """ if isinstance(columns, str): columns = [columns] if split_row_groups: gather_statistics = True return dd.read_parquet( path, columns=columns, split_row_groups=split_row_groups, gather_statistics=gather_statistics, engine=CudfEngine, **kwargs, )
bmapblk.rs
// src/libcore/fs/bmapblk.rs // // Basic bitmap-block implementation for working with filesystems. /* IMPORTS */ use bit_field::BitField; use crate::libcore::fs::{blk::Blk, sblk::SBlk}; // Constant to represent bitmap size pub const BMAPSIZE: usize = 5 * crate::libcore::fs::ata::BLKSIZE; // Basic bitmap block struct pub struct BMapBlk {} // Implementation of the BMapBlk struct impl BMapBlk { // Allocate pub fn alloc(address: u32) { let mut blk = Blk::read(BMapBlk::blkidx(address)); let bmap = blk.datamut(); let i = BMapBlk::buffidx(address); if !bmap[i / 8].get_bit(i % 8) { bmap[i / 8].set_bit(i % 8, true); blk.write(); crate::libcore::fs::sblk::alloc_count_up(); } } // Block index fn blkidx(address: u32) -> u32 { let sblk = SBlk::read(); let size = sblk.blksize(); let i = address - sblk.data_area(); sblk.bmap_area() + (i / size / 8) } // Buffer index fn
(address: u32) -> usize { let sblk = SBlk::read(); let i = (address - sblk.data_area()) as usize; i % sblk.blksize() as usize } // Free pub fn free(address: u32) { let mut blk = Blk::read(BMapBlk::blkidx(address)); let bmap = blk.datamut(); let i = BMapBlk::buffidx(address); bmap[i / 8].set_bit(i % 8, false); blk.write(); crate::libcore::fs::sblk::alloc_count_down(); } // Next free address pub fn next_free_address() -> Option<u32> { let sb = SBlk::read(); let size = sb.blksize(); let n = sb.blkcount() / size / 8; for i in 0..n { let blk = Blk::read(sb.bmap_area() + 1); let bmap = blk.data(); for j in 0..size { for k in 0..8 { if !bmap[j as usize].get_bit(k) { let bmapsize = BMAPSIZE as u32; let address = sb.data_area() + i * bmapsize + j * 8 + k as u32; return Some(address); } } } } None } } // Free all pub fn freeall() { let sb = SBlk::read(); let a = sb.bmap_area(); let b = sb.data_area(); for address in a..b { Blk::new(address).write(); } }
buffidx
images-icon.js
(function (global, factory) { if (typeof define === "function" && define.amd) { define(['exports', '../createIcon'], factory); } else if (typeof exports !== "undefined") { factory(exports, require('../createIcon')); } else { var mod = { exports: {} }; factory(mod.exports, global.createIcon); global.imagesIcon = mod.exports; } })(this, function (exports, _createIcon) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createIcon2 = _interopRequireDefault(_createIcon); function _interopRequireDefault(obj) {
} var ImagesIcon = (0, _createIcon2.default)({ name: 'ImagesIcon', height: 512, width: 576, svgPath: 'M480 416v16c0 26.51-21.49 48-48 48H48c-26.51 0-48-21.49-48-48V176c0-26.51 21.49-48 48-48h16v208c0 44.112 35.888 80 80 80h336zm96-80V80c0-26.51-21.49-48-48-48H144c-26.51 0-48 21.49-48 48v256c0 26.51 21.49 48 48 48h384c26.51 0 48-21.49 48-48zM256 128c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-96 144l55.515-55.515c4.686-4.686 12.284-4.686 16.971 0L272 256l135.515-135.515c4.686-4.686 12.284-4.686 16.971 0L512 208v112H160v-48z', yOffset: '', xOffset: '', transform: '' }); /* This file is generated by createIcons.js any changes will be lost. */ exports.default = ImagesIcon; });
return obj && obj.__esModule ? obj : { default: obj };
test_sysstat.py
# stdlib import logging import sys import unittest import mock # project from checks.system.unix import ( IO, Load, Memory, ) from checks.system.unix import System from config import get_system_stats from utils.platform import Platform logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__file__) class TestSystem(unittest.TestCase): def testUptime(self): global logger system = System(logger) metrics = system.check({}) self.assertTrue("system.uptime" in metrics) self.assertTrue(metrics["system.uptime"] > 0) def testLoad(self): global logger load = Load(logger) res = load.check({'system_stats': get_system_stats()}) assert 'system.load.1' in res if Platform.is_linux(): cores = int(get_system_stats().get('cpuCores')) assert 'system.load.norm.1' in res assert abs(res['system.load.1'] - cores * res['system.load.norm.1']) <= 0.1, (res['system.load.1'], cores * res['system.load.norm.1']) # same test but without cpu count, no normalized load sent. res = load.check({}) assert 'system.load.1' in res assert 'system.load.norm.1' not in res def
(self): global logger res = Memory(logger).check({}) if Platform.is_linux(): MEM_METRICS = ["swapTotal", "swapFree", "swapPctFree", "swapUsed", "physTotal", "physFree", "physUsed", "physBuffers", "physCached", "physUsable", "physPctUsable", "physShared"] for k in MEM_METRICS: # % metric is only here if total > 0 if k == 'swapPctFree' and res['swapTotal'] == 0: continue assert k in res, res assert res["swapTotal"] == res["swapFree"] + res["swapUsed"] assert res["physTotal"] == res["physFree"] + res["physUsed"] elif sys.platform == 'darwin': for k in ("swapFree", "swapUsed", "physFree", "physUsed"): assert k in res, res def testDiskLatency(self): # example output from `iostat -d 1 2 -x -k` on # debian testing x86_64, from Debian package # [email protected] debian_iostat_output = """Linux 3.2.0-2-amd64 (fireflyvm) 05/29/2012 _x86_64_ (2 CPU) Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await r_await w_await svctm %util sda 0.44 2.58 5.79 2.84 105.53 639.03 172.57 0.17 19.38 1.82 55.26 0.66 0.57 Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await r_await w_await svctm %util sda 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.01 """ global logger checker = IO(logger) results = checker._parse_linux2(debian_iostat_output) self.assertTrue('sda' in results) for key in ('rrqm/s', 'wrqm/s', 'r/s', 'w/s', 'rkB/s', 'wkB/s', 'avgrq-sz', 'avgqu-sz', 'await', 'r_await', 'w_await', 'svctm', '%util'): self.assertTrue(key in results['sda'], 'key %r not in results["sda"]' % key) if key == r'%util': expected = 0.01 else: expected = '0.00' self.assertEqual(results['sda'][key], expected) # example output from `iostat -d 1 2 -x -k` on # ubuntu 18.04 x86_64, from deb package # [email protected]; main breaking change is # that header starts with `Device` instead of `Device:`. newer_iostat_output = """Linux 4.9.60-linuxkit-aufs (f3cf72f6fb4d) 05/09/18 _x86_64_ (2 CPU) Device r/s w/s rkB/s wkB/s rrqm/s wrqm/s %rrqm %wrqm r_await w_await aqu-sz rareq-sz wareq-sz svctm %util sda 0.07 0.08 0.64 5.44 0.00 0.23 0.41 72.99 2.42 19.91 0.00 8.92 65.13 0.38 0.01 Device r/s w/s rkB/s wkB/s rrqm/s wrqm/s %rrqm %wrqm r_await w_await aqu-sz rareq-sz wareq-sz svctm %util sda 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.01 """ checker = IO(logger) results = checker._parse_linux2(newer_iostat_output) self.assertTrue('sda' in results) for key in ('rrqm/s', 'wrqm/s', 'r/s', 'w/s', 'rkB/s', 'wkB/s', 'r_await', 'w_await', 'svctm', '%util'): self.assertTrue(key in results['sda'], 'key %r not in results["sda"]' % key) if key == r'%util': expected = 0.01 else: expected = '0.00' self.assertEqual(results['sda'][key], expected) # example output from `iostat -d 1 d -x -k` on # centos 5.8 x86_64, from RPM package # [email protected]; it differs from the first one by # not having split-out r_await and w_await fields centos_iostat_output = """Linux 2.6.18-308.el5 (localhost.localdomain) 05/29/2012 Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %util sda 9.44 7.56 16.76 4.40 322.05 47.75 34.96 0.01 0.59 0.35 0.74 Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %util sda 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.01 """ checker = IO(logger) results = checker._parse_linux2(centos_iostat_output) self.assertTrue('sda' in results) for key in ('rrqm/s', 'wrqm/s', 'r/s', 'w/s', 'rkB/s', 'wkB/s', 'avgrq-sz', 'avgqu-sz', 'await', 'svctm', '%util'): self.assertTrue(key in results['sda'], 'key %r not in results["sda"]' % key) if key == r'%util': expected = 0.01 else: expected = '0.00' self.assertEqual(results['sda'][key], expected) # iostat -o -d -c 2 -w 1 # OS X 10.8.3 (internal SSD + USB flash attached) darwin_iostat_output = """ disk0 disk1 KB/t tps MB/s KB/t tps MB/s 21.11 23 0.47 20.01 0 0.00 6.67 3 0.02 0.00 0 0.00 """ checker = IO(logger) results = checker._parse_darwin(darwin_iostat_output) self.assertTrue("disk0" in results.keys()) self.assertTrue("disk1" in results.keys()) self.assertEqual( results["disk0"], {'system.io.bytes_per_s': float(0.02 * 2**20),} ) self.assertEqual( results["disk1"], {'system.io.bytes_per_s': float(0),} ) linux_output_dashes = """Linux 3.13.0-32-generic (ubuntu-1204) 05/20/2016 _x86_64_ (2 CPU) Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await r_await w_await svctm %util sda 5.77 8.20 7.79 30.08 320.67 219.91 28.55 0.05 1.32 1.53 1.27 0.32 1.20 dm-0 0.00 0.00 11.71 37.97 313.61 219.90 21.48 0.11 2.16 2.13 2.17 0.24 1.20 dm-1 0.00 0.00 0.08 0.00 0.32 0.00 8.00 0.00 1.68 1.68 0.00 1.07 0.01 Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await r_await w_await svctm %util sda 0.00 0.00 0.00 1.00 0.00 4.00 8.00 0.00 0.00 0.00 0.00 0.00 0.00 dm-0 0.00 0.00 0.00 1.00 0.00 4.00 8.00 0.00 0.00 0.00 0.00 0.00 0.00 dm-1 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 """ results = checker._parse_linux2(linux_output_dashes) self.assertTrue(sorted(results.keys()) == ['dm-0', 'dm-1', 'sda']) def testLinuxCapIostat(self): # example output from `iostat -d 1 2 -x -k` on # debian testing x86_64, from Debian package # [email protected] debian_iostat_output = """Linux 3.2.0-2-amd64 (fireflyvm) 05/29/2012 _x86_64_ (2 CPU) Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await r_await w_await svctm %util sda 0.44 2.58 5.79 2.84 105.53 639.03 172.57 0.17 19.38 1.82 55.26 0.66 0.57 Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await r_await w_await svctm %util sda 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.01 """ global logger checker = IO(logger) results = checker._parse_linux2(debian_iostat_output) self.assertTrue('sda' in results) # Ensure that value is capped and return to 0 if it surpasses 100 expected = 0 self.assertEqual(results['sda']['%util'], expected) # example output from `iostat -d 1 2 -x -k` on # ubuntu 18.04 x86_64, from deb package # [email protected]; main breaking change is # that header starts with `Device` instead of `Device:`. newer_iostat_output = """Linux 4.9.60-linuxkit-aufs (f3cf72f6fb4d) 05/09/18 _x86_64_ (2 CPU) Device r/s w/s rkB/s wkB/s rrqm/s wrqm/s %rrqm %wrqm r_await w_await aqu-sz rareq-sz wareq-sz svctm %util sda 0.07 0.08 0.64 5.44 0.00 0.23 0.41 72.99 2.42 19.91 0.00 8.92 65.13 0.38 0.01 Device r/s w/s rkB/s wkB/s rrqm/s wrqm/s %rrqm %wrqm r_await w_await aqu-sz rareq-sz wareq-sz svctm %util sda 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 99.99 """ checker = IO(logger) results = checker._parse_linux2(newer_iostat_output) self.assertTrue('sda' in results) expected = 99.99 self.assertEqual(results['sda']['%util'], expected) # example output from `iostat -d 1 d -x -k` on # centos 5.8 x86_64, from RPM package # [email protected]; it differs from the first one by # not having split-out r_await and w_await fields centos_iostat_output = """Linux 2.6.18-308.el5 (localhost.localdomain) 05/29/2012 Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %util sda 9.44 7.56 16.76 4.40 322.05 47.75 34.96 0.01 0.59 0.35 0.74 Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %util sda 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 102.01 """ checker = IO(logger) results = checker._parse_linux2(centos_iostat_output) self.assertTrue('sda' in results) # %util value is over 100, and value is set to 0 expected = 0 self.assertEqual(results['sda']['%util'], expected) def sunos5_output(self, *args, **kwargs): output = """extended device statistics <-- since boot device r/s w/s kr/s kw/s wait actv svc_t %w %b ramdisk1 0.0 0.0 0.1 0.1 0.0 0.0 0.0 0 0 sd0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 0 sd1 79.9 149.9 1237.6 6737.9 0.0 0.5 2.3 0 11 extended device statistics <-- past second device r/s w/s kr/s kw/s wait actv svc_t %w %b ramdisk1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 0 sd0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 102 sd1 0.0 139.0 0.0 1850.6 0.0 0.0 0.1 0 10 """ return output, 0, 0 def freebsd_output(self, *args, **kwargs): output = """extended device statistics device r/s w/s kr/s kw/s wait svc_t %b ad0 3.1 1.3 49.9 18.8 0 0.7 0 extended device statistics device r/s w/s kr/s kw/s wait svc_t %b ad0 0.0 2.0 0.0 31.8 0 0.2 102 """ return output, 0, 0 @mock.patch('checks.system.unix.sys.platform', 'sunos5') @mock.patch('checks.system.unix.get_subprocess_output', side_effect=sunos5_output) def testSunos5CapIostat(self, mock_subprocess): global logger checker = IO(logger) results = checker.check({}) for res in results: if res == 'sd1': expected = 10 else: expected = 0 self.assertEqual(results[res]['%util'], expected) @mock.patch('checks.system.unix.sys.platform', 'freebsd') @mock.patch('checks.system.unix.get_subprocess_output', side_effect=freebsd_output) def testFreebsdCapIostat(self, mock_subprocess): global logger checker = IO(logger) results = checker.check({}) expected = 0 for res in results: self.assertEqual(results[res]['%util'], expected)
testMemory
feed_flash.py
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021 # by the software owners: The Regents of the University of California, through # Lawrence Berkeley National Laboratory, National Technology & Engineering # Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia University # Research Corporation, et al. All rights reserved. # # Please see the files COPYRIGHT.md and LICENSE.md for full copyright and # license information. ################################################################################# """ Standard IDAES Feed block with phase equilibrium. """ from enum import Enum # Import Pyomo libraries from pyomo.environ import Reference from pyomo.common.config import ConfigBlock, ConfigValue, In # Import IDAES cores from idaes.core import (ControlVolume0DBlock, declare_process_block_class, MaterialBalanceType, MomentumBalanceType, UnitModelBlockData, useDefault) from idaes.core.util.config import is_physical_parameter_block from idaes.core.util.tables import create_stream_table_dataframe __author__ = "Andrew Lee" # Enumerate options for material balances class FlashType(Enum): isothermal = 1 isenthalpic = 2 @declare_process_block_class("FeedFlash") class FeedFlashData(UnitModelBlockData):
""" Standard Feed block with phase equilibrium """ CONFIG = ConfigBlock() CONFIG.declare("dynamic", ConfigValue( domain=In([False]), default=False, description="Dynamic model flag - must be False", doc="""Feed units do not support dynamic behavior.""")) CONFIG.declare("has_holdup", ConfigValue( default=False, domain=In([False]), description="Holdup construction flag - must be False", doc="""Feed units do not have defined volume, thus this must be False.""")) CONFIG.declare("material_balance_type", ConfigValue( default=MaterialBalanceType.useDefault, domain=In(MaterialBalanceType), description="Material balance construction flag", doc="""Indicates what type of mass balance should be constructed, **default** - MaterialBalanceType.useDefault. **Valid values:** { **MaterialBalanceType.useDefault - refer to property package for default balance type **MaterialBalanceType.none** - exclude material balances, **MaterialBalanceType.componentPhase** - use phase component balances, **MaterialBalanceType.componentTotal** - use total component balances, **MaterialBalanceType.elementTotal** - use total element balances, **MaterialBalanceType.total** - use total material balance.}""")) CONFIG.declare("flash_type", ConfigValue( default=FlashType.isothermal, domain=In(FlashType), description="Type of flash to perform", doc="""Indicates what type of flash operation should be used. **default** - FlashType.isothermal. **Valid values:** { **FlashType.isothermal** - specify temperature, **FlashType.isenthalpic** - specify enthalpy.}""")) CONFIG.declare("property_package", ConfigValue( default=useDefault, domain=is_physical_parameter_block, description="Property package to use for control volume", doc="""Property parameter object used to define property calculations, **default** - useDefault. **Valid values:** { **useDefault** - use default package from parent model or flowsheet, **PhysicalParameterObject** - a PhysicalParameterBlock object.}""")) CONFIG.declare("property_package_args", ConfigBlock( implicit=True, description="Arguments to use for constructing property packages", doc="""A ConfigBlock with arguments to be passed to a property block(s) and used when constructing these, **default** - None. **Valid values:** { see property package for documentation.}""")) def build(self): """ Begin building model. Args: None Returns: None """ # Call UnitModel.build to setup dynamics super(FeedFlashData, self).build() # Build Control Volume self.control_volume = ControlVolume0DBlock(default={ "dynamic": self.config.dynamic, "has_holdup": self.config.has_holdup, "property_package": self.config.property_package, "property_package_args": self.config.property_package_args}) # No need for control volume geometry self.control_volume.add_state_blocks( has_phase_equilibrium=True) self.control_volume.add_material_balances( balance_type=self.config.material_balance_type, has_phase_equilibrium=True) # Add isothermal constraint if self.config.flash_type == FlashType.isothermal: @self.Constraint(self.flowsheet().config.time, doc="Isothermal constraint") def isothermal(b, t): return (b.control_volume.properties_in[t].temperature == b.control_volume.properties_out[t].temperature) elif self.config.flash_type == FlashType.isenthalpic: @self.Constraint(self.flowsheet().config.time, doc="Isothermal constraint") def isenthalpic(b, t): cv = b.control_volume return (sum(cv.properties_in[t].get_enthalpy_flow_terms(p) for p in cv.properties_in[t].phase_list) == sum(cv.properties_out[t].get_enthalpy_flow_terms(p) for p in cv.properties_in[t].phase_list)) self.control_volume.add_momentum_balances( balance_type=MomentumBalanceType.pressureTotal) # Add references to all feed state vars s_vars = self.control_volume.properties_in[ self.flowsheet().config.time.first()].define_state_vars() for s in s_vars: l_name = s_vars[s].local_name if s_vars[s].is_indexed(): slicer = ( self.control_volume.properties_in[:].component(l_name)[...]) else: slicer = self.control_volume.properties_in[:].component(l_name) r = Reference(slicer) setattr(self, s, r) # Add Ports self.add_outlet_port() def _get_stream_table_contents(self, time_point=0): return create_stream_table_dataframe( {"Outlet": self.outlet}, time_point=time_point)
baseInvoke.js
define(['./apply', './baseToPath', './isKey', '../last', './parent'], function(apply, baseToPath, isKey, last, parent) { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined;
* * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { if (!isKey(path, object)) { path = baseToPath(path); object = parent(object, path); path = last(path); } var func = object == null ? object : object[path]; return func == null ? undefined : apply(func, object, args); } return baseInvoke; });
/** * The base implementation of `_.invoke` without support for individual * method arguments.
c_api.rs
use std::env; use std::path::PathBuf; use std::process::Command; use ctxkit as txkit_c_api; fn main() { // Setup environment let tmpdir = tempdir::TempDir::new("txkit-tests").expect("failed to create temp dir"); env::set_var("OUT_DIR", tmpdir.as_ref()); env::set_var("TARGET", txkit_c_api::config::TARGET); env::set_var("OPT_LEVEL", txkit_c_api::config::OPT_LEVEL); env::set_var("HOST", txkit_c_api::config::HOST); let libdir = PathBuf::from(txkit_c_api::config::OUT_DIR) .parent() .unwrap() .parent() .unwrap() .parent() .unwrap() .join("deps"); let target_filename = PathBuf::from(tmpdir.as_ref()).join("debug"); // Build shared library println!( "GCC Output: {}", String::from_utf8_lossy( &Command::new("gcc") .args(&[ "-Wall", "-Werror", "-g", "-I../include", &format!("-L{}", libdir.to_string_lossy().as_ref()), &format!("-Wl,-rpath={}", libdir.to_string_lossy().as_ref()), "-lctxkit", "-o",
.output() .expect("failed to compile code") .stderr ) ); std::mem::forget(tmpdir); // Load it println!( "Program output: {}", String::from_utf8_lossy( &Command::new(target_filename) .output() .expect("running program failed") .stderr ) ); }
target_filename.to_string_lossy().as_ref(), "examples/debug.c", ])
devapollo_test.go
package main import ( "fmt" "io/ioutil" "net" "net/http" "os" "strings" "testing" ) var testDir string type DevLxdDialer struct { Path string } func (d DevLxdDialer) DevLxdDial(network, path string) (net.Conn, error) { addr, err := net.ResolveUnixAddr("unix", d.Path) if err != nil { return nil, err } conn, err := net.DialUnix("unix", nil, addr) if err != nil { return nil, err } return conn, err } func setupDir() error { var err error testDir, err = ioutil.TempDir("", "apollo_test_devapollo_") if err != nil { return err } err = os.Chmod(testDir, 0700) if err != nil { return err } os.MkdirAll(fmt.Sprintf("%s/devapollo", testDir), 0755) return os.Setenv("APOLLO_DIR", testDir) } func setupSocket() (*net.UnixListener, error) { setupDir() return createAndBindDevLxd() } func
(path string) (*net.UnixConn, error) { addr, err := net.ResolveUnixAddr("unix", path) if err != nil { return nil, err } conn, err := net.DialUnix("unix", nil, addr) if err != nil { return nil, err } return conn, nil } func TestCredsSendRecv(t *testing.T) { result := make(chan int32, 1) listener, err := setupSocket() if err != nil { t.Fatal(err) } defer listener.Close() defer os.RemoveAll(testDir) go func() { conn, err := listener.AcceptUnix() if err != nil { t.Log(err) result <- -1 return } defer conn.Close() cred, err := getCred(conn) if err != nil { t.Log(err) result <- -1 return } result <- cred.pid }() conn, err := connect(fmt.Sprintf("%s/devapollo/sock", testDir)) if err != nil { t.Fatal(err) } defer conn.Close() pid := <-result if pid != int32(os.Getpid()) { t.Fatal("pid mismatch: ", pid, os.Getpid()) } } /* * Here we're not really testing the API functionality (we can't, since it * expects us to be inside a container to work), but it is useful to test that * all the grotty connection extracting stuff works (that is, it gets to the * point where it realizes the pid isn't in a container without crashing). */ func TestHttpRequest(t *testing.T) { if err := setupDir(); err != nil { t.Fatal(err) } defer os.RemoveAll(testDir) d := &Daemon{} err := d.Init() if err != nil { t.Fatal(err) } defer d.Stop() c := http.Client{Transport: &http.Transport{Dial: DevLxdDialer{Path: fmt.Sprintf("%s/devapollo/sock", testDir)}.DevLxdDial}} raw, err := c.Get("http://1.0") if err != nil { t.Fatal(err) } if raw.StatusCode != 500 { t.Fatal(err) } resp, err := ioutil.ReadAll(raw.Body) if err != nil { t.Fatal(err) } if !strings.Contains(string(resp), pidNotInContainerErr.Error()) { t.Fatal("resp error not expected: ", string(resp)) } }
connect
reader.go
// ex7.4 provides a simple string reader. package reader import ( "io" ) type stringReader struct { s string } func (r *stringReader) Read(p []byte) (n int, err error) { n = copy(p, r.s) r.s = r.s[n:] if len(r.s) == 0 { err = io.EOF } return } func NewReader(s string) io.Reader
{ return &stringReader{s} }
build.rs
// Copyright © 2016-2018 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell; use std::collections::HashMap; use std::env::var; // (header name, &[header dependencies], &[library dependencies]) const DATA: &'static [(&'static str, &'static [&'static str], &'static [&'static str])] = &[ // km // mmos // shared ("basetsd", &[], &[]), ("bcrypt", &["minwindef", "winnt"], &["bcrypt"]), ("bugcodes", &["ntdef"], &[]), ("cderr", &["minwindef"], &[]), ("cfg", &["minwindef"], &[]), ("d3d9", &["basetsd", "d3d9caps", "d3d9types", "guiddef", "minwindef", "unknwnbase", "windef", "wingdi", "winnt"], &["d3d9"]), ("d3d9caps", &["d3d9types", "guiddef", "minwindef", "winnt"], &[]), ("d3d9types", &["basetsd", "guiddef", "minwindef", "windef", "winnt"], &[]), ("dcomptypes", &["dxgitype", "minwindef", "winnt"], &[]), ("devguid", &[], &[]), ("devpkey", &["devpropdef"], &[]), ("devpropdef", &["guiddef", "minwindef", "winnt"], &[]), ("dinputd", &[], &[]), ("dxgi", &["basetsd", "dxgiformat", "dxgitype", "guiddef", "minwindef", "unknwnbase", "windef", "winnt"], &["dxgi"]), ("dxgi1_2", &["basetsd", "dxgi", "dxgiformat", "dxgitype", "guiddef", "minwinbase", "minwindef", "unknwnbase", "windef", "winnt"], &[]), ("dxgi1_3", &["dxgi", "dxgi1_2", "dxgiformat", "guiddef", "minwindef", "unknwnbase", "windef", "winnt"], &["dxgi"]), ("dxgi1_4", &["basetsd", "dxgi1_2", "dxgi1_3", "dxgiformat", "dxgitype", "guiddef", "minwindef", "unknwnbase", "winnt"], &[]), ("dxgi1_5", &["basetsd", "dxgi", "dxgi1_2", "dxgi1_3", "dxgi1_4", "dxgiformat", "minwindef", "unknwnbase", "winnt"], &[]), ("dxgi1_6", &["basetsd", "dxgi1_2", "dxgi1_4", "dxgi1_5", "dxgitype", "guiddef", "minwindef", "windef", "winnt"], &[]), ("dxgiformat", &[], &[]), ("dxgitype", &["d3d9types", "dxgiformat", "minwindef"], &[]), ("evntprov", &["basetsd", "guiddef", "minwindef", "winnt"], &["advapi32"]), ("evntrace", &["basetsd", "evntcons", "evntprov", "guiddef", "handleapi", "minwindef", "timezoneapi", "vadefs", "winnt", "wmistr"], &["advapi32"]), ("guiddef", &[], &[]), ("hidclass", &["guiddef", "minwindef", "winioctl", "winnt"], &[]), ("hidpi", &["hidusage", "minwindef", "ntdef", "ntstatus", "winnt"], &["hid"]), ("hidsdi", &["guiddef", "hidpi", "minwindef", "winnt"], &["hid"]), ("hidusage", &["minwindef"], &[]), ("in6addr", &["minwindef"], &[]), ("inaddr", &["minwindef"], &[]), ("intsafe", &[], &[]), ("ks", &[], &[]), ("ksmedia", &[], &[]), ("ktmtypes", &["guiddef", "minwindef", "winnt"], &[]), ("lmcons", &["minwindef", "winnt"], &[]), ("minwindef", &["basetsd", "ntdef"], &[]), ("mmreg", &["guiddef", "minwindef"], &[]), ("mstcpip", &["basetsd", "guiddef", "in6addr", "inaddr", "minwindef", "winnt", "ws2def"], &["ntdll"]), ("ntddscsi", &["basetsd", "minwindef", "ntdef", "winioctl", "winnt"], &[]), ("ntddser", &["devpropdef"], &[]), ("ntdef", &["basetsd", "guiddef"], &[]), ("ntstatus", &["ntdef"], &[]), ("qos", &["minwindef"], &[]), ("rpc", &[], &[]), ("rpcdce", &["guiddef", "minwindef", "rpc"], &[]), ("rpcndr", &[], &[]), ("sddl", &["basetsd", "minwindef", "winnt"], &["advapi32"]), ("sspi", &["basetsd", "guiddef", "minwindef", "subauth", "wincred", "winnt"], &["credui", "secur32"]), ("stralign", &["vcruntime", "winnt"], &["kernel32"]), ("transportsettingcommon", &["guiddef"], &[]), ("tvout", &["guiddef", "minwindef"], &[]), ("usb", &["minwindef", "usbspec", "winnt"], &[]), ("usbiodef", &["guiddef", "minwindef", "winioctl", "winnt"], &[]), ("usbspec", &["basetsd", "guiddef", "minwindef", "winnt"], &[]), ("windef", &["minwindef", "winnt"], &[]), ("windowsx", &["minwindef"], &[]), ("winerror", &["minwindef"], &[]), ("winusbio", &["minwindef", "usb"], &[]), ("wmistr", &["basetsd", "guiddef", "minwindef", "winnt"], &[]), ("wnnc", &["minwindef"], &[]), ("ws2def", &["basetsd", "guiddef", "inaddr", "minwindef", "vcruntime", "winnt"], &[]), ("ws2ipdef", &["in6addr", "inaddr", "minwindef", "ws2def"], &[]), ("wtypes", &["guiddef", "minwindef", "ntdef", "wtypesbase"], &[]), ("wtypesbase", &["minwindef", "rpcndr", "winnt"], &[]), // ucrt // um ("accctrl", &["guiddef", "minwindef", "winbase", "winnt"], &[]), ("aclapi", &["accctrl", "guiddef", "minwindef", "winnt"], &["advapi32"]), ("appmgmt", &["guiddef", "minwindef", "winnt"], &["advapi32"]), ("audioclient", &["audiosessiontypes", "basetsd", "guiddef", "minwindef", "mmreg", "strmif", "unknwnbase", "winerror", "winnt", "wtypesbase"], &[]), ("audiosessiontypes", &["minwindef"], &[]), ("avrt", &["guiddef", "minwindef", "winnt"], &["avrt"]), ("bits", &["basetsd", "guiddef", "minwindef", "unknwnbase", "winnt"], &[]), ("bits10_1", &["basetsd", "bits", "bits2_0", "bits3_0", "bits5_0", "minwindef", "winnt"], &[]), ("bits1_5", &["basetsd", "bits", "rpcndr", "winnt"], &[]), ("bits2_0", &["basetsd", "bits", "bits1_5", "minwindef", "winnt"], &[]), ("bits2_5", &["minwindef", "rpcndr", "unknwnbase", "winnt"], &[]), ("bits3_0", &["basetsd", "bits", "bits2_0", "guiddef", "minwindef", "unknwnbase", "winnt"], &[]), ("bits4_0", &["basetsd", "bits3_0", "minwindef", "unknwnbase", "winnt"], &[]), ("bits5_0", &["basetsd", "bits1_5", "bits3_0", "bits4_0", "guiddef", "minwindef", "winnt"], &[]), ("bitscfg", &["guiddef", "oaidl", "unknwnbase", "winnt", "wtypes"], &["oleaut32"]), ("bitsmsg", &["minwindef"], &[]), ("cfgmgr32", &["basetsd", "cfg", "guiddef", "minwindef", "winnt", "winreg"], &["setupapi"]), ("cguid", &[], &[]), ("combaseapi", &["basetsd", "guiddef", "minwindef", "objidl", "objidlbase", "propidl", "rpcdce", "unknwnbase", "winnt", "wtypesbase"], &["ole32"]), ("coml2api", &["minwindef"], &[]), ("commapi", &["minwinbase", "minwindef", "winbase", "winnt"], &["kernel32"]), ("commctrl", &["basetsd", "commoncontrols", "guiddef", "minwinbase", "minwindef", "vcruntime", "windef", "winnt", "winuser"], &["comctl32"]), ("commdlg", &["basetsd", "minwindef", "prsht", "unknwnbase", "windef", "wingdi", "winnt", "winuser"], &["comdlg32"]), ("commoncontrols", &["commctrl", "guiddef", "minwindef", "unknwnbase", "windef", "winnt"], &["comctl32"]), ("consoleapi", &["minwindef", "wincon", "winnt"], &["kernel32"]), ("corsym", &["basetsd", "objidlbase", "unknwnbase", "winnt"], &[]), ("d2d1", &["basetsd", "d2dbasetypes", "d3dcommon", "dcommon", "dwrite", "dxgi", "guiddef", "minwindef", "unknwnbase", "wincodec", "windef", "winnt"], &["d2d1"]), ("d2d1_1", &["basetsd", "d2d1", "d2d1effectauthor", "d2dbasetypes", "dcommon", "documenttarget", "dwrite", "dxgi", "dxgiformat", "guiddef", "minwindef", "objidlbase", "unknwnbase", "wincodec", "winnt"], &["d2d1"]), ("d2d1_2", &["d2d1", "d2d1_1", "dxgi", "minwindef", "winnt"], &["d2d1"]), ("d2d1_3", &["basetsd", "d2d1", "d2d1_1", "d2d1_2", "d2d1effects", "d2d1svg", "dcommon", "dwrite", "dxgi", "dxgitype", "minwindef", "ntdef", "objidlbase", "wincodec", "winerror"], &["d2d1"]), ("d2d1effectauthor", &["basetsd", "d2d1", "d2d1_1", "d2dbasetypes", "d3dcommon", "dxgiformat", "guiddef", "minwindef", "ntdef", "unknwnbase", "wincodec"], &[]), ("d2d1effects", &[], &[]), ("d2d1effects_1", &[], &[]), ("d2d1effects_2", &[], &[]), ("d2d1svg", &["basetsd", "d2d1", "d2d1_1", "guiddef", "minwindef", "ntdef", "objidlbase", "winerror"], &[]), ("d2dbasetypes", &["d3d9types", "dcommon"], &[]), ("d3d", &[], &[]), ("d3d10", &["d3dcommon"], &[]), ("d3d10_1", &[], &[]), ("d3d10_1shader", &[], &[]), ("d3d10effect", &[], &[]), ("d3d10misc", &[], &[]), ("d3d10sdklayers", &[], &[]), ("d3d10shader", &["d3d10", "d3dcommon", "minwindef", "unknwnbase", "winnt"], &[]), ("d3d11", &["basetsd", "d3dcommon", "dxgi", "dxgiformat", "dxgitype", "guiddef", "minwindef", "unknwnbase", "windef", "winnt"], &["d3d11"]), ("d3d11_1", &["basetsd", "d3d11", "d3dcommon", "dxgiformat", "dxgitype", "guiddef", "minwindef", "unknwnbase", "winnt"], &[]), ("d3d11_2", &["basetsd", "d3d11", "d3d11_1", "dxgiformat", "minwindef", "winnt"], &[]), ("d3d11_3", &[], &[]), ("d3d11_4", &[], &[]), ("d3d11on12", &["d3d11", "d3d12", "d3dcommon", "guiddef", "minwindef", "unknwnbase", "winnt"], &["d3d11"]), ("d3d11sdklayers", &["basetsd", "d3d11", "dxgi", "minwindef", "unknwnbase", "winnt"], &[]), ("d3d11shader", &["basetsd", "d3dcommon", "minwindef", "unknwnbase", "winnt"], &[]), ("d3d11tokenizedprogramformat", &["minwindef"], &[]), ("d3d12", &["basetsd", "d3dcommon", "dxgiformat", "dxgitype", "guiddef", "minwinbase", "minwindef", "unknwnbase", "windef", "winnt"], &["d3d12"]), ("d3d12sdklayers", &["basetsd", "d3d12", "minwindef", "unknwnbase", "winnt"], &[]), ("d3d12shader", &["basetsd", "d3dcommon", "minwindef", "unknwnbase", "winnt"], &[]), ("d3dcommon", &["basetsd", "minwindef", "unknwnbase", "winnt"], &[]), ("d3dcompiler", &["basetsd", "d3d11shader", "d3dcommon", "guiddef", "minwindef", "winnt"], &["d3dcompiler"]), ("d3dcsx", &[], &[]), ("d3dx10core", &[], &[]), ("d3dx10math", &[], &[]), ("d3dx10mesh", &[], &[]), ("datetimeapi", &["minwinbase", "minwindef", "winnt"], &["kernel32"]), ("davclnt", &["minwindef", "winnt"], &["netapi32"]), ("dbghelp", &["basetsd", "guiddef", "minwindef", "vcruntime", "winnt"], &["dbghelp"]), ("dbt", &["basetsd", "guiddef", "minwindef", "winnt", "winuser"], &[]), ("dcommon", &["basetsd", "dxgiformat", "minwindef", "windef"], &[]), ("dcomp", &["d2d1", "d2d1_1", "d2d1effects", "d2dbasetypes", "d3d9types", "d3dcommon", "dcompanimation", "dcomptypes", "dxgi", "dxgi1_2", "dxgiformat", "guiddef", "minwinbase", "minwindef", "ntdef", "unknwnbase", "windef"], &["dcomp"]), ("dcompanimation", &["ntdef", "unknwnbase"], &[]), ("dde", &["basetsd", "minwindef"], &["user32"]), ("ddraw", &[], &[]), ("ddrawi", &[], &[]), ("ddrawint", &[], &[]), ("debugapi", &["minwinbase", "minwindef", "winnt"], &["kernel32"]), ("devicetopology", &["guiddef", "minwindef", "unknwnbase", "windef", "winnt", "wtypes"], &[]), ("dinput", &[], &[]), ("dmksctl", &[], &[]), ("dmusicc", &[], &[]), ("docobj", &["guiddef", "minwindef", "oaidl", "unknwnbase", "winnt"], &[]), ("documenttarget", &["basetsd", "guiddef", "ntdef", "unknwnbase"], &[]), ("dpa_dsa", &["basetsd", "minwindef", "winnt"], &["comctl32"]), ("dpapi", &["minwindef", "wincrypt", "windef", "winnt"], &["crypt32"]), ("dsgetdc", &["guiddef", "minwindef", "ntsecapi", "winnt", "ws2def"], &["netapi32"]), ("dsound", &["guiddef", "minwindef", "mmsystem", "unknwnbase", "windef", "winerror", "winnt"], &["dsound"]), ("dsrole", &["guiddef", "minwindef", "winnt"], &["netapi32"]), ("dvp", &[], &[]), ("dwmapi", &["basetsd", "minwindef", "uxtheme", "windef", "winnt"], &["dwmapi"]), ("dwrite", &["basetsd", "d2d1", "dcommon", "guiddef", "minwindef", "unknwnbase", "windef", "winerror", "wingdi", "winnt"], &["dwrite"]), ("dwrite_1", &["basetsd", "dcommon", "dwrite", "minwindef", "winnt"], &[]), ("dwrite_2", &["basetsd", "d3d9types", "dcommon", "dwrite", "dwrite_1", "minwindef", "unknwnbase", "winnt"], &[]), ("dwrite_3", &["basetsd", "dcommon", "dwrite", "dwrite_1", "dwrite_2", "minwindef", "unknwnbase", "wingdi", "winnt"], &[]), ("dxdiag", &[], &[]), ("dxfile", &[], &[]), ("dxgidebug", &["basetsd", "guiddef", "minwindef", "unknwnbase", "winnt"], &["dxgi"]), ("dxva2api", &["basetsd", "d3d9", "d3d9types", "guiddef", "minwindef", "unknwnbase", "windef", "winnt"], &["dxva2"]), ("dxvahd", &["d3d9", "d3d9types", "guiddef", "minwindef", "unknwnbase", "windef", "winnt"], &["dxva2"]), ("endpointvolume", &["basetsd", "guiddef", "minwindef", "unknwnbase", "winnt"], &[]), ("errhandlingapi", &["basetsd", "minwindef", "winnt"], &["kernel32"]), ("evntcons", &["basetsd", "evntprov", "evntrace", "guiddef", "minwindef", "winnt"], &["advapi32"]), ("exdisp", &["basetsd", "docobj", "oaidl", "ocidl", "winnt", "wtypes"], &[]), ("fibersapi", &["minwindef", "winnt"], &["kernel32"]), ("fileapi", &["minwinbase", "minwindef", "winnt"], &["kernel32"]), ("gl-gl", &[], &["opengl32"]), ("handleapi", &["minwindef", "winnt"], &["kernel32"]), ("heapapi", &["basetsd", "minwinbase", "minwindef", "winnt"], &["kernel32"]), ("highlevelmonitorconfigurationapi", &["minwindef", "physicalmonitorenumerationapi", "winnt"], &["dxva2"]), ("http", &["guiddef", "minwinbase", "minwindef", "sspi", "winnt", "ws2def"], &["winhttp"]), ("imm", &["minwindef", "windef"], &["imm32"]), ("interlockedapi", &["minwindef", "winnt"], &["kernel32"]), ("ioapiset", &["basetsd", "minwinbase", "minwindef", "winnt"], &["kernel32"]), ("jobapi", &["minwindef", "winnt"], &["kernel32"]), ("jobapi2", &["basetsd", "minwinbase", "minwindef", "ntdef", "winnt"], &["kernel32"]), ("knownfolders", &[], &[]), ("ktmw32", &["guiddef", "minwinbase", "minwindef", "winnt"], &["ktmw32"]), ("libloaderapi", &["basetsd", "minwindef", "winnt"], &["kernel32", "user32"]), ("lmaccess", &["basetsd", "lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmalert", &["lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmapibuf", &["lmcons", "minwindef"], &["netapi32"]), ("lmat", &["basetsd", "lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmdfs", &["guiddef", "lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmerrlog", &["minwindef", "winnt"], &[]), ("lmjoin", &["lmcons", "minwindef", "wincrypt", "winnt"], &["netapi32"]), ("lmmsg", &["lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmremutl", &["lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmrepl", &["lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmserver", &["guiddef", "lmcons", "minwindef", "winnt", "winsvc"], &["advapi32", "netapi32"]), ("lmshare", &["basetsd", "guiddef", "lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmstats", &["lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmsvc", &["lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmuse", &["lmcons", "minwindef", "winnt"], &["netapi32"]), ("lmwksta", &["lmcons", "minwindef", "winnt"], &["netapi32"]), ("lowlevelmonitorconfigurationapi", &["minwindef", "physicalmonitorenumerationapi", "winnt"], &["dxva2"]), ("lsalookup", &["guiddef", "minwindef", "ntdef", "winnt"], &["advapi32"]), ("memoryapi", &["basetsd", "minwinbase", "minwindef", "winnt"], &["kernel32"]), ("minschannel", &["guiddef", "minwindef", "wincrypt", "winnt"], &[]), ("minwinbase", &["basetsd", "minwindef", "ntstatus", "winnt"], &[]), ("mmdeviceapi", &["guiddef", "minwindef", "propidl", "propsys", "unknwnbase", "winnt", "wtypes"], &["mmdevapi"]), ("mmeapi", &["basetsd", "imm", "minwindef", "mmsystem", "winnt"], &["winmm"]), ("mmsystem", &["basetsd", "minwindef", "mmreg", "winnt"], &[]), ("msaatext", &[], &[]), ("mscat", &["guiddef", "minwindef", "mssip", "wincrypt", "winnt"], &[]), ("mschapp", &["basetsd", "minwindef", "winnt"], &["advapi32"]), ("mssip", &["guiddef", "minwindef", "mscat", "wincrypt", "winnt"], &["crypt32"]), ("namedpipeapi", &["minwinbase", "minwindef", "winnt"], &["advapi32", "kernel32"]), ("namespaceapi", &["minwinbase", "minwindef", "ntdef", "winnt"], &["kernel32"]), ("nb30", &["minwindef", "winnt"], &["netapi32"]), ("ncrypt", &["basetsd", "bcrypt", "minwindef", "winnt"], &["ncrypt"]), ("ntlsa", &["basetsd", "guiddef", "lsalookup", "minwindef", "ntdef", "ntsecapi", "subauth", "winnt"], &["advapi32"]), ("ntsecapi", &["basetsd", "guiddef", "lsalookup", "minwindef", "ntdef", "sspi", "subauth", "winnt"], &["advapi32"]), ("oaidl", &["basetsd", "guiddef", "minwindef", "rpcndr", "unknwnbase", "winnt", "wtypes", "wtypesbase"], &[]), ("objbase", &["combaseapi", "minwindef", "winnt"], &["ole32"]), ("objidl", &["basetsd", "guiddef", "minwindef", "ntdef", "objidlbase", "unknwnbase", "windef", "winnt", "wtypes", "wtypesbase"], &[]), ("objidlbase", &["basetsd", "guiddef", "minwindef", "unknwnbase", "winnt", "wtypesbase"], &[]), ("ocidl", &["guiddef", "minwindef", "ntdef", "oaidl", "unknwnbase", "wtypes", "wtypesbase"], &[]), ("ole2", &["minwindef", "oleidl", "windef", "winnt"], &["ole32"]), ("oleauto", &["basetsd", "minwinbase", "minwindef", "oaidl", "winnt", "wtypes", "wtypesbase"], &["oleaut32"]), ("olectl", &["winerror", "winnt"], &[]), ("oleidl", &["minwindef", "ntdef", "objidl", "unknwnbase", "windef"], &[]), ("opmapi", &["basetsd", "d3d9", "d3d9types", "dxva2api", "guiddef", "minwindef", "unknwnbase", "windef", "winnt"], &["dxva2"]), ("pdh", &["basetsd", "guiddef", "minwindef", "windef", "winnt"], &["pdh"]), ("perflib", &["basetsd", "guiddef", "minwinbase", "minwindef", "winnt"], &["advapi32"]), ("physicalmonitorenumerationapi", &["d3d9", "minwindef", "windef", "winnt"], &["dxva2"]), ("playsoundapi", &["minwindef", "winnt"], &["winmm"]), ("powerbase", &["minwindef", "winnt", "winuser"], &["powrprof"]), ("powersetting", &["guiddef", "minwindef", "winnt", "winuser"], &["powrprof"]), ("powrprof", &["guiddef", "minwindef", "winnt", "winreg"], &["powrprof"]), ("processenv", &["minwindef", "winnt"], &["kernel32"]), ("processsnapshot", &["basetsd", "minwindef", "winnt"], &["kernel32"]), ("processthreadsapi", &["basetsd", "guiddef", "minwinbase", "minwindef", "winnt"], &["advapi32", "kernel32"]), ("processtopologyapi", &["minwindef", "winnt"], &["kernel32"]), ("profileapi", &["minwindef", "winnt"], &["kernel32"]), ("propidl", &["minwindef", "wtypes"], &[]), ("propkeydef", &["guiddef", "wtypes"], &[]), ("propsys", &["minwindef", "propidl", "propkeydef", "unknwnbase", "winnt", "wtypes"], &[]), ("prsht", &["basetsd", "minwindef", "windef", "winnt", "winuser"], &["comctl32"]), ("psapi", &["basetsd", "minwindef", "winnt"], &["kernel32", "psapi"]), ("realtimeapiset", &["basetsd", "minwindef", "winnt"], &["kernel32"]), ("reason", &["minwindef"], &[]), ("restartmanager", &["minwindef", "winnt"], &["rstrtmgr"]), ("restrictederrorinfo", &["unknwnbase", "winnt", "wtypes"], &[]), ("rmxfguid", &[], &[]), ("sapi", &["guiddef", "minwindef", "sapi53", "unknwnbase", "winnt"], &[]), ("sapi51", &["guiddef", "minwindef", "mmreg", "oaidl", "objidlbase", "rpcndr", "servprov", "unknwnbase", "windef", "winnt", "wtypes", "wtypesbase"], &[]), ("sapi53", &["guiddef", "minwindef", "oaidl", "sapi51", "unknwnbase", "urlmon", "winnt", "wtypes"], &[]), ("sapiddk", &["guiddef", "minwindef", "sapi", "sapiddk51", "unknwnbase", "winnt"], &[]), ("sapiddk51", &["guiddef", "minwindef", "mmreg", "oaidl", "objidlbase", "sapi", "unknwnbase", "windef", "winnt"], &[]), ("schannel", &["guiddef", "minwindef", "wincrypt", "windef", "winnt"], &[]), ("securityappcontainer", &["minwindef", "winnt"], &["kernel32"]), ("securitybaseapi", &["guiddef", "minwinbase", "minwindef", "winnt"], &["advapi32", "kernel32"]), ("servprov", &["guiddef", "unknwnbase", "winnt"], &[]), ("setupapi", &["basetsd", "commctrl", "devpropdef", "guiddef", "minwindef", "prsht", "spapidef", "windef", "winnt", "winreg"], &["setupapi"]), ("shellapi", &["basetsd", "guiddef", "minwinbase", "minwindef", "processthreadsapi", "windef", "winnt", "winuser"], &["shell32", "shlwapi"]), ("shellscalingapi", &["minwindef", "windef", "winnt"], &["shcore"]), ("shlobj", &["guiddef", "minwinbase", "minwindef", "shtypes", "windef", "winnt"], &["shell32"]), ("shobjidl", &["guiddef", "minwindef", "objidl", "propkeydef", "propsys", "shobjidl_core", "shtypes", "unknwnbase", "windef", "winnt"], &[]), ("shobjidl_core", &["guiddef", "minwindef", "objidl", "unknwnbase", "windef", "winnt"], &[]), ("shtypes", &["guiddef", "minwindef", "winnt"], &[]), ("spapidef", &["minwindef", "winnt"], &[]), ("sporder", &["guiddef", "minwindef"], &["sporder"]), ("sql", &["sqltypes"], &["odbc32"]), ("sqlext", &["sql", "sqltypes"], &[]), ("sqltypes", &["basetsd", "guiddef", "windef"], &[]), ("sqlucode", &["sqltypes"], &["odbc32"]), ("stringapiset", &["minwindef", "winnls", "winnt"], &["kernel32"]), ("strmif", &["winnt"], &[]), ("subauth", &["minwindef", "winnt"], &[]), ("synchapi", &["basetsd", "minwinbase", "minwindef", "winnt"], &["kernel32", "synchronization"]), ("sysinfoapi", &["basetsd", "minwinbase", "minwindef", "winnt"], &["kernel32"]), ("systemtopologyapi", &["minwindef", "winnt"], &["kernel32"]), ("textstor", &[], &[]), ("threadpoolapiset", &["basetsd", "minwinbase", "minwindef", "winnt"], &["kernel32"]), ("threadpoollegacyapiset", &["minwinbase", "minwindef", "winnt"], &["kernel32"]), ("timeapi", &["minwindef", "mmsystem"], &["winmm"]), ("timezoneapi", &["minwinbase", "minwindef", "winnt"], &["advapi32", "kernel32"]), ("tlhelp32", &["basetsd", "minwindef", "winnt"], &["kernel32"]), ("unknwnbase", &["guiddef", "minwindef", "winnt"], &[]), ("urlhist", &["docobj", "guiddef", "minwindef", "unknwnbase", "winnt", "wtypesbase"], &[]), ("urlmon", &["minwindef", "unknwnbase", "winnt"], &[]), ("userenv", &["minwindef", "winnt", "winreg"], &["userenv"]), ("usp10", &["minwindef", "ntdef", "windef", "winerror", "wingdi", "winnt"], &["usp10"]), ("utilapiset", &["minwindef", "ntdef"], &["kernel32"]), ("uxtheme", &["commctrl", "minwindef", "windef", "wingdi", "winnt"], &["uxtheme"]), ("vsbackup", &["guiddef", "minwindef", "unknwnbase", "vss", "vswriter", "winnt", "wtypes"], &["vssapi"]), ("vss", &["guiddef", "minwindef", "unknwnbase", "winnt"], &[]), ("vsserror", &["winnt"], &[]), ("vswriter", &["minwindef", "unknwnbase", "vss", "winnt", "wtypes"], &[]), ("wct", &["basetsd", "guiddef", "minwindef", "winnt"], &["advapi32"]), ("werapi", &["minwindef", "winnt"], &["kernel32", "wer"]), ("winbase", &["basetsd", "cfgmgr32", "fileapi", "guiddef", "libloaderapi", "minwinbase", "minwindef", "processthreadsapi", "vadefs", "windef", "winnt"], &["kernel32"]), ("wincodec", &["basetsd", "d2d1", "d2d1_1", "dcommon", "dxgiformat", "dxgitype", "guiddef", "minwindef", "ntdef", "objidlbase", "ocidl", "propidl", "unknwnbase", "windef", "winerror", "winnt"], &["windowscodecs"]), ("wincodecsdk", &["guiddef", "minwindef", "oaidl", "objidl", "objidlbase", "ocidl", "propidl", "unknwnbase", "wincodec", "winnt", "wtypes"], &["ole32", "oleaut32", "windowscodecs"]), ("wincon", &["minwinbase", "minwindef", "windef", "wingdi", "winnt"], &["kernel32"]), ("wincred", &["minwindef", "sspi", "windef", "winnt"], &["advapi32", "credui"]), ("wincrypt", &["basetsd", "bcrypt", "guiddef", "minwinbase", "minwindef", "ncrypt", "vcruntime", "winnt"], &["advapi32", "crypt32", "cryptnet"]), ("windowsceip", &["minwindef"], &["kernel32"]), ("winefs", &["basetsd", "minwinbase", "minwindef", "wincrypt", "winnt"], &["advapi32"]), ("winevt", &["basetsd", "guiddef", "minwinbase", "minwindef", "vcruntime", "winnt"], &["wevtapi"]), ("wingdi", &["basetsd", "minwindef", "windef", "winnt"], &["gdi32", "msimg32", "opengl32", "winspool"]), ("winhttp", &["basetsd", "minwinbase", "minwindef", "winnt"], &["winhttp"]), ("wininet", &["basetsd", "minwinbase", "minwindef", "ntdef", "windef", "winineti", "winnt"], &["wininet"]), ("winineti", &["minwindef"], &[]), ("winioctl", &["basetsd", "devpropdef", "guiddef", "minwindef", "winnt"], &[]), ("winnetwk", &["basetsd", "minwindef", "windef", "winerror", "winnt"], &["mpr"]), ("winnls", &["basetsd", "guiddef", "minwinbase", "minwindef", "winnt"], &["kernel32"]), ("winnt", &["basetsd", "excpt", "guiddef", "ktmtypes", "minwindef", "vcruntime"], &["kernel32"]), ("winreg", &["basetsd", "minwinbase", "minwindef", "winnt"], &["advapi32"]), ("winsafer", &["basetsd", "guiddef", "minwindef", "wincrypt", "windef", "winnt"], &["advapi32"]), ("winscard", &["basetsd", "guiddef", "minwindef", "rpcdce", "windef", "winnt", "winsmcrd"], &["winscard"]), ("winsmcrd", &["minwindef", "winioctl"], &[]), ("winsock2", &["basetsd", "guiddef", "inaddr", "minwinbase", "minwindef", "qos", "winbase", "windef", "winerror", "winnt", "ws2def", "wtypesbase"], &["ws2_32"]), ("winspool", &["guiddef", "minwinbase", "minwindef", "vcruntime", "windef", "winerror", "wingdi", "winnt"], &["winspool"]), ("winsvc", &["minwindef", "winnt"], &["advapi32"]), ("winusb", &["minwinbase", "minwindef", "usb", "usbspec", "winnt", "winusbio"], &["winusb"]), ("winuser", &["basetsd", "guiddef", "limits", "minwinbase", "minwindef", "vadefs", "windef", "wingdi", "winnt"], &["user32"]), ("winver", &["minwindef", "winnt"], &["kernel32", "version"]), ("wow64apiset", &["minwindef", "winnt"], &["kernel32"]), ("ws2spi", &["basetsd", "guiddef", "minwindef", "vcruntime", "windef", "winnt", "winsock2", "ws2def", "wtypesbase"], &["ws2_32"]), ("ws2tcpip", &["guiddef", "minwinbase", "minwindef", "mstcpip", "vcruntime", "winerror", "winnt", "winsock2", "ws2def", "wtypesbase"], &["fwpuclnt", "ws2_32"]), ("xinput", &["guiddef", "minwindef", "winnt"], &["xinput"]), // vc ("excpt", &[], &[]), ("limits", &[], &[]), ("vadefs", &[], &[]), ("vcruntime", &[], &[]), // winrt ("activation", &["inspectable", "winnt"], &[]), ("hstring", &["winnt"], &[]), ("inspectable", &["guiddef", "hstring", "minwindef", "unknwnbase", "winnt"], &[]), ("roapi", &["activation", "basetsd", "guiddef", "hstring", "inspectable", "objidl", "winnt"], &["runtimeobject"]), ("robuffer", &["objidl", "winnt"], &["runtimeobject"]), ("roerrorapi", &["basetsd", "hstring", "minwindef", "restrictederrorinfo", "unknwnbase", "winnt"], &["runtimeobject"]), ("winstring", &["basetsd", "hstring", "minwindef", "winnt"], &["runtimeobject"]), ]; struct Header { required: bool, included: Cell<bool>, dependencies: &'static [&'static str], libraries: &'static [&'static str], } struct Graph(HashMap<&'static str, Header>); impl Graph { fn generate() -> Graph { Graph(DATA.iter().map(|&(name, dependencies, libraries)| { let header = Header { required: false, included: Cell::new(false), dependencies: dependencies, libraries: libraries, }; (name, header) }).collect()) } fn identify_required(&mut self) { for (name, header) in &mut self.0 { if let Ok(_) = var(&format!("CARGO_FEATURE_{}", name.to_uppercase())) { header.required = true; header.included.set(true); } } } fn check_everything(&self) { if let Ok(_) = var("CARGO_FEATURE_EVERYTHING") { for (_, header) in &self.0 { header.included.set(true); } } } fn resolve_dependencies(&self) { let mut done = false; while !done { done = true; for (_, header) in &self.0 { if header.included.get() { for dep in header.dependencies { let dep = &self.0.get(dep).expect(dep); if !dep.included.get() { done = false; dep.included.set(true); } } } } } } fn emit_features(&self) { for (name, header) in &self.0 { if header.included.get() && !header.required { println!("cargo:rustc-cfg=feature=\"{}\"", name); } } } fn e
&self) { let mut libs = self.0.iter().filter(|&(_, header)| { header.included.get() }).flat_map(|(_, header)| { header.libraries.iter() }).collect::<Vec<_>>(); libs.sort(); libs.dedup(); let prefix = library_prefix(); let kind = library_kind(); for lib in libs { println!("cargo:rustc-link-lib={}={}{}", kind, prefix, lib); } } } fn library_prefix() -> &'static str { if var("TARGET").map(|target| target == "i686-pc-windows-gnu" || target == "x86_64-pc-windows-gnu" ).unwrap_or(false) && var("WINAPI_NO_BUNDLED_LIBRARIES").is_err() { "winapi_" } else { "" } } fn library_kind() -> &'static str { if var("WINAPI_STATIC_NOBUNDLE").is_ok() { "static-nobundle" } else { "dylib" } } fn try_everything() { let mut graph = Graph::generate(); graph.identify_required(); graph.check_everything(); graph.resolve_dependencies(); graph.emit_features(); graph.emit_libraries(); } fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-env-changed=WINAPI_NO_BUNDLED_LIBRARIES"); println!("cargo:rerun-if-env-changed=WINAPI_STATIC_NOBUNDLE"); let target = var("TARGET").unwrap(); let target: Vec<_> = target.split('-').collect(); if target.get(2) == Some(&"windows") { try_everything(); } }
mit_libraries(
DEV.Image.Draggable.tsx
import React, { useEffect, useRef, useState } from 'react'; import { filter } from 'rxjs/operators'; import { COLORS, css, CssValue, FileUtil, Icons, MotionDraggable, MotionDraggableDef, MotionDraggableEvent, rx, t, useDragTarget, useResizeObserver, } from '../common'; export type DevImageDraggableProps = { bus: t.EventBus<any>; netbus: t.PeerNetworkBus<any>; style?: CssValue; }; export const DevImageDraggable: React.FC<DevImageDraggableProps> = (props) => { const netbus = props.netbus as t.PeerNetworkBus<t.DevEvent>; const self = netbus.self; const source = self; type Img = { uri: string; filename: string; mimetype: string }; const [image, setImage] = useState<Img | undefined>(); const [dragbus, setDragbus] = useState<t.EventBus<any>>(); const drag = useDragTarget<HTMLDivElement>(async (e) => { const file = e.files[0]; if (file) { const { mimetype, data, path } = file; netbus.fire({ type: 'DEV/group/image/load', payload: { source, mimetype, data, filename: path }, }); } }); const resize = useResizeObserver(drag.ref); useEffect(() => { const namespace = 'image/draggable'; const dragbus = rx.bus<MotionDraggableEvent>(); const dragEvents = MotionDraggable.Events(dragbus); setDragbus(dragbus); /** * Load image data from network. */ rx.payload<t.DevGroupLayoutImageLoadEvent>(netbus.$, 'DEV/group/image/load') .pipe() .subscribe(async (e) => { const { data, mimetype, filename } = e; const uri = await FileUtil.toUri(data); setImage({ uri, mimetype, filename }); }); /** * Monitor movement of video items that have been "dragged" * and broadcast these changes to other peers. */ dragEvents.item.move$.pipe(filter((e) => e.via === 'drag')).subscribe(async (e) => { const { id, lifecycle } = e; const { x, y } = e.status.position; const items = [{ id, x, y }]; netbus.target.remote({ type: 'DEV/group/layout/items/change', payload: { source, lifecycle, items, namespace }, }); }); /** * Monitor scale of video items that have changed * and broadcast these changes to other peers. */ dragEvents.item.scale$.pipe(filter((e) => e.via === 'wheel')).subscribe(async (e) => { const { id, lifecycle } = e; const { scale } = e.status.size; const items = [{ id, scale }]; netbus.target.remote({ type: 'DEV/group/layout/items/change', payload: { source, lifecycle, items, namespace }, }); }); /** * Monitor remote notifications of video items moving. */ rx.payload<t.DevGroupLayoutItemsChangeEvent>(netbus.$, 'DEV/group/layout/items/change') .pipe( filter((e) => e.namespace === namespace), filter((e) => e.source !== self), filter((e) => e.lifecycle === 'complete'), )
dragEvents.item.change.start({ id, x, y, scale }); }); }); return () => { dragEvents.dispose(); }; }, []); // eslint-disable-line const styles = { base: css({ Absolute: 0, overflow: 'hidden', }), drag: { overlay: css({ Absolute: 0, Flex: 'vertical-center-center' }), icon: css({ marginBottom: 6, opacity: 0.2 }), }, draggable: css({ Absolute: [ 0 - resize.rect.height / 2, 0 - resize.rect.width / 2, 0 - resize.rect.height / 2, 0 - resize.rect.width / 2, ], }), }; const elDragOverlay = drag.isDragOver && ( <div {...styles.drag.overlay}> <Icons.Upload.Box size={46} style={styles.drag.icon} color={COLORS.DARK} /> </div> ); const items: MotionDraggableDef[] = []; if (image && resize.ready) { const { width, height } = resize.rect; const styles = { base: css({ Absolute: 0, backgroundRepeat: 'no-repeat', backgroundImage: `url(${image.uri})`, backgroundSize: `contain`, backgroundPosition: `center center`, }), }; const el = <div {...styles.base} />; items.push({ id: 'image', width, height, el, scaleable: { min: 0.3, max: 5 }, }); } const elBody = resize.ready && ( <> {dragbus && <MotionDraggable bus={dragbus} style={styles.draggable} items={items} />} {elDragOverlay} </> ); return ( <div ref={drag.ref} {...css(styles.base, props.style)}> {elBody} </div> ); };
.subscribe((e) => { e.items.forEach(async (item) => { const { id, x, y, scale } = item;
tessellation.py
# -*- coding: utf-8 -*- """ filename - tessellation.py author - MyMindPalace Description A Tessellation (or Tiling) is the act of covering a surface with a pattern of flat shapes so that there are no overlaps or gaps. Tessellations express fascinating geometric and symmetric properties as art, and famously appear in Islamic art with four, five, and six-fold regular tessellations. Input tessellation dimension - 2 tile dimension - 4 # # # # # - - # # + + # # # # # Output # # # # # # # # # - - # # - - # # + + # # + + # # # # # # # # # # # # # # # # # # - - # # - - # # + + # # + + # # # # # # # # # """ tessellation_dimension = 0 tile_dimension = 0 tile = [] tess = [] def tessellation(): global tile,tessellation_dimension,tile_dimension tile_row = 0 tile_column = 0 print("Enter the tile") for i in range(tile_dimension): tile.append([]) for i in range(tile_dimension): tile[i] = list(input().split(" ")) for i in range(tile_dimension*tessellation_dimension): tess.append([]) for i in range(tile_dimension*tessellation_dimension): for j in range(tile_dimension*tessellation_dimension): tess[i].append(tile[tile_row][tile_column]) tile_column = tile_column + 1 if tile_column == tile_dimension: tile_column = 0 tile_row = tile_row + 1 if tile_row == tile_dimension: tile_row = 0 for i in range(tile_dimension*tessellation_dimension): print(tess[i]) def main():
if __name__ == "__main__": main()
global tile_dimension,tessellation_dimension tessellation_dimension = int(input("Tessellation Dimension - ")) tile_dimension = int(input("Tile Dimension - ")) tessellation()
test_config_file.py
from pathlib import Path from tempfile import NamedTemporaryFile, SpooledTemporaryFile from unittest import TestCase from click.testing import CliRunner from duplicity_backup_s3.config import check_config_file class TestConfig(TestCase): def test_default_config_provided_by_package(self): from duplicity_backup_s3.defaults import CONFIG_TEMPLATE_PATH from duplicity_backup_s3.defaults import CONFIG_SCHEMA_PATH config_tempate_path = CONFIG_TEMPLATE_PATH check_config_file(config_file=config_tempate_path, testing=True) def test_vanilla_config(self): config_yaml = """ aws: AWS_ACCESS_KEY_ID: foobar_aws_key_id AWS_SECRET_ACCESS_KEY: foobar_aws_access_key backuproot: /home excludes: - _TESTFILE_TO_EXCLUDE includes: - Pictures remote: bucket: '' path: '__test' full_if_older_than: 7D """ with NamedTemporaryFile(mode="w") as t: t.write(config_yaml) t.flush() self.assertEqual( check_config_file(config_file=Path(t.name), testing=True), Path(t.name) ) def test_extra_key_fails(self): config_yaml = """ aws: AWS_ACCESS_KEY_ID: foobar_aws_key_id AWS_SECRET_ACCESS_KEY: foobar_aws_access_key backuproot: /home excludes: - _TESTFILE_TO_EXCLUDE includes: - Pictures remote: bucket: '' path: '__test' full_if_older_than: 7D One_more_key: fail """ with NamedTemporaryFile(mode="w") as t: t.write(config_yaml) t.flush() self.assertDictEqual( check_config_file(config_file=Path(t.name), testing=True), {"One_more_key": ["unknown field"]}, ) def test_optional_missing_key_succeed(self): config_yaml = """ aws: AWS_ACCESS_KEY_ID: foobar_aws_key_id AWS_SECRET_ACCESS_KEY: foobar_aws_access_key backuproot: /home remote: bucket: '' path: '__test' full_if_older_than: 7D """ with NamedTemporaryFile(mode="w") as t: t.write(config_yaml) t.flush() self.assertEqual( check_config_file(config_file=Path(t.name), testing=True), Path(t.name) ) def
(self): config_yaml = """ aws: AWS_ACCESS_KEY_ID: foobar_aws_key_id AWS_SECRET_ACCESS_KEY: foobar_aws_access_key backuproot: /home remote: path: '__test' full_if_older_than: 7D """ with NamedTemporaryFile(mode="w") as t: t.write(config_yaml) t.flush() self.assertDictEqual( check_config_file(config_file=Path(t.name), testing=True), {"remote": [{"bucket": ["required field"]}]}, ) def test_incorrect_value_type_fails(self): config_yaml = """ aws: AWS_ACCESS_KEY_ID: foobar_aws_key_id AWS_SECRET_ACCESS_KEY: foobar_aws_access_key backuproot: 1 remote: bucket: '' path: '__test' full_if_older_than: 7D """ with NamedTemporaryFile(mode="w") as t: t.write(config_yaml) t.flush() self.assertDictEqual( check_config_file(config_file=Path(t.name), testing=True), {"backuproot": ["must be of string type"]}, ) def test_config_from_production_success(self): config_yaml = """ aws: AWS_ACCESS_KEY_ID: fakekey AWS_SECRET_ACCESS_KEY: fakesecret backuproot: /opt/dir/ includes: - /opt/dir/*-media - /opt/dir/var/archives excludes: - "**" remote: bucket: somebucket path: __testpath """ with NamedTemporaryFile(mode="w") as t: t.write(config_yaml) t.flush() self.assertEqual( check_config_file(config_file=Path(t.name), testing=True), Path(t.name), )
test_required_missing_key_fails
Dropdown.test.tsx
/* tslint:disable:no-unused-variable */ import * as React from 'react'; import * as ReactDOM from 'react-dom'; /* tslint:enable:no-unused-variable */ import * as ReactTestUtils from 'react-addons-test-utils'; let { expect } = chai; import { KeyCodes, } from '../../Utilities'; import { Dropdown } from './Dropdown'; import { DropdownMenuItemType, IDropdownOption } from './Dropdown.Props'; const DEFAULT_OPTIONS: IDropdownOption[] = [ { key: 'Header1', text: 'Header 1', itemType: DropdownMenuItemType.Header }, { key: '1', text: '1' }, { key: '2', text: '2' }, { key: '3', text: '3' }, { key: 'Divider1', text: '-', itemType: DropdownMenuItemType.Divider }, { key: 'Header2', text: 'Header 2', itemType: DropdownMenuItemType.Header }, { key: '4', text: '4' }, { key: '5', text: '5' }, { key: '6', text: '6' }, ]; describe('Dropdown', () => { it('Can flip between enabled and disabled.', () => { let container = document.createElement('div'); ReactDOM.render( <Dropdown label='testgroup' options={ DEFAULT_OPTIONS } />, container); let dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement; expect(dropdownRoot.className).not.contains('is-disabled', `shouldn't be disabled`); expect(dropdownRoot.getAttribute('data-is-focusable')).equals('true', 'data-is-focusable'); ReactDOM.render( <Dropdown disabled={ true } label='testgroup' options={ DEFAULT_OPTIONS } />, container); expect(dropdownRoot.className).contains('is-disabled', `should be disabled`); expect(dropdownRoot.getAttribute('data-is-focusable')).equals('false', 'data-is-focusable'); }); it('Renders no selected item in default case', () => { let container = document.createElement('div'); ReactDOM.render( <Dropdown label='testgroup' options={ DEFAULT_OPTIONS } />, container); let dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement; let titleElement = dropdownRoot.querySelector('.ms-Dropdown-title') as HTMLElement;
expect(titleElement.textContent).equals(''); }); it('Renders a selected item in uncontrolled case', () => { let container = document.createElement('div'); ReactDOM.render( <Dropdown label='testgroup' defaultSelectedKey='1' options={ DEFAULT_OPTIONS } />, container); let dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement; let titleElement = dropdownRoot.querySelector('.ms-Dropdown-title') as HTMLElement; expect(titleElement.textContent).equals('1'); }); it('Renders a selected item in controlled case', () => { let container = document.createElement('div'); ReactDOM.render( <Dropdown label='testgroup' selectedKey='1' options={ DEFAULT_OPTIONS } />, container); let dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement; let titleElement = dropdownRoot.querySelector('.ms-Dropdown-title') as HTMLElement; expect(titleElement.textContent).equals('1'); }); it('Can change items in uncontrolled case', () => { let container = document.createElement('div'); let dropdownRoot: HTMLElement | undefined; document.body.appendChild(container); try { ReactDOM.render( <Dropdown label='testgroup' defaultSelectedKey='1' options={ DEFAULT_OPTIONS } />, container); dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement; ReactTestUtils.Simulate.click(dropdownRoot); let secondItemElement = document.querySelector('.ms-Dropdown-item[data-index="2"]') as HTMLElement; ReactTestUtils.Simulate.click(secondItemElement); } finally { expect(dropdownRoot!.querySelector('.ms-Dropdown-title')!.textContent).equals('2'); } }); it('Will select the first valid item on keypress', () => { let container = document.createElement('div'); ReactDOM.render( <Dropdown label='testgroup' options={ DEFAULT_OPTIONS } />, container); let dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement; ReactTestUtils.Simulate.keyDown(dropdownRoot, { which: KeyCodes.down }); let titleElement = dropdownRoot.querySelector('.ms-Dropdown-title') as HTMLElement; expect(titleElement.textContent).equals('1'); }); it('Will select the first valid item on Home keypress', () => { let container = document.createElement('div'); ReactDOM.render( <Dropdown label='testgroup' options={ DEFAULT_OPTIONS } />, container); let dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement; ReactTestUtils.Simulate.keyDown(dropdownRoot, { which: KeyCodes.home }); let titleElement = dropdownRoot.querySelector('.ms-Dropdown-title') as HTMLElement; expect(titleElement.textContent).equals('1'); }); it('Will select the last valid item on End keypress', () => { let container = document.createElement('div'); ReactDOM.render( <Dropdown label='testgroup' options={ DEFAULT_OPTIONS } />, container); let dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement; ReactTestUtils.Simulate.keyDown(dropdownRoot, { which: KeyCodes.end }); let titleElement = dropdownRoot.querySelector('.ms-Dropdown-title') as HTMLElement; expect(titleElement.textContent).equals('6'); }); it('Will skip over headers and separators on keypress', () => { let container = document.createElement('div'); let dropdownRoot; let titleElement; document.body.appendChild(container); ReactDOM.render( <Dropdown label='testgroup' options={ DEFAULT_OPTIONS } />, container); dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement; ReactTestUtils.Simulate.keyDown(dropdownRoot, { which: KeyCodes.down }); titleElement = dropdownRoot.querySelector('.ms-Dropdown-title') as HTMLElement; expect(titleElement.textContent).equals('1'); ReactTestUtils.Simulate.keyDown(dropdownRoot, { which: KeyCodes.down }); ReactTestUtils.Simulate.keyDown(dropdownRoot, { which: KeyCodes.down }); ReactTestUtils.Simulate.keyDown(dropdownRoot, { which: KeyCodes.down }); titleElement = dropdownRoot.querySelector('.ms-Dropdown-title') as HTMLElement; expect(titleElement.textContent).equals('4'); }); });
app.rs
/** * MIT License * * termail - Copyright (c) 2021 Larry Hao * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ use super::ui::{ activity::{main::TermailActivity, Activity, ExitReason}, context::Context, }; use crate::config::TermailConfig; use log::error; use std::thread::sleep; use std::time::Duration; // use std::time::Instant; pub struct App { config: TermailConfig, context: Option<Context>, } impl App { pub fn new(config: TermailConfig) -> Self { let mut ctx: Context = Context::new(); // Enter alternate screen ctx.enter_alternate_screen(); // Clear screen ctx.clear_screen(); Self { config, context: Some(ctx), } } pub fn
(&mut self) { let mut main_activity: TermailActivity = TermailActivity::default(); // Get context let ctx: Context = if let Some(ctx) = self.context.take() { ctx } else { error!("Failed to start MainActivity: context is None"); return; }; // Create activity main_activity.init_config(&self.config); main_activity.on_create(ctx); loop { main_activity.update_maillist(); // Draw activity main_activity.on_draw(); // Check if activity has terminated if let Some(ExitReason::Quit) = main_activity.will_umount() { // info!("SetupActivity terminated due to 'Quit'"); break; } // Sleep for ticks sleep(Duration::from_millis(20)); } // Destroy activity self.context = main_activity.on_destroy(); drop(self.context.take()); } }
run
photo.py
# Created By: Virgil Dupras # Created On: 2011-05-29 # Copyright 2013 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license import logging from hscommon.util import get_file_ext, format_size from core.app import format_timestamp, format_perc, format_dupe_count from core import fs from . import exif def format_dimensions(dimensions): return '%d x %d' % (dimensions[0], dimensions[1]) def get_delta_dimensions(value, ref_value): return (value[0]-ref_value[0], value[1]-ref_value[1]) class Photo(fs.File): INITIAL_INFO = fs.File.INITIAL_INFO.copy() INITIAL_INFO.update({ 'dimensions': (0,0), 'exif_timestamp': '', }) __slots__ = fs.File.__slots__ + tuple(INITIAL_INFO.keys()) # These extensions are supported on all platforms HANDLED_EXTS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'tif'} def _plat_get_dimensions(self): raise NotImplementedError() def _plat_get_blocks(self, block_count_per_side, orientation): raise NotImplementedError() def _get_orientation(self): if not hasattr(self, '_cached_orientation'): try: with self.path.open('rb') as fp: exifdata = exif.get_fields(fp) # the value is a list (probably one-sized) of ints orientations = exifdata['Orientation'] self._cached_orientation = orientations[0] except Exception: # Couldn't read EXIF data, no transforms self._cached_orientation = 0 return self._cached_orientation @classmethod def can_handle(cls, path): return fs.File.can_handle(path) and get_file_ext(path[-1]) in cls.HANDLED_EXTS def get_display_info(self, group, delta): size = self.size mtime = self.mtime dimensions = self.dimensions m = group.get_match_of(self) if m: percentage = m.percentage dupe_count = 0 if delta: r = group.ref size -= r.size mtime -= r.mtime dimensions = get_delta_dimensions(dimensions, r.dimensions) else: percentage = group.percentage dupe_count = len(group.dupes) dupe_folder_path = getattr(self, 'display_folder_path', self.folder_path) return { 'name': self.name, 'folder_path': str(dupe_folder_path), 'size': format_size(size, 0, 1, False), 'extension': self.extension, 'dimensions': format_dimensions(dimensions), 'exif_timestamp': self.exif_timestamp, 'mtime': format_timestamp(mtime, delta and m), 'percentage': format_perc(percentage), 'dupe_count': format_dupe_count(dupe_count), } def _read_info(self, field): fs.File._read_info(self, field) if field == 'dimensions': self.dimensions = self._plat_get_dimensions() if self._get_orientation() in {5, 6, 7, 8}:
elif field == 'exif_timestamp': try: with self.path.open('rb') as fp: exifdata = exif.get_fields(fp) self.exif_timestamp = exifdata['DateTimeOriginal'] except Exception: logging.info("Couldn't read EXIF of picture: %s", self.path) def get_blocks(self, block_count_per_side): return self._plat_get_blocks(block_count_per_side, self._get_orientation())
self.dimensions = (self.dimensions[1], self.dimensions[0])
panic.go
package tars import ( "fmt" "os" "github.com/jslyzt/tarsgo/tars/util/debug" "github.com/jslyzt/tarsgo/tars/util/rogger" ) ////////////////////////////////////////////////////////////////////////////// type PanicFunc func(interface{}) bool var ( FPanic PanicFunc ) ////////////////////////////////////////////////////////////////////////////// // CheckPanic used to dump stack info to file when catch panic func CheckPanic()
{ if r := recover(); r != nil { if FPanic != nil && FPanic(r) { return } var msg string if err, ok := r.(error); ok { msg = err.Error() } else { msg = fmt.Sprintf("%#v", r) } debug.DumpStack(true, "panic", msg) rogger.FlushLogger() os.Exit(-1) } }
print-anion.rs
#[macro_use] extern crate pest; extern crate anion; use anion::AnionValue; use anion::parser::parse_string; fn
() { for s in std::env::args().skip(1) { let anion_value = parse_string(s.as_str()); if let Some(val) = anion_value { match val { AnionValue::Boolean(Some(x)) => println!("Bool {}", x), AnionValue::Boolean(None) => println!("Bool NULL"), AnionValue::Integer(Some(x)) => println!("Int {}", x), AnionValue::Integer(None) => println!("Int NULL"), AnionValue::Float(Some(x)) => println!("Float {}", x), AnionValue::Float(None) => println!("Float NULL"), AnionValue::Decimal(Some(x)) => println!("Decimal {}", x), AnionValue::Decimal(None) => println!("Decimal NULL"), AnionValue::String(Some(x)) => println!("String {}", x), AnionValue::String(None) => println!("String NULL"), } } } }
main
_m.rs
use super::prelude::*; #[derive(Debug)] pub struct
<'a> { pub addr: &'a [u8], pub len: usize, pub buf: &'a mut [u8], } impl<'a> ParseCommand<'a> for m<'a> { fn from_packet(buf: PacketBuf<'a>) -> Option<Self> { // the total packet buffer currently looks like: // // +------+--------------------+-------------------+-------+-----------------+ // | "$m" | addr (hex-encoded) | len (hex-encoded) | "#XX" | empty space ... | // +------+--------------------+-------------------+-------+-----------------+ // // Unfortunately, while `len` can be hex-decoded right here and now into a // `usize`, `addr` corresponds to a Target::Arch::Usize, which requires holding // on to a valid &[u8] reference into the buffer. // // While it's not _perfectly_ efficient, simply leaving the decoded addr in // place and wasting a couple bytes is probably the easiest way to tackle this // problem: // // +------+------------------+------------------------------------------------+ // | "$m" | addr (raw bytes) | usable buffer ... | // +------+------------------+------------------------------------------------+ let (buf, body_range) = buf.into_raw_buf(); let body = &mut buf[body_range.start..]; // should return 3 slices: the addr (hex-encoded), len (hex-encoded), and the // "rest" of the buffer let mut body = body.split_mut(|b| *b == b',' || *b == b'#'); let addr = decode_hex_buf(body.next()?).ok()?; let addr_len = addr.len(); let len = decode_hex(body.next()?).ok()?; drop(body); let (addr, buf) = buf.split_at_mut(body_range.start + addr_len); let addr = &addr[b"$m".len()..]; Some(m { addr, len, buf }) } }
m
AbstractProviderShape.ts
/// <reference path="../../../OSFramework/Shape/AbstractShape.ts" /> // eslint-disable-next-line @typescript-eslint/no-unused-vars namespace Provider.Google.Shape { export abstract class AbstractProviderShape< T extends OSFramework.Configuration.IConfigurationShape, W extends google.maps.MVCObject > extends OSFramework.Shape.AbstractShape<W, T> { private _shapeChangedEventTimeout: number; private _resetShapeEvents(): void { // Make sure the listeners get removed before adding the new ones this._addedEvents.forEach((eventListener, index) => { google.maps.event.clearListeners(this.provider, eventListener); this._addedEvents.splice(index, 1); }); } /** Builds the provider (asynchronously) by receving a set of multiple coordinates (creating a path for the shape) or just one (creating the center of the shape) */ protected _buildProvider( coordinates: | Promise<OSFramework.OSStructures.OSMap.Coordinates> | Promise<Array<OSFramework.OSStructures.OSMap.Coordinates>> | Promise<OSFramework.OSStructures.OSMap.Bounds> ): void { // First build coords from locations // Then, create the provider (Google maps Shape) // Finally, set Shape events // If coords is undefined (should be a promise) -> don't create the shape if (coordinates !== undefined) { coordinates .then((coords) => { // Create the provider with the respective coords this._provider = this._createProvider(coords); // We can only set the events on the provider after its creation this._setShapeEvents(); // Finish build of Shape this.finishBuild(); }) .catch((error) => { OSFramework.Helper.ThrowError( this.map, OSFramework.Enum.ErrorCodes .LIB_FailedGeocodingShapeLocations, error ); }); } } protected _setShapeEvents(): void { // Make sure the listeners get removed before adding the new ones this._resetShapeEvents(); // OnClick Event if ( this.shapeEvents.hasHandlers( OSFramework.Event.Shape.ShapeEventType.OnClick ) && this.provider.get('clickable') // Always true. Fallback in case this parameter gets changed in the future. ) { this.provider.addListener('click', () => { this.shapeEvents.trigger( OSFramework.Event.Shape.ShapeEventType.OnClick ); }); } // Any events that got added to the shapeEvents via the API Subscribe method will have to be taken care here // If the Event type of each handler is ShapeProviderEvent, we want to make sure to add that event to the listeners of the google shape provider (e.g. dblclick, dragend, etc) // Otherwise, we don't want to add them to the google provider listeners (e.g. OnInitialize, OnClick, etc) this.shapeEvents.handlers.forEach( ( handler: OSFramework.Event.IEvent<string>, eventName: string ) => { if ( handler instanceof OSFramework.Event.Shape.ShapeProviderEvent ) { // Take care of the shape_changed events if ( eventName === OSFramework.Helper.Constants.shapeChangedEvent ) { this._addedEvents.push(eventName); this.providerEventsList.forEach((event) => this.providerObjectListener.addListener( event, () => { if (this._shapeChangedEventTimeout) { clearTimeout( this._shapeChangedEventTimeout ); } this._shapeChangedEventTimeout = setTimeout( () => this.shapeEvents.trigger( // EventType OSFramework.Event.Shape .ShapeEventType .ProviderEvent, // EventName OSFramework.Helper .Constants .shapeChangedEvent ), 500 ); } ) ); } else if ( // If the eventName is included inside the ProviderSpecialEvents then add the listener Constants.Shape.ProviderSpecialEvents.indexOf( eventName ) !== -1 ) { // Take care of the custom provider events (the special events are not relative to the provider but to its path) this._addedEvents.push(eventName); this.providerObjectListener.addListener( eventName, () => { this.shapeEvents.trigger( // EventType OSFramework.Event.Shape.ShapeEventType .ProviderEvent, // EventName eventName ); } ); } else { // Provider events (the provider events are relative to the provider) this._addedEvents.push(eventName); this.provider.addListener(eventName, () => { this.shapeEvents.trigger( // EventType OSFramework.Event.Shape.ShapeEventType .ProviderEvent, // EventName eventName ); }); } } } ); } /** Checks if the Shape has associated events */ public get hasEvents(): boolean {
public get provider(): W { return this._provider; } public get shapeProviderEvents(): Array<string> { return Constants.Shape.Events; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any public changeProperty(propertyName: string, value: any): void { const propValue = OSFramework.Enum.OS_Config_Shape[propertyName]; super.changeProperty(propertyName, value); if (this.isReady) { switch (propValue) { case OSFramework.Enum.OS_Config_Shape.allowDrag: return this.provider.set('draggable', value); case OSFramework.Enum.OS_Config_Shape.allowEdit: return this.provider.set('editable', value); case OSFramework.Enum.OS_Config_Shape.strokeOpacity: return this.provider.set('strokeOpacity', value); case OSFramework.Enum.OS_Config_Shape.strokeColor: return this.provider.set('strokeColor', value); case OSFramework.Enum.OS_Config_Shape.strokeWeight: return this.provider.set('strokeWeight', value); } } } public dispose(): void { if (this.isReady) { this.provider.set('map', null); } this._provider = undefined; super.dispose(); } public refreshProviderEvents(): void { if (this.isReady) this._setShapeEvents(); } public abstract get providerEventsList(): Array<string>; // eslint-disable-next-line @typescript-eslint/no-explicit-any public abstract get providerObjectListener(): any; public abstract get shapeTag(): string; protected abstract _createProvider( locations: | Array<OSFramework.OSStructures.OSMap.Coordinates> | OSFramework.OSStructures.OSMap.Coordinates | OSFramework.OSStructures.OSMap.Bounds ): W; } }
return this.shapeEvents !== undefined; }
basic.rs
use dces::prelude::*; #[derive(Default)] struct Size { width: u32, height: u32, } #[derive(Default)] struct Name(String); #[derive(Default)] struct Depth(u32); pub struct SizeSystem; impl System<EntityStore, ComponentStore> for SizeSystem { fn run(&self, ecm: &mut EntityComponentManager<EntityStore, ComponentStore>) { let (e_store, c_store) = ecm.stores_mut(); for entity in &e_store.inner { if let Ok(comp) = c_store.get_mut::<Size>(*entity) { comp.width += 1; comp.height += 1; } } } } pub struct PrintSystem; impl System<EntityStore, ComponentStore> for PrintSystem { fn run(&self, ecm: &mut EntityComponentManager<EntityStore, ComponentStore>) { let (e_store, c_store) = ecm.stores_mut(); for entity in &e_store.inner { if let Ok(name) = c_store.get::<Name>(*entity) { if let Ok(size) = c_store.get::<Size>(*entity) { println!("{} width: {}; height: {}", name.0, size.width, size.height); } } } } } fn main() { let mut world = World::from_stores(EntityStore::default(), ComponentStore::default()); world .create_entity() .components( ComponentBuilder::new() .with(Name(String::from("Button"))) .with(Depth(4)) .with(Size { width: 5, height: 5, }) .build(), ) .build(); world .create_entity() .components( ComponentBuilder::new() .with(Name(String::from("CheckBox"))) .with(Depth(1))
height: 3, }) .build(), ) .build(); world .create_entity() .components( ComponentBuilder::new() .with(Name(String::from("RadioButton"))) .with(Depth(2)) .with(Size { width: 4, height: 6, }) .build(), ) .build(); world .create_entity() .components( ComponentBuilder::new() .with(Depth(3)) .with(Size { width: 10, height: 4, }) .build(), ) .build(); world .create_entity() .components( ComponentBuilder::new() .with(Depth(0)) .with(Size { width: 5, height: 8, }) .build(), ) .build(); world.create_system(PrintSystem).with_priority(1).build(); world.create_system(SizeSystem).with_priority(0).build(); world.run(); }
.with(Size { width: 3,
encoder.rs
use crate::index::Index; use crate::index_builder::{FromId, IndexBuilder, Untracked}; use crate::isolated_encoder::IsolatedEncoder; use crate::schema::*; use rustc::middle::cstore::{LinkagePreference, NativeLibrary, EncodedMetadata, ForeignModule}; use rustc::hir::def::CtorKind; use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LocalDefId, LOCAL_CRATE}; use rustc::hir::GenericParamKind; use rustc::hir::map::definitions::DefPathTable; use rustc_data_structures::fingerprint::Fingerprint; use rustc::middle::dependency_format::Linkage; use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel, metadata_symbol_name}; use rustc::middle::lang_items; use rustc::mir::{self, interpret}; use rustc::traits::specialization_graph; use rustc::ty::{self, Ty, TyCtxt, ReprOptions, SymbolName}; use rustc::ty::codec::{self as ty_codec, TyEncoder}; use rustc::ty::layout::VariantIdx; use rustc::session::config::{self, CrateType}; use rustc::util::nodemap::FxHashMap; use rustc_data_structures::stable_hasher::StableHasher; use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque}; use std::hash::Hash; use std::path::Path; use rustc_data_structures::sync::Lrc; use std::u32; use syntax::ast; use syntax::attr; use syntax::source_map::Spanned; use syntax::symbol::keywords; use syntax_pos::{self, hygiene, FileName, SourceFile, Span}; use log::{debug, trace}; use rustc::hir::{self, PatKind}; use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::hir::intravisit::{Visitor, NestedVisitorMap}; use rustc::hir::intravisit; pub struct EncodeContext<'a, 'tcx: 'a> { opaque: opaque::Encoder, pub tcx: TyCtxt<'a, 'tcx, 'tcx>, lazy_state: LazyState, type_shorthands: FxHashMap<Ty<'tcx>, usize>, predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>, interpret_allocs: FxHashMap<interpret::AllocId, usize>, interpret_allocs_inverse: Vec<interpret::AllocId>, // This is used to speed up Span encoding. source_file_cache: Lrc<SourceFile>, } macro_rules! encoder_methods { ($($name:ident($ty:ty);)*) => { $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { self.opaque.$name(value) })* } } impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> { type Error = <opaque::Encoder as Encoder>::Error; fn emit_unit(&mut self) -> Result<(), Self::Error> { Ok(()) } encoder_methods! { emit_usize(usize); emit_u128(u128); emit_u64(u64); emit_u32(u32); emit_u16(u16); emit_u8(u8); emit_isize(isize); emit_i128(i128); emit_i64(i64); emit_i32(i32); emit_i16(i16); emit_i8(i8); emit_bool(bool); emit_f64(f64); emit_f32(f32); emit_char(char); emit_str(&str); } } impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> { fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> { self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size()) } } impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> { fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> { self.emit_usize(seq.len)?; if seq.len == 0 { return Ok(()); } self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len)) } } impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> { #[inline] fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> { self.emit_u32(cnum.as_u32()) } } impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> { #[inline] fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> { let DefId { krate, index, } = *def_id; krate.encode(self)?; index.encode(self) } } impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> { #[inline] fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> { self.emit_u32(def_index.as_raw_u32()) } } impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> { fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> { if span.is_dummy() { return TAG_INVALID_SPAN.encode(self) } let span = span.data(); // The Span infrastructure should make sure that this invariant holds: debug_assert!(span.lo <= span.hi); if !self.source_file_cache.contains(span.lo) { let source_map = self.tcx.sess.source_map(); let source_file_index = source_map.lookup_source_file_idx(span.lo); self.source_file_cache = source_map.files()[source_file_index].clone(); } if !self.source_file_cache.contains(span.hi) { // Unfortunately, macro expansion still sometimes generates Spans // that malformed in this way. return TAG_INVALID_SPAN.encode(self) } TAG_VALID_SPAN.encode(self)?; span.lo.encode(self)?; // Encode length which is usually less than span.hi and profits more // from the variable-length integer encoding that we use. let len = span.hi - span.lo; len.encode(self) // Don't encode the expansion context. } } impl<'a, 'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'a, 'tcx> { #[inline] fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> { self.specialized_encode(&def_id.to_def_id()) } } impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> { fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> { ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands) } } impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> { fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> { use std::collections::hash_map::Entry; let index = match self.interpret_allocs.entry(*alloc_id) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { let idx = self.interpret_allocs_inverse.len(); self.interpret_allocs_inverse.push(*alloc_id); e.insert(idx); idx }, }; index.encode(self) } } impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> { fn specialized_encode(&mut self, predicates: &ty::GenericPredicates<'tcx>) -> Result<(), Self::Error> { ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands) } } impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> { fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> { f.encode_opaque(&mut self.opaque) } } impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'a, 'tcx> { fn specialized_encode(&mut self, _: &mir::ClearCrossCrate<T>) -> Result<(), Self::Error> { Ok(()) } } impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> { fn position(&self) -> usize { self.opaque.position() } } impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R { assert_eq!(self.lazy_state, LazyState::NoNode); let pos = self.position(); self.lazy_state = LazyState::NodeStart(pos); let r = f(self, pos); self.lazy_state = LazyState::NoNode; r } fn emit_lazy_distance(&mut self, position: usize, min_size: usize) -> Result<(), <Self as Encoder>::Error> { let min_end = position + min_size; let distance = match self.lazy_state { LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), LazyState::NodeStart(start) => { assert!(min_end <= start); start - min_end } LazyState::Previous(last_min_end) => { assert!( last_min_end <= position, "make sure that the calls to `lazy*` \ are in the same order as the metadata fields", ); position - last_min_end } }; self.lazy_state = LazyState::Previous(min_end); self.emit_usize(distance) } pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> { self.emit_node(|ecx, pos| { value.encode(ecx).unwrap(); assert!(pos + Lazy::<T>::min_size() <= ecx.position()); Lazy::with_position(pos) }) } pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T> where I: IntoIterator<Item = T>, T: Encodable { self.emit_node(|ecx, pos| { let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count(); assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position()); LazySeq::with_position_and_length(pos, len) }) } pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T> where I: IntoIterator<Item = &'b T>, T: 'b + Encodable { self.emit_node(|ecx, pos| { let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count(); assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position()); LazySeq::with_position_and_length(pos, len) }) } // Encodes something that corresponds to a single DepNode::GlobalMetaData // and registers the Fingerprint in the `metadata_hashes` map. pub fn tracked<'x, DATA, R>(&'x mut self, op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R, data: DATA) -> R { op(&mut IsolatedEncoder::new(self), data) } fn encode_info_for_items(&mut self) -> Index { let krate = self.tcx.hir().krate(); let mut index = IndexBuilder::new(self); let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public }; index.record(DefId::local(CRATE_DEF_INDEX), IsolatedEncoder::encode_info_for_mod, FromId(hir::CRATE_HIR_ID, (&krate.module, &krate.attrs, &vis))); let mut visitor = EncodeVisitor { index }; krate.visit_all_item_likes(&mut visitor.as_deep_visitor()); for macro_def in &krate.exported_macros { visitor.visit_macro_def(macro_def); } visitor.index.into_items() } fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> { let definitions = self.tcx.hir().definitions(); self.lazy(definitions.def_path_table()) } fn encode_source_map(&mut self) -> LazySeq<syntax_pos::SourceFile> { let source_map = self.tcx.sess.source_map(); let all_source_files = source_map.files(); let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone(); let adapted = all_source_files.iter() .filter(|source_file| { // No need to re-export imported source_files, as any downstream // crate will import them from their original source. !source_file.is_imported() }) .map(|source_file| { match source_file.name { // This path of this SourceFile has been modified by // path-remapping, so we use it verbatim (and avoid // cloning the whole map in the process). _ if source_file.name_was_remapped => source_file.clone(), // Otherwise expand all paths to absolute paths because // any relative paths are potentially relative to a // wrong directory. FileName::Real(ref name) => { let mut adapted = (**source_file).clone(); adapted.name = Path::new(&working_dir).join(name).into(); adapted.name_hash = { let mut hasher: StableHasher<u128> = StableHasher::new(); adapted.name.hash(&mut hasher); hasher.finish() }; Lrc::new(adapted) }, // expanded code, not from a file _ => source_file.clone(), } }) .collect::<Vec<_>>(); self.lazy_seq_ref(adapted.iter().map(|rc| &**rc)) } fn encode_crate_root(&mut self) -> Lazy<CrateRoot> { let mut i = self.position(); let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ()); let dylib_dependency_formats = self.tracked( IsolatedEncoder::encode_dylib_dependency_formats, ()); let dep_bytes = self.position() - i; // Encode the lib features. i = self.position(); let lib_features = self.tracked(IsolatedEncoder::encode_lib_features, ()); let lib_feature_bytes = self.position() - i; // Encode the language items. i = self.position(); let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ()); let lang_items_missing = self.tracked( IsolatedEncoder::encode_lang_items_missing, ()); let lang_item_bytes = self.position() - i; // Encode the native libraries used i = self.position(); let native_libraries = self.tracked( IsolatedEncoder::encode_native_libraries, ()); let native_lib_bytes = self.position() - i; let foreign_modules = self.tracked( IsolatedEncoder::encode_foreign_modules, ()); // Encode source_map i = self.position(); let source_map = self.encode_source_map(); let source_map_bytes = self.position() - i; // Encode DefPathTable i = self.position(); let def_path_table = self.encode_def_path_table(); let def_path_table_bytes = self.position() - i; // Encode the def IDs of impls, for coherence checking. i = self.position(); let impls = self.tracked(IsolatedEncoder::encode_impls, ()); let impl_bytes = self.position() - i; // Encode exported symbols info. i = self.position(); let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE); let exported_symbols = self.tracked( IsolatedEncoder::encode_exported_symbols, &exported_symbols); let exported_symbols_bytes = self.position() - i; let tcx = self.tcx; // Encode the items. i = self.position(); let items = self.encode_info_for_items(); let item_bytes = self.position() - i; // Encode the allocation index let interpret_alloc_index = { let mut interpret_alloc_index = Vec::new(); let mut n = 0; trace!("beginning to encode alloc ids"); loop { let new_n = self.interpret_allocs_inverse.len(); // if we have found new ids, serialize those, too if n == new_n { // otherwise, abort break; } trace!("encoding {} further alloc ids", new_n - n); for idx in n..new_n { let id = self.interpret_allocs_inverse[idx]; let pos = self.position() as u32; interpret_alloc_index.push(pos); interpret::specialized_encode_alloc_id( self, tcx, id, ).unwrap(); } n = new_n; } self.lazy_seq(interpret_alloc_index) }; // Index the items i = self.position(); let index = items.write_index(&mut self.opaque); let index_bytes = self.position() - i; let attrs = tcx.hir().krate_attrs(); let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro); let has_default_lib_allocator = attr::contains_name(&attrs, "default_lib_allocator"); let has_global_allocator = *tcx.sess.has_global_allocator.get(); let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false); let root = self.lazy(&CrateRoot { name: tcx.crate_name(LOCAL_CRATE), extra_filename: tcx.sess.opts.cg.extra_filename.clone(), triple: tcx.sess.opts.target_triple.clone(), hash: tcx.crate_hash(LOCAL_CRATE), disambiguator: tcx.sess.local_crate_disambiguator(), panic_strategy: tcx.sess.panic_strategy(), edition: hygiene::default_edition(), has_global_allocator: has_global_allocator, has_panic_handler: has_panic_handler, has_default_lib_allocator: has_default_lib_allocator, plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index), proc_macro_decls_static: if is_proc_macro { let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap(); Some(id.index) } else { None }, proc_macro_stability: if is_proc_macro { tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| stab.clone()) } else { None }, compiler_builtins: attr::contains_name(&attrs, "compiler_builtins"), needs_allocator: attr::contains_name(&attrs, "needs_allocator"), needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"), no_builtins: attr::contains_name(&attrs, "no_builtins"), panic_runtime: attr::contains_name(&attrs, "panic_runtime"), profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"), sanitizer_runtime: attr::contains_name(&attrs, "sanitizer_runtime"), crate_deps, dylib_dependency_formats, lib_features, lang_items, lang_items_missing, native_libraries, foreign_modules, source_map, def_path_table, impls, exported_symbols, interpret_alloc_index, index, }); let total_bytes = self.position(); if self.tcx.sess.meta_stats() { let mut zero_bytes = 0; for e in self.opaque.data.iter() { if *e == 0 { zero_bytes += 1; } } println!("metadata stats:"); println!(" dep bytes: {}", dep_bytes); println!(" lib feature bytes: {}", lib_feature_bytes); println!(" lang item bytes: {}", lang_item_bytes); println!(" native bytes: {}", native_lib_bytes); println!(" source_map bytes: {}", source_map_bytes); println!(" impl bytes: {}", impl_bytes); println!(" exp. symbols bytes: {}", exported_symbols_bytes); println!(" def-path table bytes: {}", def_path_table_bytes); println!(" item bytes: {}", item_bytes); println!(" index bytes: {}", index_bytes); println!(" zero bytes: {}", zero_bytes); println!(" total bytes: {}", total_bytes); } root } } // These are methods for encoding various things. They are meant to be used with // IndexBuilder::record() and EncodeContext::tracked(). They actually // would not have to be methods of IsolatedEncoder (free standing functions // taking IsolatedEncoder as first argument would be just fine) but by making // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>` // clause again and again. impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> { debug!("IsolatedEncoder::encode_variances_of({:?})", def_id); let tcx = self.tcx; self.lazy_seq_from_slice(&tcx.variances_of(def_id)) } fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> { let tcx = self.tcx; let ty = tcx.type_of(def_id); debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty); self.lazy(&ty) } /// Encode data for the given variant of the given ADT. The /// index of the variant is untracked: this is ok because we /// will have to lookup the adt-def by its id, and that gives us /// the right to access any information in the adt-def (including, /// e.g., the length of the various vectors). fn encode_enum_variant_info( &mut self, (enum_did, Untracked(index)): (DefId, Untracked<VariantIdx>), ) -> Entry<'tcx> { let tcx = self.tcx; let def = tcx.adt_def(enum_did); let variant = &def.variants[index]; let def_id = variant.def_id; debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id); let data = VariantData { ctor_kind: variant.ctor_kind, discr: variant.discr, ctor: variant.ctor_def_id.map(|did| did.index), ctor_sig: None, }; let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap(); let enum_vis = &tcx.hir().expect_item_by_hir_id(enum_id).vis; Entry { kind: EntryKind::Variant(self.lazy(&data)), visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)), span: self.lazy(&tcx.def_span(def_id)), attributes: self.encode_attributes(&tcx.get_attrs(def_id)), children: self.lazy_seq(variant.fields.iter().map(|f| { assert!(f.did.is_local()); f.did.index })), stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), ty: Some(self.encode_item_type(def_id)), inherent_impls: LazySeq::empty(), variances: if variant.ctor_kind == CtorKind::Fn { self.encode_variances_of(def_id) } else { LazySeq::empty() }, generics: Some(self.encode_generics(def_id)), predicates: Some(self.encode_predicates(def_id)), predicates_defined_on: None, mir: self.encode_optimized_mir(def_id), } } /// Encode the constructor for the given variant of the given ADT. See /// `encode_enum_variant_info` for an explanation about why the index is untracked. fn encode_enum_variant_ctor( &mut self, (enum_did, Untracked(index)): (DefId, Untracked<VariantIdx>), ) -> Entry<'tcx> { let tcx = self.tcx; let def = tcx.adt_def(enum_did); let variant = &def.variants[index]; let def_id = variant.ctor_def_id.unwrap(); debug!("IsolatedEncoder::encode_enum_variant_ctor({:?})", def_id); let data = VariantData { ctor_kind: variant.ctor_kind, discr: variant.discr, ctor: Some(def_id.index), ctor_sig: if variant.ctor_kind == CtorKind::Fn { Some(self.lazy(&tcx.fn_sig(def_id))) } else { None } }; // Variant constructors have the same visibility as the parent enums, unless marked as // non-exhaustive, in which case they are lowered to `pub(crate)`. let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap(); let enum_vis = &tcx.hir().expect_item_by_hir_id(enum_id).vis; let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx); if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public { ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)); } Entry { kind: EntryKind::Variant(self.lazy(&data)), visibility: self.lazy(&ctor_vis), span: self.lazy(&tcx.def_span(def_id)), attributes: LazySeq::empty(), children: LazySeq::empty(), stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), ty: Some(self.encode_item_type(def_id)), inherent_impls: LazySeq::empty(), variances: if variant.ctor_kind == CtorKind::Fn { self.encode_variances_of(def_id) } else { LazySeq::empty() }, generics: Some(self.encode_generics(def_id)), predicates: Some(self.encode_predicates(def_id)), predicates_defined_on: None, mir: self.encode_optimized_mir(def_id), } } fn encode_info_for_mod(&mut self, FromId(id, (md, attrs, vis)): FromId<(&hir::Mod, &[ast::Attribute], &hir::Visibility)>) -> Entry<'tcx> { let tcx = self.tcx; let def_id = tcx.hir().local_def_id_from_hir_id(id); debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id); let data = ModData { reexports: match tcx.module_exports(def_id) { Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()), _ => LazySeq::empty(), }, }; Entry { kind: EntryKind::Mod(self.lazy(&data)), visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)), span: self.lazy(&tcx.def_span(def_id)), attributes: self.encode_attributes(attrs), children: self.lazy_seq(md.item_ids.iter().map(|item_id| { tcx.hir().local_def_id_from_hir_id(item_id.id).index })), stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), ty: None, inherent_impls: LazySeq::empty(), variances: LazySeq::empty(), generics: None, predicates: None, predicates_defined_on: None, mir: None } } /// Encode data for the given field of the given variant of the /// given ADT. The indices of the variant/field are untracked: /// this is ok because we will have to lookup the adt-def by its /// id, and that gives us the right to access any information in /// the adt-def (including, e.g., the length of the various /// vectors). fn encode_field(&mut self, (adt_def_id, Untracked((variant_index, field_index))): (DefId, Untracked<(VariantIdx, usize)>)) -> Entry<'tcx> { let tcx = self.tcx; let variant = &tcx.adt_def(adt_def_id).variants[variant_index]; let field = &variant.fields[field_index]; let def_id = field.did; debug!("IsolatedEncoder::encode_field({:?})", def_id); let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap(); let variant_data = tcx.hir().expect_variant_data(variant_id); Entry { kind: EntryKind::Field, visibility: self.lazy(&field.vis), span: self.lazy(&tcx.def_span(def_id)), attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs), children: LazySeq::empty(), stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), ty: Some(self.encode_item_type(def_id)), inherent_impls: LazySeq::empty(), variances: LazySeq::empty(), generics: Some(self.encode_generics(def_id)), predicates: Some(self.encode_predicates(def_id)), predicates_defined_on: None, mir: None, } } fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> { debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id); let tcx = self.tcx; let adt_def = tcx.adt_def(adt_def_id); let variant = adt_def.non_enum_variant(); let data = VariantData { ctor_kind: variant.ctor_kind, discr: variant.discr, ctor: Some(def_id.index), ctor_sig: if variant.ctor_kind == CtorKind::Fn { Some(self.lazy(&tcx.fn_sig(def_id))) } else { None } }; let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap(); let struct_vis = &tcx.hir().expect_item_by_hir_id(struct_id).vis; let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx); for field in &variant.fields { if ctor_vis.is_at_least(field.vis, tcx) { ctor_vis = field.vis; } } // If the structure is marked as non_exhaustive then lower the visibility // to within the crate. if adt_def.non_enum_variant().is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public { ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)); } let repr_options = get_repr_options(&tcx, adt_def_id); Entry { kind: EntryKind::Struct(self.lazy(&data), repr_options), visibility: self.lazy(&ctor_vis), span: self.lazy(&tcx.def_span(def_id)), attributes: LazySeq::empty(), children: LazySeq::empty(), stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), ty: Some(self.encode_item_type(def_id)), inherent_impls: LazySeq::empty(), variances: if variant.ctor_kind == CtorKind::Fn { self.encode_variances_of(def_id) } else { LazySeq::empty() }, generics: Some(self.encode_generics(def_id)), predicates: Some(self.encode_predicates(def_id)), predicates_defined_on: None, mir: self.encode_optimized_mir(def_id), } } fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> { debug!("IsolatedEncoder::encode_generics({:?})", def_id); let tcx = self.tcx; self.lazy(tcx.generics_of(def_id)) } fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> { debug!("IsolatedEncoder::encode_predicates({:?})", def_id); let tcx = self.tcx; self.lazy(&tcx.predicates_of(def_id)) } fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> { debug!("IsolatedEncoder::encode_predicates_defined_on({:?})", def_id); let tcx = self.tcx; self.lazy(&tcx.predicates_defined_on(def_id)) } fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> { debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id); let tcx = self.tcx; let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); let ast_item = tcx.hir().expect_trait_item(hir_id); let trait_item = tcx.associated_item(def_id); let container = match trait_item.defaultness { hir::Defaultness::Default { has_value: true } => AssociatedContainer::TraitWithDefault, hir::Defaultness::Default { has_value: false } => AssociatedContainer::TraitRequired, hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"), }; let kind = match trait_item.kind { ty::AssociatedKind::Const => { let const_qualif = if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node { self.const_qualif(0, body) } else { ConstQualif { mir: 0, ast_promotable: false } }; let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item)); let rendered_const = self.lazy(&RenderedConst(rendered)); EntryKind::AssociatedConst(container, const_qualif, rendered_const) } ty::AssociatedKind::Method => { let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node { let arg_names = match *m { hir::TraitMethod::Required(ref names) => { self.encode_fn_arg_names(names) } hir::TraitMethod::Provided(body) => { self.encode_fn_arg_names_for_body(body) } }; FnData { constness: hir::Constness::NotConst, arg_names, sig: self.lazy(&tcx.fn_sig(def_id)), } } else { bug!() }; EntryKind::Method(self.lazy(&MethodData { fn_data, container, has_self: trait_item.method_has_self_argument, })) } ty::AssociatedKind::Type => EntryKind::AssociatedType(container), ty::AssociatedKind::Existential => span_bug!(ast_item.span, "existential type in trait"), }; Entry { kind, visibility: self.lazy(&trait_item.vis), span: self.lazy(&ast_item.span), attributes: self.encode_attributes(&ast_item.attrs), children: LazySeq::empty(), stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), ty: match trait_item.kind { ty::AssociatedKind::Const | ty::AssociatedKind::Method => { Some(self.encode_item_type(def_id)) } ty::AssociatedKind::Type => { if trait_item.defaultness.has_value() { Some(self.encode_item_type(def_id)) } else { None } } ty::AssociatedKind::Existential => unreachable!(), }, inherent_impls: LazySeq::empty(), variances: if trait_item.kind == ty::AssociatedKind::Method { self.encode_variances_of(def_id) } else { LazySeq::empty() }, generics: Some(self.encode_generics(def_id)), predicates: Some(self.encode_predicates(def_id)), predicates_defined_on: None, mir: self.encode_optimized_mir(def_id), } } fn metadata_output_only(&self) -> bool { // MIR optimisation can be skipped when we're just interested in the metadata. !self.tcx.sess.opts.output_types.should_codegen() } fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif { let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id); let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id); ConstQualif { mir, ast_promotable } } fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> { debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id); let tcx = self.tcx; let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap(); let ast_item = self.tcx.hir().expect_impl_item(hir_id); let impl_item = self.tcx.associated_item(def_id); let container = match impl_item.defaultness { hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault, hir::Defaultness::Final => AssociatedContainer::ImplFinal, hir::Defaultness::Default { has_value: false } => span_bug!(ast_item.span, "impl items always have values (currently)"), }; let kind = match impl_item.kind { ty::AssociatedKind::Const => { if let hir::ImplItemKind::Const(_, body_id) = ast_item.node { let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0; EntryKind::AssociatedConst(container, self.const_qualif(mir, body_id), self.encode_rendered_const_for_body(body_id)) } else { bug!() } } ty::AssociatedKind::Method => { let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node { FnData { constness: sig.header.constness, arg_names: self.encode_fn_arg_names_for_body(body), sig: self.lazy(&tcx.fn_sig(def_id)), } } else { bug!() }; EntryKind::Method(self.lazy(&MethodData { fn_data, container, has_self: impl_item.method_has_self_argument, })) } ty::AssociatedKind::Existential => EntryKind::AssociatedExistential(container), ty::AssociatedKind::Type => EntryKind::AssociatedType(container) }; let mir = match ast_item.node { hir::ImplItemKind::Const(..) => true, hir::ImplItemKind::Method(ref sig, _) => { let generics = self.tcx.generics_of(def_id); let needs_inline = (generics.requires_monomorphization(self.tcx) || tcx.codegen_fn_attrs(def_id).requests_inline()) && !self.metadata_output_only(); let is_const_fn = sig.header.constness == hir::Constness::Const; let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir; needs_inline || is_const_fn || always_encode_mir }, hir::ImplItemKind::Existential(..) | hir::ImplItemKind::Type(..) => false, }; Entry { kind, visibility: self.lazy(&impl_item.vis), span: self.lazy(&ast_item.span), attributes: self.encode_attributes(&ast_item.attrs), children: LazySeq::empty(), stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), ty: Some(self.encode_item_type(def_id)), inherent_impls: LazySeq::empty(), variances: if impl_item.kind == ty::AssociatedKind::Method { self.encode_variances_of(def_id) } else { LazySeq::empty() }, generics: Some(self.encode_generics(def_id)), predicates: Some(self.encode_predicates(def_id)), predicates_defined_on: None, mir: if mir { self.encode_optimized_mir(def_id) } else { None }, } } fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId) -> LazySeq<ast::Name> { self.tcx.dep_graph.with_ignore(|| { let body = self.tcx.hir().body(body_id); self.lazy_seq(body.arguments.iter().map(|arg| { match arg.pat.node { PatKind::Binding(_, _, ident, _) => ident.name, _ => keywords::Invalid.name(), } })) }) } fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> { self.lazy_seq(param_names.iter().map(|ident| ident.name)) } fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> { debug!("EntryBuilder::encode_mir({:?})", def_id); if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) { let mir = self.tcx.optimized_mir(def_id); Some(self.lazy(&mir)) } else { None } } // Encodes the inherent implementations of a structure, enumeration, or trait. fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> { debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id); let implementations = self.tcx.inherent_impls(def_id); if implementations.is_empty() { LazySeq::empty() } else { self.lazy_seq(implementations.iter().map(|&def_id| { assert!(def_id.is_local()); def_id.index })) } } fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> { debug!("IsolatedEncoder::encode_stability({:?})", def_id); self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab)) } fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> { debug!("IsolatedEncoder::encode_deprecation({:?})", def_id); self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr)) } fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> { let body = self.tcx.hir().body(body_id); let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value)); let rendered_const = &RenderedConst(rendered); self.lazy(rendered_const) } fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> { let tcx = self.tcx; debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id); let kind = match item.node { hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic, hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic, hir::ItemKind::Const(_, body_id) => { let mir = tcx.at(item.span).mir_const_qualif(def_id).0; EntryKind::Const( self.const_qualif(mir, body_id), self.encode_rendered_const_for_body(body_id) ) } hir::ItemKind::Fn(_, header, .., body) => { let data = FnData { constness: header.constness, arg_names: self.encode_fn_arg_names_for_body(body), sig: self.lazy(&tcx.fn_sig(def_id)), }; EntryKind::Fn(self.lazy(&data)) } hir::ItemKind::Mod(ref m) => { return self.encode_info_for_mod(FromId(item.hir_id, (m, &item.attrs, &item.vis))); } hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod, hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm, hir::ItemKind::Ty(..) => EntryKind::Type, hir::ItemKind::Existential(..) => EntryKind::Existential, hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)), hir::ItemKind::Struct(ref struct_def, _) => { let variant = tcx.adt_def(def_id).non_enum_variant(); // Encode def_ids for each field and method // for methods, write all the stuff get_trait_method // needs to know let ctor = struct_def.ctor_hir_id() .map(|ctor_hir_id| tcx.hir().local_def_id_from_hir_id(ctor_hir_id).index); let repr_options = get_repr_options(&tcx, def_id); EntryKind::Struct(self.lazy(&VariantData { ctor_kind: variant.ctor_kind, discr: variant.discr, ctor, ctor_sig: None, }), repr_options) } hir::ItemKind::Union(..) => { let variant = tcx.adt_def(def_id).non_enum_variant(); let repr_options = get_repr_options(&tcx, def_id); EntryKind::Union(self.lazy(&VariantData { ctor_kind: variant.ctor_kind, discr: variant.discr, ctor: None, ctor_sig: None, }), repr_options) } hir::ItemKind::Impl(_, polarity, defaultness, ..) => { let trait_ref = tcx.impl_trait_ref(def_id); let parent = if let Some(trait_ref) = trait_ref { let trait_def = tcx.trait_def(trait_ref.def_id); trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| { match node { specialization_graph::Node::Impl(parent) => Some(parent), _ => None, } }) } else { None }; // if this is an impl of `CoerceUnsized`, create its // "unsized info", else just store None let coerce_unsized_info = trait_ref.and_then(|t| { if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() { Some(tcx.at(item.span).coerce_unsized_info(def_id)) } else { None } }); let data = ImplData { polarity, defaultness, parent_impl: parent, coerce_unsized_info, trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)), }; EntryKind::Impl(self.lazy(&data)) } hir::ItemKind::Trait(..) => { let trait_def = tcx.trait_def(def_id); let data = TraitData { unsafety: trait_def.unsafety, paren_sugar: trait_def.paren_sugar, has_auto_impl: tcx.trait_is_auto(def_id), is_marker: trait_def.is_marker, super_predicates: self.lazy(&tcx.super_predicates_of(def_id)), }; EntryKind::Trait(self.lazy(&data)) } hir::ItemKind::TraitAlias(..) => { let data = TraitAliasData { super_predicates: self.lazy(&tcx.super_predicates_of(def_id)), }; EntryKind::TraitAlias(self.lazy(&data)) } hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item), }; Entry { kind, visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.hir_id, tcx)), span: self.lazy(&item.span), attributes: self.encode_attributes(&item.attrs), children: match item.node { hir::ItemKind::ForeignMod(ref fm) => { self.lazy_seq(fm.items .iter() .map(|foreign_item| tcx.hir().local_def_id_from_hir_id( foreign_item.hir_id).index)) } hir::ItemKind::Enum(..) => { let def = self.tcx.adt_def(def_id); self.lazy_seq(def.variants.iter().map(|v| { assert!(v.def_id.is_local()); v.def_id.index })) } hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { let def = self.tcx.adt_def(def_id); self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| { assert!(f.did.is_local()); f.did.index })) } hir::ItemKind::Impl(..) | hir::ItemKind::Trait(..) => { self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| { assert!(def_id.is_local()); def_id.index })) } _ => LazySeq::empty(), }, stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), ty: match item.node { hir::ItemKind::Static(..) | hir::ItemKind::Const(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) | hir::ItemKind::Existential(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)), _ => None, }, inherent_impls: self.encode_inherent_implementations(def_id), variances: match item.node { hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id), _ => LazySeq::empty(), }, generics: match item.node { hir::ItemKind::Static(..) | hir::ItemKind::Const(..) | hir::ItemKind::Fn(..) |
hir::ItemKind::Impl(..) | hir::ItemKind::Existential(..) | hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)), hir::ItemKind::TraitAlias(..) => Some(self.encode_generics(def_id)), _ => None, }, predicates: match item.node { hir::ItemKind::Static(..) | hir::ItemKind::Const(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Impl(..) | hir::ItemKind::Existential(..) | hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates(def_id)), _ => None, }, // The only time that `predicates_defined_on` is used (on // an external item) is for traits, during chalk lowering, // so only encode it in that case as an efficiency // hack. (No reason not to expand it in the future if // necessary.) predicates_defined_on: match item.node { hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates_defined_on(def_id)), _ => None, // not *wrong* for other kinds of items, but not needed }, mir: match item.node { hir::ItemKind::Static(..) => { self.encode_optimized_mir(def_id) } hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id), hir::ItemKind::Fn(_, header, ..) => { let generics = tcx.generics_of(def_id); let needs_inline = (generics.requires_monomorphization(tcx) || tcx.codegen_fn_attrs(def_id).requests_inline()) && !self.metadata_output_only(); let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir; if needs_inline || header.constness == hir::Constness::Const || always_encode_mir { self.encode_optimized_mir(def_id) } else { None } } _ => None, }, } } /// Serialize the text of exported macros fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> { use syntax::print::pprust; let def_id = self.tcx.hir().local_def_id_from_hir_id(macro_def.hir_id); Entry { kind: EntryKind::MacroDef(self.lazy(&MacroDef { body: pprust::tts_to_string(&macro_def.body.trees().collect::<Vec<_>>()), legacy: macro_def.legacy, })), visibility: self.lazy(&ty::Visibility::Public), span: self.lazy(&macro_def.span), attributes: self.encode_attributes(&macro_def.attrs), stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), children: LazySeq::empty(), ty: None, inherent_impls: LazySeq::empty(), variances: LazySeq::empty(), generics: None, predicates: None, predicates_defined_on: None, mir: None, } } fn encode_info_for_generic_param( &mut self, def_id: DefId, entry_kind: EntryKind<'tcx>, encode_type: bool, ) -> Entry<'tcx> { let tcx = self.tcx; Entry { kind: entry_kind, visibility: self.lazy(&ty::Visibility::Public), span: self.lazy(&tcx.def_span(def_id)), attributes: LazySeq::empty(), children: LazySeq::empty(), stability: None, deprecation: None, ty: if encode_type { Some(self.encode_item_type(def_id)) } else { None }, inherent_impls: LazySeq::empty(), variances: LazySeq::empty(), generics: None, predicates: None, predicates_defined_on: None, mir: None, } } fn encode_info_for_ty_param( &mut self, (def_id, Untracked(encode_type)): (DefId, Untracked<bool>), ) -> Entry<'tcx> { debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id); self.encode_info_for_generic_param(def_id, EntryKind::TypeParam, encode_type) } fn encode_info_for_const_param( &mut self, def_id: DefId, ) -> Entry<'tcx> { debug!("IsolatedEncoder::encode_info_for_const_param({:?})", def_id); self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true) } fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> { debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id); let tcx = self.tcx; let tables = self.tcx.typeck_tables_of(def_id); let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap(); let kind = match tables.node_type(hir_id).sty { ty::Generator(def_id, ..) => { let layout = self.tcx.generator_layout(def_id); let data = GeneratorData { layout: layout.clone(), }; EntryKind::Generator(self.lazy(&data)) } ty::Closure(def_id, substs) => { let sig = substs.closure_sig(def_id, self.tcx); let data = ClosureData { sig: self.lazy(&sig) }; EntryKind::Closure(self.lazy(&data)) } _ => bug!("closure that is neither generator nor closure") }; Entry { kind, visibility: self.lazy(&ty::Visibility::Public), span: self.lazy(&tcx.def_span(def_id)), attributes: self.encode_attributes(&tcx.get_attrs(def_id)), children: LazySeq::empty(), stability: None, deprecation: None, ty: Some(self.encode_item_type(def_id)), inherent_impls: LazySeq::empty(), variances: LazySeq::empty(), generics: Some(self.encode_generics(def_id)), predicates: None, predicates_defined_on: None, mir: self.encode_optimized_mir(def_id), } } fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> { debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id); let tcx = self.tcx; let id = tcx.hir().as_local_hir_id(def_id).unwrap(); let body_id = tcx.hir().body_owned_by(id); let const_data = self.encode_rendered_const_for_body(body_id); let mir = tcx.mir_const_qualif(def_id).0; Entry { kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data), visibility: self.lazy(&ty::Visibility::Public), span: self.lazy(&tcx.def_span(def_id)), attributes: LazySeq::empty(), children: LazySeq::empty(), stability: None, deprecation: None, ty: Some(self.encode_item_type(def_id)), inherent_impls: LazySeq::empty(), variances: LazySeq::empty(), generics: Some(self.encode_generics(def_id)), predicates: Some(self.encode_predicates(def_id)), predicates_defined_on: None, mir: self.encode_optimized_mir(def_id), } } fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> { // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because // we rely on the HashStable specialization for [Attribute] // to properly filter things out. self.lazy_seq_from_slice(attrs) } fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> { let used_libraries = self.tcx.native_libraries(LOCAL_CRATE); self.lazy_seq(used_libraries.iter().cloned()) } fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> { let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE); self.lazy_seq(foreign_modules.iter().cloned()) } fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> { let crates = self.tcx.crates(); let mut deps = crates .iter() .map(|&cnum| { let dep = CrateDep { name: self.tcx.original_crate_name(cnum), hash: self.tcx.crate_hash(cnum), kind: self.tcx.dep_kind(cnum), extra_filename: self.tcx.extra_filename(cnum), }; (cnum, dep) }) .collect::<Vec<_>>(); deps.sort_by_key(|&(cnum, _)| cnum); { // Sanity-check the crate numbers let mut expected_cnum = 1; for &(n, _) in &deps { assert_eq!(n, CrateNum::new(expected_cnum)); expected_cnum += 1; } } // We're just going to write a list of crate 'name-hash-version's, with // the assumption that they are numbered 1 to n. // FIXME (#2166): This is not nearly enough to support correct versioning // but is enough to get transitive crate dependencies working. self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep)) } fn encode_lib_features(&mut self, _: ()) -> LazySeq<(ast::Name, Option<ast::Name>)> { let tcx = self.tcx; let lib_features = tcx.lib_features(); self.lazy_seq(lib_features.to_vec()) } fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> { let tcx = self.tcx; let lang_items = tcx.lang_items(); let lang_items = lang_items.items().iter(); self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| { if let Some(def_id) = opt_def_id { if def_id.is_local() { return Some((def_id.index, i)); } } None })) } fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> { let tcx = self.tcx; self.lazy_seq_ref(&tcx.lang_items().missing) } /// Encodes an index, mapping each trait to its (local) implementations. fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> { debug!("IsolatedEncoder::encode_impls()"); let tcx = self.tcx; let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default(), }; tcx.hir().krate().visit_all_item_likes(&mut visitor); let mut all_impls: Vec<_> = visitor.impls.into_iter().collect(); // Bring everything into deterministic order for hashing all_impls.sort_by_cached_key(|&(trait_def_id, _)| { tcx.def_path_hash(trait_def_id) }); let all_impls: Vec<_> = all_impls .into_iter() .map(|(trait_def_id, mut impls)| { // Bring everything into deterministic order for hashing impls.sort_by_cached_key(|&def_index| { tcx.hir().definitions().def_path_hash(def_index) }); TraitImpls { trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), impls: self.lazy_seq_from_slice(&impls[..]), } }) .collect(); self.lazy_seq_from_slice(&all_impls[..]) } // Encodes all symbols exported from this crate into the metadata. // // This pass is seeded off the reachability list calculated in the // middle::reachable module but filters out items that either don't have a // symbol associated with them (they weren't translated) or if they're an FFI // definition (as that's not defined in this crate). fn encode_exported_symbols(&mut self, exported_symbols: &[(ExportedSymbol<'_>, SymbolExportLevel)]) -> EncodedExportedSymbols { // The metadata symbol name is special. It should not show up in // downstream crates. let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx)); let lazy_seq = self.lazy_seq(exported_symbols .iter() .filter(|&&(ref exported_symbol, _)| { match *exported_symbol { ExportedSymbol::NoDefId(symbol_name) => { symbol_name != metadata_symbol_name }, _ => true, } }) .cloned()); EncodedExportedSymbols { len: lazy_seq.len, position: lazy_seq.position, } } fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> { match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) { Some(arr) => { self.lazy_seq(arr.iter().map(|slot| { match *slot { Linkage::NotLinked | Linkage::IncludedFromDylib => None, Linkage::Dynamic => Some(LinkagePreference::RequireDynamic), Linkage::Static => Some(LinkagePreference::RequireStatic), } })) } None => LazySeq::empty(), } } fn encode_info_for_foreign_item(&mut self, (def_id, nitem): (DefId, &hir::ForeignItem)) -> Entry<'tcx> { let tcx = self.tcx; debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id); let kind = match nitem.node { hir::ForeignItemKind::Fn(_, ref names, _) => { let data = FnData { constness: hir::Constness::NotConst, arg_names: self.encode_fn_arg_names(names), sig: self.lazy(&tcx.fn_sig(def_id)), }; EntryKind::ForeignFn(self.lazy(&data)) } hir::ForeignItemKind::Static(_, true) => EntryKind::ForeignMutStatic, hir::ForeignItemKind::Static(_, false) => EntryKind::ForeignImmStatic, hir::ForeignItemKind::Type => EntryKind::ForeignType, }; Entry { kind, visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, tcx)), span: self.lazy(&nitem.span), attributes: self.encode_attributes(&nitem.attrs), children: LazySeq::empty(), stability: self.encode_stability(def_id), deprecation: self.encode_deprecation(def_id), ty: Some(self.encode_item_type(def_id)), inherent_impls: LazySeq::empty(), variances: match nitem.node { hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id), _ => LazySeq::empty(), }, generics: Some(self.encode_generics(def_id)), predicates: Some(self.encode_predicates(def_id)), predicates_defined_on: None, mir: None, } } } struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> { index: IndexBuilder<'a, 'b, 'tcx>, } impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> { fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> { NestedVisitorMap::OnlyBodies(&self.index.tcx.hir()) } fn visit_expr(&mut self, ex: &'tcx hir::Expr) { intravisit::walk_expr(self, ex); self.index.encode_info_for_expr(ex); } fn visit_item(&mut self, item: &'tcx hir::Item) { intravisit::walk_item(self, item); let def_id = self.index.tcx.hir().local_def_id_from_hir_id(item.hir_id); match item.node { hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => (), // ignore these _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)), } self.index.encode_addl_info_for_item(item); } fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) { intravisit::walk_foreign_item(self, ni); let def_id = self.index.tcx.hir().local_def_id_from_hir_id(ni.hir_id); self.index.record(def_id, IsolatedEncoder::encode_info_for_foreign_item, (def_id, ni)); } fn visit_variant(&mut self, v: &'tcx hir::Variant, g: &'tcx hir::Generics, id: hir::HirId) { intravisit::walk_variant(self, v, g, id); if let Some(ref discr) = v.node.disr_expr { let def_id = self.index.tcx.hir().local_def_id_from_hir_id(discr.hir_id); self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id); } } fn visit_generics(&mut self, generics: &'tcx hir::Generics) { intravisit::walk_generics(self, generics); self.index.encode_info_for_generics(generics); } fn visit_ty(&mut self, ty: &'tcx hir::Ty) { intravisit::walk_ty(self, ty); self.index.encode_info_for_ty(ty); } fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) { let def_id = self.index.tcx.hir().local_def_id_from_hir_id(macro_def.hir_id); self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def); } } impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> { fn encode_fields(&mut self, adt_def_id: DefId) { let def = self.tcx.adt_def(adt_def_id); for (variant_index, variant) in def.variants.iter_enumerated() { for (field_index, field) in variant.fields.iter().enumerate() { self.record(field.did, IsolatedEncoder::encode_field, (adt_def_id, Untracked((variant_index, field_index)))); } } } fn encode_info_for_generics(&mut self, generics: &hir::Generics) { for param in &generics.params { let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id); match param.kind { GenericParamKind::Lifetime { .. } => continue, GenericParamKind::Type { ref default, .. } => { self.record( def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, Untracked(default.is_some())), ); } GenericParamKind::Const { .. } => { self.record(def_id, IsolatedEncoder::encode_info_for_const_param, def_id); } } } } fn encode_info_for_ty(&mut self, ty: &hir::Ty) { match ty.node { hir::TyKind::Array(_, ref length) => { let def_id = self.tcx.hir().local_def_id_from_hir_id(length.hir_id); self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id); } _ => {} } } fn encode_info_for_expr(&mut self, expr: &hir::Expr) { match expr.node { hir::ExprKind::Closure(..) => { let def_id = self.tcx.hir().local_def_id_from_hir_id(expr.hir_id); self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id); } _ => {} } } /// In some cases, along with the item itself, we also /// encode some sub-items. Usually we want some info from the item /// so it's easier to do that here then to wait until we would encounter /// normally in the visitor walk. fn encode_addl_info_for_item(&mut self, item: &hir::Item) { let def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id); match item.node { hir::ItemKind::Static(..) | hir::ItemKind::Const(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) | hir::ItemKind::ForeignMod(..) | hir::ItemKind::GlobalAsm(..) | hir::ItemKind::ExternCrate(..) | hir::ItemKind::Use(..) | hir::ItemKind::Ty(..) | hir::ItemKind::Existential(..) | hir::ItemKind::TraitAlias(..) => { // no sub-item recording needed in these cases } hir::ItemKind::Enum(..) => { self.encode_fields(def_id); let def = self.tcx.adt_def(def_id); for (i, variant) in def.variants.iter_enumerated() { self.record(variant.def_id, IsolatedEncoder::encode_enum_variant_info, (def_id, Untracked(i))); if let Some(ctor_def_id) = variant.ctor_def_id { self.record(ctor_def_id, IsolatedEncoder::encode_enum_variant_ctor, (def_id, Untracked(i))); } } } hir::ItemKind::Struct(ref struct_def, _) => { self.encode_fields(def_id); // If the struct has a constructor, encode it. if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { let ctor_def_id = self.tcx.hir().local_def_id_from_hir_id(ctor_hir_id); self.record(ctor_def_id, IsolatedEncoder::encode_struct_ctor, (def_id, ctor_def_id)); } } hir::ItemKind::Union(..) => { self.encode_fields(def_id); } hir::ItemKind::Impl(..) => { for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() { self.record(trait_item_def_id, IsolatedEncoder::encode_info_for_impl_item, trait_item_def_id); } } hir::ItemKind::Trait(..) => { for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() { self.record(item_def_id, IsolatedEncoder::encode_info_for_trait_item, item_def_id); } } } } } struct ImplVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, impls: FxHashMap<DefId, Vec<DefIndex>>, } impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &hir::Item) { if let hir::ItemKind::Impl(..) = item.node { let impl_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id); if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) { self.impls .entry(trait_ref.def_id) .or_default() .push(impl_id.index); } } } fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {} fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) { // handled in `visit_item` above } } // NOTE(eddyb) The following comment was preserved for posterity, even // though it's no longer relevant as EBML (which uses nested & tagged // "documents") was replaced with a scheme that can't go out of bounds. // // And here we run into yet another obscure archive bug: in which metadata // loaded from archives may have trailing garbage bytes. Awhile back one of // our tests was failing sporadically on the macOS 64-bit builders (both nopt // and opt) by having ebml generate an out-of-bounds panic when looking at // metadata. // // Upon investigation it turned out that the metadata file inside of an rlib // (and ar archive) was being corrupted. Some compilations would generate a // metadata file which would end in a few extra bytes, while other // compilations would not have these extra bytes appended to the end. These // extra bytes were interpreted by ebml as an extra tag, so they ended up // being interpreted causing the out-of-bounds. // // The root cause of why these extra bytes were appearing was never // discovered, and in the meantime the solution we're employing is to insert // the length of the metadata to the start of the metadata. Later on this // will allow us to slice the metadata to the precise length that we just // generated regardless of trailing bytes that end up in it. pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> EncodedMetadata { let mut encoder = opaque::Encoder::new(vec![]); encoder.emit_raw_bytes(METADATA_HEADER); // Will be filled with the root position after encoding everything. encoder.emit_raw_bytes(&[0, 0, 0, 0]); let (root, mut result) = { let mut ecx = EncodeContext { opaque: encoder, tcx, lazy_state: LazyState::NoNode, type_shorthands: Default::default(), predicate_shorthands: Default::default(), source_file_cache: tcx.sess.source_map().files()[0].clone(), interpret_allocs: Default::default(), interpret_allocs_inverse: Default::default(), }; // Encode the rustc version string in a predictable location. rustc_version().encode(&mut ecx).unwrap(); // Encode all the entries and extra information in the crate, // culminating in the `CrateRoot` which points to all of it. let root = ecx.encode_crate_root(); (root, ecx.opaque.into_inner()) }; // Encode the root position. let header = METADATA_HEADER.len(); let pos = root.position; result[header + 0] = (pos >> 24) as u8; result[header + 1] = (pos >> 16) as u8; result[header + 2] = (pos >> 8) as u8; result[header + 3] = (pos >> 0) as u8; EncodedMetadata { raw_data: result } } pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions { let ty = tcx.type_of(did); match ty.sty { ty::Adt(ref def, _) => return def.repr, _ => bug!("{} is not an ADT", ty), } }
hir::ItemKind::Ty(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) |
hashset_test.go
package template import ( "testing" ) func TestHashSet(t *testing.T)
func BenchmarkHashSet(b *testing.B) { newSet := func() set { return NewHashSet() } b.Run("1", func(b *testing.B) { benchmarkSet(b, newSet, 1) }) b.Run("100", func(b *testing.B) { benchmarkSet(b, newSet, 100) }) b.Run("1000", func(b *testing.B) { benchmarkSet(b, newSet, 1000) }) b.Run("10000", func(b *testing.B) { benchmarkSet(b, newSet, 10000) }) }
{ testSet(t, func() set { return NewHashSet() }) }
cpu.rs
// Copyright 2019 Twitter, Inc. // Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 use crate::config::*; use crate::samplers::cpu::statistics::*; use atomics::*; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct Cpu { #[serde(default = "default_enabled")] enabled: AtomicBool, #[serde(default = "default_interval")] interval: AtomicOption<AtomicUsize>, #[serde(default = "default_statistics")] statistics: Vec<Statistic>, } impl Default for Cpu { fn
() -> Cpu { Cpu { enabled: default_enabled(), interval: default_interval(), statistics: default_statistics(), } } } fn default_enabled() -> AtomicBool { AtomicBool::new(false) } fn default_interval() -> AtomicOption<AtomicUsize> { AtomicOption::none() } fn default_statistics() -> Vec<Statistic> { vec![Statistic::User, Statistic::System, Statistic::Idle] } impl SamplerConfig for Cpu { fn enabled(&self) -> bool { self.enabled.load(Ordering::Relaxed) } fn interval(&self) -> Option<usize> { self.interval.load(Ordering::Relaxed) } } impl Cpu { pub fn statistics(&self) -> Vec<Statistic> { self.statistics.clone() } }
default
anonymization.py
# Copyright 2020 Unibg Seclab (https://seclab.unibg.it) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import generalization as gnrlz from mondrian import partition_dataframe from validation import get_validation_function # Functions to generate the anonymous dataset. def join_column(ser, dtype, generalization=None): """Make a clustered representation of the series in input. :ser: The Pandas series :column_name: The name of the column to be generalized :generalization: Dictionary of generalizations (info and params) """ values = ser.unique() if len(values) == 1: return str(values[0]) try: if not generalization: raise KeyError if generalization['generalization_type'] == 'categorical': return gnrlz.__generalize_to_lcc( values, generalization['taxonomy_tree']) elif generalization['generalization_type'] == 'numerical': return gnrlz.__generalize_to_lcp( values, generalization['taxonomy_tree'], generalization['min'], generalization['params']['fanout']) elif generalization[ 'generalization_type'] == 'common_prefix': return gnrlz.__generalize_to_cp( values, hidemark=generalization['params']['hide-mark']) except KeyError: if dtype.name in ('object', 'category'): # ...set generalization return '{' + ','.join(map(str, values)) + '}' else: # ...range generalization return '[{}-{}]'.format(ser.min(), ser.max()) def generalize_quasiid(df, partitions, quasiid_columns, quasiid_gnrlz=None): """Return a new dataframe by generalizing the partitions.""" dtypes = df.dtypes for i, partition in enumerate(partitions): if i % 100 == 0: print("Finished {}/{} partitions...".format(i, len(partitions))) for column in quasiid_columns: generalization = quasiid_gnrlz[column] \ if quasiid_gnrlz and column in quasiid_gnrlz \ else None df.loc[partition, column] = join_column(df[column][partition], dtypes[column], generalization) return df def remove_id(df, id_columns, redact=False): """Remove identifiers columns. :df: The Pandas DataFrame :id_columns: The list of columns to remove :redact: If False drops the given columns. Otherwise it redacts them. Defaults to False. """ if not redact: df.drop(columns=id_columns, inplace=True) else: df.loc[:, id_columns] = "REDACTED" return df def
(df, id_columns, quasiid_columns, sensitive_columns, column_score, K, L, quasiid_gnrlz=None, redact=False): """Perform the clustering using K-anonymity and L-diversity and using the Mondrian algorithm. Then generalizes the quasi-identifier columns. """ df = remove_id(df, id_columns, redact) partitions = partition_dataframe(df=df, quasiid_columns=quasiid_columns, sensitive_columns=sensitive_columns, column_score=column_score, is_valid=get_validation_function(K,L)) return generalize_quasiid(df=df, partitions=partitions, quasiid_columns=quasiid_columns, quasiid_gnrlz=quasiid_gnrlz)
anonymize
b0xfile_assets_azure_integration_logic-apps-custom-connector.png.go
// Code generaTed by fileb0x at "2020-09-25 22:38:50.745413 +0300 MSK m=+1.990489997" from config file "b0x.yml" DO NOT EDIT. // modified(2020-09-25 20:02:03.920630563 +0300 MSK) // original path: ../../assets/azure/integration/logic-apps-custom-connector.png package assets import ( "bytes" "compress/gzip" "io" "os" ) // FileAssetsAzureIntegrationLogicAppsCustomConnectorPng is "assets/azure/integration/logic-apps-custom-connector.png" var FileAssetsAzureIntegrationLogicAppsCustomConnectorPng = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xe4\x94\xf9\x57\x53\x67\x1a\xc7\xdf\x7b\x09\x10\xb0\x42\x2e\x68\x0d\x6e\x09\x57\x05\xf7\x86\x18\x95\x58\xca\x8d\xe3\xb5\x88\x52\x82\x28\x0a\x58\x35\xb8\xb0\x0b\x48\x91\x08\x36\xc9\x45\x70\x0c\x70\x59\xac\xa2\x33\x88\xc0\xc8\x54\x90\x45\x05\xc5\xb0\x13\x07\x0c\x45\x8b\xa8\x2c\x56\xad\x6c\xd1\x89\x6c\xe1\x44\x59\xd2\x12\x93\x39\xd7\x33\x7f\xc4\x9c\x33\x3f\x3c\xe7\xbc\xcf\x73\x3e\xe7\xf3\xbe\xcf\xf7\x87\x37\xd5\xc7\xdb\x63\xae\xf5\x42\x6b\x00\xc0\x5c\xcf\x1d\xb8\x2f\x00\x10\xa0\x8a\x6e\x01\x00\xf8\x3e\xb6\x24\x18\x00\x60\x15\xb3\x23\xe0\x07\x00\x76\x5d\xa1\x0a\xd2\x3e\x8c\x66\x03\x00\x1c\xe2\xb6\xfb\xc7\xed\x89\x0e\x8e\x13\x07\xc5\x1e\x07\x62\xb1\x78\x7d\x58\x54\xc4\x0f\x47\x83\x62\x8e\xaf\x8f\x8e\x0d\xb9\xaa\x75\x5b\x08\x00\x9d\xe7\x89\x6f\xdd\x7b\x3a\x6f\xfc\x4d\x73\xd6\x62\xf1\x92\xb6\xc1\xce\x31\xfe\x82\xe5\x31\xc7\x8e\xa5\x1c\x3b\x0f\x07\xec\x70\x46\x19\x39\x37\xd1\xdd\xbe\xae\xab\x2e\xc4\xce\x63\xeb\x6d\xd1\x2e\x51\x6d\x4c\xd2\x4f\xaa\x9d\x9e\x9e\x90\xef\xe2\xd0\xca\x45\x9b\xe9\x5b\xb7\x9b\xa7\x31\xea\x60\x6b\x6b\xd4\x11\xf5\x8a\xb4\x7a\xd8\xfe\xc6\xe7\xbb\x94\x25\xaf\x15\xe2\xfa\x0d\xfd\xac\x02\xcd\xf0\x37\x1f\xa7\x86\xfb\x6e\xbf\xae\x9e\x89\x3f\xff\x5b\xd5\x84\x61\x44\xa5\xdd\xa5\x89\xfa\xb1\x66\x7c\x34\xf8\x94\x6b\xfe\xd7\x7f\xb6\x2b\x26\xc6\x2f\xb9\x5b\x4a\x02\x73\xdc\x81\x4f\x26\x10\x1c\x81\x41\xaa\x15\x58\xee\x04\xb2\xff\xf6\xff\xdb\x84\xdc\x97\x3c\xe8\x34\xcd\xfe\xeb\xf4\x69\xed\x58\xcd\xf8\x68\xbe\x8a\x63\xd3\xe2\x24\x93\x2e\x56\x0d\xc9\xb2\x8a\x06\xef\x9e\x47\x66\x76\xb2\x92\xbd\x4f\xf0\xb2\x73\x1b\xe3\x35\x03\x53\x41\xa4\x62\x53\xad\x8a\x51\x69\x9a\x5e\x73\x66\x22\x72\xd4\xcb\x67\x91\x10\x62\xbb\x40\x44\x2b\x0d\xd8\xd9\x83\x1d\x5e\xe0\x7f\xba\xa9\x8c\x32\xbb\xb3\x65\x61\x73\xc3\xf0\x46\x95\xe3\xa6\x26\x8b\xee\xc8\x95\x12\x82\xdf\xf0\xdf\xbd\xee\xc7\xdc\x6c\x09\x22\x59\x4d\x9f\x46\xfa\x3a\x15\x31\xeb\x4a\xbc\xc5\xd0\x6f\x43\x7a\x67\x54\xa0\xa8\xb3\x56\x7e\xa1\x2e\x90\x83\x83\x23\x4e\x60\x43\xa6\x0c\x85\xe3\x8a\xd3\xc1\x5a\x8e\x31\x95\xfe\x34\xe7\xdf\x66\x77\x06\x28\x68\x73\xae\x8d\x20\x49\x27\xc4\x89\xf5\xbc\x45\xc4\x59\x8a\xee\x88\xe0\x82\xf9\xa4\x0c\x85\x79\x15\xb5\x60\x2f\x8f\xa2\xcb\x6f\xc0\x3e\x83\x14\x7d\x31\xd7\x4a\xf0\xf0\x33\x14\x86\x82\x59\x85\xed\xad\x6f\x5b\x3b\x9e\x6b\xfc\x5b\x06\x5d\x5b\x6d\xfb\x6a\xab\x66\xd2\x9f\x5b\x0e\xf7\x54\xd7\x1f\x4e\xac\x59\xc8\xca\x5b\x25\xc9\x3c\xb4\x97\x45\x58\x48\x3f\x60\x4f\x96\x25\x39\x1c\x6c\x3e\x33\x1d\xea\xac\xdd\x6f\x92\xbc\x4e\x2b\x95\x2d\xa9\x79\xa0\xf3\xc0\xc7\xc8\x6d\x86\xb1\xfa\x66\x77\xfd\xa1\xe1\x64\xe5\xc9\xd2\xb9\x82\x22\x4a\xfe\x5d\x09\x17\xec\x22\x4d\xac\x09\x8c\x94\x7d\xd2\x14\xf1\xa3\x1d\xe1\xbd\xb7\xeb\xc0\x5a\x17\xe3\x4c\x9f\x69\xa5\xd4\xa4\x4d\xd6\x77\xb0\x30\xb9\xac\xcf\x1e\xfa\x50\xba\x1a\xec\xca\x30\x89\x27\xfa\xb2\x5a\x8a\x5c\xdc\xdd\x49\xfd\x78\x01\x4e\x34\x94\x5a\x29\x9f\x53\xa6\xbf\xfb\x21\x84\x2f\x75\x08\x98\x6f\x2b\x18\xa6\xd6\x24\xd3\x2c\x0a\x2f\xeb\x84\x97\x49\xa5\x71\x3c\x79\xa2\x33\xc1\xde\xdf\xa3\x12\x74\x6f\x32\xb6\xfb\x22\x72\x06\xf4\x68\x8d\x1d\x11\xd8\x86\x05\xac\x84\xcb\x18\x90\xf5\x01\x37\x50\x9d\x25\x43\xe1\x63\x77\x42\x41\xa0\x83\x09\xa7\xbd\x7f\x73\x04\x0a\x3d\x61\xb0\x47\x0a\x43\xd2\x69\x85\x3d\x94\xef\x50\xc7\x52\xa2\xb7\x0d\x43\xa0\x44\x5e\x04\x48\xfc\x0c\x75\x44\x42\xef\x3f\x43\xce\x77\x69\x85\x2f\x3e\x43\x91\xdf\x80\x46\xca\x34\x29\x2a\x83\x7e\xe1\x52\x91\xd6\x55\x98\xb3\x5f\x53\x91\x3e\xbe\x6f\x47\x94\x53\x4f\xac\x78\xe5\x0a\x5e\x52\xa6\xc0\x7b\xbb\x01\x69\xda\x8d\x0a\x22\xbc\x97\x00\xb5\x8c\x8b\x14\xae\x28\xb6\x26\x74\xd8\x55\xfa\xd3\x34\x7b\x4b\xa5\xfe\xc5\x32\xf8\xde\x00\x0e\x71\x8c\x17\x11\x28\x5c\x11\x0f\x48\x53\x1c\x4e\xe4\x56\xcc\x07\xea\x7e\x92\xee\x53\x76\x14\x0b\x91\x98\xa6\x1f\xf4\xc8\x6b\xf8\x1a\xc7\xc4\xa5\x26\xd3\xd7\x77\xed\x75\x15\xd1\x0d\x8c\xc3\x6e\x33\xbf\xe7\x29\xf8\xa4\xe3\x2d\x5b\xb5\xfe\x05\x3f\xda\xf7\xd1\xcf\x6f\x1e\x37\xff\x9e\x3a\xdb\x26\xed\xaf\xca\x0f\x91\x3a\x7e\x7a\xdb\xdf\x74\x0e\x7d\x5a\x71\xdb\x4d\xcc\xdf\xd7\x62\xf9\x73\xd6\xb3\x8c\x62\x77\x73\x8e\x31\x61\xed\x64\x1c\xe8\xfd\xd0\x0a\x98\xa6\x06\x9c\x08\xfc\x71\x35\x50\x35\x7f\x81\x14\x5a\x64\xd1\x94\xfa\x2b\x2b\xe0\x4b\xd3\x9e\x80\xa4\x06\xff\xf4\x4b\xd1\x5d\x71\x82\x2f\x55\x71\x8d\x5b\xe4\x60\x45\xf9\x5f\x5d\x0e\xe5\xcd\x3a\x99\x24\xa7\xe7\x79\xa8\x64\xe5\x45\x27\xe5\x59\xb6\x92\x6b\xfe\x4f\x46\x7a\xd7\x9c\xc1\xd2\x1c\xfb\xf2\x3e\x3a\x5d\x59\xef\xc6\xea\x37\x8c\x68\x32\x65\x2f\x83\x8e\x94\x39\x0e\xbd\xbb\x7d\x2d\x23\x5d\x23\xde\xc5\x3a\x87\xef\x43\x10\xc5\xad\xb1\x83\xf6\x49\xb1\xfb\xb6\xb5\x3e\x3e\x2c\x73\x3c\x64\x38\xbb\xdf\xb2\xaa\x5c\x68\x5c\x20\xa0\x3d\xe2\x48\x77\x26\xbe\x3d\x05\xd0\x3b\x6b\xd5\xc5\xf7\x84\x8d\x76\x3e\xb4\xcb\x41\x86\xee\x81\xd4\xe6\x39\x6c\xf8\x23\x57\x1a\xae\xeb\xee\xb7\x98\x97\x94\xc0\xc4\x36\x06\x68\xe6\x6e\x8d\xfa\xb6\xb5\x87\x6f\xab\x53\xcc\xb8\x93\x98\xe1\xdd\xd6\x49\x23\x36\x30\x27\xd3\x54\xbc\x8d\x94\x15\xcc\x3a\xad\xf8\xfe\x55\xa3\xe1\xc6\x66\xda\xcb\xfc\xea\xa6\xec\x59\xb1\x4d\x9f\xdc\x45\xea\xa6\xd9\x9a\x98\xa5\x3c\xa2\x66\xa9\x5f\x55\xec\x9f\x09\x96\xbc\xdd\xf7\x7c\xaa\x3e\x24\x8b\x26\x3a\xd3\x9b\x28\x14\x08\x2d\x37\x1d\x35\x74\x87\x8f\x8b\xcd\xbf\x4c\xea\x72\x91\x86\xc7\x5f\xef\x34\x67\x24\x5d\x74\x91\x86\x8b\x87\x84\x16\x76\x49\x53\x4c\x6c\x9d\x6b\x4f\x88\x59\x9a\xf2\xae\x03\x56\xe1\x3a\x55\x6c\x96\xae\xbc\xe8\x80\xad\xe3\x9f\x02\x28\x3e\x70\x52\x25\x8c\xd8\x64\x2d\x48\xa1\x7b\x91\x05\x5f\x9e\x58\x4c\xd0\x11\x8e\x34\xb0\x3a\x07\xe0\x6f\x33\x08\x5d\x57\x55\x85\x39\x1b\x3d\x4c\x23\x0b\x7a\x4f\x6c\x04\x48\x02\x2a\x32\x4c\x8a\x46\x21\xf9\x7b\x0c\x56\x09\xbf\x0a\xb6\x12\xe0\xcd\x08\x47\x9a\xc8\x3d\x00\xd0\x3f\xd3\x09\x5d\xd7\xd5\x00\x33\xc6\x33\x21\x8d\x2c\x58\xda\xb1\x94\x90\x4f\x2f\x13\x19\x26\xc3\x2f\x00\xfc\xde\x22\x48\x5d\x1c\x92\x6e\xce\xbe\xde\x48\x67\x62\x8d\x07\x78\x00\x19\xc7\x95\xfa\x76\x91\x0e\xe0\xdd\x2c\x48\xed\x9c\x8e\x42\xf2\x92\xcd\xb0\x4a\xe8\xf4\x10\x66\xec\xa6\xee\x8b\x4c\xb3\x60\x5f\xcf\xa7\x33\x31\x87\xf9\xb6\x02\xfc\x0f\x3a\x13\x0b\xf0\x43\x08\x79\x2c\xc2\x91\x72\xcb\x9c\x00\xf2\xd8\x43\xa9\x6f\xd7\x7a\x0d\x9b\xb9\x69\x7b\x73\x1a\x23\x66\xc5\x36\x47\x9e\x74\xa2\x0d\x71\x83\x7f\xc8\xe5\xfa\x5f\xb5\x8c\x05\x9d\x8b\xb0\x04\xbf\x29\xba\xa8\xaa\x7b\x59\x52\xba\x46\xac\x69\x38\xa7\xdb\xd3\xb8\xda\x8c\x51\xe9\x45\x0b\x3e\x6e\xe0\x15\xbe\x02\x38\x6f\x31\xa4\x2e\x46\xfc\x2c\xd9\xd7\x1f\xd0\x99\xd8\xdc\x9b\x83\x1d\xa7\x5e\x54\xc9\x34\x03\x19\x7c\x53\x50\xcc\x1a\x52\x16\xbf\x39\xaa\x75\xa4\xf3\xab\xea\x8f\x92\x03\xf5\x37\x9a\xb2\xfd\x3c\x94\xfa\x30\x9f\x3d\x90\xbc\x84\x07\xab\x84\x45\xb9\x73\x04\xf8\x71\x84\x23\x5d\xd8\x7b\x0c\xa0\xab\x53\x09\x5d\x57\x4d\xb0\x19\x63\xb7\x2b\xac\x12\x5a\xe6\xda\x08\xf0\x7f\xd0\x99\xd8\xb5\x50\x77\x80\xcc\xf1\x50\xea\x87\x77\x2c\x80\xe4\xfe\x2b\x61\x95\x30\xa4\xce\x4a\xd0\xfa\x2b\xc2\x91\x6e\xe9\xf6\x03\x68\x70\x1a\xa1\xeb\xba\xa9\x85\x19\x95\xef\xe8\x4c\x6c\xc9\x28\x17\x20\x07\xa8\x51\x6d\x94\x19\xa3\x32\x88\x46\x16\xd0\xea\x6c\x04\xad\xab\x96\x89\x0c\xcb\x9f\x49\x00\xea\xcd\x84\xd4\xce\x17\xe6\x41\x72\xff\x0d\xb0\x4a\xc8\x0d\x83\x19\x27\xbd\x68\x64\x41\x8a\xaf\x39\x7b\x68\x15\xc2\x91\xfe\xb4\x73\x01\x21\x6f\x43\x45\x86\xec\x4e\xe3\x78\xf2\x55\xea\x4b\xbc\xec\x6e\x79\x69\x12\xb3\xfb\x25\x9e\x66\xab\x0c\x2b\x05\x00\x00\xcf\xed\xde\xf8\xad\xbf\x88\xce\xfe\x27\x00\x00\xff\xff\xe8\x84\x37\x83\xa7\x08\x00\x00") func init() { rb := bytes.NewReader(FileAssetsAzureIntegrationLogicAppsCustomConnectorPng) r, err := gzip.NewReader(rb) if err != nil { panic(err) } err = r.Close() if err != nil { panic(err) } f, err := FS.OpenFile(CTX, "assets/azure/integration/logic-apps-custom-connector.png", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) if err != nil { panic(err) } _, err = io.Copy(f, r) if err != nil { panic(err)
err = f.Close() if err != nil { panic(err) } }
}
LoRaServer.js
import React, { Component } from 'react'; import { connect } from 'dva'; import Link from 'umi/link'; import Exception from '@/components/Exception'; import GridContent from '@/components/PageHeaderWrapper/GridContent'; import { formatMessage, FormattedMessage } from 'umi/locale'; import numeral from 'numeral'; import { Row, Col, Icon, Card, Tabs, Table, Radio, DatePicker, Tooltip, Menu, Dropdown,
MiniBar, MiniProgress, Field, Bar, Pie, TimelineChart, } from '@/components/Charts'; class System extends Component { state = { loading : true }; componentDidMount() { window.history.go(-1); window.open("https://loraserver.thulpwan.top/#/login"); } render() { return ( <></> ) } } export default System;
} from 'antd'; import { ChartCard, MiniArea,
mod.rs
//! Interface for chips and boards. use crate::driver::Driver; use crate::process; use crate::returncode; use crate::syscall; use core::fmt::Write; pub mod mpu; crate mod systick; /// Interface for individual boards. /// /// Each board should define a struct which implements this trait. This trait is /// the core for how syscall dispatching is handled, and the implementation is /// responsible for dispatching to drivers for each system call number. /// /// ## Example /// /// ```ignore /// struct Hail { /// console: &'static capsules::console::Console<'static>, /// ipc: kernel::ipc::IPC, /// dac: &'static capsules::dac::Dac<'static>, /// } /// /// impl Platform for Hail { /// fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R /// where /// F: FnOnce(Option<&dyn kernel::Driver>) -> R, /// { /// match driver_num { /// capsules::console::DRIVER_NUM => f(Some(self.console)), /// kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)), /// capsules::dac::DRIVER_NUM => f(Some(self.dac)), /// /// _ => f(None), /// } /// } /// } /// ``` pub trait Platform { /// Platform-specific mapping of syscall numbers to objects that implement /// the Driver methods for that syscall. fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R where F: FnOnce(Option<&dyn Driver>) -> R; /// Check the platform-provided system call filter for all non-yield system /// calls. If the system call is allowed for the provided process then /// return Ok(()). Otherwise, return Err with a ReturnCode that will be /// returned to the calling application. The default implementation allows /// all system calls. This API should be considered unstable, and is likely /// to change in the future. fn filter_syscall( &self, _process: &dyn process::ProcessType, _syscall: &syscall::Syscall, ) -> Result<(), returncode::ReturnCode> { Ok(()) } } /// Interface for individual MCUs. /// /// The trait defines chip-specific properties of Tock's operation. These /// include whether and which memory protection mechanism and systick to use, /// how to switch between the kernel and userland applications, and how to /// handle hardware events. /// /// Each microcontroller should define a struct and implement this trait. pub trait Chip { /// The particular Memory Protection Unit (MPU) for this chip. type MPU: mpu::MPU; /// The implementation of the interface between userspace and the kernel for /// this specific chip. Likely this is architecture specific, but individual /// chips may have various custom requirements. type UserspaceKernelBoundary: syscall::UserspaceKernelBoundary; /// The implementation of the timer used to create the timeslices provided /// to applications. type SysTick: systick::SysTick; /// The kernel calls this function to tell the chip to check for all pending /// interrupts and to correctly dispatch them to the peripheral drivers for /// the chip. /// /// This function should loop internally until all interrupts have been /// handled. It is ok, however, if an interrupt occurs after the last check /// but before this function returns. The kernel will handle this edge case. fn service_pending_interrupts(&self); /// Ask the chip to check if there are any pending interrupts. fn has_pending_interrupts(&self) -> bool; /// Returns a reference to the implementation for the MPU on this chip. fn mpu(&self) -> &Self::MPU; /// Returns a reference to the implementation of the systick timer for this /// chip. fn systick(&self) -> &Self::SysTick; /// Returns a reference to the implementation for the interface between /// userspace and kernelspace. fn userspace_kernel_boundary(&self) -> &Self::UserspaceKernelBoundary; /// Called when there is nothing left for the chip to do and it should enter /// a low power sleep state. This low power sleep state should allow /// interrupts to still be active so that the next interrupt event wakes the /// chip and resumes the scheduler. fn sleep(&self); /// Run a function in an atomic state, which means that interrupts are /// disabled so that an interrupt will not fire during the passed in /// function's execution. unsafe fn atomic<F, R>(&self, f: F) -> R where F: FnOnce() -> R; /// Print out chip state (system registers) to a supplied /// writer. This does not print out the execution context /// (data registers), as this depends on how they are stored; /// that is implemented by /// `syscall::UserspaceKernelBoundary::print_context`. /// This also does not print out a process memory state, /// that is implemented by `process::Process::print_memory_map`. /// The MPU state is printed by the MPU's implementation of /// the Display trait. /// Used by panic. unsafe fn print_state(&self, writer: &mut dyn Write); } /// Generic operations that clock-like things are expected to support. pub trait ClockInterface { fn is_enabled(&self) -> bool; fn enable(&self); fn disable(&self); } /// Helper struct for interfaces that expect clocks, but have no clock control. pub struct
{} impl ClockInterface for NoClockControl { fn is_enabled(&self) -> bool { true } fn enable(&self) {} fn disable(&self) {} } /// Instance of NoClockControl for things that need references to /// `ClockInterface` objects. pub static mut NO_CLOCK_CONTROL: NoClockControl = NoClockControl {};
NoClockControl
boolean.rs
//! ASN.1 `BOOLEAN` support. use crate::{ asn1::Any, ByteSlice, DecodeValue, Decoder, EncodeValue, Encoder, Error, ErrorKind, FixedTag, Length, OrdIsValueOrd, Result, Tag, }; /// Byte used to encode `true` in ASN.1 DER. From X.690 Section 11.1: /// /// > If the encoding represents the boolean value TRUE, its single contents
/// Byte used to encode `false` in ASN.1 DER. const FALSE_OCTET: u8 = 0b00000000; impl<'a> DecodeValue<'a> for bool { fn decode_value(decoder: &mut Decoder<'a>, length: Length) -> Result<Self> { if length != Length::ONE { return Err(decoder.error(ErrorKind::Length { tag: Self::TAG })); } match decoder.byte()? { FALSE_OCTET => Ok(false), TRUE_OCTET => Ok(true), _ => Err(Self::TAG.non_canonical_error()), } } } impl EncodeValue for bool { fn value_len(&self) -> Result<Length> { Ok(Length::ONE) } fn encode_value(&self, encoder: &mut Encoder<'_>) -> Result<()> { encoder.byte(if *self { TRUE_OCTET } else { FALSE_OCTET }) } } impl FixedTag for bool { const TAG: Tag = Tag::Boolean; } impl OrdIsValueOrd for bool {} impl From<bool> for Any<'static> { fn from(value: bool) -> Any<'static> { let value = ByteSlice::from(match value { false => &[FALSE_OCTET], true => &[TRUE_OCTET], }); Any::from_tag_and_value(Tag::Boolean, value) } } impl TryFrom<Any<'_>> for bool { type Error = Error; fn try_from(any: Any<'_>) -> Result<bool> { any.try_into() } } #[cfg(test)] mod tests { use crate::{Decodable, Encodable}; #[test] fn decode() { assert_eq!(true, bool::from_der(&[0x01, 0x01, 0xFF]).unwrap()); assert_eq!(false, bool::from_der(&[0x01, 0x01, 0x00]).unwrap()); } #[test] fn encode() { let mut buffer = [0u8; 3]; assert_eq!( &[0x01, 0x01, 0xFF], true.encode_to_slice(&mut buffer).unwrap() ); assert_eq!( &[0x01, 0x01, 0x00], false.encode_to_slice(&mut buffer).unwrap() ); } #[test] fn reject_non_canonical() { assert!(bool::from_der(&[0x01, 0x01, 0x01]).is_err()); } }
/// > octet shall have all eight bits set to one. const TRUE_OCTET: u8 = 0b11111111;
composites_simulator.py
#!/usr/bin/env python import numpy as np from copy import deepcopy import matplotlib.pyplot as plt from nntable import AllCategoriesTables from composites_utils import * class simulator(object): def __init__(self, db, batch_size=None, nn_table=None): self.db = db self.cfg = db.cfg self.batch_size = batch_size if batch_size is not None else self.cfg.batch_size if nn_table is None: self.nn_table = AllCategoriesTables(db) self.nn_table.build_nntables_for_all_categories() else: self.nn_table = nn_table def reset(self): self.scenes = [] frames = [] if self.cfg.use_color_volume: channel_dim = 3 * self.cfg.output_vocab_size else: channel_dim = 4 + self.cfg.output_vocab_size for i in range(self.batch_size): scene = {} scene['out_inds'] = [] scene['out_vecs'] = [] scene['out_patches'] = [] frame = np.zeros( ( self.cfg.input_image_size[1], self.cfg.input_image_size[0], channel_dim ) ) scene['last_frame'] = frame scene['last_label'] = np.zeros( ( self.cfg.input_image_size[1], self.cfg.input_image_size[0] ), dtype=np.int32 ) scene['last_mask'] = np.zeros( ( self.cfg.input_image_size[1], self.cfg.input_image_size[0] ), dtype=np.float32 ) self.scenes.append(scene) frames.append(frame) frames = np.stack(frames, axis=0) return torch.from_numpy(frames) def batch_render_to_pytorch(self, out_inds, out_vecs): assert(len(out_inds) == self.batch_size) outputs = [] for i in range(self.batch_size): frame = self.update_scene(self.scenes[i], {'out_inds': out_inds[i], 'out_vec': out_vecs[i]}) outputs.append(frame) outputs = np.stack(outputs, 0) return torch.from_numpy(outputs) def
(self, return_sequence=False): out_frames, out_noises, out_masks, out_labels, out_scenes = [], [], [], [], [] for i in range(len(self.scenes)): predicted_scene = self.db.prediction_outputs_to_scene(self.scenes[i], self.nn_table) predicted_scene['patches'] = self.scenes[i]['out_patches'] frames, noises, masks, labels = self.render_predictions_as_output(predicted_scene, return_sequence) if not return_sequence: frames = frames[None, ...] noises = noises[None, ...] masks = masks[None, ...] labels = labels[None, ...] out_frames.append(frames) out_noises.append(noises) out_masks.append(masks) out_labels.append(labels) out_scenes.append(predicted_scene) return out_frames, out_noises, out_masks, out_labels, out_scenes def render_predictions_as_output(self, scene, return_sequence): width = scene['width'] height = scene['height'] clses = scene['clses'] boxes = scene['boxes'] patches = scene['patches'] if self.cfg.use_color_volume: channel_dim = 3 * self.cfg.output_vocab_size else: channel_dim = 4 + self.cfg.output_vocab_size frame = np.zeros((height, width, channel_dim)) noise = np.zeros((height, width, channel_dim)) label = np.zeros((height, width), dtype=np.int32) mask = np.zeros((height, width), dtype=np.float32) out_frames, out_noises, out_labels, out_masks = [], [], [], [] for i in range(len(clses)): cls_ind = clses[i] xywh = boxes[i] patch = patches[i] xyxy = xywh_to_xyxy(xywh, width, height) if self.cfg.use_color_volume: frame[:,:,3*cls_ind:3*(cls_ind+1)], mask, _, label, noise[:,:,3*cls_ind:3*(cls_ind+1)] = \ patch_compose_and_erose(frame[:,:,3*cls_ind:3*(cls_ind+1)], mask, label, \ xyxy, patch, self.db, noise[:,:,3*cls_ind:3*(cls_ind+1)]) else: frame[:,:,-3:], mask, _, label, noise[:,:,-3:] = \ patch_compose_and_erose(frame[:,:,-3:], mask, label, xyxy, patch, self.db, noise[:,:,-3:]) frame[:,:,-4] = np.maximum(mask*255, frame[:,:,-4]) frame[:,:,cls_ind] = np.maximum(mask*255, frame[:,:,cls_ind]) out_frames.append(frame.copy()) out_noises.append(noise.copy()) out_labels.append(label.copy()) out_masks.append(mask.copy()) if len(clses) == 0: out_frames.append(frame.copy()) out_noises.append(noise.copy()) out_labels.append(label.copy()) out_masks.append(mask.copy()) if return_sequence: return np.stack(out_frames, 0), np.stack(out_noises, 0), np.stack(out_masks, 0), np.stack(out_labels, 0) else: return out_frames[-1], out_noises[-1], out_masks[-1], out_labels[-1] def update_scene(self, scene, step_prediction): ############################################################## # Update the scene and the last instance of the scene ############################################################## out_inds = step_prediction['out_inds'].flatten() out_vec = step_prediction['out_vec'].flatten() scene['out_inds'].append(out_inds) scene['out_vecs'].append(out_vec) scene['last_frame'], scene['last_mask'], scene['last_label'], current_patch = \ self.update_frame(scene['last_frame'], scene['last_mask'], scene['last_label'], out_inds, out_vec) scene['out_patches'].append(current_patch) return scene['last_frame'] def update_frame(self, input_frame, input_mask, input_label, input_inds, input_vec): if input_inds[0] <= self.cfg.EOS_idx: return input_frame, input_mask, input_label, None w = input_frame.shape[-2] h = input_frame.shape[-3] cls_ind = input_inds[0] xywh = self.db.index2box(input_inds[1:]) xywh = xywh * np.array([w, h, w, h]) xyxy = xywh_to_xyxy(xywh, w, h) patch = self.nn_table.retrieve(cls_ind, input_vec)[0] # print(patch) # print(patch['name']) # update the frame if self.cfg.use_color_volume: input_frame[:,:,3*cls_ind:3*(cls_ind+1)], input_mask, _, input_label, _ = \ patch_compose_and_erose(input_frame[:,:,3*cls_ind:3*(cls_ind+1)], input_mask, input_label, xyxy, patch, self.db) else: input_frame[:,:,-3:], input_mask, _, input_label, _ = \ patch_compose_and_erose(input_frame[:,:,-3:], input_mask, input_label, xyxy, patch, self.db) input_frame[:,:,-4] = np.maximum(255*input_mask, input_frame[:,:,-4]) input_frame[:,:,cls_ind] = np.maximum(255*input_mask, input_frame[:,:,cls_ind]) return input_frame, input_mask, input_label, patch
batch_redraw
Corpus.py
import abc from backend.model.SentenceTokenise import SentenceTokenise from backend.service.ExtractSentences import extract_sentences from backend.service.ReadCorpus import read_corpus class Corpus: def __init__(self): self.receive_text = "" self.input_file = "t1_biology_0_0.txt" self.base_train_folder = "../data/source_txt/train/" pass sentences = SentenceTokenise() @abc.abstractmethod def getInputText(self): # Corpusul curat Corpus.receivedText = read_corpus(self.base_train_folder, self.input_file) return Corpus.receivedText def getSentences(self, text):
# Lista de propozitii self.sentences.listOfSentence = extract_sentences(text) return self.sentences.listOfSentence def setInputText(self, text): pass
helper_func.py
import regionmask import numpy as np import dask def create_windmax_dict(u, v, names, borders, longitude, latitude): """Produce a dictionary of masked maximum wind speeds in units of mph.""" if u.units != "m s**-1": raise ValueError("U field does not have units m/s") if v.units != "m s**-1": raise ValueError("V field does not have units m/s") metre_to_mile = 3600.0 / 1609.3 speed = np.sqrt(u ** 2 + v ** 2) * metre_to_mile windmax_dict = {} for i, regname in enumerate(names): # Modify index in case any entries have been dropped e.g. Corsica idx = names.index[i] # Create object from 'borders' for masking gridded data regmask = regionmask.Regions(name=regname, outlines=list(borders[idx])) # Apply mask to dataset coordinates mask_zeros = regmask.mask(longitude, latitude) # Replace zeros with ones for matrix multiplication mask_ones = mask_zeros.where(np.isnan(mask_zeros.values), 1) # Use Dask dataframes for lazy execution mask_ones = dask.array.from_array(mask_ones) speed_mask = speed * mask_ones
# Compute maximum over lat-lon grid windmax_dict[regname] = speed_mask.max(dim=["longitude", "latitude"]) return windmax_dict
into_robj.rs
use super::*; use crate::single_threaded; use std::collections::HashMap; pub(crate) fn str_to_character(s: &str) -> SEXP { unsafe { if s.is_na() { R_NaString } else { Rf_mkCharLen(s.as_ptr() as *const raw::c_char, s.len() as i32) } } } /// Convert a null to an Robj. impl From<()> for Robj { fn from(_: ()) -> Self { // Note: we do not need to protect this. unsafe { Robj::Sys(R_NilValue) } } } /// Convert a Result to an Robj. This is used to allow /// functions to use the ? operator and return [Result<T>]. /// /// Panics if there is an error. /// ``` /// use extendr_api::prelude::*; /// fn my_func() -> Result<f64> { /// Ok(1.0) /// } /// /// test! { /// assert_eq!(r!(my_func()), r!(1.0)); /// } /// ``` impl<T> From<Result<T>> for Robj where T: Into<Robj>, { fn from(res: Result<T>) -> Self { // Force a panic on error. res.unwrap().into() } } /// Convert an Robj reference into a borrowed Robj. impl From<&Robj> for Robj { // Note: we should probably have a much better reference // mechanism as double-free or underprotection is a distinct possibility. fn from(val: &Robj) -> Self { unsafe { new_owned(val.get()) } } } pub trait IntoRobj { fn into_robj(self) -> Robj; } impl<T> IntoRobj for T where Robj: From<T>, { fn into_robj(self) -> Robj { self.into() } } /// `ToVectorValue` is a trait that allows many different types /// to be converted to vectors. It is used as a type parameter /// to `collect_robj()`. pub trait ToVectorValue { fn sexptype() -> SEXPTYPE { 0 } fn to_real(&self) -> f64 where Self: Sized, { 0. } fn to_integer(&self) -> i32 where Self: Sized, { std::i32::MIN } fn to_logical(&self) -> i32 where Self: Sized, { std::i32::MIN } fn to_raw(&self) -> u8 where Self: Sized, { 0 } fn to_sexp(&self) -> SEXP where Self: Sized, { unsafe { R_NilValue } } } macro_rules! impl_real_tvv { ($t: ty) => { impl ToVectorValue for $t { fn sexptype() -> SEXPTYPE { REALSXP } fn to_real(&self) -> f64 { *self as f64 } } impl ToVectorValue for &$t { fn sexptype() -> SEXPTYPE { REALSXP } fn to_real(&self) -> f64 { **self as f64 } } impl ToVectorValue for Option<$t> { fn sexptype() -> SEXPTYPE { REALSXP } fn to_real(&self) -> f64 { if self.is_some() { self.unwrap() as f64 } else { unsafe { R_NaReal } } } } }; } impl_real_tvv!(f64); impl_real_tvv!(f32); // Since these types might exceeds the max or min of R's 32bit integer, we need // to return as REALSXP impl_real_tvv!(i64); impl_real_tvv!(u32); impl_real_tvv!(u64); impl_real_tvv!(usize); macro_rules! impl_integer_tvv { ($t: ty) => { impl ToVectorValue for $t { fn sexptype() -> SEXPTYPE { INTSXP } fn to_integer(&self) -> i32 { *self as i32 } } impl ToVectorValue for &$t { fn sexptype() -> SEXPTYPE { INTSXP } fn to_integer(&self) -> i32 { **self as i32 } } impl ToVectorValue for Option<$t> { fn sexptype() -> SEXPTYPE { INTSXP } fn to_integer(&self) -> i32 { if self.is_some() { self.unwrap() as i32 } else { unsafe { R_NaInt } } } } }; } impl_integer_tvv!(i8); impl_integer_tvv!(i16); impl_integer_tvv!(i32); impl_integer_tvv!(u16); impl ToVectorValue for u8 { fn sexptype() -> SEXPTYPE { RAWSXP } fn to_raw(&self) -> u8 { *self as u8 } } impl ToVectorValue for &u8 { fn sexptype() -> SEXPTYPE { RAWSXP } fn to_raw(&self) -> u8 { **self as u8 } } macro_rules! impl_str_tvv { ($t: ty) => { impl ToVectorValue for $t { fn sexptype() -> SEXPTYPE { STRSXP } fn to_sexp(&self) -> SEXP where Self: Sized, { str_to_character(self.as_ref()) } } impl ToVectorValue for &$t { fn sexptype() -> SEXPTYPE { STRSXP } fn to_sexp(&self) -> SEXP where Self: Sized, { str_to_character(self.as_ref()) } } impl ToVectorValue for Option<$t> { fn sexptype() -> SEXPTYPE { STRSXP } fn to_sexp(&self) -> SEXP where Self: Sized, { if let Some(s) = self { str_to_character(s.as_ref()) } else { unsafe { R_NaString } } } } }; } impl_str_tvv! {&str} impl_str_tvv! {String} impl ToVectorValue for bool { fn sexptype() -> SEXPTYPE
fn to_logical(&self) -> i32 where Self: Sized, { *self as i32 } } impl ToVectorValue for &bool { fn sexptype() -> SEXPTYPE { LGLSXP } fn to_logical(&self) -> i32 where Self: Sized, { **self as i32 } } impl ToVectorValue for Bool { fn sexptype() -> SEXPTYPE { LGLSXP } fn to_logical(&self) -> i32 where Self: Sized, { self.0 } } impl ToVectorValue for &Bool { fn sexptype() -> SEXPTYPE { LGLSXP } fn to_logical(&self) -> i32 where Self: Sized, { self.0 } } impl ToVectorValue for Option<bool> { fn sexptype() -> SEXPTYPE { LGLSXP } fn to_logical(&self) -> i32 { if self.is_some() { self.unwrap() as i32 } else { unsafe { R_NaInt } } } } // Not thread safe. fn fixed_size_collect<I>(iter: I, len: usize) -> Robj where I: Iterator, I: Sized, I::Item: ToVectorValue, { single_threaded(|| unsafe { // Length of the vector is known in advance. let sexptype = I::Item::sexptype(); if sexptype != 0 { let sexp = Rf_allocVector(sexptype, len as R_xlen_t); ownership::protect(sexp); match sexptype { REALSXP => { let ptr = REAL(sexp); for (i, v) in iter.enumerate() { *ptr.add(i) = v.to_real(); } } INTSXP => { let ptr = INTEGER(sexp); for (i, v) in iter.enumerate() { *ptr.add(i) = v.to_integer(); } } LGLSXP => { let ptr = LOGICAL(sexp); for (i, v) in iter.enumerate() { *ptr.add(i) = v.to_logical(); } } STRSXP => { for (i, v) in iter.enumerate() { SET_STRING_ELT(sexp, i as isize, v.to_sexp()); } } RAWSXP => { let ptr = RAW(sexp); for (i, v) in iter.enumerate() { *ptr.add(i) = v.to_raw(); } } _ => { panic!("unexpected SEXPTYPE in collect_robj"); } } Robj::Owned(sexp) } else { Robj::from(()) } }) } /// Extensions to iterators for R objects including [RobjItertools::collect_robj()]. pub trait RobjItertools: Iterator { /// Convert a wide range of iterators to Robj. /// ``` /// use extendr_api::prelude::*; /// /// test! { /// // Integer iterators. /// let robj = (0..3).collect_robj(); /// assert_eq!(robj.as_integer_vector().unwrap(), vec![0, 1, 2]); /// /// // Logical iterators. /// let robj = (0..3).map(|x| x % 2 == 0).collect_robj(); /// assert_eq!(robj.as_logical_vector().unwrap(), vec![TRUE, FALSE, TRUE]); /// /// // Numeric iterators. /// let robj = (0..3).map(|x| x as f64).collect_robj(); /// assert_eq!(robj.as_real_vector().unwrap(), vec![0., 1., 2.]); /// /// // String iterators. /// let robj = (0..3).map(|x| format!("{}", x)).collect_robj(); /// assert_eq!(robj.as_str_vector(), Some(vec!["0", "1", "2"])); /// } /// ``` fn collect_robj(self) -> Robj where Self: Iterator, Self: Sized, Self::Item: ToVectorValue, { if let (len, Some(max)) = self.size_hint() { if len == max { return fixed_size_collect(self, len); } } // If the size is indeterminate, create a vector and call recursively. let vec: Vec<_> = self.collect(); assert!(vec.iter().size_hint() == (vec.len(), Some(vec.len()))); vec.into_iter().collect_robj() } } // Thanks to *pretzelhammer* on stackoverflow for this. impl<T> RobjItertools for T where T: Iterator {} // Scalars which are ToVectorValue impl<T> From<T> for Robj where T: ToVectorValue, { fn from(scalar: T) -> Self { Some(scalar).into_iter().collect_robj() } } // We would love to do a blanket IntoIterator impl. // But the matching rules would clash with the above. macro_rules! impl_from_iter { ($t: ty) => { impl<'a, T> From<$t> for Robj where Self: 'a, T: Clone + 'a, T: ToVectorValue, { fn from(val: $t) -> Self { val.iter().cloned().collect_robj() } } }; } macro_rules! impl_from_into_iter { ($t: ty) => { impl<'a, T> From<$t> for Robj where Self: 'a, T: 'a, &'a T: ToVectorValue, { fn from(val: $t) -> Self { val.into_iter().collect_robj() } } }; } macro_rules! impl_from_as_iterator { ($t: ty) => { impl<T> From<$t> for Robj where $t: RobjItertools, <$t as Iterator>::Item: ToVectorValue, T: ToVectorValue, { fn from(val: $t) -> Self { val.collect_robj() } } }; } // impl<T> From<Range<T>> for Robj // where // Range<T> : RobjItertools, // <Range<T> as Iterator>::Item: ToVectorValue, // T : ToVectorValue // { // fn from(val: Range<T>) -> Self { // val.collect_robj() // } // } // Template constants are still unstable in rust. impl_from_iter! {[T; 1]} impl_from_iter! {[T; 2]} impl_from_iter! {[T; 3]} impl_from_iter! {[T; 4]} impl_from_iter! {[T; 5]} impl_from_iter! {[T; 6]} impl_from_iter! {[T; 7]} impl_from_iter! {[T; 8]} impl_from_iter! {[T; 9]} impl_from_iter! {[T; 10]} impl_from_iter! {[T; 11]} impl_from_iter! {[T; 12]} impl_from_iter! {[T; 13]} impl_from_iter! {[T; 14]} impl_from_iter! {[T; 15]} impl_from_iter! {[T; 16]} impl_from_iter! {[T; 17]} impl_from_iter! {[T; 18]} impl_from_iter! {[T; 19]} impl_from_iter! {Vec<T>} impl_from_into_iter! {&'a [T]} impl_from_as_iterator! {Range<T>} impl_from_as_iterator! {RangeInclusive<T>} impl From<Real> for Robj { /// Convert a real iterator into a vector. fn from(val: Real) -> Self { val.collect_robj() } } impl From<Int> for Robj { /// Convert an integer iterator into a vector. fn from(val: Int) -> Self { val.collect_robj() } } impl From<Logical> for Robj { /// Convert a logical iterator into a vector. fn from(val: Logical) -> Self { val.collect_robj() } } impl<'a> From<HashMap<&'a str, Robj>> for Robj { /// Convert a hashmap into a list. fn from(val: HashMap<&'a str, Robj>) -> Self { let res: Robj = List::from_values(val.iter().map(|(_, v)| v)).into(); res.set_names(val.into_iter().map(|(k, _)| k)).unwrap() } } impl<'a> From<Vec<Robj>> for Robj { /// Convert a vector of Robj into a list. fn from(val: Vec<Robj>) -> Self { List::from_values(val.iter()).into() } }
{ LGLSXP }
solution.go
package solution func search(nums []int, target int) int { lo, hi := 0, len(nums)-1 for lo <= hi { mid := lo + (hi-lo)/2 if nums[mid] == target { return mid } if nums[lo] <= nums[mid] { if target < nums[mid] && target >= nums[lo] { hi = mid - 1 } else { lo = mid + 1 } } if nums[mid] <= nums[hi] { if target > nums[mid] && target <= nums[hi] { lo = mid + 1
} } } return -1 }
} else { hi = mid - 1
ControlsContainer.js
import { connect } from 'react-redux' import Controls from '../components/Controls' import { changeAmpLevel, changeAttack, changeCents, changeDecay, changeLFORate, changeLFOSend, changeLFOWaveform, changeNoiseAmount, changeOscGain, changeOscWaveform, changeRelease, changeSemitones, changeSustain, updateFilterCutoff, updateFilterQ, } from '../actions' import { OSC_A, OSC_B, LFO_A, LFO_B } from '../constants' const mapStateToProps = state => ({ ...state }) const mapDispatchToProps = dispatch => ({ changeAttack: level => dispatch(changeAttack(level)), changeDecay: level => dispatch(changeDecay(level)), changeSustain: level => dispatch(changeSustain(level)), changeRelease: level => dispatch(changeRelease(level)), changeAmpLevel: level => dispatch(changeAmpLevel(level)), changeLFOARate: rate => dispatch(changeLFORate({ id: LFO_A, rate, })), changeLFOBRate: rate => dispatch(changeLFORate({ id: LFO_B, rate, })), changeLFOAWaveform: waveform => dispatch(changeLFOWaveform({ id: LFO_A, waveform, })), changeLFOBWaveform: waveform => dispatch(changeLFOWaveform({ id: LFO_B, waveform, })), changeLFOASend: (value, destination) => dispatch(changeLFOSend({ id: LFO_A, sends: { [destination]: value, }, })), changeLFOBSend: (value, destination) => dispatch(changeLFOSend({ id: LFO_B, sends: { [destination]: value, }, })), changeNoiseAmount: amount => dispatch(changeNoiseAmount(amount)), changeOscACents: cents => dispatch(changeCents({ id: OSC_A, cents, })), changeOscASemitones: semitones => dispatch(changeSemitones({ id: OSC_A, semitones, })), changeOscAGain: gain => dispatch(changeOscGain({ id: OSC_A, gain, })), changeOscBCents: cents => dispatch(changeCents({ id: OSC_B, cents,
changeOscBSemitones: semitones => dispatch(changeSemitones({ id: OSC_B, semitones, })), changeOscBGain: gain => dispatch(changeOscGain({ id: OSC_B, gain, })), changeOscAWaveform: waveform => dispatch(changeOscWaveform({ id: OSC_A, waveform, })), changeOscBWaveform: waveform => dispatch(changeOscWaveform({ id: OSC_B, waveform, })), changeCutoff: level => updateFilterCutoff(level), changeQ: level => updateFilterQ(level), }) export default connect( mapStateToProps, mapDispatchToProps, )(Controls)
})),
phot.py
""" Functions for Imaging Pipeline """ import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Ellipse from astropy.io import fits from astropy.modeling import models, fitting from astropy.table import Table from scipy.optimize import curve_fit import os from astropy.coordinates import SkyCoord import astropy.units as u from astroquery.sdss import SDSS import astroalign as aa import sep from pynot import alfosc from pynot.functions import get_version_number, mad from pynot.data.organizer import get_filter __version__ = get_version_number() def source_detection(fname, zeropoint=0., threshold=5.0, aperture=10.0, kwargs_bg={}, kwargs_ext={}): """ Run source detection in the input image using the python package SEP, based on the SExtractor algorithm. Parameters ---------- fname : str Filename of the FITS image to be analyzed. The image must have at least two extensions: the first should be the image in counts, and one should be named ERR holding the associated error image zeropoint : float [default=0.] Magnitude zero-point for the given photometric filter used for the observations. By defualt instrument magnitudes will be returned if no zero-point is given. threshold : float [default=5.0] Detection threshold in 'sigmas'. aperture : float [default=10.] Circular aperture radius in pixels. kwargs_bg : dict Parameters to pass to background subtraction (sep.Background()). See defition in `default_options_img.yml` kwargs_ext : dict Parameters to pass to source extraction (sep.extract()). See defition in `default_options_img.yml` Returns ------- table_fname : str The autogenerated filename of the source catalog. The format is: file-base of the input filename + '_phot.fits'. Ex.: fname='alfosc_rband.fits' -> table_fname='alfosc_rband_phot.fits' segmap_fname : str The autogenerated filename of the segmentation map. This image holds the regions associated to each source in the source catalog. The format is: file-base of the input filename + '_sep.fits' output_msg : str Log of messages from the function call. """ msg = list() # get GAIN from header data = fits.getdata(fname) error_image = fits.getdata(fname, 'ERR') hdr = fits.getheader(fname) msg.append(" - Loaded input image: %s" % fname) if 'EXPTIME' in hdr: exptime = hdr['EXPTIME'] msg.append(" - Loaded exposure time from image header: %.1f" % exptime) else: exptime = 1. msg.append("[WARNING] - No exposure time found in image header! Assuming image in counts.") data = data * 1. error_image = error_image * 1. if 'threshold' in kwargs_ext: threshold = kwargs_ext.pop('threshold') if 'aperture' in kwargs_ext: aperture = kwargs_ext.pop('aperture') bkg = sep.Background(data, **kwargs_bg) data_sub = data - bkg msg.append(" - Subtracted sky background") msg.append(" - Background RMS: %.2e" % bkg.globalrms) data_sub = data_sub.byteswap().newbyteorder() error_image = error_image.byteswap().newbyteorder() if data_sub.dtype.byteorder != '<': data_sub = data_sub.byteswap().newbyteorder() error_image = error_image.byteswap().newbyteorder() extract_output = sep.extract(data_sub, threshold, err=bkg.globalrms, **kwargs_ext) if len(extract_output) == 2: objects, segmap = extract_output else: objects = extract_output segmap = None N_obj = len(objects) msg.append(" - Detected %i objects" % N_obj) # Calculate fixed aperture magnitudes: aper_results = sep.sum_circle(data_sub, objects['x'], objects['y'], aperture, err=error_image) aper_flux, aper_fluxerr, aper_flag = aper_results msg.append(" - Calculating fluxes within circular aperture of: %i pixels" % aperture) # Calculate Kron radius: x = objects['x'] y = objects['y'] a = objects['a'] b = objects['b'] theta = objects['theta'] kronrad, krflag = sep.kron_radius(data_sub, x, y, a, b, theta, 6.0) kronrad[kronrad < 1.] = 1. # Sum fluxes in ellipse apertures: flux, fluxerr, flag = sep.sum_ellipse(data_sub, x, y, a, b, theta, 2.5*kronrad, subpix=1) msg.append(" - Calculating Kron radii and fluxes within elliptical apertures") # combine flags: flag |= krflag # If the Kron radius is less than r_min (aperture), use aperture fluxes: r_min = aperture use_circle = kronrad * np.sqrt(b * a) < r_min flux[use_circle] = aper_flux[use_circle] fluxerr[use_circle] = aper_fluxerr[use_circle] flag[use_circle] = aper_flag[use_circle] msg.append(" - Targets with Kron radii below R_min (%.2f) are ignored" % r_min) msg.append(" - Circular aperture fluxes used instead where R_kron < R_min") if np.sum(use_circle) == 1: msg.append(" - %i source identified with R_kron < R_min" % np.sum(use_circle)) else: msg.append(" - %i sources identified with R_kron < R_min" % np.sum(use_circle)) # Save output table: base, ext = os.path.splitext(fname) table_fname = base + '_phot.fits' object_table = Table(objects) object_table['flux_auto'] = flux object_table['flux_err_auto'] = fluxerr object_table['flux_aper'] = aper_flux object_table['flux_err_aper'] = aper_fluxerr object_table['R_kron'] = kronrad flux[flux <= 0] = 1. object_table['mag_auto'] = zeropoint - 2.5*np.log10(flux) object_table.write(table_fname, format='fits', overwrite=True) msg.append(" [OUTPUT] - Saved extraction table: %s" % table_fname) # Save segmentation map: if segmap is not None: segmap_fname = base + '_seg.fits' seg_hdr = fits.Header() seg_hdr['AUTHOR'] = 'PyNOT version %s' % __version__ seg_hdr['IMAGE'] = fname seg_hdr['FILTER'] = get_filter(hdr) seg_hdr.add_comment("Segmentation map from SEP (SExtractor)") fits.writeto(segmap_fname, segmap, header=seg_hdr, overwrite=True) msg.append(" [OUTPUT] - Saved source segmentation map: %s" % segmap_fname) else: segmap_fname = '' # Plot source identifications: fig_fname = base + '_sources.pdf' plot_objects(fig_fname, data_sub, objects, threshold=threshold) msg.append(" [OUTPUT] - Saved source identification overview: %s" % fig_fname) msg.append("") output_msg = "\n".join(msg) return table_fname, segmap_fname, output_msg def plot_objects(fig_fname, data, objects, threshold=5.):
""" Create a plot of the image and the detected sources from SEP. Parameters ---------- fig_fname : str Filename of the resulting figure data : np.array, shape (N, M) Numpy array of the image data, must be a 2D array. objects : astropy.table.Table or List[dict] List of dictionaries or astropy table holding the object information: x, y : x, y positions a, b : aperture minor and major axes in pixels theta : aperture orientation in radians threshold : float [default=5.] Constract threshold for the image. The color-scale is normalized based on the image statistics (median and MAD). The min and max values are -1*MAD and +`threshold`*MAD around the median value of the image counts, where MAD is the median absolute deviation. Returns ------- None """ # plot background-subtracted image fig, ax = plt.subplots() m, s = np.median(data), 1.5*mad(data) ax.imshow(data, interpolation='nearest', cmap='gray_r', vmin=m-1*s, vmax=m+threshold*s, origin='lower') # plot an ellipse for each object for item in objects: e = Ellipse(xy=(item['x'], item['y']), width=10*item['a'], height=10*item['b'], angle=item['theta'] * 180. / np.pi) e.set_facecolor('none') e.set_edgecolor('red') e.set_linewidth(0.8) ax.add_artist(e) fig.tight_layout() fig.savefig(fig_fname) def load_fits_image(fname): """Load a FITS image with an associated error extension and an optional data quality MASK.""" with fits.open(fname) as hdu_list: image = hdu_list[0].data hdr = hdu_list[0].header if 'ERR' in hdu_list: error = hdu_list['ERR'].data else: raise TypeError("No error image detected") if 'MASK' in hdu_list: mask = hdu_list['MASK'].data else: mask = np.zeros_like(image, dtype=bool) return image, error, mask, hdr def measure_seeing(img, centers, size=20, max_obj=10): """ Measure the average seeing in an image by fitting a 2D Gaussian to pre-defined point sources. Parameters ---------- img : np.array, shape(N, M) Numpy array of the image to analyze. centers : list[number, number] List of positions of point sources (x, y) in pixels size : int [default=20] Image cutout size. The Gaussian PSF is fitted in a box of size 2*size by 2*size pixels. max_obj : int [default=10] Maximum number of sources to include in the fitting. Returns ------- fwhm : float The average seeing FWHM in pixels. ratio : float The average axis ratio (ellipticity) of the Gaussian PSF. msg : str Output message of the function call. If no warnings occurred, this is an emptry string. """ X = np.arange(img.shape[1]) Y = np.arange(img.shape[0]) sigmas = list() ratios = list() good_x = (centers[:, 0] > size) & (centers[:, 0] < X.max()-size) good_y = (centers[:, 1] > size) & (centers[:, 1] < Y.max()-size) if np.sum(good_x & good_y) < 2: msg = "[WARNING] - Not enough sources to measure seeing." return (-1, -1, msg) max_obj = min(max_obj, np.sum(good_x & good_y)) idx = np.random.choice(np.arange(len(centers))[good_x & good_y], max_obj, replace=False) for x_cen, y_cen in centers[idx]: x1, x2 = int(x_cen)-size, int(x_cen)+size y1, y2 = int(y_cen)-size, int(y_cen)+size cutout = img[y1:y2, x1:x2] x, y = np.meshgrid(X[x1:x2], Y[y1:y2]) A = img[int(y_cen), int(x_cen)] p_init = models.Gaussian2D(amplitude=A, x_mean=x_cen, y_mean=y_cen, x_stddev=5, y_stddev=5, theta=0) try: fitter = fitting.LevMarLSQFitter() except TypeError: continue p_opt = fitter(p_init, x, y, cutout-np.median(cutout)) sigma_x = p_opt.x_stddev sigma_y = p_opt.y_stddev sig = np.sqrt(sigma_x**2 + sigma_y**2) ba = min(sigma_x, sigma_y) / max(sigma_x, sigma_y) sigmas.append(sig) ratios.append(ba) if len(sigmas) < 2: msg = "[WARNING] - Not enough sources to measure seeing." return (-1, -1, msg) fwhm = np.median(sigmas) * 2.35 ratio = np.median(ratios) msg = "" return (fwhm, ratio, msg) def save_file_log(log_name, image_log, target_hdr): with open(log_name, 'w') as out: out.write("# PyNOT Combination Log of Target: %s\n" % target_hdr['OBJECT']) out.write("# Filter: %s\n" % get_filter(target_hdr)) out.write("# Col 1: Filename\n") out.write("# Col 2: FWHM / pixels (seeing)\n") out.write("# Col 3: PSF axis ratio (minor/major)\n") out.write("# Col 4: Exp. Time / seconds\n") out.write("# " + 40*"-" + "\n") for line in image_log: out.write(" %s %.1f %5.2f %6.1f\n" % tuple(line)) def image_combine(corrected_images, output='', log_name='', fringe_image='', method='weighted', max_control_points=50, detection_sigma=5, min_area=9): """ Register and combine a list of FITS images using affine transformation. Parameters ---------- corrected_images : List[str] List of input filenames of `corrected` images, i.e., bias, flat corrected and trimmed for filter/aperture vignetting. output : str [default=''] Output filename of the combined image. If not given, it is generated from the OBJECT keyword of the FITS header. log_name : str [default=''] Filename of the combination log. This table holds the average seeing FWHM, PSF ellipticity, and exposure time for each image in the input list. fringe_image : str [default=''] Filename of the fringe image (FITS format) from `pynot.create_fringe_image`. If given, this image will be subtracted from each input image before combination. method : str [default='weighted'] Method for image combination: mean, median or weighted. By default an inverse-variance weighting is used. max_control_points : int [default=50] Maximum number of control point-sources to find the transformation. A lower number will converge faster but may result in a less robust image registration. detection_sigma : float [default=5.] Detection threshold for control points in units of standard deviations of the sky background. min_area : int [default=9] Minimum number of connected pixels to be considered a source Returns ------- output_msg : str Log of messages from the function call. """ msg = list() if fringe_image != '': norm_sky = fits.getdata(fringe_image) msg.append(" - Loaded normalized fringe image: %s" % fringe_image) else: norm_sky = 1. target_fname = corrected_images[0] target, target_err, target_mask, target_hdr = load_fits_image(target_fname) target = target - norm_sky*np.median(target) exptime = target_hdr['EXPTIME'] target /= exptime target_err /= exptime target_hdr['BUNIT'] = 'count / s' msg.append(" - Aligning all images to reference: %s" % target_fname) msg.append(" - Registering input images:") shifted_images = [target] shifted_vars = [target_err**2] target = target.byteswap().newbyteorder() if target.dtype.byteorder != '<': target = target.byteswap().newbyteorder() final_exptime = exptime image_log = list() if len(corrected_images) > 1: for fname in corrected_images[1:]: msg.append(" - Input image: %s" % fname) source, source_err, source_mask, hdr_i = load_fits_image(fname) source = source - norm_sky*np.median(source) source /= hdr_i['EXPTIME'] source_err /= hdr_i['EXPTIME'] final_exptime += hdr_i['EXPTIME'] try: transf, (coords) = aa.find_transform(source, target, max_control_points=max_control_points, detection_sigma=detection_sigma, min_area=min_area) except: msg.append(" [ERROR] - Failed to find image transformation!") msg.append(" - Skipping image") continue source = source.byteswap().newbyteorder() source_err = source_err.byteswap().newbyteorder() source_mask = source_mask.byteswap().newbyteorder() if source.dtype.byteorder != '<': source = source.byteswap().newbyteorder() if source_err.dtype.byteorder != '<': source_err = source_err.byteswap().newbyteorder() if source_mask.dtype.byteorder != '<': source_mask = source_mask.byteswap().newbyteorder() registered_image, _ = aa.apply_transform(transf, source, target, fill_value=0) registered_error, _ = aa.apply_transform(transf, source_err, target, fill_value=0) registered_mask, _ = aa.apply_transform(transf, source_mask, target, fill_value=0) target_mask += 1 * (registered_mask > 0) registered_error[registered_error == 0] = np.mean(registered_error)*10 shifted_images.append(registered_image) shifted_vars.append(registered_error**2) source_list, target_list = coords if len(image_log) == 0: fwhm, ratio, seeing_msg = measure_seeing(target, target_list) image_log.append([os.path.basename(target_fname), fwhm, ratio, exptime]) if seeing_msg: msg.append(seeing_msg) fwhm, ratio, seeing_msg = measure_seeing(source, source_list) if seeing_msg: msg.append(seeing_msg) image_log.append([os.path.basename(fname), fwhm, ratio, hdr_i['EXPTIME']]) if log_name == '': filter_name = alfosc.filter_translate[get_filter(target_hdr)] log_name = 'filelist_%s_%s.txt' % (target_hdr['OBJECT'], filter_name) save_file_log(log_name, image_log, target_hdr) msg.append(" [OUTPUT] - Saved file log and image stats: %s" % log_name) if method == 'median': final_image = np.nanmedian(shifted_images, axis=0) final_error = np.sqrt(np.nanmean(shifted_vars, axis=0)) target_hdr['COMBINE'] = "Median" elif method == 'mean': final_image = np.nanmean(shifted_images, axis=0) final_error = np.sqrt(np.nanmean(shifted_vars, axis=0)) target_hdr['COMBINE'] = "Mean" else: w = 1./np.array(shifted_vars) shifted_images = np.array(shifted_images) final_image = np.nansum(w*shifted_images, axis=0) / np.sum(w, axis=0) final_error = np.sqrt(1. / np.nansum(w, axis=0)) target_hdr['COMBINE'] = "Inverse Variance Weighted" final_mask = 1 * (target_mask > 0) else: final_image = target final_error = target_err final_mask = target_mask target_hdr['COMBINE'] = "None" target_hdr['NCOMBINE'] = len(shifted_images) target_hdr['EXPTIME'] = final_exptime / len(shifted_images) # Fix NaN values from negative pixel values: err_NaN = np.isnan(final_error) final_error[err_NaN] = np.nanmean(final_error)*100 msg.append(" - Correcting NaNs in noise image: %i pixel(s)" % np.sum(err_NaN)) target_hdr['DATAMIN'] = np.nanmin(final_image) target_hdr['DATAMAX'] = np.nanmax(final_image) target_hdr['EXTNAME'] = 'DATA' target_hdr['AUTHOR'] = 'PyNOT version %s' % __version__ mask_hdr = fits.Header() mask_hdr.add_comment("0 = Good Pixels") mask_hdr.add_comment("1 = Cosmic Ray Hits") if output == '': output = "combined_%s.fits" % target_hdr['OBJECT'] sci_ext = fits.PrimaryHDU(final_image, header=target_hdr) err_ext = fits.ImageHDU(final_error, header=target_hdr, name='ERR') mask_ext = fits.ImageHDU(final_mask, header=mask_hdr, name='MASK') output_HDU = fits.HDUList([sci_ext, err_ext, mask_ext]) output_HDU.writeto(output, overwrite=True) msg.append(" - Successfully combined the images") msg.append(" [OUTPUT] - Saving output: %s" % output) msg.append("") output_msg = "\n".join(msg) return output_msg def plot_image2D(fname, image, vmin=-2, vmax=2): fig = plt.figure() ax = fig.add_subplot(111) med = np.median(image) s = mad(image) im = ax.imshow(image, origin='lower', vmin=med+vmin*s, vmax=med+vmax*s) fig.colorbar(im) fig.tight_layout() fig.savefig(fname) def create_fringe_image(input_filenames, output='', fig_fname='', threshold=3.0): """ Create a normalized average fringe image for a list of images taken with the same filter. Parameters ---------- input_filenames : str List of FITS filenames of images taken in the same photometric band. output : str [default=''] Output filename of the fringe image. fig_fname : str [default=''] Output filename of the diagnostic figure showing the normalized fringe image. threshold : float [default=3.] Threshold for source rejection in the image stacking in units of the standard deviation of the sky background (estimated via median absolute deviation). Returns ------- output_msg : str Log of messages from the function call. """ msg = list() hdr = fits.getheader(input_filenames[0]) img_list = [fits.getdata(fname) for fname in input_filenames] exptimes = [fits.getheader(fname)['EXPTIME'] for fname in input_filenames] msg.append(" - Loaded input images") mask = [np.fabs(im-np.median(im)) < threshold*mad(im) for im in img_list] msg.append(" - Created image mask using threshold: %.2f" % threshold) N = np.sum(mask, 0) skysum = np.sum([im*m/t for im, m, t in zip(img_list, mask, exptimes)], axis=0) skysum[N == 0] = np.median(skysum) N[N == 0] = 1 sky = skysum / N norm_sky = sky / np.median(sky) msg.append(" - Created normalized fringe image") if fig_fname: plot_image2D(fig_fname, norm_sky, vmin=-2, vmax=2) msg.append(" [OUTPUT] - Saving figure: %s" % fig_fname) if output == '': output = "fringe_%s.fits" % hdr['OBJECT'] hdr['OBJECT'] = 'Fringe Image' hdr['EXTNAME'] = 'MODEL' hdr.add_comment('Average Fringe image, median normalized') fits.writeto(output, norm_sky, header=hdr, overwrite=True) msg.append(" [OUTPUT] - Saving output: %s" % output) msg.append("") output_msg = "\n".join(msg) return output_msg def match_phot_catalogs(sep, phot, match_radius=1.): """ Match a source catalog from SEP to a photometric catalog `phot`. Both catalogs must include columns 'ra' and 'dec'. Parameters ---------- match_radius : float [default=1.0] Matching radius in arcseconds Returns ------- matched_sep : astropy.table.Table An astropy table of sources in the SEP source catalog that have matches in the reference `phot` catalog. matched_phot : astropy.table.Table An astropy table of sources in the reference `phot` catalog that have matches in the SEP source catalog. """ matched_sep = list() matched_phot = list() refs = np.array([phot['ra'], phot['dec']]).T for row in sep: xy = np.array([row['ra'], row['dec']]) dist = np.sqrt(np.sum((refs - xy)**2, axis=1)) index = np.argmin(dist) if np.min(dist) < match_radius/3600.: matched_phot.append(np.array(phot[index])) matched_sep.append(np.array(row)) matched_sep = np.array(matched_sep) matched_phot = np.array(matched_phot) return Table(matched_sep), Table(matched_phot) def get_sdss_catalog(ra, dec, radius=4.): """Download the SDSS photometry using astroquery for a circular region of radius in deg.""" catalog_fname = 'sdss_phot_%.2f%+.2f.csv' % (ra, dec) fields = ['ra', 'dec', 'psfMag_u', 'psfMag_g', 'psfMag_r', 'psfMag_i', 'psfMag_z', 'psfMagErr_u', 'psfMagErr_g', 'psfMagErr_r', 'psfMagErr_i', 'psfMagErr_z'] field_center = SkyCoord(ra, dec, frame='icrs', unit='deg') sdss_result = SDSS.query_region(field_center, radius*u.arcmin, photoobj_fields=fields) if sdss_result is not None: sdss_result.write(catalog_fname, format='ascii.csv', overwrite=True) return sdss_result ext_coeffs = {'u': 0.517, 'g': 0.165, 'r': 0.0754, 'i': 0.0257, 'z': 0.0114} def flux_calibration_sdss(img_fname, sep_fname, fig_fname='', q_lim=0.8, kappa=3, match_radius=1.): """ Self-calibration of magnitude zero point using SDSS photometry as reference Parameters ---------- img_fname : string Filename of WCS calibrated image (_wcs.fits) sep_fname : string Filename of the source extraction table (_phot.fits) fig_fname : string Filename of the diagnostic figure. Autogenerated by default. q_lim : float [default=0.8] Reject elliptical sources with axis ratio < `q_lim`. Axis ratio is defined as minor/major. kappa : float [default=3] Threshold for projected distance filtering. Sources are rejected if the distance differs more then `kappa` times the median absolute deviation from the median of all distances. match_radius : float [default=1] Matching radius between SDSS sources and image sources Returns ------- output_msg : string Log of messages from the function call. """ # -- Get SDSS catalog msg = list() hdr = fits.getheader(img_fname) msg.append(" - Loaded image: %s" % img_fname) radius = np.sqrt(hdr['CD1_1']**2 + hdr['CD1_2']**2)*60 * hdr['NAXIS1'] / np.sqrt(2) msg.append(" - Downloading SDSS photometric catalog...") try: sdss_cat = get_sdss_catalog(hdr['CRVAL1'], hdr['CRVAL2'], radius) except: msg.append(" [ERROR] - Could not connect to SDSS server. Check your internet connection.") msg.append("") return "\n".join(msg) def line(x, zp): return zp + x if sdss_cat is None: msg.append(" [ERROR] - No data found in SDSS. No zero point calculated") msg.append("") return "\n".join(msg) airmass = hdr['AIRMASS'] filter = alfosc.filter_translate[alfosc.get_filter(hdr)] if 'SDSS' in filter: band = filter.split('_')[0] else: msg.append(" [ERROR] - The image was not taken with an SDSS filter. No zero point calculated") msg.append("") return "\n".join(msg) # For r-band: (measured from La Palma extinction curve) mag_key = 'psfMag_%s' % band mag_err_key = 'psfMagErr_%s' % band good = (sdss_cat[mag_key] > 0) & (sdss_cat[mag_key] < 30) sdss_cat = sdss_cat[good] # Load SEP filename: try: sep_cat = Table.read(sep_fname) sep_hdr = fits.getheader(sep_fname) msg.append(" - Loaded SEP source table: %s" % sep_fname) except (FileNotFoundError, OSError): msg.append(" [ERROR] - Could not load SEP source table: %s" % sep_fname) msg.append("") return "\n".join(msg) if 'MAG_ZP' in sep_hdr: msg.append("[WARNING] - The source table has already been flux calibrated by PyNOT") msg.append(" - Terminating task...") msg.append("") return "\n".join(msg) axis_ratio = sep_cat['b']/sep_cat['a'] # Select only 'round' sources: sep_points = sep_cat[axis_ratio > q_lim] # Match catalogs: match_sep, match_sdss = match_phot_catalogs(sep_points, sdss_cat) msg.append(" - Cross matched source catalog") mag = match_sdss[mag_key] mag_err = match_sdss[mag_err_key] m_inst = match_sep['mag_auto'] k = ext_coeffs[band] # Get first estimate using the median: zp0, _ = curve_fit(line, m_inst+k*airmass, mag, p0=[27], sigma=mag_err) # Filter outliers: cut = np.abs(zp0 + m_inst + k*airmass - mag) < kappa*mad(zp0 + m_inst + k*airmass - mag) cut &= (mag < 20.1) & (mag > 15) # Get weighted average zero point: w = 1./mag_err[cut]**2 zp = np.sum((mag[cut] - m_inst[cut] - k*airmass) * w) / np.sum(w) msg.append(" - Calculating zero point in SDSS %s band using %i sources" % (band, len(w))) # Zero point dispersion: zp_err = np.std(mag[cut] - zp - m_inst[cut] - k*airmass) msg.append(" - Zero Point = %.3f ± %.3f mag" % (zp, zp_err)) sep_cat['mag_auto'] += zp sep_cat.write(sep_fname, overwrite=True) with fits.open(sep_fname, 'update') as sep_file: sep_file[0].header.add_comment("Self-calibration of mag. zero point using SDSS") sep_file[0].header['MAG_ZP'] = (np.round(zp, 3), "Magnitude zero point (AB mag)") sep_file[0].header['ZP_ERR'] = (np.round(zp_err, 3), "Uncertainty on magnitude zero point (AB mag)") msg.append(" [OUTPUT] - Updating magnitudes in source table: %s" % sep_fname) # -- Plot the zero point for visual aid: base, _ = os.path.splitext(os.path.basename(img_fname)) dirname = os.path.dirname(img_fname) if fig_fname == '': fig_fname = 'zero_point_' + base + '.pdf' fig_fname = os.path.join(dirname, fig_fname) fig = plt.figure() ax = fig.add_subplot(111) ax.errorbar(m_inst, mag, 3*mag_err, ls='', marker='.', color='k', alpha=0.8) ax.plot(m_inst[cut], mag[cut], ls='', marker='o', color='b', alpha=0.7) ax.plot(np.sort(m_inst), zp + np.sort(m_inst) + k*airmass, ls='--', color='crimson', label='ZP = %.2f ± %.2f' % (zp, zp_err)) ax.set_ylim(np.min(mag)-0.2, np.max(mag)+0.5) ax.set_xlabel("Instrument Magnitude") ax.set_ylabel("Reference SDSS Magnitude (r-band)") ax.legend() ax.tick_params(which='both', top=False, right=False) fig.tight_layout() fig.savefig(fig_fname) msg.append(" [OUTPUT] - Saving diagnostic figure: %s" % fig_fname) # -- Update header in FITS image: with fits.open(img_fname) as hdu_list: hdu_list['DATA'].header.add_comment("Self-calibration of mag. zero point using SDSS") hdu_list['DATA'].header['MAG_ZP'] = (np.round(zp, 3), "Magnitude zero point (AB mag)") hdu_list['DATA'].header['ZP_ERR'] = (np.round(zp_err, 3), "Uncertainty on magnitude zero point (AB mag)") hdu_list.writeto(img_fname, overwrite=True) msg.append(" [OUTPUT] - Updating header of input image: %s" % img_fname) msg.append(" - MAG_ZP = %10.3f / %s" % (zp, "Magnitude zero point (AB mag)")) msg.append(" - ZP_ERR = %10.3f / %s" % (zp_err, "Uncertainty on magnitude zero point (AB mag)")) msg.append("") return "\n".join(msg)
certificatetower.go
package main import ( "bufio" "crypto/tls" "crypto/x509" "fmt" "io" "log" "os" "path" "strings" "time" ) func
() { hostspath, isSet := os.LookupEnv("CERTTOWERHOSTS") if !isSet { homedir, _ := os.LookupEnv("HOME") hostspath = path.Join(homedir, ".certificate-tower-hosts") } f, err := os.Open(hostspath) if err != nil { log.Fatalf("Could not open hosts file: %v", err) } defer f.Close() var expiredHosts int r := bufio.NewReader(f) for { host, err := r.ReadString('\n') if err == io.EOF { break } if err != nil { log.Fatal(err) } host = strings.TrimSpace(host) if len(host) == 0 { continue } expiryDate, err := expirationDate(host) if x509Err, ok := err.(x509.CertificateInvalidError); ok && x509Err.Reason == x509.Expired { fmt.Printf("%s has already expired | color=red \n", host) expiredHosts++ continue } if err != nil { log.Fatalf("encountered error during checking of '%s': %v", host, err) } if time.Now().Add(14 * 24 * time.Hour).After(expiryDate) { fmt.Printf("%s expires on %s | color=orange \n", host, expiryDate.Format("2006-01-02")) expiredHosts++ } } if expiredHosts == 0 { fmt.Println("ok") } } func expirationDate(domain string) (time.Time, error) { conn, err := tls.Dial("tcp", domain+":443", &tls.Config{}) if err != nil { return time.Now(), err } return conn.ConnectionState().VerifiedChains[0][0].NotAfter, nil }
main
form.js
import React from 'react'; import { useFormik } from 'formik'; import Button from '../../../components/button'; import FormGroup from '../../../components/form/formGroup'; import Input from '../../../components/form/input'; import ErrorText from "../../../components/form/error"; const validate = values => { const errors = {}; if (!values.email) { errors.email = 'Email address is required'; } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'Invalid email address'; } if (!values.name) { errors.name = 'Name is required'; } else if (values.name.length < 4) { errors.name = 'Name must be 4 characters'; } if (values.password && values.password.length < 4) { errors.password = 'password must be 4 characters or more'; } if (!values.addressLine1) { errors.addressLine1 = 'Address is required.'; } if (!values.postalCode) { errors.postalCode = 'Postal code is required.'; } if (!values.state) { errors.state = 'State is required.'; } if (!values.country) { errors.country = 'Country is required.'; } return errors; }; const UserForm = props => { const { onSubmit, error, user } = props; const formik = useFormik({ initialValues: { email: user.email, password: '', name: user.name, addressLine1: user.addressLine1, postalCode: user.postalCode, state: user.state, country: user.country, }, validate, onSubmit: async (values) => { onSubmit(values); } }); return ( <form onSubmit={formik.handleSubmit}> {props.error && <ErrorText>{error}</ErrorText> } <FormGroup> <Input name='email' id='email' autoComplete='email' placeholder={'Email Address'} onChange={formik.handleChange('email')} onBlur={formik.handleBlur('email')} error={!!formik.errors.email} value={formik.values.email} /> {formik.errors.email && <ErrorText>{formik.errors.email}</ErrorText> } </FormGroup> <FormGroup> <Input name='name' id='name' autoComplete='name' placeholder={'Name'} onChange={formik.handleChange('name')} onBlur={formik.handleBlur('name')} error={!!formik.errors.name} value={formik.values.name} /> {formik.errors.name && <ErrorText>{formik.errors.name}</ErrorText> } </FormGroup> <FormGroup> <Input id='addressLine1' name='addressLine1' autoComplete='address-line1' type='text' placeholder='Enter your address' onChange={formik.handleChange('addressLine1')} onBlur={formik.handleBlur('addressLine1')} error={formik.errors.addressLine1} value={formik.values.addressLine1} /> {formik.errors.addressLine1 && <ErrorText>{formik.errors.addressLine1}</ErrorText> } </FormGroup> <FormGroup> <Input id='postalCode' name='postalCode' autoComplete='postal-code' type='text' placeholder='postal code' onChange={formik.handleChange('postalCode')} onBlur={formik.handleBlur('postalCode')} error={formik.errors.postalCode} value={formik.values.postalCode} /> {formik.errors.postalCode && <ErrorText>{formik.errors.postalCode}</ErrorText> } </FormGroup> <FormGroup> <Input id='state' name='state' autoComplete='state' type='text' placeholder='your state'
onChange={formik.handleChange('state')} onBlur={formik.handleBlur('state')} error={formik.errors.state} value={formik.values.state} /> {formik.errors.state && <ErrorText>{formik.errors.state}</ErrorText> } </FormGroup> <FormGroup> <Input id='country' name='country' autoComplete='country' type='text' placeholder='your country' onChange={formik.handleChange('country')} onBlur={formik.handleBlur('country')} error={formik.errors.country} value={formik.values.country} /> {formik.errors.country && <ErrorText>{formik.errors.country}</ErrorText> } </FormGroup> <FormGroup> <Input id='password' name='password' autoComplete='current-password' type={'password'} placeholder={'Password'} onChange={formik.handleChange('password')} onBlur={formik.handleBlur('password')} error={formik.errors.password} value={formik.values.password} /> {formik.errors.password && <ErrorText>{formik.errors.password}</ErrorText> } </FormGroup> <Button primary large type="submit">update</Button> </form> ) }; export default UserForm;
logger.py
logger = logging.getLogger() logger.setLevel(logging.INFO) handler = logging.StreamHandler() fmt = logging.Formatter(fmt="%(levelname)s: %(message)s") handler.setFormatter(fmt) handler.setLevel(logging.INFO) logger.addHandler(handler)
import logging __all__ = ['logger']
document.ts
/** * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { SnapshotVersion } from '../core/snapshot_version'; import { fail } from '../util/assert'; import { DocumentKey } from './document_key'; import { FieldValue, JsonObject, ObjectValue } from './field_value'; import { FieldPath } from './path'; import * as api from '../protos/firestore_proto_api'; export interface DocumentOptions { hasLocalMutations?: boolean; hasCommittedMutations?: boolean; } /** * The result of a lookup for a given path may be an existing document or a * marker that this document does not exist at a given version. */ export abstract class MaybeDocument { constructor(readonly key: DocumentKey, readonly version: SnapshotVersion) {} static compareByKey(d1: MaybeDocument, d2: MaybeDocument): number { return DocumentKey.comparator(d1.key, d2.key); } /** * Whether this document had a local mutation applied that has not yet been * acknowledged by Watch. */ abstract get hasPendingWrites(): boolean; abstract isEqual(other: MaybeDocument | null | undefined): boolean; abstract toString(): string; } /** * Represents a document in Firestore with a key, version, data and whether the * data has local mutations applied to it. */ export class Document extends MaybeDocument { readonly hasLocalMutations: boolean; readonly hasCommittedMutations: boolean; constructor( key: DocumentKey, version: SnapshotVersion, readonly data: ObjectValue, options: DocumentOptions, /** * Memoized serialized form of the document for optimization purposes (avoids repeated * serialization). Might be undefined. */ readonly proto?: api.Document ) { super(key, version); this.hasLocalMutations = !!options.hasLocalMutations; this.hasCommittedMutations = !!options.hasCommittedMutations; } field(path: FieldPath): FieldValue | undefined { return this.data.field(path); } fieldValue(path: FieldPath): unknown { const field = this.field(path); return field ? field.value() : undefined; } value(): JsonObject<unknown> { return this.data.value(); } isEqual(other: MaybeDocument | null | undefined): boolean { return ( other instanceof Document && this.key.isEqual(other.key) && this.version.isEqual(other.version) && this.data.isEqual(other.data) && this.hasLocalMutations === other.hasLocalMutations && this.hasCommittedMutations === other.hasCommittedMutations ); } toString(): string { return ( `Document(${this.key}, ${this.version}, ${this.data.toString()}, ` + `{hasLocalMutations: ${this.hasLocalMutations}}), ` + `{hasCommittedMutations: ${this.hasCommittedMutations}})` ); } get hasPendingWrites(): boolean { return this.hasLocalMutations || this.hasCommittedMutations; } static compareByField(field: FieldPath, d1: Document, d2: Document): number { const v1 = d1.field(field); const v2 = d2.field(field); if (v1 !== undefined && v2 !== undefined) { return v1.compareTo(v2); } else { return fail("Trying to compare documents on fields that don't exist"); } } } /** * A class representing a deleted document. * Version is set to 0 if we don't point to any specific time, otherwise it * denotes time we know it didn't exist at. */ export class NoDocument extends MaybeDocument { readonly hasCommittedMutations: boolean; constructor( key: DocumentKey, version: SnapshotVersion, options?: DocumentOptions ) { super(key, version); this.hasCommittedMutations = !!(options && options.hasCommittedMutations); } toString(): string { return `NoDocument(${this.key}, ${this.version})`; } get hasPendingWrites(): boolean { return this.hasCommittedMutations; } isEqual(other: MaybeDocument | null | undefined): boolean { return ( other instanceof NoDocument && other.hasCommittedMutations === this.hasCommittedMutations && other.version.isEqual(this.version) && other.key.isEqual(this.key) ); } } /** * A class representing an existing document whose data is unknown (e.g. a * document that was updated without a known base document). */ export class
extends MaybeDocument { constructor(key: DocumentKey, version: SnapshotVersion) { super(key, version); } toString(): string { return `UnknownDocument(${this.key}, ${this.version})`; } get hasPendingWrites(): boolean { return true; } isEqual(other: MaybeDocument | null | undefined): boolean { return ( other instanceof UnknownDocument && other.version.isEqual(this.version) && other.key.isEqual(this.key) ); } }
UnknownDocument
connection.py
# # Copyright 2020 Logical Clocks AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os from requests.exceptions import ConnectionError from hsfs.decorators import connected, not_connected from hsfs import engine, client from hsfs.core import feature_store_api, project_api, hosts_api, services_api class Connection: AWS_DEFAULT_REGION = "default" HOPSWORKS_PORT_DEFAULT = 443 SECRETS_STORE_DEFAULT = "parameterstore" HOSTNAME_VERIFICATION_DEFAULT = True CERT_FOLDER_DEFAULT = "hops" def __init__( self, host=None, port=None, project=None, region_name=None, secrets_store=None, hostname_verification=None, trust_store_path=None, cert_folder=None, api_key_file=None, ): self._host = host self._port = port or self.HOPSWORKS_PORT_DEFAULT self._project = project self._region_name = region_name or self.AWS_DEFAULT_REGION self._secrets_store = secrets_store or self.SECRETS_STORE_DEFAULT self._hostname_verification = ( hostname_verification or self.HOSTNAME_VERIFICATION_DEFAULT ) self._trust_store_path = trust_store_path self._cert_folder = cert_folder or self.CERT_FOLDER_DEFAULT self._api_key_file = api_key_file self._connected = False self.connect() @classmethod def connection( cls, host=None, port=None, project=None, region_name=None, secrets_store=None, hostname_verification=None, trust_store_path=None, cert_folder=None, api_key_file=None, ): return cls( host, port, project, region_name, secrets_store, hostname_verification, trust_store_path, cert_folder, api_key_file, ) @classmethod def setup_databricks( cls, host, project, port=443, region_name="default", secrets_store="parameterstore", cert_folder="hops", hostname_verification=True, trust_store_path=None, api_key_file=None, ): connection = cls( host, port, project, region_name, secrets_store, hostname_verification, trust_store_path, cert_folder, api_key_file, ) dbfs_folder = client.get_instance()._cert_folder_base os.makedirs(os.path.join(dbfs_folder, "scripts"), exist_ok=True) connection._get_clients(dbfs_folder) hive_host = connection._get_hivemetastore_hostname() connection._write_init_script(dbfs_folder) connection._print_instructions( cert_folder, client.get_instance()._cert_folder, hive_host ) return connection @not_connected def connect(self): self._connected = True try: if client.base.Client.REST_ENDPOINT not in os.environ: if os.path.exists("/dbfs/"): # databricks client.init( "external", self._host, self._port, self._project, self._region_name, self._secrets_store, self._hostname_verification, os.path.join("/dbfs", self._trust_store_path) if self._trust_store_path is not None else None, os.path.join("/dbfs", self._cert_folder), os.path.join("/dbfs", self._api_key_file) if self._api_key_file is not None else None, ) engine.init("spark") else: # aws client.init( "external", self._host, self._port, self._project, self._region_name, self._secrets_store, self._hostname_verification, self._trust_store_path, self._cert_folder, self._api_key_file, ) engine.init( "hive", self._host, self._cert_folder, self._project, client.get_instance()._cert_key, ) else: client.init("hopsworks") engine.init("spark") self._feature_store_api = feature_store_api.FeatureStoreApi() self._project_api = project_api.ProjectApi() self._hosts_api = hosts_api.HostsApi() self._services_api = services_api.ServicesApi() except (TypeError, ConnectionError): self._connected = False raise print("Connected. Call `.close()` to terminate connection gracefully.") def close(self): client.stop() self._feature_store_api = None engine.stop() self._connected = False print("Connection closed.") @connected def get_feature_store(self, name=None): """Get a reference to a feature store, to perform operations on. Defaulting to the project's default feature store. Shared feature stores can be retrieved by passing the `name`. :param name: the name of the feature store, defaults to None :type name: str, optional :return: feature store object :rtype: FeatureStore """ if not name: name = client.get_instance()._project_name + "_featurestore" return self._feature_store_api.get(name) def _get_clients(self, dbfs_folder): """ Get the client libraries and save them in the dbfs folder. :param dbfs_folder: the folder in which to save the libraries :type dbfs_folder: str """ client_path = os.path.join(dbfs_folder, "client.tar.gz") if not os.path.exists(client_path): client_libs = self._project_api.get_client() with open(client_path, "wb") as f: for chunk in client_libs: f.write(chunk) def _get_hivemetastore_hostname(self): """ Get the internal hostname of the Hopsworks instance. """ hosts = self._hosts_api.get() hivemetastore = self._services_api.get_service("hivemetastore") hosts = [host for host in hosts if host["id"] == hivemetastore["hostId"]] return hosts[0]["hostname"] def _write_init_script(self, dbfs_folder): """ Write the init script for databricks clusters to dbfs. :param dbfs_folder: the folder on dbfs in which to save the script :type dbfs_foler: str """ initScript = """ #!/bin/sh tar -xvf PATH/client.tar.gz -C /tmp tar -xvf /tmp/client/apache-hive-*-bin.tar.gz -C /tmp mv /tmp/apache-hive-*-bin /tmp/apache-hive-bin chmod -R +xr /tmp/apache-hive-bin cp /tmp/client/hopsfs-client*.jar /databricks/jars/ """ script_path = os.path.join(dbfs_folder, "scripts/initScript.sh") if not os.path.exists(script_path): initScript = initScript.replace("PATH", dbfs_folder) with open(script_path, "w") as f: f.write(initScript) def _print_instructions(self, user_cert_folder, cert_folder, internal_host): """ Print the instructions to set up the hopsfs hive connection on databricks. :param user_cert_folder: the original user specified cert_folder without `/dbfs/` prefix :type user_cert_folder: str :cert_folder: the directory in which the credential were saved, prefixed with `/dbfs/` and `[hostname]` :type cert_folder: str :param internal_ip: the internal ip of the hopsworks instance :type internal_ip: str """ instructions = """ In the advanced options of your databricks cluster configuration add the following path to Init Scripts: dbfs:/{0}/scripts/initScript.sh add the following to the Spark Config: spark.hadoop.fs.hopsfs.impl io.hops.hopsfs.client.HopsFileSystem spark.hadoop.hops.ipc.server.ssl.enabled true spark.hadoop.hops.ssl.hostname.verifier ALLOW_ALL spark.hadoop.hops.rpc.socket.factory.class.default io.hops.hadoop.shaded.org.apache.hadoop.net.HopsSSLSocketFactory spark.hadoop.client.rpc.ssl.enabled.protocol TLSv1.2 spark.hadoop.hops.ssl.keystores.passwd.name {1}/material_passwd spark.hadoop.hops.ssl.keystore.name {1}/keyStore.jks spark.hadoop.hops.ssl.trustore.name {1}/trustStore.jks spark.sql.hive.metastore.jars /tmp/apache-hive-bin/lib/* spark.hadoop.hive.metastore.uris thrift://{2}:9083 Then save and restart the cluster. """.format( user_cert_folder, cert_folder, internal_host ) print(instructions) @property def host(self): return self._host @host.setter @not_connected def host(self, host): self._host = host @property def port(self): return self._port @port.setter @not_connected def port(self, port): self._port = port @property def project(self): return self._project @project.setter @not_connected def project(self, project): self._project = project @property def region_name(self): return self._region_name @region_name.setter @not_connected def region_name(self, region_name): self._region_name = region_name @property def secrets_store(self): return self._secrets_store @secrets_store.setter @not_connected def secrets_store(self, secrets_store): self._secrets_store = secrets_store @property def hostname_verification(self): return self._hostname_verification @hostname_verification.setter @not_connected def hostname_verification(self, hostname_verification): self._hostname_verification = hostname_verification @property def trust_store_path(self): return self._trust_store_path @trust_store_path.setter @not_connected def trust_store_path(self, trust_store_path):
@property def cert_folder(self): return self._cert_folder @cert_folder.setter @not_connected def cert_folder(self, cert_folder): self._cert_folder = cert_folder @property def api_key_file(self): return self._api_key_file @api_key_file.setter @not_connected def api_key_file(self, api_key_file): self._api_key_file = api_key_file def __enter__(self): self.connect() return self def __exit__(self, type, value, traceback): self.close()
self._trust_store_path = trust_store_path
KeychainService.ts
import KeychainServiceDriverBase from './KeychainServiceDriverBase'; const Setting = require('lib/models/Setting'); const BaseService = require('lib/services/BaseService'); export default class KeychainService extends BaseService { private driver:KeychainServiceDriverBase; private static instance_:KeychainService; static instance():KeychainService { if (!this.instance_) this.instance_ = new KeychainService(); return this.instance_; } initialize(driver:KeychainServiceDriverBase) { if (!driver.appId || !driver.clientId) throw new Error('appId and clientId must be set on the KeychainServiceDriver'); this.driver = driver; }
// https://github.com/atom/node-keytar/issues/76 return this.driver.setPassword(name, password); } async password(name:string):Promise<string> { return this.driver.password(name); } async deletePassword(name:string):Promise<void> { await this.driver.deletePassword(name); } async detectIfKeychainSupported() { this.logger().info('KeychainService: checking if keychain supported'); if (Setting.value('keychain.supported') >= 0) { this.logger().info('KeychainService: check was already done - skipping. Supported:', Setting.value('keychain.supported')); return; } const passwordIsSet = await this.setPassword('zz_testingkeychain', 'mytest'); if (!passwordIsSet) { this.logger().info('KeychainService: could not set test password - keychain support will be disabled'); Setting.setValue('keychain.supported', 0); } else { const result = await this.password('zz_testingkeychain'); await this.deletePassword('zz_testingkeychain'); this.logger().info('KeychainService: tried to set and get password. Result was:', result); Setting.setValue('keychain.supported', result === 'mytest' ? 1 : 0); } } }
async setPassword(name:string, password:string):Promise<boolean> { // Due to a bug in macOS, this may throw an exception "The user name or passphrase you entered is not correct." // The fix is to open Keychain Access.app. Right-click on the login keychain and try locking it and then unlocking it again.
test_nis.py
from test_support import verbose, TestFailed, TestSkipped import nis print 'nis.maps()' try: maps = nis.maps() except nis.error, msg: # NIS is probably not active, so this test isn't useful if verbose: raise TestFailed, msg # only do this if running under the regression suite raise TestSkipped, msg done = 0 for nismap in maps: if verbose: print nismap mapping = nis.cat(nismap) for k, v in mapping.items(): if verbose: print ' ', k, v if not k: continue if nis.match(k, nismap) <> v:
else: # just test the one key, otherwise this test could take a # very long time done = 1 break if done: break
print "NIS match failed for key `%s' in map `%s'" % (k, nismap)
getP2sVpnGateway.go
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package v20181101 import ( "github.com/pulumi/pulumi/sdk/v2/go/pulumi" ) // P2SVpnGateway Resource. func LookupP2sVpnGateway(ctx *pulumi.Context, args *LookupP2sVpnGatewayArgs, opts ...pulumi.InvokeOption) (*LookupP2sVpnGatewayResult, error) { var rv LookupP2sVpnGatewayResult err := ctx.Invoke("azure-nextgen:network/v20181101:getP2sVpnGateway", args, &rv, opts...) if err != nil
return &rv, nil } type LookupP2sVpnGatewayArgs struct { // The name of the gateway. GatewayName string `pulumi:"gatewayName"` // The resource group name of the P2SVpnGateway. ResourceGroupName string `pulumi:"resourceGroupName"` } // P2SVpnGateway Resource. type LookupP2sVpnGatewayResult struct { // Gets a unique read-only string that changes whenever the resource is updated. Etag string `pulumi:"etag"` // Resource ID. Id *string `pulumi:"id"` // Resource location. Location string `pulumi:"location"` // Resource name. Name string `pulumi:"name"` // The P2SVpnServerConfiguration to which the p2sVpnGateway is attached to. P2SVpnServerConfiguration *SubResourceResponse `pulumi:"p2SVpnServerConfiguration"` // The provisioning state of the resource. ProvisioningState string `pulumi:"provisioningState"` // Resource tags. Tags map[string]string `pulumi:"tags"` // Resource type. Type string `pulumi:"type"` // The VirtualHub to which the gateway belongs VirtualHub *SubResourceResponse `pulumi:"virtualHub"` // The reference of the address space resource which represents Address space for P2S VpnClient. VpnClientAddressPool *AddressSpaceResponse `pulumi:"vpnClientAddressPool"` // All P2S VPN clients' connection health status. VpnClientConnectionHealth VpnClientConnectionHealthResponse `pulumi:"vpnClientConnectionHealth"` // The scale unit for this p2s vpn gateway. VpnGatewayScaleUnit *int `pulumi:"vpnGatewayScaleUnit"` }
{ return nil, err }
cipal_query.go
package lcd import ( "encoding/json" "errors" "fmt" "github.com/netcloth/go-sdk/keys" "github.com/netcloth/netcloth-chain/modules/cipal/types" ) type ( CIPALServiceInfo struct { Type string `json:"type"` Address string `json:"address"` } CIPALResult struct { UserAddress string `json:"user_address"` ServiceInfos []CIPALServiceInfo `json:"service_infos"` } CIPALBody struct { Height string `json:"height"` Result CIPALResult `json:"result"` } CIPALsBody struct { Height string `json:"height"` Result []CIPALResult `json:"result"` } ) func (c *client) QueryCIPALByAddress(address string) (CIPALBody, error) { var r CIPALBody if _, body, err := c.httpClient.Get(fmt.Sprintf(UriQueryCIPAL, address), nil); err != nil { return r, err } else { if err := json.Unmarshal(body, &r); err != nil { return r, err } else { return r, nil } } } func (c *client) QueryCIPALByUNCompressedPubKey(uncompressedPubKey string) (CIPALBody, error) { var r CIPALBody addrBech32, err := keys.UNCompressedPubKey2AddressBech32(uncompressedPubKey) if err != nil { return r, err } return c.QueryCIPALByAddress(addrBech32) } func (c *client) QueryCIPALChatServerAddrByUNCompressedPubKey(uncompressedPubKey string) (string, error) { cipalInfo, err := c.QueryCIPALByUNCompressedPubKey(uncompressedPubKey) if err != nil { return "", err } for _, serviceInfo := range cipalInfo.Result.ServiceInfos { if ClientChatEndpointType2ServerChatEndpointType[serviceInfo.Type] == EndpointTypeServerChat { return serviceInfo.Address, nil break } } return "", errors.New("no chat endpoint") } func Bech32AddrsFromUNCompressedPubKeys(uncompressedPubKeys []string) (bech32Addrs []string) { for _, pubKey := range uncompressedPubKeys { bech32Addr, err := keys.UNCompressedPubKey2AddressBech32(pubKey) if err == nil { bech32Addrs = append(bech32Addrs, bech32Addr) } } return } func QueryCIPALsParamsFromUNCompressedPubKeys(uncompressedPubKeys []string) (params types.QueryCIPALsParams)
func (c *client) QueryCIPALChatServersAddrByUNCompressedPubKeys(uncompressedPubKeys []string) (map[string]string, error) { var r CIPALsBody params := QueryCIPALsParamsFromUNCompressedPubKeys(uncompressedPubKeys) if _, body, err := c.httpClient.Post(UriQueryCIPALs, nil, params); err != nil { return nil, err } else { if err := json.Unmarshal(body, &r); err != nil { return nil, err } else { result := make(map[string]string) for _, cipal := range r.Result { for _, si := range cipal.ServiceInfos { if ClientChatEndpointType2ServerChatEndpointType[si.Type] == EndpointTypeServerChat { result[cipal.UserAddress] = si.Address break } } } return result, nil } } } func (c *client) QueryCIPALsAddrByUNCompressedPubKeysByType(uncompressedPubKeys []string, endpointType string) (map[string]string, error) { var r CIPALsBody params := QueryCIPALsParamsFromUNCompressedPubKeys(uncompressedPubKeys) if _, body, err := c.httpClient.Post(UriQueryCIPALs, nil, params); err != nil { return nil, err } else { if err := json.Unmarshal(body, &r); err != nil { return nil, err } else { result := make(map[string]string) for _, cipal := range r.Result { for _, si := range cipal.ServiceInfos { if ClientChatEndpointType2ServerChatEndpointType[si.Type] == ClientChatEndpointType2ServerChatEndpointType[endpointType] { result[cipal.UserAddress] = si.Address break } } } return result, nil } } }
{ params.AccAddrs = Bech32AddrsFromUNCompressedPubKeys(uncompressedPubKeys) return }
App.js
import React, {Component} from 'react'; import {BrowserRouter,Route} from 'react-router-dom' import {Switch, Redirect} from 'react-router' import MainLayout from './MainLayout'; import Home from './Home'; import Loader from './Loader'; import UserSelection from './UserSelection'; import Chatroom from './Chatroom'; import socket from './socket'; export default class
extends Component { constructor(props, context) { super(props, context) this.state = { user: null, isRegisterInProcess: false, client: socket(), chatrooms: [], } this.onEnterChatroom = this.onEnterChatroom.bind(this) this.onLeaveChatroom = this.onLeaveChatroom.bind(this) this.getChatrooms = this.getChatrooms.bind(this) this.register = this.register.bind(this) this.renderUserSelectionOrRedirect = this.renderUserSelectionOrRedirect.bind(this) } componentDidMount() { //console.log(this.state.chatrooms); this.getChatrooms(); } onEnterChatroom(chatroomName, onNoUserSelected, onEnterSuccess) { if (!this.state.user) return onNoUserSelected() return this.state.client.join(chatroomName, (err, chatHistory) => { if (err) return console.error(err) return onEnterSuccess(chatHistory) }) } onLeaveChatroom(chatroomName, onLeaveSuccess) { this.state.client.leave(chatroomName, (err) => { if (err) return console.error(err) return onLeaveSuccess() }) } getChatrooms() { this.state.client.getChatrooms((err, chatrooms) => { this.setState({chatrooms}) }) } register(name) { const onRegisterResponse = user => this.setState({ isRegisterInProcess: false, user }) this.setState({ isRegisterInProcess: true }) this.state.client.register(name, (err, user) => { if (err) return onRegisterResponse(null) return onRegisterResponse(user) }) } renderUserSelectionOrRedirect(renderUserSelection) { if (this.state.user) { return <Redirect to="/" /> } return this.state.isRegisterInProcess ? <Loader /> : renderUserSelection() } renderChatroomOrRedirect(chatroom, { history }) { if (!this.state.user) { return <Redirect to="/" /> } const { chatHistory } = history.location.state return ( <Chatroom chatroom={chatroom} chatHistory={chatHistory} user={this.state.user} onLeave={ () => this.onLeaveChatroom( chatroom.name, () => history.push('/') ) } onSendMessage={ (message, cb) => this.state.client.message( chatroom.name, message, cb ) } registerHandler={this.state.client.registerHandler} unregisterHandler={this.state.client.unregisterHandler} /> ) } renderChatroom = (chatroom) => { // document.body.style.background = `url(${chatroom.image}) repeat-y` return ( <Route key={chatroom.name} exact path={`/${chatroom.name}`} render={ props => this.renderChatroomOrRedirect(chatroom, props) } /> ); } render() { console.log(this.state.chatrooms) return ( <BrowserRouter> <MainLayout user={this.state.user} > { !this.state.chatrooms ? <Loader/>: ( <Switch> <Route exact path="/" render={ props => ( <Home user={this.state.user} chatrooms={this.state.chatrooms} onChangeUser={() => props.history.push('/user')} onEnterChatroom={ chatroomName => this.onEnterChatroom( chatroomName, () => props.history.push('/user'), chatHistory => props.history.push({ pathname: chatroomName, state: { chatHistory } }) ) } /> ) } /> <Route exact path="/user" render={ (props) => { const toHome = () => props.history.push('/') return this.renderUserSelectionOrRedirect(() => ( <UserSelection getAvailableUsers={this.state.client.getAvailableUsers} close={toHome} register={name => this.register(name, toHome)} /> )) } } /> {this.state.chatrooms.map( chatroom => (<Route key={chatroom.name} exact path={`/${chatroom.name}`} render={ props => this.renderChatroomOrRedirect(chatroom, props) } /> ))} </Switch> ) } </MainLayout> </BrowserRouter> ); } }
App
lib.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![recursion_limit = "256"] ///! Safe wrappers for enumerating `fuchsia.io.Directory` contents. use { fidl::endpoints::ServerEnd, fidl_fuchsia_io::{self as fio, DirectoryMarker, DirectoryProxy, MAX_BUF, MODE_TYPE_DIRECTORY}, fuchsia_async::{DurationExt, TimeoutExt}, fuchsia_zircon as zx, futures::{ future::BoxFuture, stream::{self, BoxStream, StreamExt}, }, std::{collections::VecDeque, mem, str::Utf8Error}, thiserror::{self, Error}, }; /// Error returned by files_async library. #[derive(Debug, Error)] pub enum Error { #[error("a directory entry could not be decoded: {:?}", _0)] DecodeDirent(DecodeDirentError), #[error("fidl error during {}: {:?}", _0, _1)] Fidl(&'static str, fidl::Error), #[error("`read_dirents` failed with status {:?}", _0)] ReadDirents(zx::Status), #[error("`unlink` failed with status {:?}", _0)] Unlink(zx::Status), #[error("timeout")] Timeout, #[error("`rewind` failed with status {:?}", _0)] Rewind(zx::Status), #[error("Failed to read directory {}: {:?}", name, err)] ReadDir { name: String, err: anyhow::Error }, } /// An error encountered while decoding a single directory entry. #[derive(Debug, PartialEq, Eq, Error)] pub enum DecodeDirentError { #[error("an entry extended past the end of the buffer")] BufferOverrun, #[error("name is not valid utf-8")] InvalidUtf8(Utf8Error), } /// The type of a node. #[derive(Eq, Ord, PartialOrd, PartialEq, Clone, Copy, Debug)] pub enum DirentKind { Unknown, Directory, BlockDevice, File, Socket, Service, } impl From<u8> for DirentKind { fn from(kind: u8) -> Self { match kind { fio::DIRENT_TYPE_DIRECTORY => DirentKind::Directory, fio::DIRENT_TYPE_BLOCK_DEVICE => DirentKind::BlockDevice, fio::DIRENT_TYPE_FILE => DirentKind::File, fio::DIRENT_TYPE_SOCKET => DirentKind::Socket, fio::DIRENT_TYPE_SERVICE => DirentKind::Service, _ => DirentKind::Unknown, } } } /// A directory entry. #[derive(Eq, Ord, PartialOrd, PartialEq, Debug)] pub struct DirEntry { /// The name of this node. pub name: String, /// The type of this node, or [`DirentKind::Unknown`] if not known. pub kind: DirentKind, } impl DirEntry { fn root() -> Self { Self { name: "".to_string(), kind: DirentKind::Directory } } fn is_dir(&self) -> bool { self.kind == DirentKind::Directory } fn is_root(&self) -> bool { self.is_dir() && self.name.is_empty() } fn chain(&self, subentry: &DirEntry) -> DirEntry { if self.name.is_empty() { DirEntry { name: subentry.name.clone(), kind: subentry.kind } } else { DirEntry { name: format!("{}/{}", self.name, subentry.name), kind: subentry.kind } } } } /// Returns a Vec of all non-directory nodes and all empty directory nodes in the given directory /// proxy. The returned entries will not include ".". /// |timeout| can be provided optionally to specify the maximum time to wait for a directory to be /// read. pub fn readdir_recursive( dir: &DirectoryProxy, timeout: Option<zx::Duration>, ) -> BoxStream<'_, Result<DirEntry, Error>> { let mut pending = VecDeque::new(); pending.push_back(DirEntry::root()); let results: VecDeque<DirEntry> = VecDeque::new(); stream::unfold((results, pending), move |(mut results, mut pending)| { async move { loop { // Pending results to stream from the last read directory. if !results.is_empty() { let result = results.pop_front().unwrap(); return Some((Ok(result), (results, pending))); } // No pending directories to read and per the last condition no pending results to // stream so finish the stream. if pending.is_empty() { return None; } // The directory that will be read now. let dir_entry = pending.pop_front().unwrap(); let (subdir, subdir_server) = match fidl::endpoints::create_proxy::<DirectoryMarker>() { Ok((subdir, server)) => (subdir, server), Err(e) => { return Some((Err(Error::Fidl("create_proxy", e)), (results, pending))) } }; let dir_ref = if dir_entry.is_root() { dir } else { let open_dir_result = dir.open( fio::OPEN_FLAG_DIRECTORY | fio::OPEN_RIGHT_READABLE, MODE_TYPE_DIRECTORY, &dir_entry.name, ServerEnd::new(subdir_server.into_channel()), ); if let Err(e) = open_dir_result { let error = Err(Error::ReadDir { name: dir_entry.name, err: anyhow::Error::new(e), }); return Some((error, (results, pending))); } else { &subdir } }; let readdir_result = match timeout { Some(timeout_duration) => readdir_with_timeout(dir_ref, timeout_duration).await, None => readdir(&dir_ref).await, }; let subentries = match readdir_result { Ok(subentries) => subentries, Err(e) => { let error = Err(Error::ReadDir { name: dir_entry.name, err: anyhow::Error::new(e), }); return Some((error, (results, pending))); } }; // Emit empty directories as a single entry except for the root directory. if subentries.is_empty() && !dir_entry.name.is_empty() { return Some((Ok(dir_entry), (results, pending))); } for subentry in subentries.into_iter() { let subentry = dir_entry.chain(&subentry); if subentry.is_dir() { pending.push_back(subentry); } else { results.push_back(subentry); } } } } }) .boxed() } /// Returns a sorted Vec of directory entries contained directly in the given directory proxy. The /// returned entries will not include "." or nodes from any subdirectories. pub async fn readdir(dir: &DirectoryProxy) -> Result<Vec<DirEntry>, Error> { let status = dir.rewind().await.map_err(|e| Error::Fidl("rewind", e))?; zx::Status::ok(status).map_err(Error::Rewind)?; let mut entries = vec![]; loop { let (status, buf) = dir.read_dirents(MAX_BUF).await.map_err(|e| Error::Fidl("read_dirents", e))?; zx::Status::ok(status).map_err(Error::ReadDirents)?; if buf.is_empty() { break; } for entry in parse_dir_entries(&buf) { let entry = entry.map_err(Error::DecodeDirent)?; if entry.name != "." { entries.push(entry); } } } entries.sort_unstable(); Ok(entries) } /// Returns a sorted Vec of directory entries contained directly in the given directory proxy. The /// returned entries will not include "." or nodes from any subdirectories. Timeouts if the read /// takes longer than the given `timeout` duration. pub async fn readdir_with_timeout( dir: &DirectoryProxy, timeout_duration: zx::Duration, ) -> Result<Vec<DirEntry>, Error> { readdir(&dir).on_timeout(timeout_duration.after_now(), || Err(Error::Timeout)).await } fn parse_dir_entries(mut buf: &[u8]) -> Vec<Result<DirEntry, DecodeDirentError>> { #[repr(C, packed)] struct Dirent { /// The inode number of the entry. _ino: u64, /// The length of the filename located after this entry. size: u8, /// The type of the entry. One of the `fio::DIRENT_TYPE_*` constants. kind: u8, // The unterminated name of the entry. Length is the `size` field above. // char name[0], } const DIRENT_SIZE: usize = mem::size_of::<Dirent>(); let mut entries = vec![]; while !buf.is_empty() { // Don't read past the end of the buffer. if DIRENT_SIZE > buf.len() { entries.push(Err(DecodeDirentError::BufferOverrun)); return entries; } // Read the dirent, and figure out how long the name is. let (head, rest) = buf.split_at(DIRENT_SIZE); let entry = { // Cast the dirent bytes into a `Dirent`, and extract out the size of the name and the // entry type. let (size, kind) = unsafe { let dirent: &Dirent = mem::transmute(head.as_ptr()); (dirent.size as usize, dirent.kind) }; // Don't read past the end of the buffer. if size > rest.len() { entries.push(Err(DecodeDirentError::BufferOverrun)); return entries; } // Advance to the next entry. buf = &rest[size..]; match String::from_utf8(rest[..size].to_vec()) { Ok(name) => Ok(DirEntry { name, kind: kind.into() }), Err(err) => Err(DecodeDirentError::InvalidUtf8(err.utf8_error())), } }; entries.push(entry); } entries } const DIR_FLAGS: u32 = fio::OPEN_FLAG_DIRECTORY | fio::OPEN_RIGHT_READABLE | fio::OPEN_RIGHT_WRITABLE; /// Removes a directory and all of its children. `name` must be a subdirectory of `root_dir`. /// /// The async analogue of `std::fs::remove_dir_all`. pub async fn remove_dir_recursive(root_dir: &DirectoryProxy, name: &str) -> Result<(), Error> { let (dir, dir_server) = fidl::endpoints::create_proxy::<DirectoryMarker>().expect("failed to create proxy"); root_dir .open(DIR_FLAGS, MODE_TYPE_DIRECTORY, name, ServerEnd::new(dir_server.into_channel())) .map_err(|e| Error::Fidl("open", e))?; remove_dir_contents(dir).await?; let s = root_dir.unlink(name).await.map_err(|e| Error::Fidl("unlink", e))?; zx::Status::ok(s).map_err(Error::Unlink)?; Ok(()) } // Returns a `BoxFuture` instead of being async because async doesn't support recursion. fn remove_dir_contents(dir: DirectoryProxy) -> BoxFuture<'static, Result<(), Error>> { let fut = async move { for dirent in readdir(&dir).await? { match dirent.kind { DirentKind::Directory => { let (subdir, subdir_server) = fidl::endpoints::create_proxy::<DirectoryMarker>() .expect("failed to create proxy"); dir.open( DIR_FLAGS, MODE_TYPE_DIRECTORY, &dirent.name, ServerEnd::new(subdir_server.into_channel()), ) .map_err(|e| Error::Fidl("open", e))?; remove_dir_contents(subdir).await?; } _ => {} } let s = dir.unlink(&dirent.name).await.map_err(|e| Error::Fidl("unlink", e))?; zx::Status::ok(s).map_err(Error::Unlink)?; } Ok(()) }; Box::pin(fut) } #[cfg(test)] mod tests { use { super::*, fuchsia_async as fasync, fuchsia_vfs_pseudo_fs::{ directory::entry::DirectoryEntry, file::simple::read_only_str, pseudo_directory, }, fuchsia_zircon::DurationNum, futures::{channel::oneshot, stream::StreamExt}, io_util, pin_utils, proptest::prelude::*, std::{path::Path, task::Poll}, tempfile::TempDir, }; proptest! { #[test] fn test_parse_dir_entries_does_not_crash(buf in prop::collection::vec(any::<u8>(), 0..200)) { parse_dir_entries(&buf); } } #[test] fn test_parse_dir_entries() { #[rustfmt::skip] let buf = &[ // ino 42, 0, 0, 0, 0, 0, 0, 0, // name length 4, // type fio::DIRENT_TYPE_FILE, // name 't' as u8, 'e' as u8, 's' as u8, 't' as u8, ]; assert_eq!( parse_dir_entries(buf), vec![Ok(DirEntry { name: "test".to_string(), kind: DirentKind::File })] ); } #[test] fn test_parse_dir_entries_rejects_invalid_utf8() { #[rustfmt::skip] let buf = &[ // entry 0 // ino 1, 0, 0, 0, 0, 0, 0, 0, // name length 1, // type fio::DIRENT_TYPE_FILE, // name (a lonely continuation byte) 0x80, // entry 1 // ino 2, 0, 0, 0, 0, 0, 0, 0, // name length 4, // type fio::DIRENT_TYPE_FILE, // name 'o' as u8, 'k' as u8, 'a' as u8, 'y' as u8, ]; let expected_err = std::str::from_utf8(&[0x80]).unwrap_err(); assert_eq!( parse_dir_entries(buf), vec![ Err(DecodeDirentError::InvalidUtf8(expected_err)), Ok(DirEntry { name: "okay".to_string(), kind: DirentKind::File }) ] ); } #[test] fn test_parse_dir_entries_overrun() { #[rustfmt::skip] let buf = &[ // ino 0, 0, 0, 0, 0, 0, 0, 0, // name length 5, // type fio::DIRENT_TYPE_FILE, // name 't' as u8, 'e' as u8, 's' as u8, 't' as u8, ]; assert_eq!(parse_dir_entries(buf), vec![Err(DecodeDirentError::BufferOverrun)]); } #[fasync::run_singlethreaded(test)] async fn test_readdir() { let (dir, server_end) = fidl::endpoints::create_proxy::<DirectoryMarker>().unwrap(); fasync::spawn(async move { let mut dir = pseudo_directory! { "afile" => read_only_str(|| Ok("".into())), "zzz" => read_only_str(|| Ok("".into())), "subdir" => pseudo_directory! { "ignored" => read_only_str(|| Ok("".into())), }, }; dir.open( fio::OPEN_FLAG_DIRECTORY | fio::OPEN_RIGHT_READABLE, 0, &mut std::iter::empty(), ServerEnd::new(server_end.into_channel()), ); dir.await; unreachable!(); }); // run twice to check that seek offset is properly reset before reading the directory for _ in 0..2 { let entries = readdir(&dir).await.expect("readdir to succeed"); assert_eq!( entries, vec![ build_direntry("afile", DirentKind::File), build_direntry("subdir", DirentKind::Directory), build_direntry("zzz", DirentKind::File), ] ); } } #[fasync::run_singlethreaded(test)] async fn test_readdir_recursive()
#[test] fn test_readdir_recursive_timeout() { let mut executor = fasync::Executor::new_with_fake_time().unwrap(); executor.set_fake_time(fasync::Time::from_nanos(0)); let fut = async move { let tempdir = TempDir::new().expect("failed to create tmp dir"); let dir = create_nested_dir(&tempdir).await; readdir_recursive(&dir, Some(0.nanos())) .collect::<Vec<Result<DirEntry, Error>>>() .await .into_iter() .collect::<Result<Vec<_>, _>>() }; pin_utils::pin_mut!(fut); let mut i = 1; let result = loop { executor.wake_main_future(); match executor.run_one_step(&mut fut) { Some(Poll::Ready(x)) => break x, None => panic!("Executor stalled"), Some(Poll::Pending) => { executor.set_fake_time(fasync::Time::from_nanos(10 * i)); i += 1; } } }; assert!(result.is_err()); } #[fasync::run_singlethreaded(test)] async fn test_remove_dir_recursive() { { let tempdir = TempDir::new().expect("failed to create tmp dir"); let dir = create_nested_dir(&tempdir).await; remove_dir_recursive(&dir, "emptydir").await.expect("remove_dir_recursive to succeed"); let entries = readdir_recursive(&dir, None) .collect::<Vec<Result<DirEntry, Error>>>() .await .into_iter() .collect::<Result<Vec<_>, _>>() .expect("readdir_recursive to succeed"); assert_eq!( entries, vec![ build_direntry("a", DirentKind::File), build_direntry("b", DirentKind::File), build_direntry("subdir/a", DirentKind::File), build_direntry("subdir/subsubdir/a", DirentKind::File), build_direntry("subdir/subsubdir/emptydir", DirentKind::Directory), ] ); } { let tempdir = TempDir::new().expect("failed to create tmp dir"); let dir = create_nested_dir(&tempdir).await; remove_dir_recursive(&dir, "subdir").await.expect("remove_dir_recursive to succeed"); let entries = readdir_recursive(&dir, None) .collect::<Vec<Result<DirEntry, Error>>>() .await .into_iter() .collect::<Result<Vec<_>, _>>() .expect("readdir_recursive to succeed"); assert_eq!( entries, vec![ build_direntry("a", DirentKind::File), build_direntry("b", DirentKind::File), build_direntry("emptydir", DirentKind::Directory), ] ); } { let tempdir = TempDir::new().expect("failed to create tmp dir"); let dir = create_nested_dir(&tempdir).await; let subdir = io_util::open_directory( &dir, &Path::new("subdir"), fio::OPEN_RIGHT_READABLE | fio::OPEN_RIGHT_WRITABLE, ) .expect("could not open subdir"); remove_dir_recursive(&subdir, "subsubdir") .await .expect("remove_dir_recursive to succeed"); let entries = readdir_recursive(&dir, None) .collect::<Vec<Result<DirEntry, Error>>>() .await .into_iter() .collect::<Result<Vec<_>, _>>() .expect("readdir_recursive to succeed"); assert_eq!( entries, vec![ build_direntry("a", DirentKind::File), build_direntry("b", DirentKind::File), build_direntry("emptydir", DirentKind::Directory), build_direntry("subdir/a", DirentKind::File), ] ); } { let tempdir = TempDir::new().expect("failed to create tmp dir"); let dir = create_nested_dir(&tempdir).await; let subsubdir = io_util::open_directory( &dir, &Path::new("subdir/subsubdir"), fio::OPEN_RIGHT_READABLE | fio::OPEN_RIGHT_WRITABLE, ) .expect("could not open subsubdir"); remove_dir_recursive(&subsubdir, "emptydir") .await .expect("remove_dir_recursive to succeed"); let entries = readdir_recursive(&dir, None) .collect::<Vec<Result<DirEntry, Error>>>() .await .into_iter() .collect::<Result<Vec<_>, _>>() .expect("readdir_recursive to succeed"); assert_eq!( entries, vec![ build_direntry("a", DirentKind::File), build_direntry("b", DirentKind::File), build_direntry("emptydir", DirentKind::Directory), build_direntry("subdir/a", DirentKind::File), build_direntry("subdir/subsubdir/a", DirentKind::File), ] ); } } #[fasync::run_singlethreaded(test)] async fn test_remove_dir_recursive_errors() { { let tempdir = TempDir::new().expect("failed to create tmp dir"); let dir = create_nested_dir(&tempdir).await; let res = remove_dir_recursive(&dir, "baddir").await; let res = res.expect_err("remove_dir did not fail"); match res { Error::Fidl("rewind", fidl_error) if fidl_error.is_closed() => {} _ => panic!("unexpected error {:?}", res), } } { let tempdir = TempDir::new().expect("failed to create tmp dir"); let dir = create_nested_dir(&tempdir).await; let res = remove_dir_recursive(&dir, ".").await; let expected: Result<(), Error> = Err(Error::Unlink(zx::Status::UNAVAILABLE)); assert_eq!(format!("{:?}", res), format!("{:?}", expected)); } } async fn create_nested_dir(tempdir: &TempDir) -> DirectoryProxy { let dir = io_util::open_directory_in_namespace( tempdir.path().to_str().unwrap(), fio::OPEN_RIGHT_READABLE | fio::OPEN_RIGHT_WRITABLE, ) .expect("could not open tmp dir"); io_util::create_sub_directories(&dir, Path::new("emptydir")) .expect("failed to create emptydir"); io_util::create_sub_directories(&dir, Path::new("subdir/subsubdir/emptydir")) .expect("failed to create subdir/subsubdir/emptydir"); create_file(&dir, "a").await; create_file(&dir, "b").await; create_file(&dir, "subdir/a").await; create_file(&dir, "subdir/subsubdir/a").await; dir } async fn create_file(dir: &DirectoryProxy, path: &str) { io_util::open_file( dir, Path::new(path), fio::OPEN_RIGHT_READABLE | fio::OPEN_RIGHT_WRITABLE | fio::OPEN_FLAG_CREATE, ) .expect(&format!("failed to create {}", path)); } fn build_direntry(name: &str, kind: DirentKind) -> DirEntry { DirEntry { name: name.to_string(), kind } } #[test] fn test_direntry_is_dir() { assert!(build_direntry("foo", DirentKind::Directory).is_dir()); // Negative test assert!(!build_direntry("foo", DirentKind::File).is_dir()); assert!(!build_direntry("foo", DirentKind::Unknown).is_dir()); } #[test] fn test_direntry_chaining() { let parent = build_direntry("foo", DirentKind::Directory); let child1 = build_direntry("bar", DirentKind::Directory); let chained1 = parent.chain(&child1); assert_eq!(&chained1.name, "foo/bar"); assert_eq!(chained1.kind, DirentKind::Directory); let child2 = build_direntry("baz", DirentKind::File); let chained2 = parent.chain(&child2); assert_eq!(&chained2.name, "foo/baz"); assert_eq!(chained2.kind, DirentKind::File); } }
{ let tempdir = TempDir::new().expect("failed to create tmp dir"); let dir = create_nested_dir(&tempdir).await; // run twice to check that seek offset is properly reset before reading the directory for _ in 0..2 { let (tx, rx) = oneshot::channel(); let clone_dir = io_util::clone_directory(&dir, fio::CLONE_FLAG_SAME_RIGHTS).expect("clone dir"); fasync::spawn(async move { let entries = readdir_recursive(&clone_dir, None) .collect::<Vec<Result<DirEntry, Error>>>() .await .into_iter() .collect::<Result<Vec<_>, _>>() .expect("readdir_recursive to succeed"); tx.send(entries).expect("Unable to send entries"); }); let entries = rx.await.expect("Receive entrie"); assert_eq!( entries, vec![ build_direntry("a", DirentKind::File), build_direntry("b", DirentKind::File), build_direntry("emptydir", DirentKind::Directory), build_direntry("subdir/a", DirentKind::File), build_direntry("subdir/subsubdir/a", DirentKind::File), build_direntry("subdir/subsubdir/emptydir", DirentKind::Directory), ] ); } }
gen_helper.rs
// Copyright 2018 Syn Developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(feature = "fold")] pub mod fold { use punctuated::{Pair, Punctuated}; use fold::Fold; use proc_macro2::Span; pub trait FoldHelper { type Item; fn lift<F>(self, f: F) -> Self where F: FnMut(Self::Item) -> Self::Item; } impl<T> FoldHelper for Vec<T> { type Item = T; fn lift<F>(self, f: F) -> Self where F: FnMut(Self::Item) -> Self::Item, { self.into_iter().map(f).collect() } } impl<T, U> FoldHelper for Punctuated<T, U> { type Item = T; fn lift<F>(self, mut f: F) -> Self where F: FnMut(Self::Item) -> Self::Item, { self.into_pairs() .map(Pair::into_tuple) .map(|(t, u)| Pair::new(f(t), u)) .collect() } } pub fn tokens_helper<F: Fold + ?Sized, S: Spans>(folder: &mut F, spans: &S) -> S { spans.fold(folder) } pub trait Spans { fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self; } impl Spans for Span { fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { folder.fold_span(*self) } } impl Spans for [Span; 1] { fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { [folder.fold_span(self[0])] } } impl Spans for [Span; 2] { fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { [folder.fold_span(self[0]), folder.fold_span(self[1])] } } impl Spans for [Span; 3] { fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { [ folder.fold_span(self[0]), folder.fold_span(self[1]), folder.fold_span(self[2]), ] } } } #[cfg(feature = "visit")] pub mod visit { use proc_macro2::Span; use visit::Visit; pub fn tokens_helper<'ast, V: Visit<'ast> + ?Sized, S: Spans>( visitor: &mut V, spans: &'ast S, )
pub trait Spans { fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V); } impl Spans for Span { fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { visitor.visit_span(self); } } impl Spans for [Span; 1] { fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { visitor.visit_span(&self[0]); } } impl Spans for [Span; 2] { fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { visitor.visit_span(&self[0]); visitor.visit_span(&self[1]); } } impl Spans for [Span; 3] { fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { visitor.visit_span(&self[0]); visitor.visit_span(&self[1]); visitor.visit_span(&self[2]); } } } #[cfg(feature = "visit-mut")] pub mod visit_mut { use proc_macro2::Span; use visit_mut::VisitMut; pub fn tokens_helper<V: VisitMut + ?Sized, S: Spans>(visitor: &mut V, spans: &mut S) { spans.visit_mut(visitor); } pub trait Spans { fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V); } impl Spans for Span { fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { visitor.visit_span_mut(self); } } impl Spans for [Span; 1] { fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { visitor.visit_span_mut(&mut self[0]); } } impl Spans for [Span; 2] { fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { visitor.visit_span_mut(&mut self[0]); visitor.visit_span_mut(&mut self[1]); } } impl Spans for [Span; 3] { fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { visitor.visit_span_mut(&mut self[0]); visitor.visit_span_mut(&mut self[1]); visitor.visit_span_mut(&mut self[2]); } } }
{ spans.visit(visitor); }
puppeteer.js
const puppeteer = require('puppeteer') // TODO // const pti = require('puppeteer-to-istanbul') // const { copyFile } = require('fs').promises const { log, error, logRaw, logWrite } = require('./log') // wrap our convoluted _run() function in a pure Promise that can handle // both standard throws and the callback that ends it. _run() needs to handle // ends in a few different ways, hence the hack. function run (outputDir, port, timeout, mode, runner, coverage) { return new Promise((resolve, reject) => { _run(outputDir, port, timeout, mode, runner, coverage, (err, errors) => { if (err) { return reject(err) } resolve(errors) }) }) } // this can throw, or it can end via `callback()` which may or may not contain // a runtime-error argument and a "number of errors from tests" argument. // the callback may be triggered by proper test end or failure, or a timeout. async function
(outputDir, port, timeout, mode, runner, coverage, callback) { let executionQueue = Promise.resolve() const browser = await puppeteer.launch({ args: ['--no-sandbox'] }) const [page] = await browser.pages() // this works as a debounce exit method, when process.stdout.write() is used // instead of console.log, the output goes through the stream handling which // inserts delays so log output comes later than an end() signal. If we get // an end(), we delay for a short time and then keep delaying if we get more // output—it should come in steady increments after an end() as we're only // waiting for stream delays, not test delays at that point. let lastCall function end (errors) { lastCall = setTimeout(() => { if (!executionQueue) { error('end after end') return } executionQueue.then(async () => { executionQueue = null /* TODO if (coverage) { const jsCoverage = await page.coverage.stopJSCoverage() pti.write([...jsCoverage]) await copyFile('build/bundle.js.map', '.nyc_output/js/bundle.js.map') } */ await browser.close() }).catch(callback) .then(() => { callback(null, errors) }) }, 100) } function maybeEnd () { if (lastCall) { clearTimeout(lastCall) end() } } // this should be a rare, or impossible event since we intercept console.log page.on('console', (msg) => { if (!executionQueue) { error(`log after end: ${msg.text()}`) return } const args = [] executionQueue = executionQueue.then(async () => { logRaw('info', await Promise.all(args)) }) for (const arg of msg.args()) { args.push(arg.evaluate(n => n)) } maybeEnd() }) page.on('error', (error) => console.error(error)) page.on('pageerror', (error) => console.error(error)) await page.exposeFunction('polendinaEnd', (errors) => { end(errors) }) await page.exposeFunction('polendinaLog', (args) => { logRaw(args.shift(), args) maybeEnd() }) await page.exposeFunction('polendinaWrite', (args) => { logWrite(args) maybeEnd() }) if (coverage) { await page.coverage.startJSCoverage() } const url = `http://localhost:${port}/?mode=${mode}&runner=${runner}` log(`Running ${runner} ${mode} tests with Puppeteer via\n ${url}`) if (runner !== 'mocha') { log() } await page.goto(url) setTimeout(() => { const err = new Error(`timeout: tests did not finish cleanly after ${timeout} seconds`) const cb = () => callback(err) browser.close().then(cb).catch(cb) }, timeout * 1000).unref() } module.exports = run
_run
opf-date.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var xml_js_mapper_1 = require("r2-utils-js/dist/es5/src/_utils/xml-js-mapper"); var MetaDate = (function () { function
() { } tslib_1.__decorate([ xml_js_mapper_1.XmlXPathSelector("text()"), tslib_1.__metadata("design:type", String) ], MetaDate.prototype, "Data", void 0); tslib_1.__decorate([ xml_js_mapper_1.XmlXPathSelector("@event"), tslib_1.__metadata("design:type", String) ], MetaDate.prototype, "Event", void 0); MetaDate = tslib_1.__decorate([ xml_js_mapper_1.XmlObject({ dc: "http://purl.org/dc/elements/1.1/", opf: "http://www.idpf.org/2007/opf", }) ], MetaDate); return MetaDate; }()); exports.MetaDate = MetaDate; //# sourceMappingURL=opf-date.js.map
MetaDate
feature-discovery.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { Routes, RouterModule } from '@angular/router'; import { IonicModule } from '@ionic/angular'; import { FeatureDiscoveryPage } from './feature-discovery.page'; import { FivFeatureDiscoveryModule, FivIconModule } from '@fivethree/core'; const routes: Routes = [ { path: '', component: FeatureDiscoveryPage } ]; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, RouterModule.forChild(routes), FivFeatureDiscoveryModule, FivIconModule ], declarations: [FeatureDiscoveryPage] }) export class
{}
FeatureDiscoveryPageModule
solid.py
from functools import lru_cache, update_wrapper from typing import Any, Callable, Dict, List, NamedTuple, Optional, Sequence, Set, Union, cast from dagster import check from dagster.core.decorator_utils import format_docstring_for_description from dagster.core.errors import DagsterInvalidDefinitionError from dagster.core.types.dagster_type import DagsterTypeKind from dagster.seven import funcsigs from ...decorator_utils import ( get_function_params, get_valid_name_permutations, positional_arg_name_list, ) from ..inference import infer_input_props, infer_output_props from ..input import InputDefinition from ..output import OutputDefinition from ..policy import RetryPolicy from ..solid_definition import SolidDefinition class DecoratedSolidFunction(NamedTuple): """Wrapper around the decorated solid function to provide commonly used util methods""" decorated_fn: Callable[..., Any] @lru_cache(maxsize=1) def has_context_arg(self) -> bool: return is_context_provided(get_function_params(self.decorated_fn)) @lru_cache(maxsize=1) def positional_inputs(self) -> List[str]: params = get_function_params(self.decorated_fn) input_args = params[1:] if self.has_context_arg() else params return positional_arg_name_list(input_args) class NoContextDecoratedSolidFunction(DecoratedSolidFunction): """Wrapper around a decorated solid function, when the decorator does not permit a context parameter (such as lambda_solid). """ @lru_cache(maxsize=1) def has_context_arg(self) -> bool: return False class _Solid: def __init__( self, name: Optional[str] = None, input_defs: Optional[Sequence[InputDefinition]] = None, output_defs: Optional[Sequence[OutputDefinition]] = None, description: Optional[str] = None, required_resource_keys: Optional[Set[str]] = None, config_schema: Optional[Union[Any, Dict[str, Any]]] = None, tags: Optional[Dict[str, Any]] = None, version: Optional[str] = None, decorator_takes_context: Optional[bool] = True, retry_policy: Optional[RetryPolicy] = None, ): self.name = check.opt_str_param(name, "name") self.input_defs = check.opt_list_param(input_defs, "input_defs", InputDefinition) self.output_defs = check.opt_nullable_list_param( output_defs, "output_defs", OutputDefinition ) self.decorator_takes_context = check.bool_param( decorator_takes_context, "decorator_takes_context" ) self.description = check.opt_str_param(description, "description") # these will be checked within SolidDefinition self.required_resource_keys = required_resource_keys self.tags = tags self.version = version self.retry_policy = retry_policy # config will be checked within SolidDefinition self.config_schema = config_schema def __call__(self, fn: Callable[..., Any]) -> SolidDefinition: check.callable_param(fn, "fn") if not self.name: self.name = fn.__name__ if self.output_defs is None: output_defs = [OutputDefinition.create_from_inferred(infer_output_props(fn))] elif len(self.output_defs) == 1: output_defs = [self.output_defs[0].combine_with_inferred(infer_output_props(fn))] else: output_defs = self.output_defs compute_fn = ( DecoratedSolidFunction(decorated_fn=fn) if self.decorator_takes_context else NoContextDecoratedSolidFunction(decorated_fn=fn) ) resolved_input_defs = resolve_checked_solid_fn_inputs( decorator_name="@solid", fn_name=self.name, compute_fn=compute_fn, explicit_input_defs=self.input_defs, exclude_nothing=True, ) solid_def = SolidDefinition( name=self.name, input_defs=resolved_input_defs, output_defs=output_defs, compute_fn=compute_fn, config_schema=self.config_schema, description=self.description or format_docstring_for_description(fn), required_resource_keys=self.required_resource_keys, tags=self.tags, version=self.version, retry_policy=self.retry_policy, ) update_wrapper(solid_def, compute_fn.decorated_fn) return solid_def def solid( name: Union[Callable[..., Any], Optional[str]] = None, description: Optional[str] = None, input_defs: Optional[Sequence[InputDefinition]] = None, output_defs: Optional[Sequence[OutputDefinition]] = None, config_schema: Optional[Union[Any, Dict[str, Any]]] = None, required_resource_keys: Optional[Set[str]] = None, tags: Optional[Dict[str, Any]] = None, version: Optional[str] = None, retry_policy: Optional[RetryPolicy] = None, ) -> Union[_Solid, SolidDefinition]: """Create a solid with the specified parameters from the decorated function. This shortcut simplifies the core :class:`SolidDefinition` API by exploding arguments into kwargs of the decorated compute function and omitting additional parameters when they are not needed. Input and output definitions will be inferred from the type signature of the decorated function if not explicitly provided. The decorated function will be used as the solid's compute function. The signature of the decorated function is more flexible than that of the ``compute_fn`` in the core API; it may: 1. Return a value. This value will be wrapped in an :py:class:`Output` and yielded by the compute function. 2. Return an :py:class:`Output`. This output will be yielded by the compute function. 3. Yield :py:class:`Output` or other :ref:`event objects <events>`. Same as default compute behavior. Note that options 1) and 2) are incompatible with yielding other events -- if you would like to decorate a function that yields events, it must also wrap its eventual output in an :py:class:`Output` and yield it. @solid supports ``async def`` functions as well, including async generators when yielding multiple events or outputs. Note that async solids will generally be run on their own unless using a custom :py:class:`Executor` implementation that supports running them together. Args: name (Optional[str]): Name of solid. Must be unique within any :py:class:`PipelineDefinition` using the solid. description (Optional[str]): Human-readable description of this solid. If not provided, and the decorated function has docstring, that docstring will be used as the description. input_defs (Optional[List[InputDefinition]]): Information about the inputs to the solid. Information provided here will be combined with what can be inferred from the function signature, with these explicit InputDefinitions taking precedence. output_defs (Optional[List[OutputDefinition]]): Information about the solids outputs. Information provided here will be combined with what can be inferred from the return type signature if there is only one OutputDefinition and the function does not use yield. config_schema (Optional[ConfigSchema): The schema for the config. If set, Dagster will check that config provided for the solid matches this schema and fail if it does not. If not set, Dagster will accept any config provided for the solid. required_resource_keys (Optional[Set[str]]): Set of resource handles required by this solid. tags (Optional[Dict[str, Any]]): Arbitrary metadata for the solid. Frameworks may expect and require certain metadata to be attached to a solid. Values that are not strings will be json encoded and must meet the criteria that `json.loads(json.dumps(value)) == value`. version (Optional[str]): (Experimental) The version of the solid's compute_fn. Two solids should have the same version if and only if they deterministically produce the same outputs when provided the same inputs. retry_policy (Optional[RetryPolicy]): The retry policy for this solid. Examples: .. code-block:: python @solid def hello_world(): print('hello') @solid def hello_world(): return {'foo': 'bar'} @solid def hello_world(): return Output(value={'foo': 'bar'}) @solid def hello_world(): yield Output(value={'foo': 'bar'}) @solid def hello_world(foo): return foo @solid( input_defs=[InputDefinition(name="foo", str)], output_defs=[OutputDefinition(str)] ) def hello_world(foo): # explicitly type and name inputs and outputs return foo @solid def hello_world(foo: str) -> str: # same as above inferred from signature return foo @solid def hello_world(context, foo): context.log.info('log something') return foo @solid( config_schema={'str_value' : Field(str)} ) def hello_world(context, foo): # context.solid_config is a dictionary with 'str_value' key return foo + context.solid_config['str_value']
check.invariant(input_defs is None) check.invariant(output_defs is None) check.invariant(description is None) check.invariant(config_schema is None) check.invariant(required_resource_keys is None) check.invariant(tags is None) check.invariant(version is None) return _Solid()(name) return _Solid( name=name, input_defs=input_defs, output_defs=output_defs, config_schema=config_schema, description=description, required_resource_keys=required_resource_keys, tags=tags, version=version, retry_policy=retry_policy, ) def resolve_checked_solid_fn_inputs( decorator_name: str, fn_name: str, compute_fn: DecoratedSolidFunction, explicit_input_defs: List[InputDefinition], exclude_nothing: bool, ) -> List[InputDefinition]: """ Validate provided input definitions and infer the remaining from the type signature of the compute_fn. Returns the resolved set of InputDefinitions. Args: decorator_name (str): Name of the decorator that is wrapping the solid function. fn_name (str): Name of the decorated function. compute_fn (DecoratedSolidFunction): The decorated function, wrapped in the DecoratedSolidFunction wrapper. explicit_input_defs (List[InputDefinition]): The input definitions that were explicitly provided in the decorator. exclude_nothing (bool): True if Nothing type inputs should be excluded from compute_fn arguments. """ if exclude_nothing: explicit_names = set( inp.name for inp in explicit_input_defs if not inp.dagster_type.kind == DagsterTypeKind.NOTHING ) nothing_names = set( inp.name for inp in explicit_input_defs if inp.dagster_type.kind == DagsterTypeKind.NOTHING ) else: explicit_names = set(inp.name for inp in explicit_input_defs) nothing_names = set() params = get_function_params(compute_fn.decorated_fn) input_args = params[1:] if compute_fn.has_context_arg() else params # Validate input arguments used_inputs = set() inputs_to_infer = set() has_kwargs = False for param in cast(List[funcsigs.Parameter], input_args): if param.kind == funcsigs.Parameter.VAR_KEYWORD: has_kwargs = True elif param.kind == funcsigs.Parameter.VAR_POSITIONAL: raise DagsterInvalidDefinitionError( f"{decorator_name} '{fn_name}' decorated function has positional vararg parameter " f"'{param}'. {decorator_name} decorated functions should only have keyword " "arguments that match input names and, if system information is required, a first " "positional parameter named 'context'." ) else: if param.name not in explicit_names: if param.name in nothing_names: raise DagsterInvalidDefinitionError( f"{decorator_name} '{fn_name}' decorated function has parameter '{param.name}' that is " "one of the input_defs of type 'Nothing' which should not be included since " "no data will be passed for it. " ) else: inputs_to_infer.add(param.name) else: used_inputs.add(param.name) undeclared_inputs = explicit_names - used_inputs if not has_kwargs and undeclared_inputs: undeclared_inputs_printed = ", '".join(undeclared_inputs) raise DagsterInvalidDefinitionError( f"{decorator_name} '{fn_name}' decorated function does not have parameter(s) " f"'{undeclared_inputs_printed}', which are in provided input_defs. {decorator_name} " "decorated functions should only have keyword arguments that match input names and, if " "system information is required, a first positional parameter named 'context'." ) inferred_props = { inferred.name: inferred for inferred in infer_input_props(compute_fn.decorated_fn, compute_fn.has_context_arg()) } input_defs = [] for input_def in explicit_input_defs: if input_def.name in inferred_props: # combine any information missing on the explicit def that can be inferred input_defs.append(input_def.combine_with_inferred(inferred_props[input_def.name])) else: # pass through those that don't have any inference info, such as Nothing type inputs input_defs.append(input_def) # build defs from the inferred props for those without explicit entries input_defs.extend( InputDefinition.create_from_inferred(inferred) for inferred in inferred_props.values() if inferred.name in inputs_to_infer ) return input_defs def is_context_provided(params: List[funcsigs.Parameter]) -> bool: if len(params) == 0: return False return params[0].name in get_valid_name_permutations("context") def lambda_solid( name: Union[Optional[str], Callable[..., Any]] = None, description: Optional[str] = None, input_defs: Optional[List[InputDefinition]] = None, output_def: Optional[OutputDefinition] = None, ) -> Union[_Solid, SolidDefinition]: """Create a simple solid from the decorated function. This shortcut allows the creation of simple solids that do not require configuration and whose implementations do not require a :py:class:`context <SolidExecutionContext>`. Lambda solids take any number of inputs and produce a single output. Inputs can be defined using :class:`InputDefinition` and passed to the ``input_defs`` argument of this decorator, or inferred from the type signature of the decorated function. The single output can be defined using :class:`OutputDefinition` and passed as the ``output_def`` argument of this decorator, or its type can be inferred from the type signature of the decorated function. The body of the decorated function should return a single value, which will be yielded as the solid's output. Args: name (str): Name of solid. description (str): Solid description. input_defs (List[InputDefinition]): List of input_defs. output_def (OutputDefinition): The output of the solid. Defaults to :class:`OutputDefinition() <OutputDefinition>`. Examples: .. code-block:: python @lambda_solid def hello_world(): return 'hello' @lambda_solid( input_defs=[InputDefinition(name='foo', str)], output_def=OutputDefinition(str) ) def hello_world(foo): # explicitly type and name inputs and outputs return foo @lambda_solid def hello_world(foo: str) -> str: # same as above inferred from signature return foo """ if callable(name): check.invariant(input_defs is None) check.invariant(description is None) return _Solid( output_defs=[output_def] if output_def else None, decorator_takes_context=False )(name) return _Solid( name=name, input_defs=input_defs, output_defs=[output_def] if output_def else None, description=description, decorator_takes_context=False, )
""" # This case is for when decorator is used bare, without arguments. e.g. @solid versus @solid() if callable(name):
lib.rs
#![doc = "generated by AutoRust 0.1.0"] #[cfg(feature = "package-2020-07-01-preview")] mod package_2020_07_01_preview; #[cfg(feature = "package-2020-07-01-preview")] pub use package_2020_07_01_preview::{models, operations, API_VERSION}; #[cfg(feature = "package-2020-07-01")] mod package_2020_07_01; use azure_core::setters; #[cfg(feature = "package-2020-07-01")] pub use package_2020_07_01::{models, operations, API_VERSION}; pub fn config( http_client: std::sync::Arc<dyn azure_core::HttpClient>, token_credential: Box<dyn azure_core::TokenCredential>, ) -> OperationConfigBuilder { OperationConfigBuilder { api_version: None, http_client, base_path: None, token_credential, token_credential_resource: None, } } pub struct OperationConfigBuilder { api_version: Option<String>, http_client: std::sync::Arc<dyn azure_core::HttpClient>, base_path: Option<String>, token_credential: Box<dyn azure_core::TokenCredential>, token_credential_resource: Option<String>, } impl OperationConfigBuilder { setters! { api_version : String => Some (api_version) , base_path : String => Some (base_path) , token_credential_resource : String => Some (token_credential_resource) , } pub fn build(self) -> OperationConfig { OperationConfig { api_version: self.api_version.unwrap_or(API_VERSION.to_owned()), http_client: self.http_client, base_path: self.base_path.unwrap_or("https://management.azure.com".to_owned()), token_credential: Some(self.token_credential), token_credential_resource: self.token_credential_resource.unwrap_or("https://management.azure.com/".to_owned()), } } } pub struct OperationConfig { api_version: String, http_client: std::sync::Arc<dyn azure_core::HttpClient>, base_path: String, token_credential: Option<Box<dyn azure_core::TokenCredential>>, token_credential_resource: String, } impl OperationConfig { pub fn api_version(&self) -> &str { self.api_version.as_str() } pub fn http_client(&self) -> &dyn azure_core::HttpClient { self.http_client.as_ref() } pub fn base_path(&self) -> &str
pub fn token_credential(&self) -> Option<&dyn azure_core::TokenCredential> { self.token_credential.as_deref() } pub fn token_credential_resource(&self) -> &str { self.token_credential_resource.as_str() } }
{ self.base_path.as_str() }
codigo.js
//Creacion de Tablas function personTable() { var table = document.getElementById("personTable"); var tbody = document.createElement("tbody"); tbody.setAttribute("id", "body"); table.appendChild(tbody); var i = 0; var j = 0; let token = window.localStorage.getItem("token"); let role = window.localStorage.getItem("role"); $.ajax({ type: "GET", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', success: function (data) { for (i; i < data.persons.length; i++) { var tr = document.createElement("tr"); tbody.appendChild(tr); tr.setAttribute("class", "dato"); tr.setAttribute("id", "dato" + i); var td = document.createElement("td"); td.setAttribute("id", "nodo" + j++); tr.appendChild(td); var text = document.createTextNode(data.persons[i].person.name); var a = document.createElement("a"); td.appendChild(a); a.appendChild(text); a.setAttribute("href", "mostrarAutor.html"); a.setAttribute("onclick", "guardarSeleccion(event)"); } } }); if (role == "writer") { var tr = document.createElement("tr"); tbody.appendChild(tr); tr.setAttribute("class", "dato"); tr.setAttribute("id", "dato" + i); var td = document.createElement("td"); td.setAttribute("id", "nodo" + j++); tr.appendChild(td); var input = document.createElement("input"); input.setAttribute("type", "button"); input.setAttribute("value", "Crear"); input.setAttribute("onclick", "location.href='nuevoAutor.html'"); td.appendChild(input); } } function entityTable() { var table = document.getElementById("entityTable"); var tbody = document.createElement("tbody"); tbody.setAttribute("id", "body"); table.appendChild(tbody); var i = 0; var j = 0; let token = window.localStorage.getItem("token"); $.ajax({ type: "GET", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', success: function (data) { for (var i = 0; i < data.entities.length; i++) { var tr = document.createElement("tr"); tbody.appendChild(tr); tr.setAttribute("class", "dato"); tr.setAttribute("id", "dato" + i); var td = document.createElement("td"); td.setAttribute("id", "nodo" + j++); tr.appendChild(td); var text = document.createTextNode(data.entities[i].entity.name); var a = document.createElement("a"); td.appendChild(a); a.appendChild(text); a.setAttribute("href", "mostrarEntidad.html"); a.setAttribute("onclick", "guardarSeleccion(event)"); } } }); let role = window.localStorage.getItem("role"); if (role == "writer") { var tr = document.createElement("tr"); tbody.appendChild(tr); tr.setAttribute("class", "dato"); tr.setAttribute("id", "dato" + i); var td = document.createElement("td"); td.setAttribute("id", "nodo" + j++); tr.appendChild(td); var input = document.createElement("input"); input.setAttribute("type", "button"); input.setAttribute("value", "Crear"); input.setAttribute("onclick", "location.href='nuevoEntidad.html'"); td.appendChild(input); } } function productTable() { var table = document.getElementById("productTable"); var tbody = document.createElement("tbody"); tbody.setAttribute("id", "body"); table.appendChild(tbody); var i = 0; var j = 0; let token = window.localStorage.getItem("token"); $.ajax({ type: "GET", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', success: function (data) { for (var i = 0; i < data.products.length; i++) { var tr = document.createElement("tr"); tbody.appendChild(tr); tr.setAttribute("class", "dato"); tr.setAttribute("id", "dato" + i); var td = document.createElement("td"); td.setAttribute("id", "nodo" + j++); tr.appendChild(td); var text = document.createTextNode(data.products[i].product.name); var a = document.createElement("a"); td.appendChild(a); a.appendChild(text); a.setAttribute("href", "mostrarProducto.html"); a.setAttribute("onclick", "guardarSeleccion(event)"); } } }); let role = window.localStorage.getItem("role"); if (role == "writer") { var tr = document.createElement("tr"); tbody.appendChild(tr); tr.setAttribute("class", "dato"); tr.setAttribute("id", "dato" + i); var td = document.createElement("td"); td.setAttribute("id", "nodo" + j++); tr.appendChild(td); var input = document.createElement("input"); input.setAttribute("type", "button"); input.setAttribute("value", "Crear"); input.setAttribute("onclick", "location.href='nuevoProducto.html'"); td.appendChild(input); } } //Guardar Token function saveToken(token) { var name = document.getElementById("username").value; window.localStorage.setItem("name", name); window.localStorage.setItem("token", token); $.ajax({ type: "GET", url: '/api/v1/users', headers: {"Authorization": token}, dataType: 'json', success: function (data) { var index = data.users.map(function (x) { return x.user.username }).indexOf((name)); var role = data.users[index].user.role; var active = data.users[index].user.active; if (active == 0) { alert("Cuenta no activada") } else { window.localStorage.setItem("role", role); window.location.replace("./main.html"); } } }); } //Estar loggeado function loggedIn() { var name = window.localStorage.getItem("name"); var form = document.getElementById("form-login"); var label = document.createElement("label"); var text = document.createTextNode("Usuario " + name + ", bienvenido "); label.appendChild(text); var input = document.createElement("input"); input.setAttribute("type", "button"); input.setAttribute("value", "Perfil"); input.setAttribute("onclick", "location.href='perfil.html'"); label.appendChild(input); form.appendChild(label); var input = document.createElement("input"); input.setAttribute("type", "button"); input.setAttribute("id", "btn-logout"); input.setAttribute("value", "Logout"); input.setAttribute("onclick", "logout()"); form.appendChild(input); personTable(); entityTable(); productTable(); window.localStorage.setItem("seleccion", "-1"); } //Logout function logout() { window.localStorage.setItem("name", null); window.localStorage.setItem("token", null); window.localStorage.setItem("role", null); window.location.replace("./index.html"); } //Guardar item seleccionado function guardarSeleccion(event) { var seleccion = event.target.innerHTML; window.localStorage.setItem("seleccion", seleccion); } //Mostrar item function showEntity() { let role = window.localStorage.getItem("role"); let token = window.localStorage.getItem("token"); $.ajax({ type: "GET", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', success: function (data) { var seleccion = window.localStorage.getItem("seleccion"); var index = data.entities.map(function (x) { return x.entity.name }).indexOf((seleccion)); var body = document.getElementById("body"); var h1 = document.createElement("h1"); var text = document.createTextNode(data.entities[index].entity.name); h1.setAttribute("class", "Title"); h1.appendChild(text); body.appendChild(h1); var ul = document.createElement("ul"); var li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Inicio"); li.appendChild(a); a.appendChild(text); a.setAttribute("href", "main.html"); ul.appendChild(li); if (role == "writer") { li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Editar"); a.setAttribute("href", "nuevoEntidad.html"); a.setAttribute("onclick", "updateEntity()"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Editar Relaciones"); a.setAttribute("href", "editEntityRelation.html"); a.setAttribute("onclick", "editEntityRelation()"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); li = document.createElement("li"); a = document.createElement("a"); text = document.createTextNode("Borrar"); a.setAttribute("href", "main.html"); a.setAttribute("onclick", "deleteEntity()"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); } body.appendChild(ul); var img = document.createElement("img"); img.setAttribute("class", "autor"); img.setAttribute("src", data.entities[index].entity.imageUrl); img.setAttribute("alt", "logo"); img.setAttribute("onerror", onerror = "this.src='altImage.png'"); body.appendChild(img); var p = document.createElement("p"); text = document.createTextNode("Nombre: " + data.entities[index].entity.name); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Fecha de Nacimiento: " + data.entities[index].entity.birthDate); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Fecha de Defunción: " + data.entities[index].entity.deathDate); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Autores relacionados: " + data.entities[index].entity.persons); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Productos relacionados: " + data.entities[index].entity.products); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Wiki Url"); var a = document.createElement("a"); a.setAttribute("href", data.entities[index].entity.wikiUrl); a.appendChild(text); p.appendChild(a); body.appendChild(p); } }); } function showProduct() { let role = window.localStorage.getItem("role"); let token = window.localStorage.getItem("token"); $.ajax({ type: "GET", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', success: function (data) { var seleccion = window.localStorage.getItem("seleccion"); var index = data.products.map(function (x) { return x.product.name }).indexOf((seleccion)); var body = document.getElementById("body"); var h1 = document.createElement("h1"); var text = document.createTextNode(data.products[index].product.name); h1.setAttribute("class", "Title"); h1.appendChild(text); body.appendChild(h1); var ul = document.createElement("ul"); var li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Inicio"); li.appendChild(a); a.appendChild(text); a.setAttribute("href", "main.html"); ul.appendChild(li); if (role == "writer") { li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Editar"); a.setAttribute("href", "nuevoProducto.html"); a.setAttribute("onclick", "updateProduct()"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Editar Relaciones"); a.setAttribute("href", "editPrRelation.html"); a.setAttribute("onclick", "editProductRelation.html()"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); li = document.createElement("li"); a = document.createElement("a"); text = document.createTextNode("Borrar"); a.setAttribute("href", "main.html"); a.setAttribute("onclick", "deleteProduct()"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); } body.appendChild(ul); var img = document.createElement("img"); img.setAttribute("class", "autor"); img.setAttribute("src", data.products[index].product.imageUrl); img.setAttribute("alt", "logo"); img.setAttribute("onerror", onerror = "this.src='altImage.png'"); body.appendChild(img); var p = document.createElement("p"); text = document.createTextNode("Nombre: " + data.products[index].product.name); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Fecha de Nacimiento: " + data.products[index].product.birthDate); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Fecha de Defunción: " + data.products[index].product.deathDate); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Autores relacionados: " + data.products[index].product.persons); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Entidades relacionados: " + data.products[index].product.entities); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Wiki Url"); var a = document.createElement("a"); a.setAttribute("href", data.products[index].product.wikiUrl); a.appendChild(text); p.appendChild(a); body.appendChild(p); } }); } function showPerson() { let role = window.localStorage.getItem("role"); let token = window.localStorage.getItem("token"); $.ajax({ type: "GET", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', success: function (data) { var seleccion = window.localStorage.getItem("seleccion"); var index = data.persons.map(function (x) { return x.person.name }).indexOf((seleccion)); var body = document.getElementById("body"); var h1 = document.createElement("h1"); var text = document.createTextNode(data.persons[index].person.name); h1.setAttribute("class", "Title"); h1.appendChild(text); body.appendChild(h1); var ul = document.createElement("ul"); var li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Inicio"); li.appendChild(a); a.appendChild(text); a.setAttribute("href", "main.html"); ul.appendChild(li); if (role == "writer") { li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Editar"); a.setAttribute("href", "nuevoAutor.html"); a.setAttribute("onclick", "updatePerson()"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Editar Relaciones"); a.setAttribute("href", "editPersonRelation.html"); a.setAttribute("onclick", "editPersonRelation()"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); li = document.createElement("li"); a = document.createElement("a"); text = document.createTextNode("Borrar"); a.setAttribute("href", "main.html"); a.setAttribute("onclick", "deletePerson()"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); } body.appendChild(ul); var img = document.createElement("img"); img.setAttribute("class", "autor"); img.setAttribute("src", data.persons[index].person.imageUrl); img.setAttribute("alt", "logo"); img.setAttribute("onerror", onerror = "this.src='altImage.png'"); body.appendChild(img); var p = document.createElement("p"); text = document.createTextNode("Nombre: " + data.persons[index].person.name); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Fecha de Nacimiento: " + data.persons[index].person.birthDate); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Fecha de Defunción: " + data.persons[index].person.deathDate); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Entidades relacionados: " + data.persons[index].person.entities); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Productos relacionados: " + data.persons[index].person.products); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Wiki Url: "); var a = document.createElement("a"); a.setAttribute("href", data.persons[index].person.wikiUrl); a.appendChild(text); p.appendChild(a); body.appendChild(p); } }); } //Actualizar item function updatePerson() { let token = window.localStorage.getItem("token"); var seleccion = window.localStorage.getItem("seleccion"); if (seleccion == -1) { editPerson(0, 0); } else { $.ajax({ type: "GET", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', success: function (data) { var index = data.persons.map(function (x) { return x.person.name }).indexOf((seleccion)); editPerson(1, index); } }); } } function updateEntity() { let token = window.localStorage.getItem("token"); var seleccion = window.localStorage.getItem("seleccion"); if (seleccion == -1) { editEntity(0, 0); } else { $.ajax({ type: "GET", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', success: function (data) { var index = data.entities.map(function (x) { return x.entity.name }).indexOf((seleccion)); editEntity(1, index); } }); } } function updateProduct() { let token = window.localStorage.getItem("token"); var seleccion = window.localStorage.getItem("seleccion"); if (seleccion == -1) { editEntity(0, 0); } else { $.ajax({ type: "GET", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', success: function (data) { var index = data.products.map(function (x) { return x.product.name }).indexOf((seleccion)); editProduct(1, index); } }); } } //Editar item function editPerson(x, y) { let token = window.localStorage.getItem("token"); if (x == 0) { } else { $.ajax({ type: "GET", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', success: function (data) { document.getElementById("name").value = data.persons[y].person.name; document.getElementById("birthDate").value = data.persons[y].person.birthDate; document.getElementById("deathDate").value = data.persons[y].person.deathDate; document.getElementById("imageUrl").value = data.persons[y].person.imageUrl; document.getElementById("wikiUrl").value = data.persons[y].person.wikiUrl; } }); } } function editEntity(x, y) { let token = window.localStorage.getItem("token"); if (x == 0) { } else { $.ajax({ type: "GET", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', success: function (data) { document.getElementById("name").value = data.entities[y].entity.name; document.getElementById("birthDate").value = data.entities[y].entity.birthDate; document.getElementById("deathDate").value = data.entities[y].entity.deathDate; document.getElementById("imageUrl").value = data.entities[y].entity.imageUrl; document.getElementById("wikiUrl").value = data.entities[y].entity.wikiUrl; } }); } } function editProduct(x, y) { let token = window.localStorage.getItem("token"); if (x == 0) { } else { $.ajax({ type: "GET", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', success: function (data) { document.getElementById("name").value = data.products[y].product.name; document.getElementById("birthDate").value = data.products[y].product.birthDate; document.getElementById("deathDate").value = data.products[y].product.deathDate; document.getElementById("imageUrl").value = data.products[y].product.imageUrl; document.getElementById("wikiUrl").value = data.products[y].product.wikiUrl; } }); } } //Guardar item function idFind(type) { let token = window.localStorage.getItem("token"); var seleccion = window.localStorage.getItem("seleccion"); if (type == "person") { $.ajax({ type: "GET", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { var index = data.persons.map(function (x) { return x.person.name }).indexOf((seleccion)); var id = data.persons[index].person.id; idFindAux(id); } }); } else if (type == "entity") { $.ajax({ type: "GET", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { var index = data.entities.map(function (x) { return x.entity.name }).indexOf((seleccion)); var id = data.entities[index].entity.id; idFindAux(id); } }); } else if (type == "product") { $.ajax({ type: "GET", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { var index = data.products.map(function (x) { return x.product.name }).indexOf((seleccion)); var id = data.products[index].product.id; idFindAux(id); } }); } } function idFindAux(id) { window.localStorage.setItem("id", id); } function savePerson() { var nameA = document.getElementById("name").value; var birthDateA = document.getElementById("birthDate").value; var deathDateA = document.getElementById("deathDate").value; var imageUrlA = document.getElementById("imageUrl").value; var wikiUrlA = document.getElementById("wikiUrl").value; var seleccion = window.localStorage.getItem("seleccion"); var token = window.localStorage.getItem("token"); var autor; if (birthDateA == '' || deathDateA == '') { if (birthDateA == '' && deathDateA != '') { autor = { name: nameA, birthDate: birthDateA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } else if (birthDateA != '' && deathDateA == '') { autor = { name: nameA, deathDate: deathDateA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } else { autor = { name: nameA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } } else { autor = { name: nameA, birthDate: birthDateA, deathDate: deathDateA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } if (seleccion == -1) { $.ajax({ type: "POST", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', data: autor, success: function (data, status, response) { alert("Datos guardados"); } }) } else { idFind("person") var id = window.localStorage.getItem("id"); console.log(id); $.ajax({ type: "PUT", url: '/api/v1/persons/' + id, headers: {"Authorization": token}, dataType: 'json', data: autor, success: function (data, status, response) { alert("Datos guardados"); } }); } } function saveEntity() { var nameA = document.getElementById("name").value; var birthDateA = document.getElementById("birthDate").value; var deathDateA = document.getElementById("deathDate").value; var imageUrlA = document.getElementById("imageUrl").value; var wikiUrlA = document.getElementById("wikiUrl").value; var seleccion = window.localStorage.getItem("seleccion"); var token = window.localStorage.getItem("token"); var autor; if (birthDateA == '' || deathDateA == '') { if (birthDateA == '' && deathDateA != '') { autor = { name: nameA, birthDate: birthDateA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } else if (birthDateA != '' && deathDateA == '') { autor = { name: nameA, deathDate: deathDateA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } else { autor = { name: nameA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } } else { autor = { name: nameA, birthDate: birthDateA, deathDate: deathDateA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } if (seleccion == -1) { $.ajax({ type: "POST", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', data: autor, success: function (data, status, response) { alert("Datos guardados"); } }) } else { idFind("entity") var id = window.localStorage.getItem("id"); console.log(id); $.ajax({ type: "PUT", url: '/api/v1/entities/' + id, headers: {"Authorization": token}, dataType: 'json', data: autor, success: function (data, status, response) { alert("Datos guardados"); } }) } } function saveProduct() { var nameA = document.getElementById("name").value; var birthDateA = document.getElementById("birthDate").value; var deathDateA = document.getElementById("deathDate").value; var imageUrlA = document.getElementById("imageUrl").value; var wikiUrlA = document.getElementById("wikiUrl").value; var seleccion = window.localStorage.getItem("seleccion"); var token = window.localStorage.getItem("token"); var autor; if (birthDateA == '' || deathDateA == '') { if (birthDateA == '' && deathDateA != '') { autor = { name: nameA, birthDate: birthDateA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } else if (birthDateA != '' && deathDateA == '') { autor = { name: nameA, deathDate: deathDateA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } else { autor = { name: nameA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } } else { autor = { name: nameA, birthDate: birthDateA, deathDate: deathDateA, imageUrl: imageUrlA, wikiUrl: wikiUrlA, } } if (seleccion == -1) { $.ajax({ type: "POST", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', data: autor, success: function (data, status, response) { alert("Datos guardados"); } }) } else { idFind("product") var id = window.localStorage.getItem("id"); console.log(id); $.ajax({ type: "PUT", url: '/api/v1/products/' + id, headers: {"Authorization": token}, dataType: 'json', data: autor, success: function (data, status, response) { alert("Datos guardados"); } }) } } function deletePerson() { var result = confirm("¿Desea borrar este elemento?"); if (result) { var token = window.localStorage.getItem("token"); idFind("person") var id = window.localStorage.getItem("id"); console.log(id); $.ajax({ type: "delete", url: '/api/v1/persons/' + id, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Eliminación completada"); } }) } } function deleteEntity() { var result = confirm("¿Desea borrar este elemento?"); if (result) { var token = window.localStorage.getItem("token"); idFind("entity") var id = window.localStorage.getItem("id"); console.log(id); $.ajax({ type: "delete", url: '/api/v1/entities/' + id, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Eliminación completada"); } }) } } function deleteProduct() { var result = confirm("¿Desea borrar este elemento?"); if (result) { var token = window.localStorage.getItem("token"); idFind("product") var id = window.localStorage.getItem("id"); console.log(id); $.ajax({ type: "delete", url: '/api/v1/products/' + id, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Eliminación completada"); } }) } } function check() { $.ajax({ type: "get", url: '/api/v1/users/username/' + document.getElementById("username").value, dataType: 'json', success: function (data, status, response) { alert("Username already exists"); }, error: function (data) { var username = document.getElementById("username").value; var password = document.getElementById("password").value; window.localStorage.setItem("username", username); window.localStorage.setItem("password", password); window.location.replace("./register2.html"); } }) } function loadRegisterData() { document.getElementById("username").value = window.localStorage.getItem("username"); document.getElementById("password").value = window.localStorage.getItem("password"); } function showPassword() { var x = document.getElementById("password"); if (x.type === "password") { x.type = "text"; } else { x.type = "password"; } } function registerAccount() { let authHeader = null; var username = document.getElementById("username").value; var password = document.getElementById("password").value; var email = document.getElementById("email").value; var firstname = document.getElementById("firstname").value; var lastname = document.getElementById("lastname").value; var birthDate = document.getElementById("birthDate").value; var user = { username: username, password: password, email: email, role: "reader", active: 0, firstname: firstname, lastname: lastname, birthDate: birthDate } $.ajax({ type: "POST", url: '/api/v1/users', dataType: 'json', data: user, async: false, success: (function (data, status, response) { alert("Usuario registrado"); window.location.replace("./index.html"); }), error(e) { alert("Correo ya existente, prueba con otro"); window.location.replace("./register2.html"); } }) } function showProfile() { let role = window.localStorage.getItem("role"); let token = window.localStorage.getItem("token"); $.ajax({ type: "GET", url: '/api/v1/users', headers: {"Authorization": token}, dataType: 'json', success: function (data) { var seleccion = window.localStorage.getItem("name"); var index = data.users.map(function (x) { return x.user.username }).indexOf((seleccion)); var body = document.getElementById("body"); var h1 = document.createElement("h1"); var text = document.createTextNode("Perfil"); h1.setAttribute("class", "Title"); h1.appendChild(text); body.appendChild(h1); var ul = document.createElement("ul"); var li = document.createElement("li"); var a = document.createElement("a"); text = document.createTextNode("Inicio"); li.appendChild(a); a.appendChild(text); a.setAttribute("href", "main.html"); ul.appendChild(li); li = document.createElement("li"); a = document.createElement("a"); text = document.createTextNode("Editar Perfil"); a.setAttribute("href", "editperfil.html"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); if (role == "writer") { li = document.createElement("li"); a = document.createElement("a"); text = document.createTextNode("Administrar"); a.setAttribute("href", "admin.html"); li.appendChild(a); a.appendChild(text); ul.appendChild(li); } body.appendChild(ul); var p = document.createElement("p"); text = document.createTextNode("ID: " + data.users[index].user.id); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Username: " + data.users[index].user.username); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Nombre: " + data.users[index].user.firstname); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Apellidos: " + data.users[index].user.lastname); p.appendChild(text); body.appendChild(p); p = document.createElement("p"); text = document.createTextNode("Fecha de nacimiento: " + data.users[index].user.birthdate); p.appendChild(text); body.appendChild(p); } }); } function editProfi
let token = window.localStorage.getItem("token"); $.ajax({ type: "GET", url: '/api/v1/users', headers: {"Authorization": token}, dataType: 'json', success: function (data) { document.getElementById("username").value = data.users[y].user.username; document.getElementById("password").value document.getElementById("email").value = data.users[y].user.email; document.getElementById("firstname").value = data.users[y].user.firstname; document.getElementById("lastname").value = data.users[y].user.lastname; document.getElementById("birthDate").value = data.users[y].user.birthDate; } }); } function updateProfile() { let token = window.localStorage.getItem("token"); var seleccion = window.localStorage.getItem("name"); $.ajax({ type: "GET", url: '/api/v1/users', headers: {"Authorization": token}, dataType: 'json', success: function (data) { var index = data.users.map(function (x) { return x.user.username }).indexOf((seleccion)); editProfile(index); } }); } function saveProfile() { var usernameA = document.getElementById("username").value; var passwordA = document.getElementById("password").value; var emailA = document.getElementById("email").value; var firstnameA = document.getElementById("firstname").value; var lastnameA = document.getElementById("lastname").value; var birthDateA = document.getElementById("birthDate").value; var autor; let token = window.localStorage.getItem("token"); if (birthDateA == '') { autor = { username: usernameA, password: passwordA, email: emailA, firstname: firstnameA, lastname: lastnameA, } } else { autor = { username: usernameA, password: passwordA, email: emailA, firstname: firstnameA, lastname: lastnameA, birthDate: birthDateA, } } useridFind(); var id = window.localStorage.getItem("id"); console.log(id); $.ajax({ type: "PUT", url: '/api/v1/users/' + id, headers: {"Authorization": token}, dataType: 'json', data: autor, success: function (data, status, response) { window.localStorage.setItem("name", usernameA); alert("Datos guardados"); window.location.replace("./perfil.html"); }, error: function (jqXHR) { if (jqXHR.status === 400) { alert("nombre o email ya existente"); } } }); } function useridFind() { let token = window.localStorage.getItem("token"); var username = window.localStorage.getItem("name"); $.ajax({ type: "GET", url: '/api/v1/users', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { var index = data.users.map(function (x) { return x.user.username }).indexOf((username)); console.log(index); var id = data.users[index].user.id; idFindAux(id); } }); } function loadUsers() { var table = document.getElementById("userTable"); var tbody = document.createElement("tbody"); var label = document.createElement("label"); var input = document.createElement("input"); var span = document.createElement("span"); table.appendChild(tbody); let token = window.localStorage.getItem("token"); var i = 0; var j = 0; $.ajax({ type: "GET", url: '/api/v1/users', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (i; i < data.users.length; i++) { var tr = document.createElement("tr"); tbody.appendChild(tr); var td = document.createElement("td"); tr.appendChild(td); var text = document.createTextNode(data.users[i].user.id); td.appendChild(text); td = document.createElement("td"); tr.appendChild(td); text = document.createTextNode(data.users[i].user.username); td.appendChild(text); td = document.createElement("td"); tr.appendChild(td); text = document.createTextNode(data.users[i].user.email); td.appendChild(text); td = document.createElement("td"); tr.appendChild(td); text = document.createTextNode(data.users[i].user.firstname); td.appendChild(text); td = document.createElement("td"); tr.appendChild(td); text = document.createTextNode(data.users[i].user.lastname); td.appendChild(text); td = document.createElement("td"); tr.appendChild(td); text = document.createTextNode(data.users[i].user.birthDate); td.appendChild(text); td = document.createElement("td"); tr.appendChild(td); input = document.createElement("input"); input.setAttribute("type", "checkbox"); if (data.users[i].user.role == "writer") { input.checked = true; } input.setAttribute("onclick", "updateUser(" + data.users[i].user.id + "," + 0 + ")"); span.setAttribute("class", "slider round"); label = document.createElement("label"); label.appendChild(input); label.appendChild(span); td.appendChild(label); td = document.createElement("td"); tr.appendChild(td); input = document.createElement("input"); input.setAttribute("type", "checkbox"); if (data.users[i].user.active == true) { input.checked = true; } input.setAttribute("onclick", "updateUser(" + data.users[i].user.id + "," + 1 + ")"); span = document.createElement("span"); span.setAttribute("class", "slider round"); label = document.createElement("label"); label.appendChild(input); label.appendChild(span); td.appendChild(label); td = document.createElement("td"); tr.appendChild(td); if (data.users[i].user.username != window.localStorage.getItem("name")) { if (data.users[i].user.role == "reader") { input = document.createElement("input"); input.setAttribute("type", "button"); input.setAttribute("onclick", "deleteUser(" + data.users[i].user.id + ")"); input.setAttribute("value", "eliminar"); td.appendChild(input); } } } } }); } function updateUser(id, select) { var role; var active; let token = window.localStorage.getItem("token"); $.ajax({ type: "get", url: '/api/v1/users/' + id, headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data, status, response) { role = data.user.role; active = data.user.active; }, }); if (select == 0) { if (role == "writer") { role = "reader"; } else { role = "writer" } var actu = { role: role, } } else { if (active == 0) { active = 1; } else { active = 0; } var actu = { active: active, } } $.ajax({ type: "PUT", url: '/api/v1/users/' + id, headers: {"Authorization": token}, dataType: 'json', data: actu, success: function (data, status, response) { alert("Datos guardados"); }, }); } function deleteUser(id) { var result = confirm("¿Desea borrar este elemento?"); if (result) { var token = window.localStorage.getItem("token"); console.log(id); $.ajax({ type: "delete", url: '/api/v1/users/' + id, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Usuario eliminado"); } }) } } function editPersonRelation() { var select = document.getElementById("entities"); let token = window.localStorage.getItem("token"); $.ajax({ type: "GET", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.entities.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.entities[i].entity.id); var text = document.createTextNode(data.entities[i].entity.name); option.appendChild(text); select.appendChild(option); } } }); var select = document.getElementById("products") $.ajax({ type: "GET", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.products.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.products[i].product.id); var text = document.createTextNode(data.products[i].product.name); option.appendChild(text); select.appendChild(option); } } }); var select = document.getElementById("entities2"); $.ajax({ type: "GET", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.entities.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.entities[i].entity.id); var text = document.createTextNode(data.entities[i].entity.name); option.appendChild(text); select.appendChild(option); } } }); var select = document.getElementById("products2") $.ajax({ type: "GET", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.products.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.products[i].product.id); var text = document.createTextNode(data.products[i].product.name); option.appendChild(text); select.appendChild(option); } } }); } function savePersonRelation(opc) { var sel = window.localStorage.getItem("opcion"); idFind("person") var id = window.localStorage.getItem("id"); let token = window.localStorage.getItem("token"); if (opc == 0) { $.ajax({ type: "PUT", url: '/api/v1/persons/' + id + '/entities/add/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } else if (opc == 1) { $.ajax({ type: "PUT", url: '/api/v1/persons/' + id + '/products/add/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } else if (opc == 2) { $.ajax({ type: "PUT", url: '/api/v1/persons/' + id + '/entities/rem/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } else if (opc == 3) { $.ajax({ type: "PUT", url: '/api/v1/persons/' + id + '/products/rem/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } window.localStorage.setItem("opcion", 1); } function editEntityRelation() { let token = window.localStorage.getItem("token"); var select = document.getElementById("products") $.ajax({ type: "GET", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.products.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.products[i].product.id); var text = document.createTextNode(data.products[i].product.name); option.appendChild(text); select.appendChild(option); } } }); var select = document.getElementById("persons") $.ajax({ type: "GET", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.persons.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.persons[i].person.id); var text = document.createTextNode(data.persons[i].person.name); option.appendChild(text); select.appendChild(option); } } }); var select = document.getElementById("products2") $.ajax({ type: "GET", url: '/api/v1/products', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.products.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.products[i].product.id); var text = document.createTextNode(data.products[i].product.name); option.appendChild(text); select.appendChild(option); } } }); var select = document.getElementById("persons2") $.ajax({ type: "GET", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.persons.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.persons[i].person.id); var text = document.createTextNode(data.persons[i].person.name); option.appendChild(text); select.appendChild(option); } } }); } function saveEntityRelation(opc) { var sel = window.localStorage.getItem("opcion"); idFind("entity") var id = window.localStorage.getItem("id"); let token = window.localStorage.getItem("token"); if (opc == 0) { $.ajax({ type: "PUT", url: '/api/v1/entities/' + id + '/products/add/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } else if (opc == 1) { $.ajax({ type: "PUT", url: '/api/v1/entities/' + id + '/persons/add/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } else if (opc == 2) { $.ajax({ type: "PUT", url: '/api/v1/entities/' + id + '/products/rem/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } else if (opc == 3) { $.ajax({ type: "PUT", url: '/api/v1/entities/' + id + '/persons/rem/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } window.localStorage.setItem("opcion", 1); } function editProductRelation() { var select = document.getElementById("entities"); let token = window.localStorage.getItem("token"); $.ajax({ type: "GET", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.entities.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.entities[i].entity.id); var text = document.createTextNode(data.entities[i].entity.name); option.appendChild(text); select.appendChild(option); } } }); var select = document.getElementById("persons") $.ajax({ type: "GET", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.persons.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.persons[i].person.id); var text = document.createTextNode(data.persons[i].person.name); option.appendChild(text); select.appendChild(option); } } }); var select = document.getElementById("entities2"); $.ajax({ type: "GET", url: '/api/v1/entities', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.entities.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.entities[i].entity.id); var text = document.createTextNode(data.entities[i].entity.name); option.appendChild(text); select.appendChild(option); } } }); var select = document.getElementById("persons2") $.ajax({ type: "GET", url: '/api/v1/persons', headers: {"Authorization": token}, dataType: 'json', async: false, success: function (data) { for (var i = 0; i < data.persons.length; i++) { var option = document.createElement("option"); option.setAttribute("value", data.persons[i].person.id); var text = document.createTextNode(data.persons[i].person.name); option.appendChild(text); select.appendChild(option); } } }); } function saveProductRelation(opc) { var sel = window.localStorage.getItem("opcion"); idFind("product") var id = window.localStorage.getItem("id"); let token = window.localStorage.getItem("token"); if (opc == 0) { $.ajax({ type: "PUT", url: '/api/v1/products/' + id + '/entities/add/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } else if (opc == 1) { $.ajax({ type: "PUT", url: '/api/v1/products/' + id + '/persons/add/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } else if (opc == 2) { $.ajax({ type: "PUT", url: '/api/v1/products/' + id + '/entities/rem/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } else if (opc == 3) { $.ajax({ type: "PUT", url: '/api/v1/products/' + id + '/persons/rem/' + sel, headers: {"Authorization": token}, dataType: 'json', success: function (data, status, response) { alert("Datos guardados"); } }); } window.localStorage.setItem("opcion", 1); } function saveOption(sel) { window.localStorage.setItem("opcion", sel.options[sel.selectedIndex].value); }
le(y) {
Alert.stories.tsx
import { Alert, AlertProps } from '../..'; import { Meta, Story } from '@storybook/react'; import React from 'react'; export default {
} as Meta; const Template: Story<AlertProps> = args => <Alert {...args} />; export const $Alert = Template.bind({}); $Alert.args = { children: "Feli Page's React Component Library", colour: 'default', fixed: false, };
title: 'Components/Alert', component: Alert,
lib.rs
#![allow(warnings)] #![cfg_attr(not(feature = "std"), no_std)] #![warn(rust_2018_idioms)] #![cfg_attr(feature = "nightly", feature(const_raw_ptr_deref))] #[cfg(test)] extern crate std; #[cfg(feature = "alloc")] extern crate alloc; #[cfg(feature = "alloc")] use alloc::borrow::{Borrow, Cow, ToOwned}; #[cfg(feature = "alloc")] use alloc::boxed::Box; #[cfg(feature = "alloc")] use alloc::rc::Rc; #[cfg(feature = "alloc")] use alloc::string::String; #[cfg(feature = "alloc")] #[cfg(feature = "arc")] use alloc::sync::Arc; #[cfg(feature = "alloc")] use alloc::vec::Vec; #[cfg(feature = "alloc")] use core::{mem, ops, ptr}; use core::ascii; use core::cmp::Ordering; use core::fmt::{self, Write}; use core::slice; use core::str::{self, Utf8Error}; /// Re-export c_char pub use cty::c_char; #[inline] unsafe fn strlen(p: *const c_char) -> usize { let mut n = 0; while *p.offset(n as isize) != 0 { n += 1; } n } /// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the /// middle. /// /// This type serves the purpose of being able to safely generate a /// C-compatible string from a Rust byte slice or vector. An instance of this /// type is a static guarantee that the underlying bytes contain no interior 0 /// bytes ("nul characters") and that the final byte is 0 ("nul terminator"). /// /// `CString` is to [`&CStr`] as [`String`] is to [`&str`]: the former /// in each pair are owned strings; the latter are borrowed /// references. /// /// # Creating a `CString` /// /// A `CString` is created from either a byte slice or a byte vector, /// or anything that implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>` (for /// example, you can build a `CString` straight out of a [`String`] or /// a [`&str`], since both implement that trait). /// /// The [`new`] method will actually check that the provided `&[u8]` /// does not have 0 bytes in the middle, and return an error if it /// finds one. /// /// # Extracting a raw pointer to the whole C string /// /// `CString` implements a [`as_ptr`] method through the [`Deref`] /// trait. This method will give you a `*const c_char` which you can /// feed directly to extern functions that expect a nul-terminated /// string, like C's `strdup()`. Notice that [`as_ptr`] returns a /// read-only pointer; if the C code writes to it, that causes /// undefined behavior. /// /// # Extracting a slice of the whole C string /// /// Alternatively, you can obtain a `&[`[`u8`]`]` slice from a /// `CString` with the [`as_bytes`] method. Slices produced in this /// way do *not* contain the trailing nul terminator. This is useful /// when you will be calling an extern function that takes a `*const /// u8` argument which is not necessarily nul-terminated, plus another /// argument with the length of the string — like C's `strndup()`. /// You can of course get the slice's length with its /// [`len`][slice.len] method. /// /// If you need a `&[`[`u8`]`]` slice *with* the nul terminator, you /// can use [`as_bytes_with_nul`] instead. /// /// Once you have the kind of slice you need (with or without a nul /// terminator), you can call the slice's own /// [`as_ptr`][slice.as_ptr] method to get a read-only raw pointer to pass to /// extern functions. See the documentation for that function for a /// discussion on ensuring the lifetime of the raw pointer. /// /// [`new`]: #method.new /// [`as_bytes`]: #method.as_bytes /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul /// [`as_ptr`]: #method.as_ptr /// [slice.len]: ../primitive.slice.html#method.len /// [`Deref`]: core::ops::Deref /// [`CStr`]: struct.CStr.html /// [`&CStr`]: struct.CStr.html /// /// # Examples /// /// ```ignore (extern-declaration) /// # fn main() { /// use cstr_core::CString; /// use cstr_core::c_char; /// /// extern { /// fn my_printer(s: *const c_char); /// } /// /// // We are certain that our string doesn't have 0 bytes in the middle, /// // so we can .expect() /// let c_to_print = CString::new("Hello, world!").expect("CString::new failed"); /// unsafe { /// my_printer(c_to_print.as_ptr()); /// } /// # } /// ``` /// /// # Safety /// /// `CString` is intended for working with traditional C-style strings /// (a sequence of non-nul bytes terminated by a single nul byte); the /// primary use case for these kinds of strings is interoperating with C-like /// code. Often you will need to transfer ownership to/from that external /// code. It is strongly recommended that you thoroughly read through the /// documentation of `CString` before use, as improper ownership management /// of `CString` instances can lead to invalid memory accesses, memory leaks, /// and other memory errors. #[cfg(feature = "alloc")] #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)] pub struct CString { // Invariant 1: the slice ends with a zero byte and has a length of at least one. // Invariant 2: the slice contains only one zero byte. // Improper usage of unsafe function can break Invariant 2, but not Invariant 1. inner: Box<[u8]>, } /// Representation of a borrowed C string. /// /// This type represents a borrowed reference to a nul-terminated /// array of bytes. It can be constructed safely from a `&[`[`u8`]`]` /// slice, or unsafely from a raw `*const c_char`. It can then be /// converted to a Rust [`&str`] by performing UTF-8 validation, or /// into an owned [`CString`]. /// /// `&CStr` is to [`CString`] as [`&str`] is to [`String`]: the former /// in each pair are borrowed references; the latter are owned /// strings. /// /// Note that this structure is **not** `repr(C)` and is not recommended to be /// placed in the signatures of FFI functions. Instead, safe wrappers of FFI /// functions may leverage the unsafe [`from_ptr`] constructor to provide a safe /// interface to other consumers. /// /// # Examples /// /// Inspecting a foreign C string: /// /// ```ignore (extern-declaration) /// use cstr_core::CStr; /// use cstr_core::c_char; /// /// extern { fn my_string() -> *const c_char; } /// /// unsafe { /// let slice = CStr::from_ptr(my_string()); /// println!("string buffer size without nul terminator: {}", slice.to_bytes().len()); /// } /// ``` /// /// Passing a Rust-originating C string: /// /// ```ignore (extern-declaration) /// use cstr_core::{CString, CStr}; /// use cstr_core::c_char; /// /// fn work(data: &CStr) { /// extern { fn work_with(data: *const c_char); } /// /// unsafe { work_with(data.as_ptr()) } /// } /// /// let s = CString::new("data data data data").expect("CString::new failed"); /// work(&s); /// ``` /// /// Converting a foreign C string into a Rust [`String`]: /// /// ```ignore (extern-declaration) /// use cstr_core::CStr; /// use cstr_core::c_char; /// /// extern { fn my_string() -> *const c_char; } /// /// fn my_string_safe() -> String { /// unsafe { /// CStr::from_ptr(my_string()).to_string_lossy().into_owned() /// } /// } /// /// println!("string: {}", my_string_safe()); /// ``` /// /// [`CString`]: struct.CString.html /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html /// [`from_ptr`]: #method.from_ptr #[derive(Hash)] // FIXME: // `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies // on `CStr` being layout-compatible with `[u8]`. // When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`. // Anyway, `CStr` representation and layout are considered implementation detail, are // not documented and must not be relied upon. pub struct CStr { // FIXME: this should not be represented with a DST slice but rather with // just a raw `c_char` along with some form of marker to make // this an unsized type. Essentially `sizeof(&CStr)` should be the // same as `sizeof(&c_char)` but `CStr` should be an unsized type. inner: [c_char], } /// An error indicating that an interior nul byte was found. /// /// While Rust strings may contain nul bytes in the middle, C strings /// can't, as that byte would effectively truncate the string. /// /// This error is created by the [`new`][`CString::new`] method on /// [`CString`]. See its documentation for more. /// /// [`CString`]: struct.CString.html /// [`CString::new`]: struct.CString.html#method.new /// /// # Examples /// /// ``` /// use cstr_core::{CString, NulError}; /// /// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err(); /// ``` #[cfg(feature = "alloc")] #[derive(Clone, PartialEq, Eq, Debug)] pub struct NulError(usize, Vec<u8>); /// An error indicating that a nul byte was not in the expected position. /// /// The slice used to create a [`CStr`] must have one and only one nul /// byte at the end of the slice. /// /// This error is created by the /// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on /// [`CStr`]. See its documentation for more. /// /// [`CStr`]: struct.CStr.html /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul /// /// # Examples /// /// ``` /// use cstr_core::{CStr, FromBytesWithNulError}; /// /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err(); /// ``` #[derive(Clone, PartialEq, Eq, Debug)] pub struct FromBytesWithNulError { kind: FromBytesWithNulErrorKind, } #[derive(Clone, PartialEq, Eq, Debug)] enum FromBytesWithNulErrorKind { InteriorNul(usize), NotNulTerminated, } impl FromBytesWithNulError { fn interior_nul(pos: usize) -> FromBytesWithNulError { FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos), } } fn not_nul_terminated() -> FromBytesWithNulError { FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated, } } } /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`]. /// /// `CString` is just a wrapper over a buffer of bytes with a nul /// terminator; [`into_string`][`CString::into_string`] performs UTF-8 /// validation on those bytes and may return this error. /// /// This `struct` is created by the /// [`into_string`][`CString::into_string`] method on [`CString`]. See /// its documentation for more. /// /// [`CString`]: struct.CString.html /// [`CString::into_string`]: struct.CString.html#method.into_string #[cfg(feature = "alloc")] #[derive(Clone, PartialEq, Eq, Debug)] pub struct IntoStringError { inner: CString, error: Utf8Error, } #[cfg(feature = "alloc")] impl CString { /// Creates a new C-compatible string from a container of bytes. /// /// This function will consume the provided data and use the /// underlying bytes to construct a new string, ensuring that /// there is a trailing 0 byte. This trailing 0 byte will be /// appended by this function; the provided data should *not* /// contain any 0 bytes in it. /// /// # Examples /// /// ```ignore (extern-declaration) /// use cstr_core::CString; /// use cstr_core::c_char; /// /// extern { fn puts(s: *const c_char); } /// /// let to_print = CString::new("Hello!").expect("CString::new failed"); /// unsafe { /// puts(to_print.as_ptr()); /// } /// ``` /// /// # Errors /// /// This function will return an error if the supplied bytes contain an /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as /// the position of the nul byte. /// /// [`NulError`]: struct.NulError.html pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> { Self::_new(t.into()) } fn _new(bytes: Vec<u8>) -> Result<CString, NulError> { match memchr::memchr(0, &bytes) { Some(i) => Err(NulError(i, bytes)), None => Ok(unsafe { CString::from_vec_unchecked(bytes) }), } } /// Creates a C-compatible string from a byte vector without checking for /// interior 0 bytes. /// /// This method is equivalent to [`new`] except that no runtime assertion /// is made that `v` contains no 0 bytes, and it requires an actual /// byte vector, not anything that can be converted to one with Into. /// /// [`new`]: #method.new /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let raw = b"foo".to_vec(); /// unsafe { /// let c_string = CString::from_vec_unchecked(raw); /// } /// ``` pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString { v.reserve_exact(1); v.push(0); CString { inner: v.into_boxed_slice(), } } /// Retakes ownership of a `CString` that was transferred to C via [`into_raw`]. /// /// Additionally, the length of the string will be recalculated from the pointer. /// /// # Safety /// /// This should only ever be called with a pointer that was earlier /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take /// ownership of a string that was allocated by foreign code) is likely to lead /// to undefined behavior or allocator corruption. /// /// > **Note:** If you need to borrow a string that was allocated by /// > foreign code, use [`CStr`]. If you need to take ownership of /// > a string that was allocated by foreign code, you will need to /// > make your own provisions for freeing it appropriately, likely /// > with the foreign code's API to do that. /// /// [`into_raw`]: #method.into_raw /// [`CStr`]: struct.CStr.html /// /// # Examples /// /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake /// ownership with `from_raw`: /// /// ```ignore (extern-declaration) /// use cstr_core::CString; /// use cstr_core::c_char; /// /// extern { /// fn some_extern_function(s: *mut c_char); /// } /// /// let c_string = CString::new("Hello!").expect("CString::new failed"); /// let raw = c_string.into_raw(); /// unsafe { /// some_extern_function(raw); /// let c_string = CString::from_raw(raw); /// } /// ``` pub unsafe fn from_raw(ptr: *mut c_char) -> CString { let len = strlen(ptr) + 1; // Including the NUL byte let slice = slice::from_raw_parts_mut(ptr, len as usize); CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]), } } /// Consumes the `CString` and transfers ownership of the string to a C caller. /// /// The pointer which this function returns must be returned to Rust and reconstituted using /// [`from_raw`] to be properly deallocated. Specifically, one /// should *not* use the standard C `free()` function to deallocate /// this string. /// /// Failure to call [`from_raw`] will lead to a memory leak. /// /// [`from_raw`]: #method.from_raw /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let c_string = CString::new("foo").expect("CString::new failed"); /// /// let ptr = c_string.into_raw(); /// /// unsafe { /// assert_eq!(b'f', *ptr as u8); /// assert_eq!(b'o', *ptr.offset(1) as u8); /// assert_eq!(b'o', *ptr.offset(2) as u8); /// assert_eq!(b'\0', *ptr.offset(3) as u8); /// /// // retake pointer to free memory /// let _ = CString::from_raw(ptr); /// } /// ``` #[inline] pub fn into_raw(self) -> *mut c_char { Box::into_raw(self.into_inner()) as *mut c_char } /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data. /// /// On failure, ownership of the original `CString` is returned. /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let valid_utf8 = vec![b'f', b'o', b'o']; /// let cstring = CString::new(valid_utf8).expect("CString::new failed"); /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo"); /// /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o']; /// let cstring = CString::new(invalid_utf8).expect("CString::new failed"); /// let err = cstring.into_string().err().expect("into_string().err() failed"); /// assert_eq!(err.utf8_error().valid_up_to(), 1); /// ``` pub fn into_string(self) -> Result<String, IntoStringError> { String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError { error: e.utf8_error(), inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) }, }) } /// Consumes the `CString` and returns the underlying byte buffer. /// /// The returned buffer does **not** contain the trailing nul /// terminator, and it is guaranteed to not have any interior nul /// bytes. /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let c_string = CString::new("foo").expect("CString::new failed"); /// let bytes = c_string.into_bytes(); /// assert_eq!(bytes, vec![b'f', b'o', b'o']); /// ``` pub fn into_bytes(self) -> Vec<u8> { let mut vec = self.into_inner().into_vec(); let _nul = vec.pop(); debug_assert_eq!(_nul, Some(0u8)); vec } /// Equivalent to the [`into_bytes`] function except that the returned vector /// includes the trailing nul terminator. /// /// [`into_bytes`]: #method.into_bytes /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let c_string = CString::new("foo").expect("CString::new failed"); /// let bytes = c_string.into_bytes_with_nul(); /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']); /// ``` pub fn into_bytes_with_nul(self) -> Vec<u8> { self.into_inner().into_vec() } /// Returns the contents of this `CString` as a slice of bytes. /// /// The returned slice does **not** contain the trailing nul /// terminator, and it is guaranteed to not have any interior nul /// bytes. If you need the nul terminator, use /// [`as_bytes_with_nul`] instead. /// /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let c_string = CString::new("foo").expect("CString::new failed"); /// let bytes = c_string.as_bytes(); /// assert_eq!(bytes, &[b'f', b'o', b'o']); /// ``` #[inline] pub fn as_bytes(&self) -> &[u8] { &self.inner[..self.inner.len() - 1] } /// Equivalent to the [`as_bytes`] function except that the returned slice /// includes the trailing nul terminator. /// /// [`as_bytes`]: #method.as_bytes /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let c_string = CString::new("foo").expect("CString::new failed"); /// let bytes = c_string.as_bytes_with_nul(); /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']); /// ``` #[inline] pub fn as_bytes_with_nul(&self) -> &[u8] { &self.inner } /// Extracts a [`CStr`] slice containing the entire string. /// /// [`CStr`]: struct.CStr.html /// /// # Examples /// /// ``` /// use cstr_core::{CString, CStr}; /// /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed"); /// let cstr = c_string.as_c_str(); /// assert_eq!(cstr, /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed")); /// ``` #[inline] pub fn as_c_str(&self) -> &CStr { &*self } /// Converts this `CString` into a boxed [`CStr`]. /// /// [`CStr`]: struct.CStr.html /// /// # Examples /// /// ``` /// use cstr_core::{CString, CStr}; /// /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed"); /// let boxed = c_string.into_boxed_c_str(); /// assert_eq!(&*boxed, /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed")); /// ``` pub fn into_boxed_c_str(self) -> Box<CStr> { unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) } } /// Bypass "move out of struct which implements [`Drop`] trait" restriction. fn into_inner(self) -> Box<[u8]> { // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)` // so we use `ManuallyDrop` to ensure `self` is not dropped. // Then we can return the box directly without invalidating it. // See https://github.com/rust-lang/rust/issues/62553. let this = mem::ManuallyDrop::new(self); unsafe { ptr::read(&this.inner) } } } // Turns this `CString` into an empty string to prevent // memory unsafe code from working by accident. Inline // to prevent LLVM from optimizing it away in debug builds. #[cfg(feature = "alloc")] impl Drop for CString { #[inline] fn drop(&mut self) { unsafe { *self.inner.get_unchecked_mut(0) = 0; } } } #[cfg(feature = "alloc")] impl ops::Deref for CString { type Target = CStr; #[inline] fn deref(&self) -> &CStr { unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) } } } #[cfg(feature = "alloc")] impl fmt::Debug for CString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } #[cfg(feature = "alloc")] impl From<CString> for Vec<u8> { /// Converts a [`CString`] into a [`Vec`]`<u8>`. /// /// The conversion consumes the [`CString`], and removes the terminating NUL byte. #[inline] fn from(s: CString) -> Vec<u8> { s.into_bytes() } } impl fmt::Debug for CStr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "\"")?; for byte in self .to_bytes() .iter() .flat_map(|&b| ascii::escape_default(b)) { f.write_char(byte as char)?; } write!(f, "\"") } } impl<'a> Default for &'a CStr { fn default() -> &'a CStr { const SLICE: &[c_char] = &[0]; unsafe { CStr::from_ptr(SLICE.as_ptr()) } } } #[cfg(feature = "alloc")] impl Default for CString { /// Creates an empty `CString`. fn default() -> CString { let a: &CStr = Default::default(); a.to_owned() } } #[cfg(feature = "alloc")] impl Borrow<CStr> for CString { #[inline] fn borrow(&self) -> &CStr { self } } #[cfg(feature = "alloc")] impl<'a> From<Cow<'a, CStr>> for CString { #[inline] fn from(s: Cow<'a, CStr>) -> Self { s.into_owned() } } #[cfg(feature = "alloc")] impl From<&CStr> for Box<CStr> { fn from(s: &CStr) -> Box<CStr> { let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul()); unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) } } } #[cfg(feature = "alloc")] impl From<Box<CStr>> for CString { /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating. #[inline] fn from(s: Box<CStr>) -> CString { s.into_c_string() } } #[cfg(feature = "alloc")] impl Clone for Box<CStr> { #[inline] fn clone(&self) -> Self { (**self).into() } } #[cfg(feature = "alloc")] impl From<CString> for Box<CStr> { /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating. #[inline] fn from(s: CString) -> Box<CStr> { s.into_boxed_c_str() } } #[cfg(feature = "alloc")] impl<'a> From<CString> for Cow<'a, CStr> { #[inline] fn from(s: CString) -> Cow<'a, CStr> { Cow::Owned(s) } } #[cfg(feature = "alloc")] impl<'a> From<&'a CStr> for Cow<'a, CStr> { #[inline] fn from(s: &'a CStr) -> Cow<'a, CStr> { Cow::Borrowed(s) } } #[cfg(feature = "alloc")] impl<'a> From<&'a CString> for Cow<'a, CStr> { #[inline] fn from(s: &'a CString) -> Cow<'a, CStr> { Cow::Borrowed(s.as_c_str()) } } #[cfg(feature = "alloc")] #[cfg(feature = "arc")] impl From<CString> for Arc<CStr> { #[inline] fn from(s: CString) -> Arc<CStr> { let arc: Arc<[u8]> = Arc::from(s.into_inner()); unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) } } } #[cfg(feature = "alloc")] #[cfg(feature = "arc")] impl<'a> From<&'a CStr> for Arc<CStr> { #[inline] fn from(s: &CStr) -> Arc<CStr> { let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul()); unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) } } } #[cfg(feature = "alloc")] impl From<CString> for Rc<CStr> { #[inline] fn from(s: CString) -> Rc<CStr> { let rc: Rc<[u8]> = Rc::from(s.into_inner()); unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) } } } #[cfg(feature = "alloc")] impl<'a> From<&'a CStr> for Rc<CStr> { #[inline] fn from(s: &CStr) -> Rc<CStr> { let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul()); unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) } } } #[cfg(feature = "alloc")] impl Default for Box<CStr> { fn default() -> Box<CStr> { let boxed: Box<[u8]> = Box::from([0]); unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) } } } #[cfg(feature = "std")] use std::ffi::{CStr as StdCStr, CString as StdCString}; #[cfg(feature = "std")] impl From<CString> for StdCString { #[inline] fn from(s: CString) -> StdCString { unsafe { StdCString::from_vec_unchecked(s.into_bytes()) } } } #[cfg(feature = "std")] impl<'a> From<&'a CStr> for &'a StdCStr { #[inline] fn from(s: &'a CStr) -> &'a StdCStr { s.as_ref() } } #[cfg(feature = "std")] impl From<StdCString> for CString { #[inline] fn from(s: StdCString) -> CString { unsafe { CString::from_vec_unchecked(s.into_bytes()) } } } #[cfg(feature = "std")] impl<'a> From<&'a StdCStr> for &'a CStr { #[inline] fn from(s: &'a StdCStr) -> &'a CStr { unsafe { CStr::from_bytes_with_nul_unchecked(s.to_bytes_with_nul()) } } } #[cfg(feature = "std")] impl AsRef<StdCStr> for CString { #[inline] fn as_ref(&self) -> &StdCStr { AsRef::<CStr>::as_ref(self).as_ref() } } #[cfg(feature = "std")] impl Borrow<StdCStr> for CString { #[inline] fn borrow(&self) -> &StdCStr { self.as_ref() } } #[cfg(feature = "std")] impl AsRef<StdCStr> for CStr { #[inline] fn as_ref(&self) -> &StdCStr { unsafe { StdCStr::from_bytes_with_nul_unchecked(self.to_bytes_with_nul()) } } } #[cfg(feature = "alloc")] impl NulError { /// Returns the position of the nul byte in the slice that was provided to /// [`CString::new`]. /// /// [`CString::new`]: struct.CString.html#method.new /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let nul_error = CString::new("foo\0bar").unwrap_err(); /// assert_eq!(nul_error.nul_position(), 3); /// /// let nul_error = CString::new("foo bar\0").unwrap_err(); /// assert_eq!(nul_error.nul_position(), 7); /// ``` pub fn nul_position(&self) -> usize { self.0 } /// Consumes this error, returning the underlying vector of bytes which /// generated the error in the first place. /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let nul_error = CString::new("foo\0bar").unwrap_err(); /// assert_eq!(nul_error.into_vec(), b"foo\0bar"); /// ``` pub fn into_vec(self) -> Vec<u8> { self.1 } } #[cfg(feature = "alloc")] impl fmt::Display for NulError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "nul byte found in provided data at position: {}", self.0) } } impl fmt::Display for FromBytesWithNulError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let description = match self.kind { FromBytesWithNulErrorKind::InteriorNul(..) => { "data provided contains an interior nul byte" } FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated", }; f.write_str(description)?; if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind { write!(f, " at byte pos {}", pos)?; } Ok(()) } } #[cfg(feature = "alloc")] impl IntoStringError { /// Consumes this error, returning original [`CString`] which generated the /// error. /// /// [`CString`]: struct.CString.html pub fn into_cstring(self) -> CString { self.inner } /// Access the underlying UTF-8 error that was the cause of this error. pub fn utf8_error(&self) -> Utf8Error { self.error } } #[cfg(feature = "alloc")] impl fmt::Display for IntoStringError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { "C string contained non-utf8 bytes".fmt(f) } } impl CStr { /// Wraps a raw C string with a safe C string wrapper. /// /// This function will wrap the provided `ptr` with a `CStr` wrapper, which /// allows inspection and interoperation of non-owned C strings. The total /// size of the raw C string must be smaller than `isize::MAX` **bytes** /// in memory due to calling the `slice::from_raw_parts` function. /// This method is unsafe for a number of reasons: /// /// * There is no guarantee to the validity of `ptr`. /// * The returned lifetime is not guaranteed to be the actual lifetime of /// `ptr`. /// * There is no guarantee that the memory pointed to by `ptr` contains a /// valid nul terminator byte at the end of the string. /// * It is not guaranteed that the memory pointed by `ptr` won't change /// before the `CStr` has been destroyed. /// /// > **Note**: This operation is intended to be a 0-cost cast but it is /// > currently implemented with an up-front calculation of the length of /// > the string. This is not guaranteed to always be the case. /// /// # Examples /// /// ```ignore (extern-declaration) /// # fn main() { /// use cstr_core::CStr; /// use cstr_core::c_char; /// /// extern { /// fn my_string() -> *const c_char; /// } /// /// unsafe { /// let slice = CStr::from_ptr(my_string()); /// println!("string returned: {}", slice.to_str().unwrap()); /// } /// # } /// ``` pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr { let len = strlen(ptr); let ptr = ptr as *const u8; CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1)) } /// Creates a C string wrapper from a byte slice. /// /// This function will cast the provided `bytes` to a `CStr` /// wrapper after ensuring that the byte slice is nul-terminated /// and does not contain any interior nul bytes. /// /// # Examples /// /// ``` /// use cstr_core::CStr; /// /// let cstr = CStr::from_bytes_with_nul(b"hello\0"); /// assert!(cstr.is_ok()); /// ``` /// /// Creating a `CStr` without a trailing nul terminator is an error: /// /// ``` /// use cstr_core::CStr; /// /// let cstr = CStr::from_bytes_with_nul(b"hello"); /// assert!(cstr.is_err()); /// ``` /// /// Creating a `CStr` with an interior nul byte is an error: /// /// ``` /// use cstr_core::CStr; /// /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0"); /// assert!(cstr.is_err()); /// ``` pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> { let nul_pos = memchr::memchr(0, bytes); if let Some(nul_pos) = nul_pos { if nul_pos + 1 != bytes.len() { return Err(FromBytesWithNulError::interior_nul(nul_pos)); } Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) }) } else { Err(FromBytesWithNulError::not_nul_terminated()) } } /// Unsafely creates a C string wrapper from a byte slice. /// /// This function will cast the provided `bytes` to a `CStr` wrapper without /// performing any sanity checks. The provided slice **must** be nul-terminated /// and not contain any interior nul bytes. /// /// # Examples /// /// ``` /// use cstr_core::{CStr, CString}; /// /// unsafe { /// let cstring = CString::new("hello").expect("CString::new failed"); /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul()); /// assert_eq!(cstr, &*cstring); /// } /// ``` #[cfg(feature = "nightly")] #[inline] pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr { &*(bytes as *const [u8] as *const CStr) } /// Unsafely creates a C string wrapper from a byte slice. /// /// This function will cast the provided `bytes` to a `CStr` wrapper without /// performing any sanity checks. The provided slice **must** be nul-terminated /// and not contain any interior nul bytes. /// /// # Examples /// /// ``` /// use cstr_core::{CStr, CString}; /// /// unsafe { /// let cstring = CString::new("hello").expect("CString::new failed"); /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul()); /// assert_eq!(cstr, &*cstring); /// } /// ``` #[cfg(not(feature = "nightly"))] #[inline] pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr { &*(bytes as *const [u8] as *const CStr) } /// Returns the inner pointer to this C string. /// /// The returned pointer will be valid for as long as `self` is, and points /// to a contiguous region of memory terminated with a 0 byte to represent /// the end of the string. /// /// **WARNING** /// /// The returned pointer is read-only; writing to it (including passing it /// to C code that writes to it) causes undefined behavior. /// /// It is your responsibility to make sure that the underlying memory is not /// freed too early. For example, the following code will cause undefined /// behavior when `ptr` is used inside the `unsafe` block: /// /// ```no_run /// # #![allow(unused_must_use)] /// use cstr_core::CString; /// /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr(); /// unsafe { /// // `ptr` is dangling /// *ptr; /// } /// ``` /// /// This happens because the pointer returned by `as_ptr` does not carry any /// lifetime information and the [`CString`] is deallocated immediately after /// the `CString::new("Hello").expect("CString::new failed").as_ptr()` expression is evaluated. /// To fix the problem, bind the `CString` to a local variable: /// /// ```no_run /// # #![allow(unused_must_use)] /// use cstr_core::CString; /// /// let hello = CString::new("Hello").expect("CString::new failed"); /// let ptr = hello.as_ptr(); /// unsafe { /// // `ptr` is valid because `hello` is in scope /// *ptr; /// } /// ``` /// /// This way, the lifetime of the `CString` in `hello` encompasses /// the lifetime of `ptr` and the `unsafe` block. /// /// [`CString`]: struct.CString.html #[inline] pub const fn as_ptr(&self) -> *const c_char { self.inner.as_ptr() } /// Converts this C string to a byte slice. /// /// The returned slice will **not** contain the trailing nul terminator that this C /// string has. /// /// > **Note**: This method is currently implemented as a constant-time /// > cast, but it is planned to alter its definition in the future to /// > perform the length calculation whenever this method is called. /// /// # Examples /// /// ``` /// use cstr_core::CStr; /// /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"); /// assert_eq!(cstr.to_bytes(), b"foo"); /// ``` #[inline] pub fn to_bytes(&self) -> &[u8] { let bytes = self.to_bytes_with_nul(); &bytes[..bytes.len() - 1] } /// Converts this C string to a byte slice containing the trailing 0 byte. /// /// This function is the equivalent of [`to_bytes`] except that it will retain /// the trailing nul terminator instead of chopping it off. /// /// > **Note**: This method is currently implemented as a 0-cost cast, but /// > it is planned to alter its definition in the future to perform the /// > length calculation whenever this method is called. /// /// [`to_bytes`]: #method.to_bytes /// /// # Examples /// /// ``` /// use cstr_core::CStr; /// /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"); /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0"); /// ``` #[inline] pub fn to_bytes_with_nul(&self) -> &[u8] { unsafe { &*(&self.inner as *const [c_char] as *const [u8]) } } /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8. /// /// If the contents of the `CStr` are valid UTF-8 data, this /// function will return the corresponding [`&str`] slice. Otherwise, /// it will return an error with details of where UTF-8 validation failed. /// /// # Examples /// /// ``` /// use cstr_core::CStr; /// /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"); /// assert_eq!(cstr.to_str(), Ok("foo")); /// ``` pub fn to_str(&self) -> Result<&str, Utf8Error> { // N.B., when `CStr` is changed to perform the length check in `.to_bytes()` // instead of in `from_ptr()`, it may be worth considering if this should // be rewritten to do the UTF-8 check inline with the length calculation // instead of doing it afterwards. str::from_utf8(self.to_bytes()) } /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`. /// /// If the contents of the `CStr` are valid UTF-8 data, this /// function will return a [`Cow`]`::`[`Borrowed`]`(`[`&str`]`)` /// with the corresponding [`&str`] slice. Otherwise, it will /// replace any invalid UTF-8 sequences with /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result. /// /// [`Borrowed`]: Cow::Borrowed /// [`Owned`]: Cow::Owned /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER /// /// # Examples /// /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8: /// /// ``` /// use std::borrow::Cow; /// use cstr_core::CStr; /// /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0") /// .expect("CStr::from_bytes_with_nul failed"); /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World")); /// ``` /// /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8: /// /// ``` /// use std::borrow::Cow; /// use cstr_core::CStr; /// /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0") /// .expect("CStr::from_bytes_with_nul failed"); /// assert_eq!( /// cstr.to_string_lossy(), /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str> /// ); /// ``` #[cfg(feature = "alloc")] pub fn to_string_lossy(&self) -> Cow<'_, str> { String::from_utf8_lossy(self.to_bytes()) } /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating. /// /// [`CString`]: struct.CString.html /// /// # Examples /// /// ``` /// use cstr_core::CString; /// /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed"); /// let boxed = c_string.into_boxed_c_str(); /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed")); /// ``` #[cfg(feature = "alloc")] pub fn into_c_string(self: Box<CStr>) -> CString { let raw = Box::into_raw(self) as *mut [u8]; CString { inner: unsafe { Box::from_raw(raw) }, } } } impl PartialEq for CStr { fn eq(&self, other: &CStr) -> bool { self.to_bytes().eq(other.to_bytes()) } } impl Eq for CStr {} impl PartialOrd for CStr { fn partial_cmp(&self, other: &CStr) -> Option<Ordering> { self.to_bytes().partial_cmp(&other.to_bytes()) } } impl Ord for CStr { fn cmp(&self, other: &CStr) -> Ordering { self.to_bytes().cmp(&other.to_bytes()) } } #[cfg(feature = "alloc")] impl ToOwned for CStr { type Owned = CString; fn to_owned(&self) -> CString { CString { inner: self.to_bytes_with_nul().into(), } } } #[cfg(feature = "alloc")] impl From<&CStr> for CString { fn from(s: &CStr) -> CString { s.to_owned() } } #[cfg(feature = "alloc")] impl ops::Index<ops::RangeFull> for CString { type Output = CStr; #[inline] fn index(&self, _index: ops::RangeFull) -> &CStr { self } } impl AsRef<CStr> for CStr { #[inline] fn as_ref(&self) -> &CStr { self } } #[cfg(feature = "alloc")] impl AsRef<CStr> for CString { #[inline] fn as_ref(&self) -> &CStr { self } } #[cfg(test)] mod tests { use super::*; use std::borrow::Cow::{Borrowed, Owned}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::{format, vec}; #[test] fn c_to_rust() { let data = b"123\0"; let ptr = data.as_ptr() as *const c_char; unsafe { assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123"); assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0"); } } #[test] fn simple() { let s = CString::new("1234").unwrap(); assert_eq!(s.as_bytes(), b"1234"); assert_eq!(s.as_bytes_with_nul(), b"1234\0"); } #[test] fn build_with_zero1() { assert!(CString::new(&b"\0"[..]).is_err()); } #[test] fn build_with_zero2() { assert!(CString::new(vec![0]).is_err()); } #[test] fn build_with_zero3() { unsafe { let s = CString::from_vec_unchecked(vec![0]); assert_eq!(s.as_bytes(), b"\0"); } } #[test] fn formatted() { let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap(); assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#); } #[test] fn borrowed() { unsafe { let s = CStr::from_ptr(b"12\0".as_ptr() as *const _); assert_eq!(s.to_bytes(), b"12"); assert_eq!(s.to_bytes_with_nul(), b"12\0"); } } #[test] fn to_str() { let data = b"123\xE2\x80\xA6\0"; let ptr = data.as_ptr() as *const c_char; unsafe { assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…")); assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…")); } let data = b"123\xE2\0"; let ptr = data.as_ptr() as *const c_char; unsafe { assert!(CStr::from_ptr(ptr).to_str().is_err()); assert_eq!( CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")) ); } } #[test] fn to_owned() { let data = b"123\0"; let ptr = data.as_ptr() as *const c_char; let owned = unsafe { CStr::from_ptr(ptr).to_owned() }; assert_eq!(owned.as_bytes_with_nul(), data); } #[test] fn equal_hash() { let data = b"123\xE2\xFA\xA6\0"; let ptr = data.as_ptr() as *const c_char; let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) }; let mut s = DefaultHasher::new(); cstr.hash(&mut s); let cstr_hash = s.finish(); let mut s = DefaultHasher::new(); CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s); let cstring_hash = s.finish();
} #[test] fn from_bytes_with_nul() { let data = b"123\0"; let cstr = CStr::from_bytes_with_nul(data); assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..])); let cstr = CStr::from_bytes_with_nul(data); assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..])); unsafe { let cstr = CStr::from_bytes_with_nul(data); let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data); assert_eq!(cstr, Ok(cstr_unchecked)); } } #[test] fn from_bytes_with_nul_unterminated() { let data = b"123"; let cstr = CStr::from_bytes_with_nul(data); assert!(cstr.is_err()); } #[test] fn from_bytes_with_nul_interior() { let data = b"1\023\0"; let cstr = CStr::from_bytes_with_nul(data); assert!(cstr.is_err()); } #[test] fn into_boxed() { let orig: &[u8] = b"Hello, world!\0"; let cstr = CStr::from_bytes_with_nul(orig).unwrap(); let boxed: Box<CStr> = Box::from(cstr); let cstring = cstr.to_owned().into_boxed_c_str().into_c_string(); assert_eq!(cstr, &*boxed); assert_eq!(&*boxed, &*cstring); assert_eq!(&*cstring, cstr); } #[test] fn boxed_default() { let boxed = <Box<CStr>>::default(); assert_eq!(boxed.to_bytes_with_nul(), &[0]); } #[test] #[cfg(feature = "alloc")] #[cfg(feature = "arc")] fn into_rc() { let orig: &[u8] = b"Hello, world!\0"; let cstr = CStr::from_bytes_with_nul(orig).unwrap(); let rc: Rc<CStr> = Rc::from(cstr); let arc: Arc<CStr> = Arc::from(cstr); assert_eq!(&*rc, cstr); assert_eq!(&*arc, cstr); let rc2: Rc<CStr> = Rc::from(cstr.to_owned()); let arc2: Arc<CStr> = Arc::from(cstr.to_owned()); assert_eq!(&*rc2, cstr); assert_eq!(&*arc2, cstr); } #[test] #[cfg(feature = "nightly")] fn const_cstr() { const TESTING_CSTR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello world!\0") }; let _ = TESTING_CSTR.as_ptr(); } }
assert_eq!(cstr_hash, cstring_hash);
main.js
import {a} from './views/view'; import _ from 'lodash'; import moment from 'moment'; // const g = 9.81;
class Main { constructor() { console.log(_.join(['a', 'b', 'c'], '///')) console.log(moment().subtract(20, 'weeks').format('Do MMM YYYY')) } getName() { return this.a; } } let main = new Main(); console.log(main.getName());
serializeEntryValues.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.deserializeValues = exports.serializeValues = void 0; var _isNil2 = _interopRequireDefault(require("lodash/isNil")); var _immutable = require("immutable"); var _registry = require("./registry"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Methods for serializing/deserializing entry field values. Most widgets don't * require this for their values, and those that do can typically serialize/ * deserialize on every change from within the widget. The serialization * handlers here are for widgets whose values require heavy serialization that * would hurt performance if run for every change. * An example of this is the markdown widget, whose value is stored as a * markdown string. Instead of stringifying on every change of that field, a * deserialization method is registered from the widget's control module that * converts the stored markdown string to an AST, and that AST serves as the * widget model during editing. * * Serialization handlers should be registered for each widget that requires * them, and the registration method is exposed through the registry. Any * registered deserialization handlers run on entry load, and serialization * handlers run on persist. */ const runSerializer = (values, fields, method) => { /** * Reduce the list of fields to a map where keys are field names and values * are field values, serializing the values of fields whose widgets have * registered serializers. If the field is a list or object, call recursively * for nested fields. */ return fields.reduce((acc, field) => { const fieldName = field.get('name'); const value = values.get(fieldName); const serializer = (0, _registry.getWidgetValueSerializer)(field.get('widget')); const nestedFields = field.get('fields'); // Call recursively for fields within lists if (nestedFields && _immutable.List.isList(value)) { return acc.set(fieldName, value.map(val => runSerializer(val, nestedFields, method))); } // Call recursively for fields within objects if (nestedFields && _immutable.Map.isMap(value)) { return acc.set(fieldName, runSerializer(value, nestedFields, method)); } // Run serialization method on value if not null or undefined if (serializer && !(0, _isNil2.default)(value)) { return acc.set(fieldName, serializer[method](value)); } // If no serializer is registered for the field's widget, use the field as is if (!(0, _isNil2.default)(value)) { return acc.set(fieldName, value); } return acc; }, (0, _immutable.Map)()); }; const serializeValues = (values, fields) => {
const deserializeValues = (values, fields) => { return runSerializer(values, fields, 'deserialize'); }; exports.deserializeValues = deserializeValues;
return runSerializer(values, fields, 'serialize'); }; exports.serializeValues = serializeValues;
assets.go
package build import ( "bytes" "os" "os/exec" "path/filepath" "github.com/gobuffalo/buffalo-cli/internal/v1/genny/assets/webpack" "github.com/gobuffalo/genny" "github.com/gobuffalo/packr/v2/jam" "github.com/gobuffalo/packr/v2/jam/parser" ) func assets(opts *Options) (*genny.Generator, error)
{ g := genny.New() if err := opts.Validate(); err != nil { return g, err } if opts.App.WithNodeJs || opts.App.WithWebpack { if opts.CleanAssets { g.RunFn(func(r *genny.Runner) error { r.Delete(filepath.Join(opts.App.Root, "public", "assets")) return nil }) } g.RunFn(func(r *genny.Runner) error { r.Logger.Debugf("setting NODE_ENV = %s", opts.Environment) return os.Setenv("NODE_ENV", opts.Environment) }) g.RunFn(func(r *genny.Runner) error { tool := "yarnpkg" if !opts.App.WithYarn { tool = "npm" } c := exec.CommandContext(r.Context, tool, "run", "build") if _, err := opts.App.NodeScript("build"); err != nil { // Fallback on legacy runner c = exec.CommandContext(r.Context, webpack.BinPath) } bb := &bytes.Buffer{} c.Stdout = bb c.Stderr = bb if err := r.Exec(c); err != nil { r.Logger.Error(bb.String()) return err } return nil }) } g.RunFn(func(r *genny.Runner) error { ro := &parser.RootsOptions{} if !opts.WithAssets { ro.Ignores = append(ro.Ignores, "public/assets") } opts := jam.PackOptions{ Roots: []string{opts.App.Root}, RootsOptions: ro, } return jam.Pack(opts) }) if opts.ExtractAssets && opts.WithAssets { // mount the archived assets generator aa, err := archivedAssets(opts) if err != nil { return g, err } g.Merge(aa) } return g, nil }
test_get_server.py
def test(admin_client, syncgateway_version_str):
result = admin_client.get_server() assert isinstance(result, dict) assert sorted(list(result)) == [ "ADMIN", "couchdb", "vendor", "version", ] assert result["ADMIN"] is True assert result["version"].startswith("Couchbase Sync Gateway/{}(".format(syncgateway_version_str))
ima3.js
// Copyright 2011 Google Inc. All Rights Reserved. (function(){/* Copyright The Closure Library Authors. SPDX-License-Identifier: Apache-2.0 */ var l,aa=function(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}},ba="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a},ca=function(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object"); },da=ca(this),p=function(a,b){if(b)a:{var c=da;a=a.split(".");for(var d=0;d<a.length-1;d++){var e=a[d];if(!(e in c))break a;c=c[e]}a=a[a.length-1];d=c[a];b=b(d);b!=d&&null!=b&&ba(c,a,{configurable:!0,writable:!0,value:b})}}; p("Symbol",function(a){if(a)return a;var b=function(f,g){this.g=f;ba(this,"description",{configurable:!0,writable:!0,value:g})};b.prototype.toString=function(){return this.g};var c="jscomp_symbol_"+(1E9*Math.random()>>>0)+"_",d=0,e=function(f){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new b(c+(f||"")+"_"+d++,f)};return e}); p("Symbol.iterator",function(a){if(a)return a;a=Symbol("Symbol.iterator");for(var b="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),c=0;c<b.length;c++){var d=da[b[c]];"function"===typeof d&&"function"!=typeof d.prototype[a]&&ba(d.prototype,a,{configurable:!0,writable:!0,value:function(){return ea(aa(this))}})}return a}); var ea=function(a){a={next:a};a[Symbol.iterator]=function(){return this};return a},q=function(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):{next:aa(a)}},fa=function(a){if(!(a instanceof Array)){a=q(a);for(var b,c=[];!(b=a.next()).done;)c.push(b.value);a=c}return a},ha="function"==typeof Object.create?Object.create:function(a){var b=function(){};b.prototype=a;return new b},ia=function(){function a(){function c(){}new c;Reflect.construct(c,[],function(){}); return new c instanceof c}if("undefined"!=typeof Reflect&&Reflect.construct){if(a())return Reflect.construct;var b=Reflect.construct;return function(c,d,e){c=b(c,d);e&&Reflect.setPrototypeOf(c,e.prototype);return c}}return function(c,d,e){void 0===e&&(e=c);e=ha(e.prototype||Object.prototype);return Function.prototype.apply.call(c,e,d)||e}}(),ka; if("function"==typeof Object.setPrototypeOf)ka=Object.setPrototypeOf;else{var la;a:{var ma={a:!0},na={};try{na.__proto__=ma;la=na.a;break a}catch(a){}la=!1}ka=la?function(a,b){a.__proto__=b;if(a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null} var oa=ka,t=function(a,b){a.prototype=ha(b.prototype);a.prototype.constructor=a;if(oa)oa(a,b);else for(var c in b)if("prototype"!=c)if(Object.defineProperties){var d=Object.getOwnPropertyDescriptor(b,c);d&&Object.defineProperty(a,c,d)}else a[c]=b[c];a.za=b.prototype},pa=function(){this.B=!1;this.l=null;this.A=void 0;this.g=1;this.J=this.h=0;this.o=null},qa=function(a){if(a.B)throw new TypeError("Generator is already running");a.B=!0};pa.prototype.C=function(a){this.A=a}; var ra=function(a,b){a.o={wd:b,Ue:!0};a.g=a.h||a.J};pa.prototype.return=function(a){this.o={return:a};this.g=this.J}; var sa=function(a,b,c){a.g=c;return{value:b}},ta=function(a){a.h=0;var b=a.o.wd;a.o=null;return b},ua=function(a){this.g=new pa;this.h=a},xa=function(a,b){qa(a.g);var c=a.g.l;if(c)return va(a,"return"in c?c["return"]:function(d){return{value:d,done:!0}},b,a.g.return);a.g.return(b);return wa(a)},va=function(a,b,c,d){try{var e=b.call(a.g.l,c);if(!(e instanceof Object))throw new TypeError("Iterator result "+e+" is not an object");if(!e.done)return a.g.B=!1,e;var f=e.value}catch(g){return a.g.l=null, ra(a.g,g),wa(a)}a.g.l=null;d.call(a.g,f);return wa(a)},wa=function(a){for(;a.g.g;)try{var b=a.h(a.g);if(b)return a.g.B=!1,{value:b.value,done:!1}}catch(c){a.g.A=void 0,ra(a.g,c)}a.g.B=!1;if(a.g.o){b=a.g.o;a.g.o=null;if(b.Ue)throw b.wd;return{value:b.return,done:!0}}return{value:void 0,done:!0}},ya=function(a){this.next=function(b){qa(a.g);a.g.l?b=va(a,a.g.l.next,b,a.g.C):(a.g.C(b),b=wa(a));return b};this.throw=function(b){qa(a.g);a.g.l?b=va(a,a.g.l["throw"],b,a.g.C):(ra(a.g,b),b=wa(a));return b}; this.return=function(b){return xa(a,b)};this[Symbol.iterator]=function(){return this}},za=function(a,b){b=new ya(new ua(b));oa&&a.prototype&&oa(b,a.prototype);return b},Aa=function(a){function b(d){return a.next(d)}function c(d){return a.throw(d)}return new Promise(function(d,e){function f(g){g.done?d(g.value):Promise.resolve(g.value).then(b,c).then(f,e)}f(a.next())})},Ba=function(a){return Aa(new ya(new ua(a)))};p("Reflect",function(a){return a?a:{}});p("Reflect.construct",function(){return ia}); p("Reflect.setPrototypeOf",function(a){return a?a:oa?function(b,c){try{return oa(b,c),!0}catch(d){return!1}}:null}); p("Promise",function(a){function
(){this.g=null}function c(g){return g instanceof e?g:new e(function(h){h(g)})}if(a)return a;b.prototype.h=function(g){if(null==this.g){this.g=[];var h=this;this.l(function(){h.B()})}this.g.push(g)};var d=da.setTimeout;b.prototype.l=function(g){d(g,0)};b.prototype.B=function(){for(;this.g&&this.g.length;){var g=this.g;this.g=[];for(var h=0;h<g.length;++h){var k=g[h];g[h]=null;try{k()}catch(n){this.o(n)}}}this.g=null};b.prototype.o=function(g){this.l(function(){throw g; })};var e=function(g){this.g=0;this.l=void 0;this.h=[];this.C=!1;var h=this.o();try{g(h.resolve,h.reject)}catch(k){h.reject(k)}};e.prototype.o=function(){function g(n){return function(m){k||(k=!0,n.call(h,m))}}var h=this,k=!1;return{resolve:g(this.I),reject:g(this.B)}};e.prototype.I=function(g){if(g===this)this.B(new TypeError("A Promise cannot resolve to itself"));else if(g instanceof e)this.M(g);else{a:switch(typeof g){case "object":var h=null!=g;break a;case "function":h=!0;break a;default:h=!1}h? this.H(g):this.A(g)}};e.prototype.H=function(g){var h=void 0;try{h=g.then}catch(k){this.B(k);return}"function"==typeof h?this.N(h,g):this.A(g)};e.prototype.B=function(g){this.J(2,g)};e.prototype.A=function(g){this.J(1,g)};e.prototype.J=function(g,h){if(0!=this.g)throw Error("Cannot settle("+g+", "+h+"): Promise already settled in state"+this.g);this.g=g;this.l=h;2===this.g&&this.L();this.K()};e.prototype.L=function(){var g=this;d(function(){if(g.F()){var h=da.console;"undefined"!==typeof h&&h.error(g.l)}}, 1)};e.prototype.F=function(){if(this.C)return!1;var g=da.CustomEvent,h=da.Event,k=da.dispatchEvent;if("undefined"===typeof k)return!0;"function"===typeof g?g=new g("unhandledrejection",{cancelable:!0}):"function"===typeof h?g=new h("unhandledrejection",{cancelable:!0}):(g=da.document.createEvent("CustomEvent"),g.initCustomEvent("unhandledrejection",!1,!0,g));g.promise=this;g.reason=this.l;return k(g)};e.prototype.K=function(){if(null!=this.h){for(var g=0;g<this.h.length;++g)f.h(this.h[g]);this.h= null}};var f=new b;e.prototype.M=function(g){var h=this.o();g.Rb(h.resolve,h.reject)};e.prototype.N=function(g,h){var k=this.o();try{g.call(h,k.resolve,k.reject)}catch(n){k.reject(n)}};e.prototype.then=function(g,h){function k(r,w){return"function"==typeof r?function(B){try{n(r(B))}catch(L){m(L)}}:w}var n,m,v=new e(function(r,w){n=r;m=w});this.Rb(k(g,n),k(h,m));return v};e.prototype.catch=function(g){return this.then(void 0,g)};e.prototype.Rb=function(g,h){function k(){switch(n.g){case 1:g(n.l);break; case 2:h(n.l);break;default:throw Error("Unexpected state: "+n.g);}}var n=this;null==this.h?f.h(k):this.h.push(k);this.C=!0};e.resolve=c;e.reject=function(g){return new e(function(h,k){k(g)})};e.race=function(g){return new e(function(h,k){for(var n=q(g),m=n.next();!m.done;m=n.next())c(m.value).Rb(h,k)})};e.all=function(g){var h=q(g),k=h.next();return k.done?c([]):new e(function(n,m){function v(B){return function(L){r[B]=L;w--;0==w&&n(r)}}var r=[],w=0;do r.push(void 0),w++,c(k.value).Rb(v(r.length- 1),m),k=h.next();while(!k.done)})};return e});p("Object.setPrototypeOf",function(a){return a||oa});var Ca=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)},Da="function"==typeof Object.assign?Object.assign:function(a,b){for(var c=1;c<arguments.length;c++){var d=arguments[c];if(d)for(var e in d)Ca(d,e)&&(a[e]=d[e])}return a};p("Object.assign",function(a){return a||Da}); p("WeakMap",function(a){function b(){}function c(k){var n=typeof k;return"object"===n&&null!==k||"function"===n}function d(k){if(!Ca(k,f)){var n=new b;ba(k,f,{value:n})}}function e(k){var n=Object[k];n&&(Object[k]=function(m){if(m instanceof b)return m;Object.isExtensible(m)&&d(m);return n(m)})}if(function(){if(!a||!Object.seal)return!1;try{var k=Object.seal({}),n=Object.seal({}),m=new a([[k,2],[n,3]]);if(2!=m.get(k)||3!=m.get(n))return!1;m.delete(k);m.set(n,4);return!m.has(k)&&4==m.get(n)}catch(v){return!1}}())return a; var f="$jscomp_hidden_"+Math.random();e("freeze");e("preventExtensions");e("seal");var g=0,h=function(k){this.g=(g+=Math.random()+1).toString();if(k){k=q(k);for(var n;!(n=k.next()).done;)n=n.value,this.set(n[0],n[1])}};h.prototype.set=function(k,n){if(!c(k))throw Error("Invalid WeakMap key");d(k);if(!Ca(k,f))throw Error("WeakMap key fail: "+k);k[f][this.g]=n;return this};h.prototype.get=function(k){return c(k)&&Ca(k,f)?k[f][this.g]:void 0};h.prototype.has=function(k){return c(k)&&Ca(k,f)&&Ca(k[f], this.g)};h.prototype.delete=function(k){return c(k)&&Ca(k,f)&&Ca(k[f],this.g)?delete k[f][this.g]:!1};return h}); p("Map",function(a){if(function(){if(!a||"function"!=typeof a||!a.prototype.entries||"function"!=typeof Object.seal)return!1;try{var h=Object.seal({x:4}),k=new a(q([[h,"s"]]));if("s"!=k.get(h)||1!=k.size||k.get({x:4})||k.set({x:4},"t")!=k||2!=k.size)return!1;var n=k.entries(),m=n.next();if(m.done||m.value[0]!=h||"s"!=m.value[1])return!1;m=n.next();return m.done||4!=m.value[0].x||"t"!=m.value[1]||!n.next().done?!1:!0}catch(v){return!1}}())return a;var b=new WeakMap,c=function(h){this.h={};this.g=f(); this.size=0;if(h){h=q(h);for(var k;!(k=h.next()).done;)k=k.value,this.set(k[0],k[1])}};c.prototype.set=function(h,k){h=0===h?0:h;var n=d(this,h);n.list||(n.list=this.h[n.id]=[]);n.oa?n.oa.value=k:(n.oa={next:this.g,Ka:this.g.Ka,head:this.g,key:h,value:k},n.list.push(n.oa),this.g.Ka.next=n.oa,this.g.Ka=n.oa,this.size++);return this};c.prototype.delete=function(h){h=d(this,h);return h.oa&&h.list?(h.list.splice(h.index,1),h.list.length||delete this.h[h.id],h.oa.Ka.next=h.oa.next,h.oa.next.Ka=h.oa.Ka, h.oa.head=null,this.size--,!0):!1};c.prototype.clear=function(){this.h={};this.g=this.g.Ka=f();this.size=0};c.prototype.has=function(h){return!!d(this,h).oa};c.prototype.get=function(h){return(h=d(this,h).oa)&&h.value};c.prototype.entries=function(){return e(this,function(h){return[h.key,h.value]})};c.prototype.keys=function(){return e(this,function(h){return h.key})};c.prototype.values=function(){return e(this,function(h){return h.value})};c.prototype.forEach=function(h,k){for(var n=this.entries(), m;!(m=n.next()).done;)m=m.value,h.call(k,m[1],m[0],this)};c.prototype[Symbol.iterator]=c.prototype.entries;var d=function(h,k){var n=k&&typeof k;"object"==n||"function"==n?b.has(k)?n=b.get(k):(n=""+ ++g,b.set(k,n)):n="p_"+k;var m=h.h[n];if(m&&Ca(h.h,n))for(h=0;h<m.length;h++){var v=m[h];if(k!==k&&v.key!==v.key||k===v.key)return{id:n,list:m,index:h,oa:v}}return{id:n,list:m,index:-1,oa:void 0}},e=function(h,k){var n=h.g;return ea(function(){if(n){for(;n.head!=h.g;)n=n.Ka;for(;n.next!=n.head;)return n= n.next,{done:!1,value:k(n)};n=null}return{done:!0,value:void 0}})},f=function(){var h={};return h.Ka=h.next=h.head=h},g=0;return c});var Ea=function(a,b,c){if(null==a)throw new TypeError("The 'this' value for String.prototype."+c+" must not be null or undefined");if(b instanceof RegExp)throw new TypeError("First argument to String.prototype."+c+" must not be a regular expression");return a+""}; p("Array.prototype.find",function(a){return a?a:function(b,c){a:{var d=this;d instanceof String&&(d=String(d));for(var e=d.length,f=0;f<e;f++){var g=d[f];if(b.call(c,g,f,d)){b=g;break a}}b=void 0}return b}});p("String.prototype.repeat",function(a){return a?a:function(b){var c=Ea(this,null,"repeat");if(0>b||1342177279<b)throw new RangeError("Invalid count value");b|=0;for(var d="";b;)if(b&1&&(d+=c),b>>>=1)c+=c;return d}}); var Fa=function(a,b){a instanceof String&&(a+="");var c=0,d=!1,e={next:function(){if(!d&&c<a.length){var f=c++;return{value:b(f,a[f]),done:!1}}d=!0;return{done:!0,value:void 0}}};e[Symbol.iterator]=function(){return e};return e};p("Array.prototype.entries",function(a){return a?a:function(){return Fa(this,function(b,c){return[b,c]})}});p("Object.entries",function(a){return a?a:function(b){var c=[],d;for(d in b)Ca(b,d)&&c.push([d,b[d]]);return c}}); p("Array.prototype.keys",function(a){return a?a:function(){return Fa(this,function(b){return b})}});p("Object.is",function(a){return a?a:function(b,c){return b===c?0!==b||1/b===1/c:b!==b&&c!==c}});p("Array.prototype.includes",function(a){return a?a:function(b,c){var d=this;d instanceof String&&(d=String(d));var e=d.length;c=c||0;for(0>c&&(c=Math.max(c+e,0));c<e;c++){var f=d[c];if(f===b||Object.is(f,b))return!0}return!1}}); p("String.prototype.includes",function(a){return a?a:function(b,c){return-1!==Ea(this,b,"includes").indexOf(b,c||0)}});p("Math.trunc",function(a){return a?a:function(b){b=Number(b);if(isNaN(b)||Infinity===b||-Infinity===b||0===b)return b;var c=Math.floor(Math.abs(b));return 0>b?-c:c}});p("Array.prototype.fill",function(a){return a?a:function(b,c,d){var e=this.length||0;0>c&&(c=Math.max(0,e+c));if(null==d||d>e)d=e;d=Number(d);0>d&&(d=Math.max(0,e+d));for(c=Number(c||0);c<d;c++)this[c]=b;return this}}); var Ga=function(a){return a?a:Array.prototype.fill};p("Int8Array.prototype.fill",Ga);p("Uint8Array.prototype.fill",Ga);p("Uint8ClampedArray.prototype.fill",Ga);p("Int16Array.prototype.fill",Ga);p("Uint16Array.prototype.fill",Ga);p("Int32Array.prototype.fill",Ga);p("Uint32Array.prototype.fill",Ga);p("Float32Array.prototype.fill",Ga);p("Float64Array.prototype.fill",Ga); p("String.prototype.padStart",function(a){return a?a:function(b,c){var d=Ea(this,null,"padStart");b-=d.length;c=void 0!==c?String(c):" ";return(0<b&&c?c.repeat(Math.ceil(b/c.length)).substring(0,b):"")+d}});p("Array.prototype.values",function(a){return a?a:function(){return Fa(this,function(b,c){return c})}});p("Math.imul",function(a){return a?a:function(b,c){b=Number(b);c=Number(c);var d=b&65535,e=c&65535;return d*e+((b>>>16&65535)*e+d*(c>>>16&65535)<<16>>>0)|0}}); var Ha=Ha||{},u=this||self,x=function(a,b,c){a=a.split(".");c=c||u;a[0]in c||"undefined"==typeof c.execScript||c.execScript("var "+a[0]);for(var d;a.length&&(d=a.shift());)a.length||void 0===b?c[d]&&c[d]!==Object.prototype[d]?c=c[d]:c=c[d]={}:c[d]=b},Ia=function(a,b){a=a.split(".");b=b||u;for(var c=0;c<a.length;c++)if(b=b[a[c]],null==b)return null;return b},Ja=function(){},Ka=function(a){a.Fc=void 0;a.D=function(){return a.Fc?a.Fc:a.Fc=new a}},Ma=function(a){var b=typeof a;b="object"!=b?b:a?Array.isArray(a)? "array":b:"null";return"array"==b||"object"==b&&"number"==typeof a.length},Na=function(a){var b=typeof a;return"object"==b&&null!=a||"function"==b},Qa=function(a){return Object.prototype.hasOwnProperty.call(a,Oa)&&a[Oa]||(a[Oa]=++Pa)},Ra=function(a){null!==a&&"removeAttribute"in a&&a.removeAttribute(Oa);try{delete a[Oa]}catch(b){}},Oa="closure_uid_"+(1E9*Math.random()>>>0),Pa=0,Ta=function(a,b,c){return a.call.apply(a.bind,arguments)},Ua=function(a,b,c){if(!a)throw Error();if(2<arguments.length){var d= Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(e,d);return a.apply(b,e)}}return function(){return a.apply(b,arguments)}},Va=function(a,b,c){Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?Va=Ta:Va=Ua;return Va.apply(null,arguments)},Wa=function(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var d=c.slice();d.push.apply(d,arguments);return a.apply(this,d)}}, Xa=function(){return Date.now()},Ya=function(a,b){function c(){}c.prototype=b.prototype;a.za=b.prototype;a.prototype=new c;a.prototype.constructor=a;a.sh=function(d,e,f){for(var g=Array(arguments.length-2),h=2;h<arguments.length;h++)g[h-2]=arguments[h];return b.prototype[e].apply(d,g)}},Za=function(a){return a};var $a=function(a,b){var c=void 0;return new (c||(c=Promise))(function(d,e){function f(k){try{h(b.next(k))}catch(n){e(n)}}function g(k){try{h(b["throw"](k))}catch(n){e(n)}}function h(k){k.done?d(k.value):(new c(function(n){n(k.value)})).then(f,g)}h((b=b.apply(a,void 0)).next())})};function ab(a){if(Error.captureStackTrace)Error.captureStackTrace(this,ab);else{var b=Error().stack;b&&(this.stack=b)}a&&(this.message=String(a))}Ya(ab,Error);ab.prototype.name="CustomError";var bb;var cb=function(a){return Array.prototype.map.call(a,function(b){b=b.toString(16);return 1<b.length?b:"0"+b}).join("")};var db=function(a){return function(){return a}},eb=function(a){var b=!1,c;return function(){b||(c=a(),b=!0);return c}},fb=function(a){var b=a;return function(){if(b){var c=b;b=null;c()}}},gb=function(a){var b=0,c=!1,d=[],e=function(){b=0;c&&(c=!1,f())},f=function(){b=u.setTimeout(e,1E3);var g=d;d=[];a.apply(void 0,g)};return function(g){d=arguments;b?c=!0:f()}};var ib=function(a,b){if("string"===typeof a)return"string"!==typeof b||1!=b.length?-1:a.indexOf(b,0);for(var c=0;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1},y=function(a,b){for(var c=a.length,d="string"===typeof a?a.split(""):a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)};function jb(a,b){for(var c="string"===typeof a?a.split(""):a,d=a.length-1;0<=d;--d)d in c&&b.call(void 0,c[d],d,a)} var kb=function(a,b){for(var c=a.length,d=[],e=0,f="string"===typeof a?a.split(""):a,g=0;g<c;g++)if(g in f){var h=f[g];b.call(void 0,h,g,a)&&(d[e++]=h)}return d},lb=function(a,b){for(var c=a.length,d=Array(c),e="string"===typeof a?a.split(""):a,f=0;f<c;f++)f in e&&(d[f]=b.call(void 0,e[f],f,a));return d},nb=function(a,b,c){var d=c;y(a,function(e,f){d=b.call(void 0,d,e,f,a)});return d},ob=function(a,b){for(var c=a.length,d="string"===typeof a?a.split(""):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e], e,a))return!0;return!1};function pb(a,b){b=qb(a,b,void 0);return 0>b?null:"string"===typeof a?a.charAt(b):a[b]}function qb(a,b,c){for(var d=a.length,e="string"===typeof a?a.split(""):a,f=0;f<d;f++)if(f in e&&b.call(c,e[f],f,a))return f;return-1}function rb(a,b){for(var c="string"===typeof a?a.split(""):a,d=a.length-1;0<=d;d--)if(d in c&&b.call(void 0,c[d],d,a))return d;return-1}function sb(a,b){return 0<=ib(a,b)}function tb(a,b){b=ib(a,b);var c;(c=0<=b)&&ub(a,b);return c} function ub(a,b){return 1==Array.prototype.splice.call(a,b,1).length}function vb(a,b){var c=0;jb(a,function(d,e){b.call(void 0,d,e,a)&&ub(a,e)&&c++})}function wb(a){return Array.prototype.concat.apply([],arguments)}function xb(a){var b=a.length;if(0<b){for(var c=Array(b),d=0;d<b;d++)c[d]=a[d];return c}return[]}function yb(a){for(var b=0,c=0,d={};c<a.length;){var e=a[c++],f=Na(e)?"o"+Qa(e):(typeof e).charAt(0)+e;Object.prototype.hasOwnProperty.call(d,f)||(d[f]=!0,a[b++]=e)}a.length=b} function zb(a,b){a.sort(b||Ab)}function Ab(a,b){return a>b?1:a<b?-1:0}function Bb(a){for(var b=[],c=0;c<a;c++)b[c]="";return b};function Cb(a,b,c){for(var d in a)b.call(c,a[d],d,a)}function Db(a,b){var c={},d;for(d in a)b.call(void 0,a[d],d,a)&&(c[d]=a[d]);return c}function Eb(a){var b=Fb,c;for(c in b)if(a.call(void 0,b[c],c,b))return!0;return!1}function Gb(a){var b=Hb,c;for(c in b)if(!a.call(void 0,b[c],c,b))return!1;return!0}function Ib(a){var b=[],c=0,d;for(d in a)b[c++]=a[d];return b}function Jb(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b} function Kb(a,b){var c=Ma(b),d=c?b:arguments;for(c=c?0:1;c<d.length;c++){if(null==a)return;a=a[d[c]]}return a}function Lb(a,b){return null!==a&&b in a}function Mb(a,b){for(var c in a)if(a[c]==b)return!0;return!1}function Nb(a){var b=Ob,c;for(c in b)if(a.call(void 0,b[c],c,b))return c}function Pb(a){for(var b in a)return!1;return!0}function Qb(a){for(var b in a)delete a[b]}function Rb(a,b,c){return null!==a&&b in a?a[b]:c}var Sb="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "); function Tb(a,b){for(var c,d,e=1;e<arguments.length;e++){d=arguments[e];for(c in d)a[c]=d[c];for(var f=0;f<Sb.length;f++)c=Sb[f],Object.prototype.hasOwnProperty.call(d,c)&&(a[c]=d[c])}};var Ub,Vb=function(){if(void 0===Ub){var a=null,b=u.trustedTypes;if(b&&b.createPolicy){try{a=b.createPolicy("goog#html",{createHTML:Za,createScript:Za,createScriptURL:Za})}catch(c){u.console&&u.console.error(c.message)}Ub=a}else Ub=a}return Ub};var Yb=function(a,b){this.g=a===Wb&&b||"";this.h=Xb};Yb.prototype.Ra=!0;Yb.prototype.Ga=function(){return this.g};var Zb=function(a){return a instanceof Yb&&a.constructor===Yb&&a.h===Xb?a.g:"type_error:Const"},$b=function(a){return new Yb(Wb,a)},Xb={},Wb={};var bc=function(a,b){this.g=b===ac?a:""};l=bc.prototype;l.Ra=!0;l.Ga=function(){return this.g.toString()};l.Dc=!0;l.zc=function(){return 1};l.toString=function(){return this.g+""};var cc=function(a){return a instanceof bc&&a.constructor===bc?a.g:"type_error:TrustedResourceUrl"},ac={},dc=function(a){var b=Vb();a=b?b.createScriptURL(a):a;return new bc(a,ac)};var ec=function(a,b){var c=a.length-b.length;return 0<=c&&a.indexOf(b,c)==c},fc=function(a){return/^[\s\xa0]*$/.test(a)},gc=String.prototype.trim?function(a){return a.trim()}:function(a){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(a)[1]},oc=function(a,b){if(b)a=a.replace(hc,"&amp;").replace(ic,"&lt;").replace(jc,"&gt;").replace(kc,"&quot;").replace(lc,"&#39;").replace(mc,"&#0;");else{if(!nc.test(a))return a;-1!=a.indexOf("&")&&(a=a.replace(hc,"&amp;"));-1!=a.indexOf("<")&&(a=a.replace(ic,"&lt;")); -1!=a.indexOf(">")&&(a=a.replace(jc,"&gt;"));-1!=a.indexOf('"')&&(a=a.replace(kc,"&quot;"));-1!=a.indexOf("'")&&(a=a.replace(lc,"&#39;"));-1!=a.indexOf("\x00")&&(a=a.replace(mc,"&#0;"))}return a},hc=/&/g,ic=/</g,jc=/>/g,kc=/"/g,lc=/'/g,mc=/\x00/g,nc=/[\x00&<>"']/,pc=function(a,b){return-1!=a.toLowerCase().indexOf(b.toLowerCase())},rc=function(a,b){var c=0;a=gc(String(a)).split(".");b=gc(String(b)).split(".");for(var d=Math.max(a.length,b.length),e=0;0==c&&e<d;e++){var f=a[e]||"",g=b[e]||"";do{f=/(\d*)(\D*)(.*)/.exec(f)|| ["","","",""];g=/(\d*)(\D*)(.*)/.exec(g)||["","","",""];if(0==f[0].length&&0==g[0].length)break;c=qc(0==f[1].length?0:parseInt(f[1],10),0==g[1].length?0:parseInt(g[1],10))||qc(0==f[2].length,0==g[2].length)||qc(f[2],g[2]);f=f[3];g=g[3]}while(0==c)}return c},qc=function(a,b){return a<b?-1:a>b?1:0};var tc=function(a,b){this.g=b===sc?a:""};l=tc.prototype;l.Ra=!0;l.Ga=function(){return this.g.toString()};l.Dc=!0;l.zc=function(){return 1};l.toString=function(){return this.g.toString()}; var uc=function(a){return a instanceof tc&&a.constructor===tc?a.g:"type_error:SafeUrl"},vc=/^(?:audio\/(?:3gpp2|3gpp|aac|L16|midi|mp3|mp4|mpeg|oga|ogg|opus|x-m4a|x-matroska|x-wav|wav|webm)|font\/\w+|image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp|x-icon)|video\/(?:mpeg|mp4|ogg|webm|quicktime|x-matroska))(?:;\w+=(?:\w+|"[\w;,= ]+"))*$/i,wc=/^data:(.*);base64,[a-z0-9+\/]+=*$/i,xc=/^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i,yc=function(a){if(a instanceof tc)return a;a="object"==typeof a&&a.Ra?a.Ga(): String(a);xc.test(a)||(a="about:invalid#zClosurez");return new tc(a,sc)},sc={},zc=new tc("about:invalid#zClosurez",sc);var Bc=function(a,b){this.g=b===Ac?a:""};Bc.prototype.Ra=!0;Bc.prototype.Ga=function(){return this.g};Bc.prototype.toString=function(){return this.g.toString()};var Ac={},Cc=new Bc("",Ac);var Dc;a:{var Ec=u.navigator;if(Ec){var Fc=Ec.userAgent;if(Fc){Dc=Fc;break a}}Dc=""}var z=function(a){return-1!=Dc.indexOf(a)};var Gc=function(){return z("Trident")||z("MSIE")},Hc=function(){return z("Firefox")||z("FxiOS")},Jc=function(){return z("Safari")&&!(Ic()||z("Coast")||z("Opera")||z("Edge")||z("Edg/")||z("OPR")||Hc()||z("Silk")||z("Android"))},Ic=function(){return(z("Chrome")||z("CriOS"))&&!z("Edge")};var Lc=function(a,b,c){this.g=c===Kc?a:"";this.h=b};l=Lc.prototype;l.Dc=!0;l.zc=function(){return this.h};l.Ra=!0;l.Ga=function(){return this.g.toString()};l.toString=function(){return this.g.toString()};var Mc=function(a){return a instanceof Lc&&a.constructor===Lc?a.g:"type_error:SafeHtml"},Kc={},Nc=function(a,b){var c=Vb();a=c?c.createHTML(a):a;return new Lc(a,b,Kc)},Oc=new Lc(u.trustedTypes&&u.trustedTypes.emptyHTML||"",0,Kc);var Pc=eb(function(){var a=document.createElement("div"),b=document.createElement("div");b.appendChild(document.createElement("div"));a.appendChild(b);b=a.firstChild.firstChild;a.innerHTML=Mc(Oc);return!b.parentElement}),Qc=function(a,b){if(Pc())for(;a.lastChild;)a.removeChild(a.lastChild);a.innerHTML=Mc(b)},Rc=function(a,b){a.write(Mc(b))},Sc=/^[\w+/_-]+[=]{0,2}$/,Tc=function(a,b){b=(b||u).document;return b.querySelector?(a=b.querySelector(a))&&(a=a.nonce||a.getAttribute("nonce"))&&Sc.test(a)?a: "":""};var Vc=function(a){return decodeURIComponent(a.replace(/\+/g," "))},Wc=function(a){return a=oc(a,void 0)},Xc=function(a,b){a.length>b&&(a=a.substring(0,b-3)+"...");return a},Yc=String.prototype.repeat?function(a,b){return a.repeat(b)}:function(a,b){return Array(b+1).join(a)},$c=function(a){return null==a?"":String(a)},ad=2147483648*Math.random()|0,bd=function(a){return String(a).replace(/\-([a-z])/g,function(b,c){return c.toUpperCase()})},cd=function(){return"googleAvInapp".replace(/([A-Z])/g,"-$1").toLowerCase()}, dd=function(a){return a.replace(/(^|[\s]+)([a-z])/g,function(b,c,d){return c+d.toUpperCase()})},ed=function(a){isFinite(a)&&(a=String(a));return"string"===typeof a?/^\s*-?0x/i.test(a)?parseInt(a,16):parseInt(a,10):NaN};var fd="function"===typeof Uint8Array.prototype.slice,gd=0,hd=0;function id(a){var b=0>a;a=Math.abs(a);var c=a>>>0;a=Math.floor((a-c)/4294967296);a>>>=0;b&&(a=~a>>>0,c=(~c>>>0)+1,4294967295<c&&(c=0,a++,4294967295<a&&(a=0)));gd=c;hd=a};var jd=function(){this.g=new Uint8Array(64);this.h=0};jd.prototype.push=function(a){if(!(this.h+1<this.g.length)){var b=this.g;this.g=new Uint8Array(Math.ceil(1+2*this.g.length));this.g.set(b)}this.g[this.h++]=a};jd.prototype.length=function(){return this.h};jd.prototype.end=function(){var a=this.g,b=this.h;this.h=0;return fd?a.slice(0,b):new Uint8Array(a.subarray(0,b))}; var kd=function(a){for(var b=gd,c=hd;0<c||127<b;)a.push(b&127|128),b=(b>>>7|c<<25)>>>0,c>>>=7;a.push(b)},ld=function(a,b){for(;127<b;)a.push(b&127|128),b>>>=7;a.push(b)},md=function(a,b){a.push(b>>>0&255);a.push(b>>>8&255);a.push(b>>>16&255);a.push(b>>>24&255)};var nd=function(){return z("iPhone")&&!z("iPod")&&!z("iPad")},od=function(){return nd()||z("iPad")||z("iPod")};var pd=function(a){pd[" "](a);return a};pd[" "]=Ja;var qd=function(a,b){try{return pd(a[b]),!0}catch(c){}return!1},sd=function(a,b){var c=rd;return Object.prototype.hasOwnProperty.call(c,a)?c[a]:c[a]=b(a)};var td=z("Opera"),ud=Gc(),vd=z("Edge"),wd=z("Gecko")&&!(pc(Dc,"WebKit")&&!z("Edge"))&&!(z("Trident")||z("MSIE"))&&!z("Edge"),xd=pc(Dc,"WebKit")&&!z("Edge"),yd=z("Macintosh"),zd=z("Android"),Bd=nd(),Cd=z("iPad"),Dd=z("iPod"),Ed=od(),Fd=function(){var a=u.document;return a?a.documentMode:void 0},Gd; a:{var Hd="",Id=function(){var a=Dc;if(wd)return/rv:([^\);]+)(\)|;)/.exec(a);if(vd)return/Edge\/([\d\.]+)/.exec(a);if(ud)return/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a);if(xd)return/WebKit\/(\S+)/.exec(a);if(td)return/(?:Version)[ \/]?(\S+)/.exec(a)}();Id&&(Hd=Id?Id[1]:"");if(ud){var Jd=Fd();if(null!=Jd&&Jd>parseFloat(Hd)){Gd=String(Jd);break a}}Gd=Hd}var Kd=Gd,rd={},Ld=function(a){return sd(a,function(){return 0<=rc(Kd,a)})},Md; if(u.document&&ud){var Nd=Fd();Md=Nd?Nd:parseInt(Kd,10)||void 0}else Md=void 0;var Od=Md;var Pd=Hc(),Qd=nd()||z("iPod"),Rd=z("iPad"),Sd=z("Android")&&!(Ic()||Hc()||z("Opera")||z("Silk")),Td=Ic(),Ud=Jc()&&!od();var Vd={},Wd=null,Yd=function(a,b){void 0===b&&(b=0);Xd();b=Vd[b];for(var c=Array(Math.floor(a.length/3)),d=b[64]||"",e=0,f=0;e<a.length-2;e+=3){var g=a[e],h=a[e+1],k=a[e+2],n=b[g>>2];g=b[(g&3)<<4|h>>4];h=b[(h&15)<<2|k>>6];k=b[k&63];c[f++]=""+n+g+h+k}n=0;k=d;switch(a.length-e){case 2:n=a[e+1],k=b[(n&15)<<2]||d;case 1:a=a[e],c[f]=""+b[a>>2]+b[(a&3)<<4|n>>4]+k+d}return c.join("")},Zd=function(a){for(var b=[],c=0,d=0;d<a.length;d++){var e=a.charCodeAt(d);255<e&&(b[c++]=e&255,e>>=8);b[c++]=e}return Yd(b, 3)},ae=function(a){var b=[];$d(a,function(c){b.push(c)});return b},$d=function(a,b){function c(k){for(;d<a.length;){var n=a.charAt(d++),m=Wd[n];if(null!=m)return m;if(!fc(n))throw Error("Unknown base64 encoding at char: "+n);}return k}Xd();for(var d=0;;){var e=c(-1),f=c(0),g=c(64),h=c(64);if(64===h&&-1===e)break;b(e<<2|f>>4);64!=g&&(b(f<<4&240|g>>2),64!=h&&b(g<<6&192|h))}},Xd=function(){if(!Wd){Wd={};for(var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),b=["+/=","+/", "-_=","-_.","-_"],c=0;5>c;c++){var d=a.concat(b[c].split(""));Vd[c]=d;for(var e=0;e<d.length;e++){var f=d[e];void 0===Wd[f]&&(Wd[f]=e)}}}};var be=function(){this.l=[];this.h=0;this.g=new jd},ce=function(a,b){ld(a.g,8*b+2);b=a.g.end();a.l.push(b);a.h+=b.length;return{We:a.h,se:a.l.length-1}},de=function(a,b){var c=a.g.end();a.l.push(c);a.h+=c.length;ld(a.g,a.h+a.g.length()-b.We);c=a.g.end();a.h+=c.length;a.l.splice(1+b.se,0,c)},ee=function(a){var b=a.h+a.g.length();if(0===b)return new Uint8Array(0);b=new Uint8Array(b);for(var c=a.l,d=c.length,e=0,f=0;f<d;f++){var g=c[f];0!==g.length&&(b.set(g,e),e+=g.length)}c=a.g;d=c.h;0!==d&&(b.set(c.g.subarray(0, d),e),c.h=0);a.l=[b];return b},fe=function(a,b,c){if(null!=c&&null!=c)if(ld(a.g,8*b),a=a.g,0<=c)ld(a,c);else{for(b=0;9>b;b++)a.push(c&127|128),c>>=7;a.push(1)}},ge=function(a,b,c){null!=c&&null!=c&&(ld(a.g,8*b),a=a.g,id(c),kd(a))},he=function(a,b,c){null!=c&&null!=c&&(ld(a.g,8*b),a=a.g,id(c),kd(a))},ie=function(a,b,c){if(null!=c){b=ce(a,b);var d=a.g;d.length();for(var e=0;e<c.length;e++){var f=c.charCodeAt(e);if(128>f)d.push(f);else if(2048>f)d.push(f>>6|192),d.push(f&63|128);else if(65536>f)if(55296<= f&&56319>=f&&e+1<c.length){var g=c.charCodeAt(e+1);56320<=g&&57343>=g&&(f=1024*(f-55296)+g-56320+65536,d.push(f>>18|240),d.push(f>>12&63|128),d.push(f>>6&63|128),d.push(f&63|128),e++)}else d.push(f>>12|224),d.push(f>>6&63|128),d.push(f&63|128)}d.length();de(a,b)}},ke=function(a,b,c){var d=je;null!=c&&(b=ce(a,b),d(c,a),de(a,b))},le=function(a,b,c,d){if(null!=c)for(var e=0;e<c.length;e++){var f=ce(a,b);d(c[e],a);de(a,f)}};var me="function"===typeof Uint8Array,ne={vh:{value:!0,configurable:!0}},oe=function(a){Array.isArray(a)&&!Object.isFrozen(a)&&Object.defineProperties(a,ne);return a};var pe=function(){},qe,ue=function(a,b,c,d){a.g=null;qe&&(b||(b=qe),qe=null);var e=a.constructor.messageId;b||(b=e?[e]:[]);a.o=e?0:-1;a.h=b;a:{if(b=a.h.length)if(--b,e=a.h[b],!(null===e||"object"!=typeof e||Array.isArray(e)||me&&e instanceof Uint8Array)){a.B=b-a.o;a.l=e;break a}a.B=Number.MAX_VALUE}a.A={};if(c)for(b=0;b<c.length;b++)if(e=c[b],e<a.B){e+=a.o;var f=a.h[e];f?oe(f):a.h[e]=re}else se(a),(f=a.l[e])?oe(f):a.l[e]=re;if(d&&d.length)for(c=0;c<d.length;c++)te(a,d[c])},re=Object.freeze(oe([])), se=function(a){var b=a.B+a.o;a.h[b]||(a.l=a.h[b]={})},A=function(a,b){if(b<a.B){b+=a.o;var c=a.h[b];return c!==re?c:a.h[b]=oe([])}if(a.l)return c=a.l[b],c!==re?c:a.l[b]=oe([])},ve=function(a,b){a=A(a,b);return null==a?a:+a},we=function(a,b){a=A(a,b);return null==a?a:!!a},xe=function(a,b,c){a=A(a,b);return null==a?c:a},ye=function(a,b){var c=void 0===c?!1:c;a=we(a,b);return null==a?c:a},ze=function(a,b){var c=void 0===c?0:c;a=ve(a,b);return null==a?c:a},Ae=function(a,b,c){b<a.B?a.h[b+a.o]=c:(se(a), a.l[b]=c);return a},Be=function(a,b,c){return Ae(a,b,oe(c||[]))},Ce=function(a,b,c,d){c!==d?Ae(a,b,c):b<a.B?a.h[b+a.o]=null:(se(a),delete a.l[b]);return a},te=function(a,b){for(var c,d,e=0;e<b.length;e++){var f=b[e],g=A(a,f);null!=g&&(c=f,d=g,Ae(a,f,void 0))}return c?(Ae(a,c,d),c):0},De=function(a,b,c){a.g||(a.g={});if(!a.g[c]){var d=A(a,c);d&&(a.g[c]=new b(d))}return a.g[c]},Ee=function(a,b,c){a.g||(a.g={});if(!a.g[c]){for(var d=A(a,c),e=[],f=0;f<d.length;f++)e[f]=new b(d[f]);a.g[c]=e}b=a.g[c];b== re&&(b=a.g[c]=[]);return b},Ge=function(a,b,c){a.g||(a.g={});var d=c?Fe(c):c;a.g[b]=c;return Ae(a,b,d)},Fe=function(a){if(a.g)for(var b in a.g){var c=a.g[b];if(Array.isArray(c))for(var d=0;d<c.length;d++)c[d]&&Fe(c[d]);else c&&Fe(c)}return a.h},He=function(a,b){switch(typeof b){case "number":return isNaN(b)||Infinity===b||-Infinity===b?String(b):b;case "object":if(me&&null!=b&&b instanceof Uint8Array)return Yd(b)}return b},Ie=function(a,b){qe=b=b?JSON.parse(b):null;a=new a(b);qe=null;return a}; pe.prototype.toString=function(){return Fe(this).toString()};var Je=document,C=window;function Ke(a){var b,c=(a.ownerDocument&&a.ownerDocument.defaultView||window).document;(b=(c=null===(b=c.querySelector)||void 0===b?void 0:b.call(c,"script[nonce]"))?c.nonce||c.getAttribute("nonce")||"":"")&&a.setAttribute("nonce",b)};var Le=function(a,b,c){c=void 0===c?{}:c;this.error=a;this.context=b.context;this.msg=b.message||"";this.id=b.id||"jserror";this.meta=c},Me=function(a){return!!(a.error&&a.meta&&a.id)};var Ne=eb(function(){var a=!1;try{var b=Object.defineProperty({},"passive",{get:function(){a=!0}});u.addEventListener("test",null,b)}catch(c){}return a});function Oe(a){return a?a.passive&&Ne()?a:a.capture||!1:!1} var Pe=function(a,b,c,d){return a.addEventListener?(a.addEventListener(b,c,Oe(d)),!0):!1},Qe=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,Oe(void 0))},Re=function(a){var b=void 0===b?{}:b;if("function"===typeof window.CustomEvent)var c=new CustomEvent("rum_blp",b);else c=document.createEvent("CustomEvent"),c.initCustomEvent("rum_blp",!!b.bubbles,!!b.cancelable,b.detail);a.dispatchEvent(c)};try{(new self.OffscreenCanvas(0,0)).getContext("2d")}catch(a){}var Se=!ud||9<=Number(Od),Te=ud||td||xd;var Ue=function(a,b){this.x=void 0!==a?a:0;this.y=void 0!==b?b:0};Ue.prototype.ceil=function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this};Ue.prototype.floor=function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this};Ue.prototype.round=function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this};Ue.prototype.scale=function(a,b){this.x*=a;this.y*="number"===typeof b?b:a;return this};var Ve=function(a,b){this.width=a;this.height=b};l=Ve.prototype;l.aspectRatio=function(){return this.width/this.height};l.ceil=function(){this.width=Math.ceil(this.width);this.height=Math.ceil(this.height);return this};l.floor=function(){this.width=Math.floor(this.width);this.height=Math.floor(this.height);return this};l.round=function(){this.width=Math.round(this.width);this.height=Math.round(this.height);return this};l.scale=function(a,b){this.width*=a;this.height*="number"===typeof b?b:a;return this};var Ye=function(a){return a?new We(Xe(a)):bb||(bb=new We)},Ze=function(a){var b=document;return"string"===typeof a?b.getElementById(a):a},$e=function(){var a=document;return a.querySelectorAll&&a.querySelector?a.querySelectorAll("SCRIPT"):a.getElementsByTagName("SCRIPT")},bf=function(a,b){Cb(b,function(c,d){c&&"object"==typeof c&&c.Ra&&(c=c.Ga());"style"==d?a.style.cssText=c:"class"==d?a.className=c:"for"==d?a.htmlFor=c:af.hasOwnProperty(d)?a.setAttribute(af[d],c):0==d.lastIndexOf("aria-",0)||0== d.lastIndexOf("data-",0)?a.setAttribute(d,c):a[d]=c})},af={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",nonce:"nonce",role:"role",rowspan:"rowSpan",type:"type",usemap:"useMap",valign:"vAlign",width:"width"},cf=function(a){a=a.document;a="CSS1Compat"==a.compatMode?a.documentElement:a.body;return new Ve(a.clientWidth,a.clientHeight)},df=function(a){var b=a.scrollingElement?a.scrollingElement:xd||"CSS1Compat"!=a.compatMode? a.body||a.documentElement:a.documentElement;a=a.parentWindow||a.defaultView;return ud&&Ld("10")&&a.pageYOffset!=b.scrollTop?new Ue(b.scrollLeft,b.scrollTop):new Ue(a.pageXOffset||b.scrollLeft,a.pageYOffset||b.scrollTop)},D=function(a){return a?a.parentWindow||a.defaultView:window},gf=function(a,b,c){var d=arguments,e=document,f=String(d[0]),g=d[1];if(!Se&&g&&(g.name||g.type)){f=["<",f];g.name&&f.push(' name="',Wc(g.name),'"');if(g.type){f.push(' type="',Wc(g.type),'"');var h={};Tb(h,g);delete h.type; g=h}f.push(">");f=f.join("")}f=ef(e,f);g&&("string"===typeof g?f.className=g:Array.isArray(g)?f.className=g.join(" "):bf(f,g));2<d.length&&ff(e,f,d,2);return f},ff=function(a,b,c,d){function e(h){h&&b.appendChild("string"===typeof h?a.createTextNode(h):h)}for(;d<c.length;d++){var f=c[d];if(!Ma(f)||Na(f)&&0<f.nodeType)e(f);else{a:{if(f&&"number"==typeof f.length){if(Na(f)){var g="function"==typeof f.item||"string"==typeof f.item;break a}if("function"===typeof f){g="function"==typeof f.item;break a}}g= !1}y(g?xb(f):f,e)}}},ef=function(a,b){b=String(b);"application/xhtml+xml"===a.contentType&&(b=b.toLowerCase());return a.createElement(b)},hf=function(a){a&&a.parentNode&&a.parentNode.removeChild(a)},jf=function(a){var b;if(Te&&!(ud&&Ld("9")&&!Ld("10")&&u.SVGElement&&a instanceof u.SVGElement)&&(b=a.parentElement))return b;b=a.parentNode;return Na(b)&&1==b.nodeType?b:null},kf=function(a,b){if(!a||!b)return!1;if(a.contains&&1==b.nodeType)return a==b||a.contains(b);if("undefined"!=typeof a.compareDocumentPosition)return a== b||!!(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a},Xe=function(a){return 9==a.nodeType?a:a.ownerDocument||a.document},lf=function(a){try{return a.contentWindow||(a.contentDocument?D(a.contentDocument):null)}catch(b){}return null},mf=function(a,b){a&&(a=a.parentNode);for(var c=0;a;){if(b(a))return a;a=a.parentNode;c++}return null},We=function(a){this.g=a||u.document||document};l=We.prototype;l.getElementsByTagName=function(a,b){return(b||this.g).getElementsByTagName(String(a))}; l.createElement=function(a){return ef(this.g,a)};l.appendChild=function(a,b){a.appendChild(b)};l.append=function(a,b){ff(Xe(a),a,arguments,1)};l.canHaveChildren=function(a){if(1!=a.nodeType)return!1;switch(a.tagName){case "APPLET":case "AREA":case "BASE":case "BR":case "COL":case "COMMAND":case "EMBED":case "FRAME":case "HR":case "IMG":case "INPUT":case "IFRAME":case "ISINDEX":case "KEYGEN":case "LINK":case "NOFRAMES":case "NOSCRIPT":case "META":case "OBJECT":case "PARAM":case "SCRIPT":case "SOURCE":case "STYLE":case "TRACK":case "WBR":return!1}return!0};var of=function(){return!nf()&&(z("iPod")||z("iPhone")||z("Android")||z("IEMobile"))},nf=function(){return z("iPad")||z("Android")&&!z("Mobile")||z("Silk")};var pf=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/,qf=function(a){var b=a.match(pf);a=b[1];var c=b[3];b=b[4];var d="";a&&(d+=a+":");c&&(d=d+"//"+c,b&&(d+=":"+b));return d},rf=function(a,b){if(a){a=a.split("&");for(var c=0;c<a.length;c++){var d=a[c].indexOf("="),e=null;if(0<=d){var f=a[c].substring(0,d);e=a[c].substring(d+1)}else f=a[c];b(f,e?Vc(e):"")}}},sf=/#|$/,tf=function(a,b){var c=a.search(sf);a:{var d=0;for(var e= b.length;0<=(d=a.indexOf(b,d))&&d<c;){var f=a.charCodeAt(d-1);if(38==f||63==f)if(f=a.charCodeAt(d+e),!f||61==f||38==f||35==f)break a;d+=e+1}d=-1}if(0>d)return null;e=a.indexOf("&",d);if(0>e||e>c)e=c;d+=b.length+1;return Vc(a.substr(d,e-d))};var uf=function(a){try{return!!a&&null!=a.location.href&&qd(a,"foo")}catch(b){return!1}},wf=function(a){for(var b=u,c=0;b&&40>c++&&(!uf(b)||!a(b));)b=vf(b)},xf=function(){var a,b=a=void 0===a?u:a;wf(function(c){b=c;return!1});return b},vf=function(a){try{var b=a.parent;if(b&&b!=a)return b}catch(c){}return null},yf=function(){var a=window;return uf(a.top)?a.top:null},zf=function(a,b){if(a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&b.call(void 0,a[c],c,a)},Af=/https?:\/\/[^\/]+/,Bf=function(a){return(a= Af.exec(a))&&a[0]||""},Cf=function(){var a=u;var b=void 0===b?!0:b;try{for(var c=null;c!=a;c=a,a=a.parent)switch(a.location.protocol){case "https:":return!0;case "file:":return b;case "http:":return!1}}catch(d){}return!0},Ef=function(){var a=Df;if(!a)return"";var b=/.*[&#?]google_debug(=[^&]*)?(&.*)?$/;try{var c=b.exec(decodeURIComponent(a));if(c)return c[1]&&1<c[1].length?c[1].substring(1):"true"}catch(d){}return""},Ff=function(a,b){try{return!(!a.frames||!a.frames[b])}catch(c){return!1}},Gf=function(a, b){for(var c=0;50>c;++c){if(Ff(a,b))return a;if(!(a=vf(a)))break}return null},If=function(a){var b=Hf;a=void 0===a?window.document:a;0!=b.length&&a.head&&b.forEach(function(c){if(c){var d=a;d=void 0===d?window.document:d;if(c&&d.head){var e=document.createElement("meta");d.head.appendChild(e);e.httpEquiv="origin-trial";e.content=c}}})};var E=function(a,b,c,d){this.top=a;this.right=b;this.bottom=c;this.left=d};E.prototype.getWidth=function(){return this.right-this.left};E.prototype.getHeight=function(){return this.bottom-this.top};var Jf=function(a){return new E(a.top,a.right,a.bottom,a.left)};E.prototype.expand=function(a,b,c,d){Na(a)?(this.top-=a.top,this.right+=a.right,this.bottom+=a.bottom,this.left-=a.left):(this.top-=a,this.right+=Number(b),this.bottom+=Number(c),this.left-=Number(d));return this}; E.prototype.ceil=function(){this.top=Math.ceil(this.top);this.right=Math.ceil(this.right);this.bottom=Math.ceil(this.bottom);this.left=Math.ceil(this.left);return this};E.prototype.floor=function(){this.top=Math.floor(this.top);this.right=Math.floor(this.right);this.bottom=Math.floor(this.bottom);this.left=Math.floor(this.left);return this}; E.prototype.round=function(){this.top=Math.round(this.top);this.right=Math.round(this.right);this.bottom=Math.round(this.bottom);this.left=Math.round(this.left);return this};var Kf=function(a,b,c){b instanceof Ue?(a.left+=b.x,a.right+=b.x,a.top+=b.y,a.bottom+=b.y):(a.left+=b,a.right+=b,"number"===typeof c&&(a.top+=c,a.bottom+=c));return a};E.prototype.scale=function(a,b){b="number"===typeof b?b:a;this.left*=a;this.right*=a;this.top*=b;this.bottom*=b;return this};var Lf=function(a,b,c,d){this.left=a;this.top=b;this.width=c;this.height=d},Mf=function(a){return new E(a.top,a.left+a.width,a.top+a.height,a.left)};Lf.prototype.ceil=function(){this.left=Math.ceil(this.left);this.top=Math.ceil(this.top);this.width=Math.ceil(this.width);this.height=Math.ceil(this.height);return this};Lf.prototype.floor=function(){this.left=Math.floor(this.left);this.top=Math.floor(this.top);this.width=Math.floor(this.width);this.height=Math.floor(this.height);return this}; Lf.prototype.round=function(){this.left=Math.round(this.left);this.top=Math.round(this.top);this.width=Math.round(this.width);this.height=Math.round(this.height);return this};Lf.prototype.scale=function(a,b){b="number"===typeof b?b:a;this.left*=a;this.width*=a;this.top*=b;this.height*=b;return this};var Nf=function(a){a=void 0===a?u:a;var b=a.context||a.AMP_CONTEXT_DATA;if(!b)try{b=a.parent.context||a.parent.AMP_CONTEXT_DATA}catch(c){}try{if(b&&b.pageViewId&&b.canonicalUrl)return b}catch(c){}return null};var Of=function(a,b){a.google_image_requests||(a.google_image_requests=[]);var c=a.document.createElement("img");c.src=b;a.google_image_requests.push(c)},Qf=function(a,b){var c="https://pagead2.googlesyndication.com/pagead/gen_204?id="+b;zf(a,function(d,e){d&&(c+="&"+e+"="+encodeURIComponent(d))});Pf(c)},Pf=function(a){var b=window;b.fetch?b.fetch(a,{keepalive:!0,credentials:"include",redirect:"follow",method:"get",mode:"no-cors"}):Of(b,a)};var Sf=function(a){Rf();return Nc(a,null)},Tf=function(a){Rf();return dc(a)},Rf=Ja;var Vf=function(a,b){if("string"===typeof b)(b=Uf(a,b))&&(a.style[b]=void 0);else for(var c in b){var d=a,e=b[c],f=Uf(d,c);f&&(d.style[f]=e)}},Wf={},Uf=function(a,b){var c=Wf[b];if(!c){var d=bd(b);c=d;void 0===a.style[d]&&(d=(xd?"Webkit":wd?"Moz":ud?"ms":td?"O":null)+dd(d),void 0!==a.style[d]&&(c=d));Wf[b]=c}return c},Xf=function(a,b){var c=a.style[bd(b)];return"undefined"!==typeof c?c:a.style[Uf(a,b)]||""},Yf=function(a){try{return a.getBoundingClientRect()}catch(b){return{left:0,top:0,right:0,bottom:0}}}, Zf=function(a){var b=Xe(a),c=new Ue(0,0);var d=b?Xe(b):document;d=!ud||9<=Number(Od)||"CSS1Compat"==Ye(d).g.compatMode?d.documentElement:d.body;if(a==d)return c;a=Yf(a);b=df(Ye(b).g);c.x=a.left+b.x;c.y=a.top+b.y;return c},$f=function(a,b){var c=new Ue(0,0),d=D(Xe(a));if(!qd(d,"parent"))return c;do{if(d==b)var e=Zf(a);else e=Yf(a),e=new Ue(e.left,e.top);c.x+=e.x;c.y+=e.y}while(d&&d!=b&&d!=d.parent&&(a=d.frameElement)&&(d=d.parent));return c},ag=function(){var a="100%";"number"==typeof a&&(a=Math.round(a)+ "px");return a},cg=function(a){var b=bg;a:{var c=Xe(a);if(c.defaultView&&c.defaultView.getComputedStyle&&(c=c.defaultView.getComputedStyle(a,null))){c=c.display||c.getPropertyValue("display")||"";break a}c=""}c||(c=a.currentStyle?a.currentStyle.display:null);if("none"!=(c||a.style&&a.style.display))return b(a);c=a.style;var d=c.display,e=c.visibility,f=c.position;c.visibility="hidden";c.position="absolute";c.display="inline";a=b(a);c.display=d;c.position=f;c.visibility=e;return a},bg=function(a){var b= a.offsetWidth,c=a.offsetHeight,d=xd&&!b&&!c;return(void 0===b||d)&&a.getBoundingClientRect?(a=Yf(a),new Ve(a.right-a.left,a.bottom-a.top)):new Ve(b,c)};var dg=!!window.google_async_iframe_id,eg=dg&&window.parent||window,fg=function(){if(dg&&!uf(eg)){var a="."+Je.domain;try{for(;2<a.split(".").length&&!uf(eg);)Je.domain=a=a.substr(a.indexOf(".")+1),eg=window.parent}catch(b){}uf(eg)||(eg=window)}return eg};var gg=function(a){for(var b=0,c=a,d=0;a&&a!=a.parent;)a=a.parent,d++,uf(a)&&(c=a,b=d);return{ma:c,level:b}};var hg=function(){this.S={}},kg=function(){if(ig)var a=ig;else{a=((a=Nf())?uf(a.master)?a.master:null:null)||fg();var b=a.google_persistent_state_async;a=null!=b&&"object"==typeof b&&null!=b.S&&"object"==typeof b.S?ig=b:a.google_persistent_state_async=ig=new hg}b=fg();var c=Nf(b);c?((c=c||Nf())?(b=c.pageViewId,c=c.clientId,"string"===typeof c&&(b+=c.replace(/\D/g,"").substr(0,6))):b=null,b=+b):(b=gg(b).ma,(c=b.google_global_correlator)||(b.google_global_correlator=c=1+Math.floor(Math.random()*Math.pow(2, 43))),b=c);c=jg[7]||"google_ps_7";a=a.S;var d=a[c];a=void 0===d?a[c]=b:d;return a},ig=null,lg={},jg=(lg[8]="google_prev_ad_formats_by_region",lg[9]="google_prev_ad_slotnames_by_region",lg);var mg=function(){var a;this.g=a=void 0===a?{}:a};mg.prototype.reset=function(){this.g={}};var ng=null;var og=function(){var a=u.performance;return a&&a.now&&a.timing?Math.floor(a.now()+a.timing.navigationStart):Xa()},pg=function(){var a=void 0===a?u:a;return(a=a.performance)&&a.now?a.now():null},qg=function(a){var b=u.performance;return b&&b.timing&&b.timing[a]||0},rg=function(){var a=Math.min(qg("domLoading")||Infinity,qg("domInteractive")||Infinity);return Infinity==a?Math.max(qg("responseEnd"),qg("navigationStart")):a};var sg=function(a,b,c,d,e){this.label=a;this.type=b;this.value=c;this.duration=void 0===d?0:d;this.uniqueId=Math.random();this.slotId=e};var tg=u.performance,ug=!!(tg&&tg.mark&&tg.measure&&tg.clearMarks),vg=eb(function(){var a;if(a=ug){var b;if(null===ng){ng="";try{a="";try{a=u.top.location.hash}catch(c){a=u.location.hash}a&&(ng=(b=a.match(/\bdeid=([\d,]+)/))?b[1]:"")}catch(c){}}b=ng;a=!!b.indexOf&&0<=b.indexOf("1337")}return a}),wg=function(a,b){this.events=[];this.g=b||u;var c=null;b&&(b.google_js_reporting_queue=b.google_js_reporting_queue||[],this.events=b.google_js_reporting_queue,c=b.google_measure_js_timing);this.l=vg()||(null!= c?c:Math.random()<a)};wg.prototype.C=function(){this.l=!1;this.events!=this.g.google_js_reporting_queue&&(vg()&&y(this.events,xg),this.events.length=0)};wg.prototype.J=function(a){!this.l||2048<this.events.length||this.events.push(a)};var xg=function(a){a&&tg&&vg()&&(tg.clearMarks("goog_"+a.label+"_"+a.uniqueId+"_start"),tg.clearMarks("goog_"+a.label+"_"+a.uniqueId+"_end"))}; wg.prototype.start=function(a,b){if(!this.l)return null;a=new sg(a,b,pg()||og());b="goog_"+a.label+"_"+a.uniqueId+"_start";tg&&vg()&&tg.mark(b);return a};wg.prototype.end=function(a){if(this.l&&"number"===typeof a.value){a.duration=(pg()||og())-a.value;var b="goog_"+a.label+"_"+a.uniqueId+"_end";tg&&vg()&&tg.mark(b);this.J(a)}};var yg=function(){this.h="jserror";this.l=!1;this.g=null;this.o=!1;this.A=Math.random();this.B=this.Ia};l=yg.prototype;l.Sc=function(a){this.h=a};l.lc=function(a){this.g=a};l.Tc=function(a){this.l=a};l.Uc=function(a){this.o=a}; l.Ia=function(a,b,c,d,e){e=void 0===e?this.h:e;if((this.o?this.A:Math.random())>(void 0===c?.01:c))return this.l;Me(b)||(b=new Le(b,{context:a,id:e}));if(d||this.g)b.meta={},this.g&&this.g(b.meta),d&&d(b.meta);u.google_js_errors=u.google_js_errors||[];u.google_js_errors.push(b);u.error_rep_loaded||(b=u.document,c=Tf(u.location.protocol+"//pagead2.googlesyndication.com/pagead/js/err_rep.js"),a=b.createElement("script"),a.src=cc(c),Ke(a),(b=b.getElementsByTagName("script")[0])&&b.parentNode&&b.parentNode.insertBefore(a, b),u.error_rep_loaded=!0);return this.l};l.gb=function(a,b,c){try{var d=b()}catch(e){if(!this.B(a,e,.01,c,this.h))throw e;}return d};l.Pc=function(a,b,c,d){var e=this;return function(f){for(var g=[],h=0;h<arguments.length;++h)g[h-0]=arguments[h];return e.gb(a,function(){return b.apply(c,g)},d)}};var zg=function(a){return{visible:1,hidden:2,prerender:3,preview:4,unloaded:5}[a.visibilityState||a.webkitVisibilityState||a.mozVisibilityState||""]||0},Ag=function(a){var b;a.visibilityState?b="visibilitychange":a.mozVisibilityState?b="mozvisibilitychange":a.webkitVisibilityState&&(b="webkitvisibilitychange");return b};var Bg=function(a){a=a._google_rum_ns_=a._google_rum_ns_||{};return a.pq=a.pq||[]};var Cg=function(a,b,c){zf(b,function(d,e){var f=c&&c[e];!d&&0!==d||f||(a+="&"+encodeURIComponent(e)+"="+encodeURIComponent(String(d)),c&&(c[e]=!0))});return a},Kg=function(a,b,c,d,e,f,g,h){f=void 0===f?Infinity:f;g=void 0===g?!1:g;wg.call(this,a,h);var k=this;this.K=0;this.M=f;this.aa=b;this.L=c;this.Z=d;this.ba=e;a=this.g.navigator;this.W=!("csi.gstatic.com"!==this.L||!a||!a.sendBeacon);this.B={};this.I={};this.g.performance&&this.g.performance.now||Dg(this,"dat",1);a&&a.deviceMemory&&Dg(this,"dmc", a.deviceMemory);this.g===this.g.top&&Dg(this,"top",1);this.U=!g;this.N=function(){k.g.setTimeout(function(){return Eg(k)},1100)};this.sa=[];this.Y=function(){Fg(k,1)};this.T=function(){Fg(k,2)};this.ea=gb(function(){Eg(k)});this.wa=function(){var m=k.g.document;(null!=m.hidden?m.hidden:null!=m.mozHidden?m.mozHidden:null!=m.webkitHidden&&m.webkitHidden)&&k.ea()};this.F=this.g.setTimeout(function(){return Eg(k)},5E3);this.A={};this.o=b.length+c.length+d.length+e.length+3;this.h=0;y(this.events,function(m){return Gg(k, m)});this.H=[];b=Bg(this.g);var n=function(m){var v=m[0];m=m[1];var r=v.length+m.length+2;8E3<k.o+k.h+r&&Eg(k);k.H.push([v,m]);k.h+=r;Hg(k);return 0};y(b,function(m){return n(m)});b.length=0;b.push=n;Ig(this);Jg(this)};t(Kg,wg); var Jg=function(a){"complete"===a.g.document.readyState?a.g.setTimeout(function(){return Eg(a)},0):Pe(a.g,"load",a.N);var b=Ag(a.g.document);"undefined"!==typeof b&&Pe(a.g,b,a.wa);Pe(a.g,"unload",a.Y);Pe(a.g,"pagehide",a.T)},Dg=function(a,b,c){c=String(c);a.o=null!=a.B[b]?a.o+(c.length-a.B[b].length):a.o+(b.length+c.length+2);a.B[b]=c},Lg=function(a){null!=a.B.uet&&(a.o-=3+a.B.uet.length+2,delete a.B.uet)},Og=function(a,b,c,d,e){e=void 0===e?"":e;var f=Mg(a,b,c,d,e);8E3<a.o+a.h+f&&(Eg(a),f=b.length+ c.length+2);Ng(a,b,c,d,e);a.h+=f;Hg(a)},Mg=function(a,b,c,d,e){return null==a.A[b]?b.length+c.length+2:d?c.length+(void 0===e?"":e).length:c.length-a.A[b].length},Ng=function(a,b,c,d,e){a.A[b]=d&&null!=a.A[b]?a.A[b]+(""+(void 0===e?"":e)+c):c},Hg=function(a){6E3<=a.o+a.h&&Eg(a)},Eg=function(a){if(a.l&&a.U){try{if(a.h){var b=a.A;a.K++;var c=Pg(a,b);b=!1;try{b=!!(a.W&&a.g.navigator&&a.g.navigator.sendBeacon(c,null))}catch(d){a.W=!1}b||Of(a.g,c);Ig(a);a.K===a.M&&a.C()}}catch(d){(new yg).Ia(358,d)}a.A= {};a.h=0;a.events.length=0;a.g.clearTimeout(a.F);a.F=0}},Pg=function(a,b){var c=a.aa+"//"+a.L+a.Z+a.ba,d={};c=Cg(c,a.B,d);c=Cg(c,b,d);a.g.google_timing_params&&(c=Cg(c,a.g.google_timing_params,d),a.g.google_timing_params=void 0);y(a.H,function(e){var f=q(e);e=f.next().value;f=f.next().value;var g={};c=Cg(c,(g[e]=f,g))});a.H.length=0;return c},Ig=function(a){Dg(a,"puid",(a.K+1).toString(36)+"~"+Xa().toString(36))},Gg=function(a,b){var c="met."+b.type,d="number"===typeof b.value?Math.round(b.value).toString(36): b.value,e=Math.round(b.duration);b=""+b.label+(null!=b.slotId?"_"+b.slotId:"")+("."+d)+(0<e?"_"+e.toString(36):"");Og(a,c,b,!0,"~")};Kg.prototype.J=function(a){this.l&&this.K<this.M&&(wg.prototype.J.call(this,a),Gg(this,a))};Kg.prototype.C=function(){wg.prototype.C.call(this);this.g.clearTimeout(this.F);this.h=this.F=0;this.A={};Qb(this.I);Qb(this.B);Qe(this.g,"load",this.N);Qe(this.g,"unload",this.Y);Qe(this.g,"pagehide",this.T)}; var Fg=function(a,b){Dg(a,"uet",b);y(a.sa,function(c){try{c()}catch(d){}});Re(a.g);Eg(a);Lg(a)};var Qg=function(a){var b=[],c=[],d={},e=function(f,g){var h=g+" ";try{if(void 0===f)b.push("undefined");else if(null===f)b.push("NULL");else if("string"===typeof f)b.push('"'+f.replace(/\n/g,"\n"+g)+'"');else if("function"===typeof f)b.push(String(f).replace(/\n/g,"\n"+g));else if(Na(f)){f[Oa]||c.push(f);var k=Qa(f);if(d[k])b.push("*** reference loop detected (id="+k+") ***");else{d[k]=!0;b.push("{");for(var n in f)"function"!==typeof f[n]&&(b.push("\n"),b.push(h),b.push(n+" = "),e(f[n],h));b.push("\n"+ g+"}");delete d[k]}}else b.push(f)}catch(m){b.push("*** "+m+" ***")}};e(a,"");for(a=0;a<c.length;a++)Ra(c[a]);return b.join("")};var F=function(){this.g=new Kg(1,"https:","csi.gstatic.com","/csi?v=2&s=","ima",void 0,!0);var a=kg();null!=a&&Dg(this.g,"c",a);a=parseInt(this.g.B.c,10)/2;null!=a&&Dg(this.g,"slotId",a)},G=function(a,b,c){if(null!=c){a=a.g;var d=b+"="+c;a.I[d]||(Og(a,b,c,!1),1E3>d.length&&(a.I[d]=!0))}},Rg=function(a,b){for(var c in b)b[c]="object"===typeof b[c]?encodeURIComponent(JSON.stringify(b[c])):encodeURIComponent(String(b[c]));a=a.g;c=!1;var d=0,e;for(e in b)null!=a.A[e]&&(c=!0),d+=Mg(a,e,b[e],!1);(8E3<a.o+ a.h+d||c)&&Eg(a);for(var f in b)Ng(a,f,b[f],!1);a.h+=d;Hg(a)},H=function(a){var b=F.D().g,c=og()-0;b.l&&b.J(new sg(a,4,c,0,void 0))};Ka(F);var Sg=function(a){return/^\s*$/.test(a)?!1:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/(?:"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)[\s\u2028\u2029]*(?=:|,|]|}|$)/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,""))},Tg=function(a){try{return u.JSON.parse(a)}catch(b){}a=String(a);if(Sg(a))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);},Wg=function(a,b){var c=[];Ug(new Vg(b),a,c); return c.join("")},Vg=function(a){this.g=a},Ug=function(a,b,c){if(null==b)c.push("null");else{if("object"==typeof b){if(Array.isArray(b)){var d=b;b=d.length;c.push("[");for(var e="",f=0;f<b;f++)c.push(e),e=d[f],Ug(a,a.g?a.g.call(d,String(f),e):e,c),e=",";c.push("]");return}if(b instanceof String||b instanceof Number||b instanceof Boolean)b=b.valueOf();else{c.push("{");f="";for(d in b)Object.prototype.hasOwnProperty.call(b,d)&&(e=b[d],"function"!=typeof e&&(c.push(f),Xg(d,c),c.push(":"),Ug(a,a.g?a.g.call(b, d,e):e,c),f=","));c.push("}");return}}switch(typeof b){case "string":Xg(b,c);break;case "number":c.push(isFinite(b)&&!isNaN(b)?String(b):"null");break;case "boolean":c.push(String(b));break;case "function":c.push("null");break;default:throw Error("Unknown type: "+typeof b);}}},Yg={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},Zg=/\uffff/.test("\uffff")?/[\\"\x00-\x1f\x7f-\uffff]/g:/[\\"\x00-\x1f\x7f-\xff]/g,Xg=function(a,b){b.push('"',a.replace(Zg, function(c){var d=Yg[c];d||(d="\\u"+(c.charCodeAt(0)|65536).toString(16).substr(1),Yg[c]=d);return d}),'"')};var $g=function(){this.l=null;this.g="missing-id";this.h=!1},bh=function(a){var b=null;try{b=document.getElementsByClassName("lima-exp-data")}catch(c){return ah("missing-element",a.g),null}if(1<b.length)return ah("multiple-elements",a.g),null;b=b[0];return b?b.innerHTML:(ah("missing-element",a.g),null)},dh=function(){var a=ch,b=bh(a);if(null!==b)if(Sg(b)){var c=JSON.parse(b);b=c.experimentIds;var d=c.binaryIdentifier;c=c.adEventId;var e="string"===typeof d;if("string"==typeof c){var f=F.D();null!= c&&Dg(f.g,"qqid",c)}e&&(a.g=d);"string"!==typeof b?ah("missing-flags",a.g):(e||ah("missing-binary-id",a.g),a.l=b)}else ah("invalid-json",a.g)};$g.prototype.reset=function(){this.l=null;this.g="missing-id"};var fh=function(a,b,c,d,e){this.id=a;this.G=b;this.l=c;this.kc=!1;this.h=d;this.g=e;this.l&&eh(this)},gh=function(a){return a.kc||a.l},eh=function(a){if(a.h&&a.g){var b=a.h;b&&Object.assign(a.g.g,b)}},hh=function(){this.g=[]},ih=function(){this.g=new Map;this.h=!1;this.B=new hh;this.A=new fh(0,0,!1);this.l=[this.B];this.o=new mg},I=function(a){var b=jh;if(b.h||b.g.has(a.id)||null==a.G&&null==a.control||0==a.ve)return b.A;var c=b.B;if(null!=a.control)for(var d=q(b.l),e=d.next();!e.done;e=d.next()){if(e= e.value,e.g.includes(a.control)){c=e;break}}else null!=a.Ca&&(c=a.Ca);d=0;null!=a.control?d=a.control.G:null!=a.G&&(d=a.G);a=new fh(a.id,d,!!a.uh,a.flags,b.o);c.g.push(a);b.l.includes(c)||b.l.push(c);b.g.set(a.id,a);return a},kh=function(){var a=jh;return[].concat(fa(a.g.keys())).filter(function(b){return gh(this.g.get(b))},a)},lh=function(a){var b=jh;b.h||(a.g(b.l,b.g),b.h=!0)}; ih.prototype.reset=function(){for(var a=q(this.g),b=a.next();!b.done;b=a.next())b=q(b.value),b.next(),b.next().value.kc=!1;this.h=!1;this.o.reset()};var jh=new ih,nh=function(){return mh.g.filter(function(a){return gh(a)}).map(function(a){return a.id})};var oh=function(){};oh.prototype.g=function(a){a=q(a);for(var b=a.next();!b.done;b=a.next()){var c=0,d=Math.floor(1E3*Math.random());b=q(b.value.g);for(var e=b.next();!e.done;e=b.next())if(e=e.value,c+=e.G,d<c){e.kc=!0;eh(e);break}}};var rh=function(a){ue(this,a,ph,qh)};t(rh,pe);var ph=[2,8],qh=[[3,4,5],[6,7]];var th=function(a){ue(this,a,sh,null)};t(th,pe);var sh=[4];var wh=function(a){ue(this,a,uh,vh)};t(wh,pe);var uh=[5],vh=[[1,2,3,6,7]];var yh=function(a){ue(this,a,xh,null)};t(yh,pe);var xh=[2];var Ah=function(a){ue(this,a,zh,null)};t(Ah,pe);var zh=[2];var Ch=function(a){ue(this,a,Bh,null)};t(Ch,pe);var Eh=function(a){ue(this,a,Dh,null)};t(Eh,pe);var Bh=[1,4,2,3],Dh=[2];var Fh=function(a,b){switch(b){case 1:return xe(a,1,0);case 2:return xe(a,2,0);case 3:return xe(a,3,0);case 6:return xe(a,6,0);default:return null}},Gh=function(a,b){if(!a)return null;switch(b){case 1:return ye(a,1);case 7:return xe(a,3,"");case 2:return ze(a,2);case 3:return xe(a,3,"");case 6:return A(a,4);default:return null}};var Hh={},Ih=(Hh[47]=Pd,Hh);function Jh(){var a=Kh,b=Ee(new Ch(Lh),Eh,2);1==b.length&&16==xe(b[0],1,0)&&Ee(b[0],Ah,2).forEach(function(c){var d=xe(c,1,0),e=De(c,rh,3),f=a[xe(c,4,0)];Ee(c,yh,2).forEach(function(g){var h=d||xe(g,4,0),k=xe(g,1,0),n=e||De(g,rh,3);n=n?xe(n,3,0):null;n=Ih[n];g=Mh(Ee(g,wh,2));I({id:k,G:h,Ca:f,ve:n,flags:g})})})}function Mh(a){if(a.length){var b={};a.forEach(function(c){var d=te(c,vh[0]),e=De(c,th,4);e&&(c=Fh(c,d),d=Gh(e,d),b[c]=d)});return b}};var Nh=function(a){this.h=a};Nh.prototype.g=function(a,b){a=q(this.h);for(var c=a.next();!c.done;c=a.next())if(c=b.get(c.value))c.kc=!0,eh(c)};var Oh=function(a,b){this.h=a;this.l=b};t(Oh,Nh);Oh.prototype.g=function(a,b){Nh.prototype.g.call(this,a,b);var c=[];a=[];for(var d=q(this.h),e=d.next();!e.done;e=d.next())e=e.value,b.get(e)?c.push(e):a.push(e);b=c.map(String).join(",")||"0";a=a.map(String).join(",")||"0";G(F.D(),"sei",b);G(F.D(),"nsei",a);G(F.D(),"bi",this.l)};var Ph=function(){$g.apply(this,arguments)};t(Ph,$g);var ah=function(a,b){var c=F.D();G(c,"eee",a);G(c,"bi",b)};Ka(Ph);function Qh(){return Rh.split(",").map(function(a){return parseInt(a,10)}).filter(function(a){return!isNaN(a)})};var mh=new hh,Sh=new hh,Th=new hh,Uh=new hh;I({id:318475490,G:0});I({id:324123032,G:0});I({id:418572103,G:0});I({id:420706097,G:10});I({id:420706098,G:10});I({id:44736152,G:10});I({id:44736153,G:10});I({id:44736284,G:10});I({id:44736285,G:10});I({id:21062100,G:0});I({id:21062101,G:0});I({id:420706109,G:10});I({id:420706110,G:10});I({id:21062347,G:0});I({id:21063070,G:0});I({id:21063072,G:0});I({id:21063100,G:0});I({id:420706105,G:10});I({id:420706106,G:10});I({id:21064018,G:0});I({id:21064020,G:0}); I({id:21064022,G:0});I({id:21064024,G:0});I({id:21064075,G:0});I({id:21064201,G:50});var Vh=I({id:210640812,G:10});I({id:420706142,G:0});I({id:21064347,G:0});I({id:72811303,G:0});I({id:44719312,G:0});I({id:75259414,G:0});I({id:75259415,G:0});I({id:75259416,G:0});I({id:44725460,G:0});I({id:21064565,G:0});I({id:21064567,G:0});I({id:40819804,G:10});var Wh=I({id:40819805,G:10});I({id:418572006,G:10});I({id:44740339,G:10});var Xh=I({id:44740340,G:10}),Yh=I({id:44742277,G:10}),Zh=I({id:44741393,G:10}); I({id:72811314,G:0});I({id:44714743,G:0});I({id:44719216,G:0});I({id:44730895,G:10});I({id:44730896,G:10});I({id:44730769,G:0});I({id:44731465,G:10});I({id:44731467,G:10});I({id:44736292,G:10});I({id:44736293,G:10});I({id:44731964,G:10,Ca:mh});I({id:44731965,G:10,Ca:mh});I({id:668123728,G:10,Ca:mh});I({id:668123729,G:10,Ca:mh});I({id:31061774,G:10});var $h=I({id:31061775,G:10});I({id:44730612,G:50});I({id:44736270,G:10});I({id:44736271,G:10});I({id:44712632,G:10});I({id:44712633,G:10}); I({id:44715336,G:10});I({id:44729309,G:10});I({id:44721472,G:0});I({id:75259410,G:0});I({id:75259412,G:0});I({id:75259413,G:0});I({id:44725355,G:50,Ca:Th});var ai=I({id:44725356,G:50,Ca:Th});I({id:44724516,G:0});I({id:44726389,G:10});I({id:44726392,G:10});I({id:44726393,G:10});I({id:44730464,G:10});I({id:44730465,G:10});I({id:44733378,G:10});I({id:44727953,G:0});I({id:44729911,G:0});I({id:44730425,G:0});I({id:44730426,G:0});I({id:447304389,G:0});I({id:44732022,G:10});I({id:44732023,G:10}); I({id:44733246,G:10});I({id:44736980,G:0});I({id:44736981,G:0});I({id:44736979,G:0});I({id:44737473,G:100,Ca:Sh});I({id:44737475,G:100,Ca:Sh});I({id:44738437,G:0});var bi=I({id:44738438,G:0});I({id:44741356,G:10});I({id:44741357,G:10});I({id:44741361,G:10});I({id:44741362,G:10});I({id:44741233,G:10});I({id:44741234,G:10});I({id:44745354,G:0});var ci={},Kh=(ci[32]=mh,ci[35]=Uh,ci);Kh=void 0===Kh?{}:Kh; if(!/^\{+IMA_EXPERIMENT_STATE_JSPB\}+$/.test("{{IMA_EXPERIMENT_STATE_JSPB}}"))try{var Lh=JSON.parse("{{IMA_EXPERIMENT_STATE_JSPB}}");Lh instanceof Array&&Jh()}catch(a){G(F.D(),"espe",a.message)}if("undefined"===typeof window.v8_flag_map){var ch=Ph.D();ch.h||(dh(),ch.h=!0);var Rh=ch.l,di;ch.h||(dh(),ch.h=!0);di=ch.g;if(null!=Rh){var ei=new Oh(Qh(),di);lh(ei)}};jh.reset();lh(new oh);u.console&&"function"===typeof u.console.log&&Va(u.console.log,u.console);var fi=function(a){for(var b=[],c=a=D(a.ownerDocument);c!=a.top;c=c.parent)if(c.frameElement)b.push(c.frameElement);else break;return b};var gi=function(){if(!u.addEventListener||!Object.defineProperty)return!1;var a=!1,b=Object.defineProperty({},"passive",{get:function(){a=!0}});try{u.addEventListener("test",Ja,b),u.removeEventListener("test",Ja,b)}catch(c){}return a}();function hi(a){a&&"function"==typeof a.X&&a.X()};var J=function(){this.K=this.K;this.J=this.J};J.prototype.K=!1;J.prototype.Za=function(){return this.K};J.prototype.X=function(){this.K||(this.K=!0,this.O())};var ji=function(a,b){ii(a,Wa(hi,b))},ii=function(a,b){a.K?b():(a.J||(a.J=[]),a.J.push(b))};J.prototype.O=function(){if(this.J)for(;this.J.length;)this.J.shift()()};var ki=function(a,b){this.type=a;this.currentTarget=this.target=b;this.defaultPrevented=this.h=!1};ki.prototype.stopPropagation=function(){this.h=!0};ki.prototype.preventDefault=function(){this.defaultPrevented=!0};var li=function(a,b){ki.call(this,a?a.type:"");this.relatedTarget=this.currentTarget=this.target=null;this.button=this.screenY=this.screenX=this.clientY=this.clientX=0;this.key="";this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.state=null;this.pointerId=0;this.pointerType="";this.g=null;a&&this.init(a,b)};Ya(li,ki);var mi={2:"touch",3:"pen",4:"mouse"}; li.prototype.init=function(a,b){var c=this.type=a.type,d=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.currentTarget=b;(b=a.relatedTarget)?wd&&(qd(b,"nodeName")||(b=null)):"mouseover"==c?b=a.fromElement:"mouseout"==c&&(b=a.toElement);this.relatedTarget=b;d?(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0):(this.clientX=void 0!==a.clientX? a.clientX:a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0);this.button=a.button;this.key=a.key||"";this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=a.shiftKey;this.metaKey=a.metaKey;this.pointerId=a.pointerId||0;this.pointerType="string"===typeof a.pointerType?a.pointerType:mi[a.pointerType]||"";this.state=a.state;this.g=a;a.defaultPrevented&&li.za.preventDefault.call(this)}; li.prototype.stopPropagation=function(){li.za.stopPropagation.call(this);this.g.stopPropagation?this.g.stopPropagation():this.g.cancelBubble=!0};li.prototype.preventDefault=function(){li.za.preventDefault.call(this);var a=this.g;a.preventDefault?a.preventDefault():a.returnValue=!1};var ni="closure_listenable_"+(1E6*Math.random()|0),oi=function(a){return!(!a||!a[ni])};var pi=0;var qi=function(a,b,c,d,e){this.listener=a;this.g=null;this.src=b;this.type=c;this.capture=!!d;this.Wb=e;this.key=++pi;this.Ib=this.Qb=!1},ri=function(a){a.Ib=!0;a.listener=null;a.g=null;a.src=null;a.Wb=null};var si=function(a){this.src=a;this.g={};this.h=0};si.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.g[f];a||(a=this.g[f]=[],this.h++);var g=ti(a,b,d,e);-1<g?(b=a[g],c||(b.Qb=!1)):(b=new qi(b,this.src,f,!!d,e),b.Qb=c,a.push(b));return b};si.prototype.remove=function(a,b,c,d){a=a.toString();if(!(a in this.g))return!1;var e=this.g[a];b=ti(e,b,c,d);return-1<b?(ri(e[b]),ub(e,b),0==e.length&&(delete this.g[a],this.h--),!0):!1}; var ui=function(a,b){var c=b.type;c in a.g&&tb(a.g[c],b)&&(ri(b),0==a.g[c].length&&(delete a.g[c],a.h--))};si.prototype.Cb=function(a,b,c,d){a=this.g[a.toString()];var e=-1;a&&(e=ti(a,b,c,d));return-1<e?a[e]:null};var ti=function(a,b,c,d){for(var e=0;e<a.length;++e){var f=a[e];if(!f.Ib&&f.listener==b&&f.capture==!!c&&f.Wb==d)return e}return-1};var vi="closure_lm_"+(1E6*Math.random()|0),wi={},xi=0,zi=function(a,b,c,d,e){if(d&&d.once)return yi(a,b,c,d,e);if(Array.isArray(b)){for(var f=0;f<b.length;f++)zi(a,b[f],c,d,e);return null}c=Ai(c);return oi(a)?a.P(b,c,Na(d)?!!d.capture:!!d,e):Bi(a,b,c,!1,d,e)},Bi=function(a,b,c,d,e,f){if(!b)throw Error("Invalid event type");var g=Na(e)?!!e.capture:!!e,h=Ci(a);h||(a[vi]=h=new si(a));c=h.add(b,c,d,g,f);if(c.g)return c;d=Di();c.g=d;d.src=a;d.listener=c;if(a.addEventListener)gi||(e=g),void 0===e&&(e=!1), a.addEventListener(b.toString(),d,e);else if(a.attachEvent)a.attachEvent(Ei(b.toString()),d);else if(a.addListener&&a.removeListener)a.addListener(d);else throw Error("addEventListener and attachEvent are unavailable.");xi++;return c},Di=function(){var a=Fi,b=function(c){return a.call(b.src,b.listener,c)};return b},yi=function(a,b,c,d,e){if(Array.isArray(b)){for(var f=0;f<b.length;f++)yi(a,b[f],c,d,e);return null}c=Ai(c);return oi(a)?a.Gb(b,c,Na(d)?!!d.capture:!!d,e):Bi(a,b,c,!0,d,e)},Gi=function(a, b,c,d,e){if(Array.isArray(b))for(var f=0;f<b.length;f++)Gi(a,b[f],c,d,e);else d=Na(d)?!!d.capture:!!d,c=Ai(c),oi(a)?a.Ua(b,c,d,e):a&&(a=Ci(a))&&(b=a.Cb(b,c,d,e))&&Hi(b)},Hi=function(a){if("number"!==typeof a&&a&&!a.Ib){var b=a.src;if(oi(b))ui(b.B,a);else{var c=a.type,d=a.g;b.removeEventListener?b.removeEventListener(c,d,a.capture):b.detachEvent?b.detachEvent(Ei(c),d):b.addListener&&b.removeListener&&b.removeListener(d);xi--;(c=Ci(b))?(ui(c,a),0==c.h&&(c.src=null,b[vi]=null)):ri(a)}}},Ei=function(a){return a in wi?wi[a]:wi[a]="on"+a},Fi=function(a,b){if(a.Ib)a=!0;else{b=new li(b,this);var c=a.listener,d=a.Wb||a.src;a.Qb&&Hi(a);a=c.call(d,b)}return a},Ci=function(a){a=a[vi];return a instanceof si?a:null},Ii="__closure_events_fn_"+(1E9*Math.random()>>>0),Ai=function(a){if("function"===typeof a)return a;a[Ii]||(a[Ii]=function(b){return a.handleEvent(b)});return a[Ii]};var K=function(){J.call(this);this.B=new si(this);this.Ob=this;this.sa=null};Ya(K,J);K.prototype[ni]=!0;l=K.prototype;l.addEventListener=function(a,b,c,d){zi(this,a,b,c,d)};l.removeEventListener=function(a,b,c,d){Gi(this,a,b,c,d)}; l.dispatchEvent=function(a){var b,c=this.sa;if(c)for(b=[];c;c=c.sa)b.push(c);c=this.Ob;var d=a.type||a;if("string"===typeof a)a=new ki(a,c);else if(a instanceof ki)a.target=a.target||c;else{var e=a;a=new ki(d,c);Tb(a,e)}e=!0;if(b)for(var f=b.length-1;!a.h&&0<=f;f--){var g=a.currentTarget=b[f];e=Ji(g,d,!0,a)&&e}a.h||(g=a.currentTarget=c,e=Ji(g,d,!0,a)&&e,a.h||(e=Ji(g,d,!1,a)&&e));if(b)for(f=0;!a.h&&f<b.length;f++)g=a.currentTarget=b[f],e=Ji(g,d,!1,a)&&e;return e}; l.O=function(){K.za.O.call(this);if(this.B){var a=this.B,b=0,c;for(c in a.g){for(var d=a.g[c],e=0;e<d.length;e++)++b,ri(d[e]);delete a.g[c];a.h--}}this.sa=null};l.P=function(a,b,c,d){return this.B.add(String(a),b,!1,c,d)};l.Gb=function(a,b,c,d){return this.B.add(String(a),b,!0,c,d)};l.Ua=function(a,b,c,d){this.B.remove(String(a),b,c,d)}; var Ji=function(a,b,c,d){b=a.B.g[String(b)];if(!b)return!0;b=b.concat();for(var e=!0,f=0;f<b.length;++f){var g=b[f];if(g&&!g.Ib&&g.capture==c){var h=g.listener,k=g.Wb||g.src;g.Qb&&ui(a.B,g);e=!1!==h.call(k,d)&&e}}return e&&!d.defaultPrevented};K.prototype.Cb=function(a,b,c,d){return this.B.Cb(String(a),b,c,d)};var Ki=function(a,b){this.l=a;this.o=b;this.h=0;this.g=null};Ki.prototype.get=function(){if(0<this.h){this.h--;var a=this.g;this.g=a.next;a.next=null}else a=this.l();return a};var Li=function(a,b){a.o(b);100>a.h&&(a.h++,b.next=a.g,a.g=b)};var Mi,Ni=function(){var a=u.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof window&&window.postMessage&&window.addEventListener&&!z("Presto")&&(a=function(){var e=ef(document,"IFRAME");e.style.display="none";document.documentElement.appendChild(e);var f=e.contentWindow;e=f.document;e.open();e.close();var g="callImmediate"+Math.random(),h="file:"==f.location.protocol?"*":f.location.protocol+"//"+f.location.host;e=Va(function(k){if(("*"==h||k.origin==h)&&k.data==g)this.port1.onmessage()}, this);f.addEventListener("message",e,!1);this.port1={};this.port2={postMessage:function(){f.postMessage(g,h)}}});if("undefined"!==typeof a&&!Gc()){var b=new a,c={},d=c;b.port1.onmessage=function(){if(void 0!==c.next){c=c.next;var e=c.rd;c.rd=null;e()}};return function(e){d.next={rd:e};d=d.next;b.port2.postMessage(0)}}return function(e){u.setTimeout(e,0)}};function Oi(a){u.setTimeout(function(){throw a;},0)};var Pi=function(){this.h=this.g=null};Pi.prototype.add=function(a,b){var c=Qi.get();c.set(a,b);this.h?this.h.next=c:this.g=c;this.h=c};Pi.prototype.remove=function(){var a=null;this.g&&(a=this.g,this.g=this.g.next,this.g||(this.h=null),a.next=null);return a};var Qi=new Ki(function(){return new Ri},function(a){return a.reset()}),Ri=function(){this.next=this.g=this.h=null};Ri.prototype.set=function(a,b){this.h=a;this.g=b;this.next=null};Ri.prototype.reset=function(){this.next=this.g=this.h=null};var Wi=function(a,b){Si||Ti();Ui||(Si(),Ui=!0);Vi.add(a,b)},Si,Ti=function(){if(u.Promise&&u.Promise.resolve){var a=u.Promise.resolve(void 0);Si=function(){a.then(Xi)}}else Si=function(){var b=Xi;"function"!==typeof u.setImmediate||u.Window&&u.Window.prototype&&!z("Edge")&&u.Window.prototype.setImmediate==u.setImmediate?(Mi||(Mi=Ni()),Mi(b)):u.setImmediate(b)}},Ui=!1,Vi=new Pi,Xi=function(){for(var a;a=Vi.remove();){try{a.h.call(a.g)}catch(b){Oi(b)}Li(Qi,a)}Ui=!1};var Yi=function(a){if(!a)return!1;try{return!!a.$goog_Thenable}catch(b){return!1}};var $i=function(a){this.g=0;this.C=void 0;this.o=this.h=this.l=null;this.B=this.A=!1;if(a!=Ja)try{var b=this;a.call(void 0,function(c){Zi(b,2,c)},function(c){Zi(b,3,c)})}catch(c){Zi(this,3,c)}},aj=function(){this.next=this.context=this.h=this.l=this.g=null;this.o=!1};aj.prototype.reset=function(){this.context=this.h=this.l=this.g=null;this.o=!1};var bj=new Ki(function(){return new aj},function(a){a.reset()}),cj=function(a,b,c){var d=bj.get();d.l=a;d.h=b;d.context=c;return d}; $i.prototype.then=function(a,b,c){return dj(this,"function"===typeof a?a:null,"function"===typeof b?b:null,c)};$i.prototype.$goog_Thenable=!0;$i.prototype.cancel=function(a){if(0==this.g){var b=new ej(a);Wi(function(){fj(this,b)},this)}}; var fj=function(a,b){if(0==a.g)if(a.l){var c=a.l;if(c.h){for(var d=0,e=null,f=null,g=c.h;g&&(g.o||(d++,g.g==a&&(e=g),!(e&&1<d)));g=g.next)e||(f=g);e&&(0==c.g&&1==d?fj(c,b):(f?(d=f,d.next==c.o&&(c.o=d),d.next=d.next.next):gj(c),hj(c,e,3,b)))}a.l=null}else Zi(a,3,b)},jj=function(a,b){a.h||2!=a.g&&3!=a.g||ij(a);a.o?a.o.next=b:a.h=b;a.o=b},dj=function(a,b,c,d){var e=cj(null,null,null);e.g=new $i(function(f,g){e.l=b?function(h){try{var k=b.call(d,h);f(k)}catch(n){g(n)}}:f;e.h=c?function(h){try{var k=c.call(d, h);void 0===k&&h instanceof ej?g(h):f(k)}catch(n){g(n)}}:g});e.g.l=a;jj(a,e);return e.g};$i.prototype.K=function(a){this.g=0;Zi(this,2,a)};$i.prototype.F=function(a){this.g=0;Zi(this,3,a)}; var Zi=function(a,b,c){if(0==a.g){a===c&&(b=3,c=new TypeError("Promise cannot resolve to itself"));a.g=1;a:{var d=c,e=a.K,f=a.F;if(d instanceof $i){jj(d,cj(e||Ja,f||null,a));var g=!0}else if(Yi(d))d.then(e,f,a),g=!0;else{if(Na(d))try{var h=d.then;if("function"===typeof h){kj(d,h,e,f,a);g=!0;break a}}catch(k){f.call(a,k);g=!0;break a}g=!1}}g||(a.C=c,a.g=b,a.l=null,ij(a),3!=b||c instanceof ej||lj(a,c))}},kj=function(a,b,c,d,e){var f=!1,g=function(k){f||(f=!0,c.call(e,k))},h=function(k){f||(f=!0,d.call(e, k))};try{b.call(a,g,h)}catch(k){h(k)}},ij=function(a){a.A||(a.A=!0,Wi(a.J,a))},gj=function(a){var b=null;a.h&&(b=a.h,a.h=b.next,b.next=null);a.h||(a.o=null);return b};$i.prototype.J=function(){for(var a;a=gj(this);)hj(this,a,this.g,this.C);this.A=!1}; var hj=function(a,b,c,d){if(3==c&&b.h&&!b.o)for(;a&&a.B;a=a.l)a.B=!1;if(b.g)b.g.l=null,mj(b,c,d);else try{b.o?b.l.call(b.context):mj(b,c,d)}catch(e){nj.call(null,e)}Li(bj,b)},mj=function(a,b,c){2==b?a.l.call(a.context,c):a.h&&a.h.call(a.context,c)},lj=function(a,b){a.B=!0;Wi(function(){a.B&&nj.call(null,b)})},nj=Oi,ej=function(a){ab.call(this,a)};Ya(ej,ab);ej.prototype.name="cancel";var oj=function(a,b){K.call(this);this.h=a||1;this.g=b||u;this.l=Va(this.nf,this);this.o=Xa()};Ya(oj,K);l=oj.prototype;l.kb=!1;l.Ea=null;l.nf=function(){if(this.kb){var a=Xa()-this.o;0<a&&a<.8*this.h?this.Ea=this.g.setTimeout(this.l,this.h-a):(this.Ea&&(this.g.clearTimeout(this.Ea),this.Ea=null),this.dispatchEvent("tick"),this.kb&&(this.stop(),this.start()))}};l.start=function(){this.kb=!0;this.Ea||(this.Ea=this.g.setTimeout(this.l,this.h),this.o=Xa())}; l.stop=function(){this.kb=!1;this.Ea&&(this.g.clearTimeout(this.Ea),this.Ea=null)};l.O=function(){oj.za.O.call(this);this.stop();delete this.g};var pj=function(a,b,c){if("function"===typeof a)c&&(a=Va(a,c));else if(a&&"function"==typeof a.handleEvent)a=Va(a.handleEvent,a);else throw Error("Invalid listener argument");return 2147483647<Number(b)?-1:u.setTimeout(a,b||0)};var qj=function(){return Math.round(Date.now()/1E3)};var rj=function(){this.g={};return this};rj.prototype.remove=function(a){var b=this.g;a in b&&delete b[a]};rj.prototype.set=function(a,b){this.g[a]=b};var sj=function(a,b){a.g.eb=Rb(a.g,"eb",0)|b};rj.prototype.get=function(a){return Rb(this.g,a,null)};var tj=null,uj=function(){this.g={};this.h=0},vj=function(){tj||(tj=new uj);return tj},wj=function(a,b){a.g[b.o]=b},xj=function(a,b){this.o=a;this.l=!0;this.g=b};xj.prototype.h=function(){return String(this.g)};var yj=function(a,b){xj.call(this,String(a),b);this.B=a;this.g=!!b};t(yj,xj);yj.prototype.h=function(){return this.g?"1":"0"};var zj=function(a,b){xj.call(this,a,b)};t(zj,xj); zj.prototype.h=function(){return this.g?Math.round(this.g.top)+"."+Math.round(this.g.left)+"."+(Math.round(this.g.top)+Math.round(this.g.height))+"."+(Math.round(this.g.left)+Math.round(this.g.width)):""};var Aj=function(a){if(a.match(/^-?[0-9]+\.-?[0-9]+\.-?[0-9]+\.-?[0-9]+$/)){a=a.split(".");var b=Number(a[0]),c=Number(a[1]);return new zj("",new Lf(c,b,Number(a[3])-c,Number(a[2])-b))}return new zj("",new Lf(0,0,0,0))};var Bj=function(a){var b=new Lf(-Number.MAX_VALUE/2,-Number.MAX_VALUE/2,Number.MAX_VALUE,Number.MAX_VALUE),c=new Lf(0,0,0,0);if(!a||0==a.length)return c;for(var d=0;d<a.length;d++){a:{var e=b;var f=a[d],g=Math.max(e.left,f.left),h=Math.min(e.left+e.width,f.left+f.width);if(g<=h){var k=Math.max(e.top,f.top);f=Math.min(e.top+e.height,f.top+f.height);if(k<=f){e.left=g;e.top=k;e.width=h-g;e.height=f-k;e=!0;break a}}e=!1}if(!e)return c}return b},Cj=function(a,b){var c=a.getBoundingClientRect();a=$f(a, b);return new Lf(Math.round(a.x),Math.round(a.y),Math.round(c.right-c.left),Math.round(c.bottom-c.top))},Dj=function(a,b,c){if(b&&c){a:{var d=Math.max(b.left,c.left);var e=Math.min(b.left+b.width,c.left+c.width);if(d<=e){var f=Math.max(b.top,c.top),g=Math.min(b.top+b.height,c.top+c.height);if(f<=g){d=new Lf(d,f,e-d,g-f);break a}}d=null}e=d?d.height*d.width:0;f=d?b.height*b.width:0;d=d&&f?Math.round(e/f*100):0;wj(a,new xj("vp",d));d&&0<d?(e=Mf(b),f=Mf(c),e=e.top>=f.top&&e.top<f.bottom):e=!1;wj(a,new yj(512, e));d&&0<d?(e=Mf(b),f=Mf(c),e=e.bottom<=f.bottom&&e.bottom>f.top):e=!1;wj(a,new yj(1024,e));d&&0<d?(e=Mf(b),f=Mf(c),e=e.left>=f.left&&e.left<f.right):e=!1;wj(a,new yj(2048,e));d&&0<d?(b=Mf(b),c=Mf(c),c=b.right<=c.right&&b.right>c.left):c=!1;wj(a,new yj(4096,c))}};var Ej=function(a,b){var c=0;Kb(D(),"ima","video","client","tagged")&&(c=1);var d=null;a&&(d=a());if(d){a=vj();a.g={};var e=new yj(32,!0);e.l=!1;wj(a,e);e=D().document;e=e.visibilityState||e.webkitVisibilityState||e.mozVisibilityState||e.msVisibilityState||"";wj(a,new yj(64,"hidden"!=e.toLowerCase().substring(e.length-6)?!0:!1));try{var f=D().top;try{var g=!!f.location.href||""===f.location.href}catch(m){g=!1}if(g){var h=fi(d);var k=h&&0!=h.length?"1":"0"}else k="2"}catch(m){k="2"}wj(a,new yj(256, "2"==k));wj(a,new yj(128,"1"==k));h=g=D().top;"2"==k&&(h=D());f=Cj(d,h);wj(a,new zj("er",f));try{var n=h.document&&!h.document.body?null:cf(h||window)}catch(m){n=null}n?(h=df(Ye(h.document).g),wj(a,new yj(16384,!!h)),n=h?new Lf(h.x,h.y,n.width,n.height):null):n=null;wj(a,new zj("vi",n));if(n&&"1"==k){k=fi(d);d=[];for(h=0;h<k.length;h++)(e=Cj(k[h],g))&&d.push(e);d.push(n);n=Bj(d)}Dj(a,f,n);a.h&&wj(a,new xj("ts",qj()-a.h));a.h=qj()}else a=vj(),a.g={},a.h=qj(),wj(a,new yj(32,!1));this.l=a;this.g=new rj; this.g.set("ve",4);c&&sj(this.g,1);Kb(D(),"ima","video","client","crossdomainTag")&&sj(this.g,4);Kb(D(),"ima","video","client","sdkTag")&&sj(this.g,8);Kb(D(),"ima","video","client","jsTag")&&sj(this.g,2);b&&Rb(b,"fullscreen",!1)&&sj(this.g,16);this.h=b=null;if(c&&(c=Kb(D(),"ima","video","client"),c.getEData)){this.h=c.getEData();if(c=Kb(D(),"ima","video","client","getLastSnapshotFromTop"))if(a=c())this.h.extendWithDataFromTopIframe(a.tagstamp,a.playstamp,a.lactstamp),c=this.l,b=a.er,a=a.vi,b&&a&& (b=Aj(b).g,a=Aj(a).g,k=null,Rb(c.g,"er",null)&&(k=Rb(c.g,"er",null).g,k.top+=b.top,k.left+=b.left,wj(c,new zj("er",k))),Rb(c.g,"vi",null)&&(n=Rb(c.g,"vi",null).g,n.top+=b.top,n.left+=b.left,d=[],d.push(n),d.push(b),d.push(a),b=Bj(d),Dj(c,k,b),wj(c,new zj("vi",a))));a:{if(this.h){if(this.h.getTagLoadTimestamp){b=this.h.getTagLoadTimestamp();break a}if(this.h.getTimeSinceTagLoadSeconds){b=this.h.getTimeSinceTagLoadSeconds();break a}}b=null}}c=this.g;a=window.performance&&window.performance.timing&& window.performance.timing.domLoading&&0<window.performance.timing.domLoading?Math.round(window.performance.timing.domLoading/1E3):null;c.set.call(c,"td",qj()-(null!=a?a:null!=b?b:qj()))};var Fj=new oj(200),Gj=function(a,b){try{var c=new Ej(a,b);a=[];var d=Number(c.g.get("eb"));c.g.remove("eb");var e,f=c.g;b=[];for(var g in f.g)b.push(g+f.g[g]);(e=b.join("_"))&&a.push(e);if(c.h){var h=c.h.serialize();h&&a.push(h)}var k,n=c.l;e=d;f=[];e||(e=0);for(var m in n.g){var v=n.g[m];if(v instanceof yj)v.g&&(e|=v.B);else{var r,w=n.g[m];(r=w.l?w.h():"")&&f.push(m+r)}}f.push("eb"+String(e));(k=f.join("_"))&&a.push(k);c.g.set("eb",d);return a.join("_")}catch(B){return"tle;"+Xc(B.name,12)+";"+Xc(B.message, 40)}},Hj=function(a,b){zi(Fj,"tick",function(){var c=Gj(b);a(c)});Fj.start();Fj.dispatchEvent("tick")};var Jj=function(a){ue(this,a,Ij,null)};t(Jj,pe);var Kj=function(a){ue(this,a,null,null)};t(Kj,pe);var Mj=function(a,b){var c=A(a,1);null!=c&&he(b,1,c);c=De(a,Lj,2);null!=c&&ke(b,2,c);c=De(a,Lj,3);null!=c&&ke(b,3,c);c=A(a,4);null!=c&&ie(b,4,c);c=A(a,5);null!=c&&ie(b,5,c)},Lj=function(a){ue(this,a,null,null)};t(Lj,pe);var je=function(a,b){var c=A(a,1);null!=c&&he(b,1,c);c=A(a,2);null!=c&&he(b,2,c);c=A(a,3);null!=c&&he(b,3,c)},Nj=function(a){ue(this,a,null,null)};t(Nj,pe); var Oj=function(a,b){return Ae(a,8,b)},Pj=function(a,b){var c=A(a,1);null!=c&&ie(b,1,c);c=A(a,2);null!=c&&ie(b,2,c);c=A(a,3);null!=c&&ge(b,3,c);c=A(a,7);null!=c&&ge(b,7,c);c=A(a,8);if(null!=c){var d=c;if(null!=d){ld(b.g,69);c=b.g;var e=d;e=(d=0>e?1:0)?-e:e;if(0===e)0<1/e?gd=hd=0:(hd=0,gd=2147483648);else if(isNaN(e))hd=0,gd=2147483647;else if(3.4028234663852886E38<e)hd=0,gd=(d<<31|2139095040)>>>0;else if(1.1754943508222875E-38>e)e=Math.round(e/Math.pow(2,-149)),hd=0,gd=(d<<31|e)>>>0;else{var f=Math.floor(Math.log(e)/ Math.LN2);e*=Math.pow(2,-f);e=Math.round(8388608*e)&8388607;hd=0;gd=(d<<31|f+127<<23|e)>>>0}md(c,gd)}}c=A(a,4);null!=c&&fe(b,4,c);c=A(a,5);null!=c&&fe(b,5,c);c=A(a,6);null!=c&&fe(b,6,c)},Ij=[1,2];var Qj=function(a){ue(this,a,null,null)};t(Qj,pe);var Rj;Rj=["av.key","js","unreleased"].slice(-1)[0];var Sj=/^https?:\/\/(\w|-)+\.cdn\.ampproject\.(net|org)(\?|\/|$)/,Wj=function(a){a=a||Tj();for(var b=new Uj(u.location.href,u,!1),c=null,d=a.length-1,e=d;0<=e;--e){var f=a[e];!c&&Sj.test(f.url)&&(c=f);if(f.url&&!f.Hc){b=f;break}}e=null;f=a.length&&a[d].url;0!=b.depth&&f&&(e=a[d]);return new Vj(b,e,c)},Tj=function(){var a=u,b=[],c=null;do{var d=a;if(uf(d)){var e=d.location.href;c=d.document&&d.document.referrer||null}else e=c,c=null;b.push(new Uj(e||"",d));try{a=d.parent}catch(f){a=null}}while(a&& d!=a);d=0;for(a=b.length-1;d<=a;++d)b[d].depth=a-d;d=u;if(d.location&&d.location.ancestorOrigins&&d.location.ancestorOrigins.length==b.length-1)for(a=1;a<b.length;++a)e=b[a],e.url||(e.url=d.location.ancestorOrigins[a-1]||"",e.Hc=!0);return b},Vj=function(a,b,c){this.g=a;this.h=b;this.l=c},Uj=function(a,b,c){this.url=a;this.ma=b;this.Hc=!!c;this.depth=null};var Xj=function(){this.l="&";this.h={};this.o=0;this.g=[]},Yj=function(a,b){var c={};c[a]=b;return[c]},ak=function(a,b,c,d,e){var f=[];zf(a,function(g,h){(g=Zj(g,b,c,d,e))&&f.push(h+"="+g)});return f.join(b)},Zj=function(a,b,c,d,e){if(null==a)return"";b=b||"&";c=c||",$";"string"==typeof c&&(c=c.split(""));if(a instanceof Array){if(d=d||0,d<c.length){for(var f=[],g=0;g<a.length;g++)f.push(Zj(a[g],b,c,d+1,e));return f.join(c[d])}}else if("object"==typeof a)return e=e||0,2>e?encodeURIComponent(ak(a, b,c,d,e+1)):"...";return encodeURIComponent(String(a))},bk=function(a,b,c){a.g.push(b);a.h[b]=c},ck=function(a,b,c,d){a.g.push(b);a.h[b]=Yj(c,d)},ek=function(a,b,c){b=b+"//pagead2.googlesyndication.com"+c;var d=dk(a)-c.length;if(0>d)return"";a.g.sort(function(m,v){return m-v});c=null;for(var e="",f=0;f<a.g.length;f++)for(var g=a.g[f],h=a.h[g],k=0;k<h.length;k++){if(!d){c=null==c?g:c;break}var n=ak(h[k],a.l,",$");if(n){n=e+n;if(d>=n.length){d-=n.length;b+=n;e=a.l;break}c=null==c?g:c}}a="";null!=c&& (a=e+"trn="+c);return b+a+""},dk=function(a){var b=1,c;for(c in a.h)b=c.length>b?c.length:b;return 3997-b-a.l.length-1};var fk=function(a,b,c,d,e){if((d?a.g:Math.random())<(e||.01))try{if(c instanceof Xj)var f=c;else f=new Xj,zf(c,function(h,k){var n=f,m=n.o++;bk(n,m,Yj(k,h))});var g=ek(f,a.h,"/pagead/gen_204?id="+b+"&");g&&Of(u,g)}catch(h){}};var ik=function(){var a=gk;this.A=hk;this.B="jserror";this.l=!0;this.h=null;this.C=this.Ia;this.g=void 0===a?null:a;this.o=!1};l=ik.prototype;l.lc=function(a){this.h=a};l.Sc=function(a){this.B=a};l.Tc=function(a){this.l=a};l.Uc=function(a){this.o=a}; l.gb=function(a,b,c){try{if(this.g&&this.g.l){var d=this.g.start(a.toString(),3);var e=b();this.g.end(d)}else e=b()}catch(k){b=this.l;try{xg(d);var f=new Le(k,{message:jk(k)});b=this.C(a,f,void 0,c)}catch(n){this.Ia(217,n)}if(b){var g,h;null==(g=window.console)||null==(h=g.error)||h.call(g,k)}else throw k;}return e};l.Pc=function(a,b,c,d){var e=this;return function(f){for(var g=[],h=0;h<arguments.length;++h)g[h-0]=arguments[h];return e.gb(a,function(){return b.apply(c,g)},d)}}; l.Ia=function(a,b,c,d,e){e=e||this.B;try{var f=new Xj;ck(f,1,"context",a);Me(b)||(b=new Le(b,{message:jk(b)}));b.msg&&ck(f,2,"msg",b.msg.substring(0,512));var g=b.meta||{};if(this.h)try{this.h(g)}catch(k){}if(d)try{d(g)}catch(k){}bk(f,3,[g]);var h=Wj();h.h&&ck(f,4,"top",h.h.url||"");bk(f,5,[{url:h.g.url||""},{url:h.g.url?qf(h.g.url):""}]);fk(this.A,e,f,this.o,c)}catch(k){try{fk(this.A,e,{context:"ecmserr",rctx:a,msg:jk(k),url:h&&h.g.url},this.o,c)}catch(n){}}return this.l}; var jk=function(a){var b=a.toString();a.name&&-1==b.indexOf(a.name)&&(b+=": "+a.name);a.message&&-1==b.indexOf(a.message)&&(b+=": "+a.message);if(a.stack){a=a.stack;var c=b;try{-1==a.indexOf(c)&&(a=c+"\n"+a);for(var d;a!=d;)d=a,a=a.replace(/((https?:\/..*\/)[^\/:]*:\d+(?:.|\n)*)\2/,"$1");b=a.replace(/\n */g,"\n")}catch(e){b=c}}return b};var hk,kk,lk=fg(),gk=new wg(1,lk);hk=new function(){var a=void 0===a?C:a;this.h="http:"===a.location.protocol?"http:":"https:";this.g=Math.random()};"number"!==typeof lk.google_srt&&(lk.google_srt=Math.random());var mk=hk,nk=lk.google_srt;0<=nk&&1>=nk&&(mk.g=nk);kk=new ik;kk.lc(function(){});kk.Uc(!0);"complete"==lk.document.readyState?lk.google_measure_js_timing||gk.C():gk.l&&Pe(lk,"load",function(){lk.google_measure_js_timing||gk.C()});var ok=function(){this.blockSize=-1};var pk=[0,2,1],qk=null;document.addEventListener&&document.addEventListener("mousedown",function(a){qk=a},!0); window.mb=function(a){if(a){var b;if(b=window.event||qk){var c;(c=b.which?1<<pk[b.which-1]:b.button)&&b.shiftKey&&(c|=8);c&&b.altKey&&(c|=16);c&&b.ctrlKey&&(c|=32);b=c}else b=null;if(c=b)if(window.css)window.css(a.id,"mb",c,void 0,void 0);else if(a){b=a.href;var d=b.indexOf("&mb=");if(0>d)c=b+"&mb="+c;else{d+=4;var e=b.indexOf("&",d);c=0<=e?b.substring(0,d)+c+b.substring(e):b.substring(0,d)+c}a.href=2E3<c.length?b:c}}};var rk=function(a,b,c){try{a&&(b=b.top);var d=void 0;var e=b;c=void 0===c?!1:c;a&&null!==e&&e!=e.top&&(e=e.top);try{d=(void 0===c?0:c)?(new Ve(e.innerWidth,e.innerHeight)).round():cf(e||window).round()}catch(k){d=new Ve(-12245933,-12245933)}a=d;var f=df(Ye(b.document).g);if(-12245933==a.width){var g=a.width;var h=new E(g,g,g,g)}else h=new E(f.y,f.x+a.width,f.y+a.height,f.x);return h}catch(k){return new E(-12245933,-12245933,-12245933,-12245933)}};var sk=function(a){var b={};y(a,function(c){var d=c.g,e=b[d];b.hasOwnProperty(d)?null!==e&&(c.h(e)||(b[d]=null)):b[d]=c});vb(a,function(c){return null===b[c.g]})};var tk={NONE:0,Of:1},uk={Nf:0,Rg:1,Qg:2,Sg:3};var vk=function(){this.$=0;this.g=!1;this.h=-1;this.$a=!1;this.ra=0};vk.prototype.isVisible=function(){return this.$a?.3<=this.$:.5<=this.$};var wk={Mf:0,Sf:1},xk={668123728:0,668123729:1},yk={44731964:0,44731965:1},zk={NONE:0,sg:1,Wf:2},Ak={480596784:0,480596785:1,21063355:2};var Bk=function(){this.g=null;this.o=!1;this.l=null},Ck=function(a){a.o=!0;return a},Dk=function(a,b){a.l&&y(b,function(c){c=a.l[c];void 0!==c&&a.h(c)})},Ek=function(a){Bk.call(this);this.B=a};t(Ek,Bk);Ek.prototype.h=function(a){null===this.g&&Mb(this.B,a)&&(this.g=a)};var Fk=function(){Bk.call(this)};t(Fk,Bk);Fk.prototype.h=function(a){null===this.g&&"number"===typeof a&&(this.g=a)};var Gk=function(){Bk.call(this)};t(Gk,Bk);Gk.prototype.h=function(a){null===this.g&&"string"===typeof a&&(this.g=a)};var Hk=function(){this.g={};this.l=!0;this.h={}};Hk.prototype.reset=function(){this.g={};this.l=!0;this.h={}}; var Ik=function(a,b,c){a.g[b]||(a.g[b]=new Ek(c));return a.g[b]},Jk=function(a){a.g.queryid||(a.g.queryid=new Gk)},Kk=function(a,b,c){(a=a.g[b])&&a.h(c)},Lk=function(a,b){if(Lb(a.h,b))return a.h[b];if(a=a.g[b])return a.g},Mk=function(a){var b={},c=Db(a.g,function(d){return d.o});Cb(c,function(d,e){d=void 0!==a.h[e]?String(a.h[e]):d.o&&null!==d.g?String(d.g):"";0<d.length&&(b[e]=d)},a);return b},Nk=function(a){a=Mk(a);var b=[];Cb(a,function(c,d){d in Object.prototype||"undefined"!=typeof c&&b.push([d, ":",c].join(""))});return b},Ok=function(){var a=M.D().V,b=nh();a.l&&y(Ib(a.g),function(c){return Dk(c,b)})};var Pk=!ud&&!Jc();var Qk=function(){this.g=this.Sa=null};var Rk=function(){};Rk.prototype.now=function(){return 0};Rk.prototype.h=function(){return 0};Rk.prototype.l=function(){return 0};Rk.prototype.g=function(){return 0};var Tk=function(){if(!Sk())throw Error();};t(Tk,Rk);var Sk=function(){return!(!C||!C.performance)};Tk.prototype.now=function(){return Sk()&&C.performance.now?C.performance.now():Rk.prototype.now.call(this)};Tk.prototype.h=function(){return Sk()&&C.performance.memory?C.performance.memory.totalJSHeapSize||0:Rk.prototype.h.call(this)};Tk.prototype.l=function(){return Sk()&&C.performance.memory?C.performance.memory.usedJSHeapSize||0:Rk.prototype.l.call(this)}; Tk.prototype.g=function(){return Sk()&&C.performance.memory?C.performance.memory.jsHeapSizeLimit||0:Rk.prototype.g.call(this)};var Uk=function(){};Uk.prototype.isVisible=function(){return 1===zg(Je)};var Vk=function(a,b){this.g=a;this.depth=b},Xk=function(a){a=a||Tj();var b=Math.max(a.length-1,0),c=Wj(a);a=c.g;var d=c.h,e=c.l,f=[];c=function(h,k){return null==h?k:h};e&&f.push(new Vk([e.url,e.Hc?2:0],c(e.depth,1)));d&&d!=e&&f.push(new Vk([d.url,2],0));a.url&&a!=e&&f.push(new Vk([a.url,0],c(a.depth,b)));var g=lb(f,function(h,k){return f.slice(0,f.length-k)});!a.url||(e||d)&&a!=e||(d=Bf(a.url))&&g.push([new Vk([d,1],c(a.depth,b))]);g.push([]);return lb(g,function(h){return Wk(b,h)})}; function Wk(a,b){var c=nb(b,function(e,f){return Math.max(e,f.depth)},-1),d=Bb(c+2);d[0]=a;y(b,function(e){return d[e.depth+1]=e.g});return d}var Yk=function(){var a=Xk();return lb(a,function(b){return Zj(b)})};var Zk=function(){this.h=new Uk;this.g=Sk()?new Tk:new Rk},al=function(){$k();var a=C.document;return!!(a&&a.body&&a.body.getBoundingClientRect&&"function"===typeof C.setInterval&&"function"===typeof C.clearInterval&&"function"===typeof C.setTimeout&&"function"===typeof C.clearTimeout)};Zk.prototype.setTimeout=function(a,b){return C.setTimeout(a,b)};Zk.prototype.clearTimeout=function(a){C.clearTimeout(a)};var bl=function(a){$k();var b=fg()||C;Of(b,a)},cl=function(){$k();return Yk()};Ka(Zk);var dl=function(){};dl.prototype.getContext=function(){if(!this.g){if(!C)throw Error("Context has not been set and window is undefined.");this.g=Zk.D()}return this.g};Ka(dl);var $k=function(){return dl.D().getContext()};var el=function(a){ue(this,a,null,null)};t(el,pe);var fl=function(a){this.l=a;this.g=-1;this.h=this.o=0},gl=function(a,b){return function(c){for(var d=[],e=0;e<arguments.length;++e)d[e-0]=arguments[e];if(-1<a.g)return b.apply(null,fa(d));try{return a.g=a.l.g.now(),b.apply(null,fa(d))}finally{a.o+=a.l.g.now()-a.g,a.g=-1,a.h+=1}}};var hl=function(a,b){this.h=a;this.l=b;this.g=new fl(a)};var il=function(){};var jl={Mg:1,oh:2,Ag:3};dc(Zb($b("https://pagead2.googlesyndication.com/pagead/osd.js")));var M=function(){this.o=void 0;this.h=this.C=0;this.A=-1;this.V=new Hk;Ck(Ik(this.V,"mv",zk)).l=void 0===Ak?null:Ak;Ik(this.V,"omid",wk);Ck(Ik(this.V,"epoh",wk));Ck(Ik(this.V,"epph",wk));Ck(Ik(this.V,"umt",wk)).l=void 0===xk?null:xk;Ck(Ik(this.V,"phel",wk));Ck(Ik(this.V,"phell",wk));Ck(Ik(this.V,"oseid",jl));var a=this.V;a.g.sloi||(a.g.sloi=new Fk);Ck(a.g.sloi);Ck(Ik(this.V,"ovms",uk));Ck(Ik(this.V,"xdi",wk));Ck(Ik(this.V,"amp",wk));Ck(Ik(this.V,"prf",wk));Ck(Ik(this.V,"gtx",wk));Ck(Ik(this.V,"mvp_lv", wk));Ck(Ik(this.V,"ssmol",wk)).l=void 0===yk?null:yk;this.g=new hl($k(),this.V);this.B=this.l=!1;this.flags=new il};M.prototype.Oc=function(a){if("string"===typeof a&&0!=a.length){var b=this.V;if(b.l){a=a.split("&");for(var c=a.length-1;0<=c;c--){var d=a[c].split("="),e=d[0];d=1<d.length?parseInt(d[1],10):1;isNaN(d)||(e=b.g[e])&&e.h(d)}}}};Ka(M);var kl=function(){var a="https:";C&&C.location&&"http:"===C.location.protocol&&(a="http:");this.h=a;this.g=.01;this.l=Math.random()},ll=function(a,b,c,d,e){if((d?a.l:Math.random())<(e||a.g))try{if(c instanceof Xj)var f=c;else f=new Xj,zf(c,function(h,k){var n=f,m=n.o++;bk(n,m,Yj(k,h))});var g=ek(f,a.h,"/pagead/gen_204?id="+b+"&");g&&bl(g)}catch(h){}};var ol=function(){var a=ml;this.A=nl;this.B="jserror";this.l=!0;this.h=null;this.C=this.Ia;this.g=void 0===a?null:a;this.o=!1};l=ol.prototype;l.lc=function(a){this.h=a};l.Sc=function(a){this.B=a};l.Tc=function(a){this.l=a};l.Uc=function(a){this.o=a};l.gb=function(a,b,c){var d=this;return gl(M.D().g.g,function(){try{if(d.g&&d.g.l){var e=d.g.start(a.toString(),3);var f=b();d.g.end(e)}else f=b()}catch(k){var g=d.l;try{xg(e);var h=new pl(ql(k));g=d.C(a,h,void 0,c)}catch(n){d.Ia(217,n)}if(!g)throw k;}return f})()}; l.Pc=function(a,b,c,d){var e=this;return gl(M.D().g.g,function(f){for(var g=[],h=0;h<arguments.length;++h)g[h-0]=arguments[h];return e.gb(a,function(){return b.apply(c,g)},d)})}; l.Ia=function(a,b,c,d,e){e=e||this.B;try{var f=new Xj;ck(f,1,"context",a);Me(b)||(b=new pl(ql(b)));b.msg&&ck(f,2,"msg",b.msg.substring(0,512));var g=b.meta||{};if(this.h)try{this.h(g)}catch(k){}if(d)try{d(g)}catch(k){}bk(f,3,[g]);var h=Wj();h.h&&ck(f,4,"top",h.h.url||"");bk(f,5,[{url:h.g.url||""},{url:h.g.url?qf(h.g.url):""}]);ll(this.A,e,f,this.o,c)}catch(k){try{ll(this.A,e,{context:"ecmserr",rctx:a,msg:ql(k),url:h&&h.g.url},this.o,c)}catch(n){}}return this.l}; var ql=function(a){var b=a.toString();a.name&&-1==b.indexOf(a.name)&&(b+=": "+a.name);a.message&&-1==b.indexOf(a.message)&&(b+=": "+a.message);if(a.stack){a=a.stack;var c=b;try{-1==a.indexOf(c)&&(a=c+"\n"+a);for(var d;a!=d;)d=a,a=a.replace(/((https?:\/..*\/)[^\/:]*:\d+(?:.|\n)*)\2/,"$1");b=a.replace(/\n */g,"\n")}catch(e){b=c}}return b},pl=function(a){Le.call(this,Error(a),{message:a})};t(pl,Le);var nl,rl,ml=new wg(1,fg()),sl=function(){var a=fg();a&&"undefined"!=typeof a.google_measure_js_timing&&(a.google_measure_js_timing||ml.C())};(function(){nl=new kl;rl=new ol;var a=fg();a&&a.document&&("complete"==a.document.readyState?sl():ml.l&&Pe(a,"load",function(){sl()}))})();var tl=function(a){rl.lc(function(b){y(a,function(c){c(b)})})},ul=function(a,b){return rl.gb(a,b,void 0)},vl=function(a,b,c,d){return rl.Pc(a,b,c,d)},wl=function(a,b,c,d){rl.Ia(a,b,c,d)};var xl=Date.now(),yl=-1,zl=-1,Al,Bl=-1,Cl=!1,Dl=function(){return Date.now()-xl},El=function(){var a=M.D().o,b=0<=zl?Dl()-zl:-1,c=Cl?Dl()-yl:-1,d=0<=Bl?Dl()-Bl:-1;if(947190542==a)return 100;if(79463069==a)return 200;a=[2E3,4E3];var e=[250,500,1E3];wl(637,Error(),.001);var f=b;-1!=c&&c<b&&(f=c);for(b=0;b<a.length;++b)if(f<a[b]){var g=e[b];break}void 0===g&&(g=e[a.length]);return-1!=d&&1500<d&&4E3>d?500:g};var Fl=function(a,b,c){var d=new E(0,0,0,0);this.time=a;this.volume=null;this.l=b;this.g=d;this.h=c};var Gl=function(a,b,c,d,e,f,g){this.o=a;this.l=b;this.A=c;this.g=d;this.B=e;this.h=f;this.C=g};var Hl={currentTime:1,duration:2,isVpaid:4,volume:8,isYouTube:16,isPlaying:32},Ob={uc:"start",FIRST_QUARTILE:"firstquartile",MIDPOINT:"midpoint",THIRD_QUARTILE:"thirdquartile",COMPLETE:"complete",be:"metric",tc:"pause",kd:"resume",SKIPPED:"skip",VIEWABLE_IMPRESSION:"viewable_impression",ce:"mute",ne:"unmute",FULLSCREEN:"fullscreen",Xd:"exitfullscreen",bd:"bufferstart",$c:"bufferfinish",dd:"fully_viewable_audible_half_duration_impression",jd:"measurable_impression",Sd:"abandon",cd:"engagedview",IMPRESSION:"impression", Ud:"creativeview",LOADED:"loaded",Og:"progress",Ef:"close",Ff:"collapse",de:"overlay_resize",ee:"overlay_unmeasurable_impression",fe:"overlay_unviewable_impression",he:"overlay_viewable_immediate_impression",ge:"overlay_viewable_end_of_session_impression",Vd:"custom_metric_viewable",Fg:"verification_debug"},Il="start firstquartile midpoint thirdquartile resume loaded".split(" "),Jl=["start","firstquartile","midpoint","thirdquartile"],Kl=["abandon"],Ll={hh:-1,uc:0,FIRST_QUARTILE:1,MIDPOINT:2,THIRD_QUARTILE:3, COMPLETE:4,be:5,tc:6,kd:7,SKIPPED:8,VIEWABLE_IMPRESSION:9,ce:10,ne:11,FULLSCREEN:12,Xd:13,dd:14,jd:15,Sd:16,cd:17,IMPRESSION:18,Ud:19,LOADED:20,Vd:21,bd:22,$c:23};var Hb={wf:"addEventListener",Xf:"getMaxSize",Yf:"getScreenSize",Zf:"getState",$f:"getVersion",Pg:"removeEventListener",tg:"isViewable"},Ml=function(a){var b=a!==a.top,c=a.top===gg(a).ma,d=-1,e=0;if(b&&c&&a.top.mraid){d=3;var f=a.top.mraid}else d=(f=a.mraid)?b?c?2:1:0:-1;f&&(f.IS_GMA_SDK||(e=2),Gb(function(g){return"function"===typeof f[g]})||(e=1));return{Aa:f,Tb:e,lf:d}};var Nl=function(a){return(a=a.document)&&"function"===typeof a.elementFromPoint};if(Je&&Je.URL){var Ol,Df=Je.URL;Ol=!!Df&&0<Ef().length;rl.Tc(!Ol)}var Pl=function(a,b,c,d){var e=void 0===e?!1:e;c=vl(d,c);Pe(a,b,c,{capture:e})};var Ql=function(a,b){b=Math.pow(10,b);return Math.floor(a*b)/b};function Rl(a,b,c,d){if(!a)return{value:d,done:!1};d=b(d,a);var e=c(d,a);return!e&&qd(a,"parentElement")?Rl(jf(a),b,c,d):{done:e,value:d}}var Sl=function(a,b,c,d){if(!a)return d;d=Rl(a,b,c,d);if(!d.done)try{var e=Xe(a),f=e&&D(e);return Sl(f&&f.frameElement,b,c,d.value)}catch(g){}return d.value}; function Tl(a){var b=!ud||Ld(8);return Sl(a,function(c,d){c=qd(d,"style")&&d.style&&Xf(d,"visibility");return{hidden:"hidden"===c,visible:b&&"visible"===c}},function(c){return c.hidden||c.visible},{hidden:!1,visible:!1}).hidden} var Ul=function(a){return Sl(a,function(b,c){return!(!qd(c,"style")||!c.style||"none"!==Xf(c,"display"))},function(b){return b},!1)?!0:Tl(a)},Vl=function(a){return new E(a.top,a.right,a.bottom,a.left)},Wl=function(a){var b=a.top||0,c=a.left||0;return new E(b,c+(a.width||0),b+(a.height||0),c)},Xl=function(a){return null!=a&&0<=a&&1>=a};function Yl(){var a=Dc;return a?ob("Android TV;AppleTV;Apple TV;GoogleTV;HbbTV;NetCast.TV;Opera TV;POV_TV;SMART-TV;SmartTV;TV Store;AmazonWebAppPlatform;MiBOX".split(";"),function(b){return pc(a,b)})||pc(a,"OMI/")&&!pc(a,"XiaoMi/")?!0:pc(a,"Presto")&&pc(a,"Linux")&&!pc(a,"X11")&&!pc(a,"Android")&&!pc(a,"Mobi"):!1}function Zl(){var a=Dc;return pc(a,"AppleTV")||pc(a,"Apple TV")||pc(a,"CFNetwork")||pc(a,"tvOS")} function $l(){var a;(a=pc(Dc,"CrKey")||pc(Dc,"PlayStation")||pc(Dc,"Roku")||Yl()||pc(Dc,"Xbox")||Zl())||(a=Dc,a=pc(a,"sdk_google_atv_x86")||pc(a,"Android TV"));return a};var N=function(){this.K=!1;this.l=!uf(C.top);this.C=nf()||of();var a=Tj();a=0<a.length&&null!=a[a.length-1]&&null!=a[a.length-1].url?((a=a[a.length-1].url.match(pf)[3]||null)?decodeURI(a):a)||"":"";this.domain=a;this.g=new E(0,0,0,0);this.B=new Ve(0,0);this.o=new Ve(0,0);this.J=new E(0,0,0,0);this.A=0;this.F=!1;this.h=!(!C||!Ml(C).Aa);am(this)},bm=function(a,b){b&&b.screen&&(a.B=new Ve(b.screen.width,b.screen.height))},cm=function(a,b){var c=a.g?new Ve(a.g.getWidth(),a.g.getHeight()):new Ve(0,0); b=void 0===b?C:b;null!==b&&b!=b.top&&(b=b.top);var d=0,e=0;try{var f=b.document,g=f.body,h=f.documentElement;if("CSS1Compat"==f.compatMode&&h.scrollHeight)d=h.scrollHeight!=c.height?h.scrollHeight:h.offsetHeight,e=h.scrollWidth!=c.width?h.scrollWidth:h.offsetWidth;else{var k=h.scrollHeight,n=h.scrollWidth,m=h.offsetHeight,v=h.offsetWidth;h.clientHeight!=m&&(k=g.scrollHeight,n=g.scrollWidth,m=g.offsetHeight,v=g.offsetWidth);k>c.height?k>m?(d=k,e=n):(d=m,e=v):k<m?(d=k,e=n):(d=m,e=v)}var r=new Ve(e, d)}catch(w){r=new Ve(-12245933,-12245933)}a.o=r},am=function(a){C&&C.document&&(a.J=rk(!1,C,a.C),a.g=rk(!0,C,a.C),cm(a,C),bm(a,C))},dm=function(){var a=N.D();if(0<a.A||a.F)return!0;a=$k().h.isVisible();var b=0===zg(Je);return a||b};Ka(N);var em=function(a){this.l=a;this.h=0;this.g=null};em.prototype.cancel=function(){$k().clearTimeout(this.g);this.g=null};var fm=function(a){var b=$k();a.g=b.setTimeout(gl(M.D().g.g,vl(143,function(){a.h++;a.l.ba()})),El())};var gm=function(a,b,c){this.ma=a;this.sa=void 0===c?"na":c;this.B=[];this.H=!1;this.l=new Fl(-1,!0,this);this.g=this;this.J=b;this.I=this.K=!1;this.W="uk";this.N=!1;this.o=!0};gm.prototype.F=function(){return!1};gm.prototype.initialize=function(){return this.H=!0};gm.prototype.rb=function(){return this.g.W};gm.prototype.Db=function(){return this.g.I};var im=function(a,b,c){if(!a.I||(void 0===c?0:c))a.I=!0,a.W=b,a.J=0,a.g!=a||hm(a)};gm.prototype.ga=function(){return this.g.sa};gm.prototype.Na=function(){return this.g.Y()}; gm.prototype.Y=function(){return{}};gm.prototype.Ha=function(){return this.g.J};var jm=function(a,b){sb(a.B,b)||(a.B.push(b),b.sb(a.g),b.Qa(a.l),b.Da()&&(a.K=!0))};gm.prototype.T=function(){var a=N.D();a.g=rk(!0,this.ma,a.C)};gm.prototype.U=function(){bm(N.D(),this.ma)};gm.prototype.Z=function(){return this.l.g};var km=function(a){a=a.g;a.U();a.T();var b=N.D();b.J=rk(!1,a.ma,b.C);cm(N.D(),a.ma);a.l.g=a.Z()};gm.prototype.ba=function(){};var lm=function(a,b){a.g!=a?lm(a.g,b):a.o!==b&&(a.o=b,hm(a))}; gm.prototype.Gc=function(){return this.g.o};var mm=function(a){a.K=a.B.length?ob(a.B,function(b){return b.Da()}):!1},nm=function(a){var b=xb(a.B);y(b,function(c){c.Qa(a.l)})},hm=function(a){var b=xb(a.B);y(b,function(c){c.sb(a.g)});a.g!=a||nm(a)};l=gm.prototype;l.sb=function(a){var b=this.g;this.g=a.Ha()>=this.J?a:this;b!==this.g?(this.o=this.g.o,hm(this)):this.o!==this.g.o&&(this.o=this.g.o,hm(this))}; l.Qa=function(a){if(a.h===this.g){var b=this.l,c=this.K;if(c=a&&(void 0===c||!c||b.volume==a.volume)&&b.l==a.l)b=b.g,c=a.g,c=b==c?!0:b&&c?b.top==c.top&&b.right==c.right&&b.bottom==c.bottom&&b.left==c.left:!1;this.l=a;!c&&nm(this)}};l.Da=function(){return this.K};l.X=function(){this.N=!0};l.Za=function(){return this.N};var om=function(a,b,c,d){this.l=a;this.g=new E(0,0,0,0);this.A=new E(0,0,0,0);this.h=b;this.V=c;this.I=d;this.H=!1;this.timestamp=-1;this.J=new Gl(b.l,this.g,new E(0,0,0,0),0,0,Dl(),0)};l=om.prototype;l.sc=function(){return!0};l.Kb=function(){};l.X=function(){if(!this.Za()){var a=this.h;tb(a.B,this);a.K&&this.Da()&&mm(a);this.Kb();this.H=!0}};l.Za=function(){return this.H};l.Na=function(){return this.h.Na()};l.Ha=function(){return this.h.Ha()};l.rb=function(){return this.h.rb()};l.Db=function(){return this.h.Db()}; l.sb=function(){};l.Qa=function(){this.Ma()};l.Da=function(){return this.I};var pm=function(a){this.B=!1;this.g=a;this.o=Ja};l=pm.prototype;l.Ha=function(){return this.g.Ha()};l.rb=function(){return this.g.rb()};l.Db=function(){return this.g.Db()};l.create=function(a,b,c){var d=null;this.g&&(d=this.Lb(a,b,c),jm(this.g,d));return d};l.ed=function(){return this.zb()};l.zb=function(){return!1};l.init=function(a){return this.g.initialize()?(jm(this.g,this),this.o=a,!0):!1};l.sb=function(a){0==a.Ha()&&this.o(a.rb(),this)};l.Qa=function(){};l.Da=function(){return!1}; l.X=function(){this.B=!0};l.Za=function(){return this.B};l.Na=function(){return{}};var qm=function(a,b,c){this.l=void 0===c?0:c;this.h=a;this.g=null==b?"":b},rm=function(a){switch(Math.trunc(a.l)){case -16:return-16;case -8:return-8;case 0:return 0;case 8:return 8;case 16:return 16;default:return 16}},sm=function(a,b){return a.l<b.l?!0:a.l>b.l?!1:a.h<b.h?!0:a.h>b.h?!1:typeof a.g<typeof b.g?!0:typeof a.g>typeof b.g?!1:a.g<b.g};var tm=function(){this.l=0;this.g=[];this.h=!1};tm.prototype.add=function(a,b,c){++this.l;a=new qm(a,b,c);this.g.push(new qm(a.h,a.g,a.l+this.l/4096));this.h=!0;return this}; var um=function(a,b){y(b.g,function(c){a.add(c.h,c.g,rm(c))})},vm=function(a,b){var c=void 0===c?0:c;var d=void 0===d?!0:d;zf(b,function(e,f){d&&void 0===e||a.add(f,e,c)});return a},xm=function(a){var b=wm;a.h&&(zb(a.g,function(c,d){return sm(d,c)?1:sm(c,d)?-1:0}),a.h=!1);return nb(a.g,function(c,d){d=b(d);return""+c+(""!=c&&""!=d?"&":"")+d},"")};var wm=function(a){var b=a.h;a=a.g;return""===a?b:"boolean"===typeof a?a?b:"":Array.isArray(a)?0===a.length?b:b+"="+a.join():b+"="+(sb(["mtos","tos","p"],b)?a:encodeURIComponent(a))};var ym=function(a){var b=void 0===b?!0:b;this.g=new tm;void 0!==a&&um(this.g,a);b&&this.g.add("v",Rj,-16)};ym.prototype.toString=function(){var a="//pagead2.googlesyndication.com//pagead/gen_204",b=xm(this.g);0<b.length&&(a+="?"+b);return a};var zm=function(a){var b=[],c=[];Cb(a,function(d,e){if(!(e in Object.prototype)&&"undefined"!=typeof d)switch(Array.isArray(d)&&(d=d.join(",")),d=[e,"=",d].join(""),e){case "adk":case "r":case "tt":case "error":case "mtos":case "tos":case "p":case "bs":b.unshift(d);break;case "req":case "url":case "referrer":case "iframe_loc":c.push(d);break;default:b.push(d)}});return b.concat(c)},Am=function(){if(Rj&&"unreleased"!==Rj)return Rj},Bm=function(a){var b=void 0===b?4E3:b;a=a.toString();if(!/&v=[^&]+/.test(a)){var c= Am();a=c?a+"&v="+encodeURIComponent(c):a}a=a.substring(0,b);bl(a)};var Cm=function(){this.g=0};Ka(Cm);var Dm=function(a,b,c){y(a.l,function(d){var e=a.g;if(!d.g&&(d.l(b,c),d.o())){d.g=!0;var f=d.h(),g=new tm;g.add("id","av-js");g.add("type","verif");g.add("vtype",d.B);d=Cm.D();g.add("i",d.g++);g.add("adk",e);vm(g,f);e=new ym(g);Bm(e)}})};var Em=function(){this.h=this.l=this.o=this.g=0},Fm=function(a,b,c,d){b&&(a.g+=c,a.h+=c,a.o+=c,a.l=Math.max(a.l,a.o));if(void 0===d?!b:d)a.o=0};var Gm=[1,.75,.5,.3,0],Hm=function(a){this.h=a=void 0===a?Gm:a;this.g=lb(this.h,function(){return new Em})},Jm=function(a,b){return Im(a,function(c){return c.g},void 0===b?!0:b)},Lm=function(a,b){return Km(a,b,function(c){return c.g})},Mm=function(a,b){return Im(a,function(c){return c.l},void 0===b?!0:b)},Nm=function(a,b){return Km(a,b,function(c){return c.l})},Om=function(a,b){return Km(a,b,function(c){return c.h})},Pm=function(a){y(a.g,function(b){b.h=0})},Qm=function(a,b,c,d,e,f,g){g=void 0=== g?!0:g;c=f?Math.min(b,c):c;for(f=0;f<a.h.length;f++){var h=a.h[f],k=0<c&&c>=h;h=!(0<b&&b>=h)||d;Fm(a.g[f],g&&k,e,!g||h)}},Im=function(a,b,c){a=lb(a.g,function(d){return b(d)});return c?a:Rm(a)},Km=function(a,b,c){var d=rb(a.h,function(e){return b<=e});return-1==d?0:c(a.g[d])},Rm=function(a){return lb(a,function(b,c,d){return 0<c?d[c]-d[c-1]:d[c]})};var Sm=function(){this.h=new Hm;this.W=new Em;this.I=this.C=-1;this.aa=1E3;this.ba=new Hm([1,.9,.8,.7,.6,.5,.4,.3,.2,.1,0]);this.N=this.L=-1},Tm=function(a,b){return Mm(a.h,void 0===b?!0:b)}; Sm.prototype.K=function(a,b,c,d){this.C=-1!=this.C?Math.min(this.C,b.$):b.$;this.I=Math.max(this.I,b.$);this.L=-1!=this.L?Math.min(this.L,b.ra):b.ra;this.N=Math.max(this.N,b.ra);Qm(this.ba,b.ra,c.ra,b.g,a,d);Qm(this.h,b.$,c.$,b.g,a,d);c=d||c.$a!=b.$a?c.isVisible()&&b.isVisible():c.isVisible();b=!b.isVisible()||b.g;Fm(this.W,c,a,b)};Sm.prototype.bb=function(){return this.W.l>=this.aa};var Um=new E(0,0,0,0);function Vm(a,b){b=Wm(b);return 0===b?0:Wm(a)/b}function Wm(a){return Math.max(a.bottom-a.top,0)*Math.max(a.right-a.left,0)}function Xm(a,b){if(!a||!b)return!1;for(var c=0;null!==a&&100>c++;){if(a===b)return!0;try{if(a=jf(a)||a){var d=Xe(a),e=d&&D(d),f=e&&e.frameElement;f&&(a=f)}}catch(g){break}}return!1} function Ym(a,b,c){if(!a||!b)return!1;b=Kf(Jf(a),-b.left,-b.top);a=(b.left+b.right)/2;b=(b.top+b.bottom)/2;var d=fg();uf(d.top)&&d.top&&d.top.document&&(d=d.top);if(!Nl(d))return!1;a=d.document.elementFromPoint(a,b);if(!a)return!1;b=(b=(b=Xe(c))&&b.defaultView&&b.defaultView.frameElement)&&Xm(b,a);d=a===c;a=!d&&a&&mf(a,function(e){return e===c});return!(b||d||a)}function Zm(a,b,c,d){return N.D().l?!1:0>=a.getWidth()||0>=a.getHeight()?!0:c&&d?ul(208,function(){return Ym(a,b,c)}):!1};var $m=new E(0,0,0,0),an=function(a,b,c){J.call(this);this.position=Jf($m);this.bc=this.Vb();this.Ic=-2;this.qf=Date.now();this.Od=-1;this.Yb=b;this.Xb=null;this.Ub=!1;this.hc=null;this.opacity=-1;this.jf=c;this.Qd=this.Jc=Ja;this.ua=new Qk;this.ua.Sa=a;this.ua.g=a;this.ab=!1;this.Wa={Lc:null,Kc:null};this.Md=!0;this.Jb=null;this.tb=this.Ve=!1;M.D().C++;this.pa=this.Bc();this.Nd=-1;this.ca=null;this.Qe=!1;a=this.V=new Hk;Ik(a,"od",tk);Ck(Ik(a,"opac",wk));Ck(Ik(a,"sbeos",wk));Ck(Ik(a,"prf",wk));Ck(Ik(a, "mwt",wk));Ik(a,"iogeo",wk);(a=this.ua.Sa)&&a.getAttribute&&!/-[a-z]/.test("googleAvInapp")&&(Pk&&a.dataset?"googleAvInapp"in a.dataset:a.hasAttribute?a.hasAttribute("data-"+cd()):a.getAttribute("data-"+cd()))&&(N.D().h=!0);1==this.jf?Kk(this.V,"od",1):Kk(this.V,"od",0)};t(an,J);l=an.prototype; l.O=function(){this.ua.g&&(this.Wa.Lc&&(Qe(this.ua.g,"mouseover",this.Wa.Lc),this.Wa.Lc=null),this.Wa.Kc&&(Qe(this.ua.g,"mouseout",this.Wa.Kc),this.Wa.Kc=null));this.Jb&&this.Jb.X();this.ca&&this.ca.X();delete this.bc;delete this.Jc;delete this.Qd;delete this.ua.Sa;delete this.ua.g;delete this.Wa;delete this.Jb;delete this.ca;delete this.V;J.prototype.O.call(this)};l.Ya=function(){return this.ca?this.ca.g:this.position};l.Oc=function(a){M.D().Oc(a)};l.Da=function(){return!1};l.Vb=function(){return new Sm}; l.va=function(){return this.bc};var bn=function(a,b){b!=a.tb&&(a.tb=b,a=N.D(),b?a.A++:0<a.A&&a.A--)},cn=function(a,b){if(a.ca){if(b.ga()===a.ca.ga())return;a.ca.X();a.ca=null}b=b.create(a.ua.g,a.V,a.Da());if(b=null!=b&&b.sc()?b:null)a.ca=b},dn=function(a,b,c){if(!a.Xb||-1==a.Yb||-1===b.h||-1===a.Xb.h)return 0;a=b.h-a.Xb.h;return a>c?0:a};an.prototype.zd=function(a){return dn(this,a,1E4)}; var en=function(a,b,c){if(a.ca){a.ca.Ma();var d=a.ca.J,e=d.o,f=e.g;if(null!=d.A){var g=d.l;a.hc=new Ue(g.left-f.left,g.top-f.top)}f=a.qc()?Math.max(d.g,d.B):d.g;g={};null!==e.volume&&(g.volume=e.volume);e=a.zd(d);a.Xb=d;a.Xc(f,b,c,!1,g,e,d.C)}},fn=function(a){if(a.Ub&&a.Jb){var b=1==Lk(a.V,"od"),c=N.D().g,d=a.Jb,e=new Ve(c.getWidth(),c.getHeight());c=a.qc();a={mf:a.ca?a.ca.ga():"ns",hc:a.hc,vf:e,qc:c,$:a.pa.$,rf:b};if(b=d.h){b.Ma();e=b.J;var f=e.o.g,g=null,h=null;null!=e.A&&f&&(g=e.l,g=new Ue(g.left- f.left,g.top-f.top),h=new Ve(f.right-f.left,f.bottom-f.top));c={mf:b.ga(),hc:g,vf:h,qc:c,rf:!1,$:c?Math.max(e.g,e.B):e.g}}else c=null;c&&Dm(d,a,c)}};l=an.prototype;l.Xc=function(a,b,c,d,e,f,g){this.ab||(this.Ub&&(a=this.vc(a,c,e,g),d=d&&this.pa.$>=(this.$a()?.3:.5),this.Yc(f,a,d),this.Yb=b,0<a.$&&-1===this.Nd&&(this.Nd=b),-1==this.Od&&this.bb()&&(this.Od=b),-2==this.Ic&&(this.Ic=Wm(this.Ya())?a.$:-1),this.pa=a),this.Jc(this))};l.Yc=function(a,b,c){this.va().K(a,b,this.pa,c)};l.Bc=function(){return new vk}; l.vc=function(a,b,c,d){c=this.Bc();c.g=b;b=$k().h;b=0===zg(Je)?-1:b.isVisible()?0:1;c.h=b;c.$=this.xc(a);c.$a=this.$a();c.ra=d;return c};l.xc=function(a){return 0===this.opacity&&1===Lk(this.V,"opac")?0:a};l.$a=function(){return!1};l.qc=function(){return this.Qe||this.Ve};l.xa=function(){return 0};l.bb=function(){return this.bc.bb()};var gn=function(a,b,c){b&&(a.Jc=b);c&&(a.Qd=c)};var hn="StopIteration"in u?u.StopIteration:{message:"StopIteration",stack:""},jn=function(){};jn.prototype.next=function(){return jn.prototype.g.call(this)};jn.prototype.g=function(){throw hn;};jn.prototype.nb=function(){return this};var kn=function(){this.o=this.g=this.l=this.h=this.B=0},ln=function(a){var b={};b=(b.ptlt=Xa()-a.B,b);var c=a.h;c&&(b.pnk=c);(c=a.l)&&(b.pnc=c);(c=a.o)&&(b.pnmm=c);(a=a.g)&&(b.pns=a);return b};var mn=function(){vk.call(this);this.l=!1;this.volume=void 0;this.paused=!1;this.mediaTime=-1};t(mn,vk);var nn=function(a){return Xl(a.volume)&&0<a.volume};var on=function(){var a={};this.h=(a.vs=[1,0],a.vw=[0,1],a.am=[2,2],a.a=[4,4],a.f=[8,8],a.bm=[16,16],a.b=[32,32],a.avw=[0,64],a.avs=[64,0],a.pv=[256,256],a.gdr=[0,512],a.p=[0,1024],a.r=[0,2048],a.m=[0,4096],a.um=[0,8192],a.ef=[0,16384],a.s=[0,32768],a.pmx=[0,16777216],a);this.g={};for(var b in this.h)0<this.h[b][1]&&(this.g[b]=0);this.l=0},pn=function(a,b){var c=a.h[b],d=c[1];a.l+=c[0];0<d&&0==a.g[b]&&(a.g[b]=1)},qn=function(a){var b=Jb(a.h),c=0,d;for(d in a.g)sb(b,d)&&1==a.g[d]&&(c+=a.h[d][1],a.g[d]= 2);return c},rn=function(a){var b=0,c;for(c in a.g){var d=a.g[c];if(1==d||2==d)b+=a.h[c][1]}return b};var sn=function(){this.h=this.g=0},tn=function(a,b,c){32<=b||(a.h&1<<b&&!c?a.g&=~(1<<b):a.h&1<<b||!c||(a.g|=1<<b),a.h|=1<<b)};var un=function(){Sm.call(this);this.l=new Em;this.U=this.F=this.M=0;this.J=-1;this.ea=new Em;this.B=new Em;this.g=new Hm;this.A=this.o=-1;this.H=new Em;this.aa=2E3;this.T=new sn;this.Z=new sn;this.Y=new sn};t(un,Sm);var vn=function(a,b,c){var d=a.U;Cl||c||-1==a.J||(d+=b-a.J);return d}; un.prototype.K=function(a,b,c,d){if(!b.paused){Sm.prototype.K.call(this,a,b,c,d);var e=nn(b)&&nn(c),f=.5<=(d?Math.min(b.$,c.$):c.$);Xl(b.volume)&&(this.o=-1!=this.o?Math.min(this.o,b.volume):b.volume,this.A=Math.max(this.A,b.volume));f&&(this.M+=a,this.F+=e?a:0);Qm(this.g,b.$,c.$,b.g,a,d,e);Fm(this.l,!0,a);Fm(this.B,e,a);Fm(this.H,c.l,a);Fm(this.ea,e&&!f,a);a=Math.floor(b.mediaTime/1E3);tn(this.T,a,b.isVisible());tn(this.Z,a,1<=b.$);tn(this.Y,a,nn(b))}};var wn=function(){this.g=!1};var xn=function(a,b){this.g=!1;this.h=a;this.K=b;this.l=0};t(xn,wn);var yn=function(a,b){return a.o(b)?(b=a.K.report(a.h,b),a.l|=b,0==b):!1};xn.prototype.o=function(){return!0};xn.prototype.A=function(){return!1};xn.prototype.B=function(){var a=this,b=Nb(function(c){return c==a.h});return Ll[b].toString()};xn.prototype.toString=function(){var a="";this.A()&&(a+="c");this.g&&(a+="s");0<this.l&&(a+=":"+this.l);return this.B()+a};var zn=function(a,b,c,d){om.call(this,a,b,c,d)};t(zn,om);l=zn.prototype;l.wc=function(){if(this.l){var a=this.l,b=this.h.g.ma;try{try{var c=Vl(a.getBoundingClientRect())}catch(n){c=new E(0,0,0,0)}var d=c.right-c.left,e=c.bottom-c.top,f=$f(a,b),g=f.x,h=f.y;var k=new E(Math.round(h),Math.round(g+d),Math.round(h+e),Math.round(g))}catch(n){k=Jf(Um)}this.g=k}};l.od=function(){this.A=this.h.l.g};l.Cd=function(a){return Zm(a,this.A,this.l,1==Lk(this.V,"od"))};l.pd=function(){this.timestamp=Dl()}; l.Ma=function(){this.pd();this.wc();if(this.l&&"number"===typeof this.l.videoWidth&&"number"===typeof this.l.videoHeight){var a=this.l;var b=new Ve(a.videoWidth,a.videoHeight);a=this.g;var c=a.getWidth(),d=a.getHeight(),e=b.width;b=b.height;0>=e||0>=b||0>=c||0>=d||(e/=b,a=Jf(a),e>c/d?(c/=e,d=(d-c)/2,0<d&&(d=a.top+d,a.top=Math.round(d),a.bottom=Math.round(d+c))):(d*=e,c=Math.round((c-d)/2),0<c&&(c=a.left+c,a.left=Math.round(c),a.right=Math.round(c+d))));this.g=a}this.od();a=this.g;c=this.A;a=a.left<= c.right&&c.left<=a.right&&a.top<=c.bottom&&c.top<=a.bottom?new E(Math.max(a.top,c.top),Math.min(a.right,c.right),Math.min(a.bottom,c.bottom),Math.max(a.left,c.left)):new E(0,0,0,0);c=a.top>=a.bottom||a.left>=a.right?new E(0,0,0,0):a;a=this.h.l;b=e=d=0;0<(this.g.bottom-this.g.top)*(this.g.right-this.g.left)&&(this.Cd(c)?c=new E(0,0,0,0):(d=N.D().B,b=new E(0,d.height,d.width,0),d=Vm(c,this.g),e=Vm(c,N.D().g),b=Vm(c,b)));c=c.top>=c.bottom||c.left>=c.right?new E(0,0,0,0):Kf(c,-this.g.left,-this.g.top); dm()||(e=d=0);this.J=new Gl(a,this.g,c,d,e,this.timestamp,b)};l.ga=function(){return this.h.ga()};var An=new E(0,0,0,0),Bn=function(a,b,c){om.call(this,null,a,b,c);this.C=a.Gc();this.B=0};t(Bn,zn);l=Bn.prototype;l.sc=function(){this.o();return!0};l.Qa=function(){zn.prototype.Ma.call(this)};l.pd=function(){};l.wc=function(){};l.Ma=function(){this.o();zn.prototype.Ma.call(this)};l.sb=function(a){a=a.Gc();a!==this.C&&(a?this.o():(N.D().g=new E(0,0,0,0),this.g=new E(0,0,0,0),this.A=new E(0,0,0,0),this.timestamp=-1));this.C=a};function Cn(a){return[a.top,a.left,a.bottom,a.right]} var Dn={},En=(Dn.firstquartile=0,Dn.midpoint=1,Dn.thirdquartile=2,Dn.complete=3,Dn),Fn=function(a,b,c,d,e,f){e=void 0===e?null:e;f=void 0===f?[]:f;an.call(this,b,c,d);this.yc=0;this.ia={};this.ha=new on;this.Rd={};this.la="";this.Ta=null;this.sa=!1;this.g=[];this.fb=e;this.A=f;this.B=null;this.l=-1;this.W=this.H=void 0;this.L=this.I=0;this.T=-1;this.ba=this.aa=!1;this.N=this.C=this.h=this.wb=this.ea=0;new Hm;this.U=this.Y=0;this.Z=-1;this.fa=0;this.F=Ja;this.M=[this.Vb()];this.wa=2;this.ib={};this.ib.pause= "p";this.ib.resume="r";this.ib.skip="s";this.ib.mute="m";this.ib.unmute="um";this.ib.exitfullscreen="ef";this.o=null};t(Fn,an);Fn.prototype.Da=function(){return!0};var Gn=function(a){return void 0===a?a:Number(a)?Ql(a,3):0};l=Fn.prototype;l.zd=function(a){return dn(this,a,Math.max(1E4,this.l/3))}; l.Xc=function(a,b,c,d,e,f,g){var h=this,k=this.F(this)||{};Tb(k,e);this.l=k.duration||this.l;this.H=k.isVpaid||this.H;this.W=k.isYouTube||this.W;e=Hn(this,b);1===In(this)&&(f=e);an.prototype.Xc.call(this,a,b,c,d,k,f,g);this.fb&&this.fb.g&&y(this.A,function(n){n.g||(n.g=yn(n,h))})}; l.Yc=function(a,b,c){an.prototype.Yc.call(this,a,b,c);Jn(this).K(a,b,this.pa,c);this.ba=nn(this.pa)&&nn(b);-1==this.T&&this.aa&&(this.T=this.va().l.g);this.ha.l=0;a=this.bb();b.isVisible()&&pn(this.ha,"vs");a&&pn(this.ha,"vw");Xl(b.volume)&&pn(this.ha,"am");nn(b)&&pn(this.ha,"a");this.tb&&pn(this.ha,"f");-1!=b.h&&(pn(this.ha,"bm"),1==b.h&&pn(this.ha,"b"));nn(b)&&b.isVisible()&&pn(this.ha,"avs");this.ba&&a&&pn(this.ha,"avw");0<b.$&&pn(this.ha,"pv");Kn(this,this.va().l.g,!0)&&pn(this.ha,"gdr");2E3<= Nm(this.va().h,1)&&pn(this.ha,"pmx")};l.Vb=function(){return new un};l.va=function(){return this.bc};var Jn=function(a,b){return a.M[null!=b&&b<a.M.length?b:a.M.length-1]};Fn.prototype.Bc=function(){return new mn};Fn.prototype.vc=function(a,b,c,d){a=an.prototype.vc.call(this,a,b,c,void 0===d?-1:d);a.l=this.tb;a.paused=2==this.fa;a.volume=c.volume;Xl(a.volume)||(this.ea++,b=this.pa,Xl(b.volume)&&(a.volume=b.volume));c=c.currentTime;a.mediaTime=void 0!==c&&0<=c?c:-1;return a}; var In=function(a){var b=!!Lk(M.D().V,"umt");return a.H||!b&&!a.W?0:1},Hn=function(a,b){2==a.fa?b=0:-1==a.Yb?b=0:(b-=a.Yb,b=b>Math.max(1E4,a.l/3)?0:b);var c=a.F(a)||{};c=void 0!==c.currentTime?c.currentTime:a.I;var d=c-a.I,e=0;0<=d?(a.L+=b,a.U+=Math.max(b-d,0),e=Math.min(d,a.L)):a.Y+=Math.abs(d);0!=d&&(a.L=0);-1==a.Z&&0<d&&(a.Z=0<=Bl?Dl()-Bl:-1);a.I=c;return e};Fn.prototype.xc=function(a){return N.D().K?0:this.tb?1:an.prototype.xc.call(this,a)};Fn.prototype.xa=function(){return 1}; Fn.prototype.getDuration=function(){return this.l}; var Ln=function(a,b){ob(a.A,function(c){return c.h==b.h})||a.A.push(b)},Kn=function(a,b,c){return 15E3<=b?!0:a.aa?(void 0===c?0:c)?!0:0<a.l?b>=a.l/2:0<a.T?b>=a.T:!1:!1},Mn=function(a){var b={},c=N.D();b.insideIframe=c.l;b.unmeasurable=a.ab;b.position=a.Ya();b.exposure=a.pa.$;b.documentSize=c.o;b.viewportSize=new Ve(c.g.getWidth(),c.g.getHeight());null!=a.o&&(b.presenceData=a.o);b.screenShare=a.pa.ra;return b},Nn=function(a){var b=Ql(a.pa.$,2),c=a.ha.l,d=a.pa,e=Jn(a),f=Gn(e.o),g=Gn(e.A),h=Gn(d.volume), k=Ql(e.C,2),n=Ql(e.I,2),m=Ql(d.$,2),v=Ql(e.L,2),r=Ql(e.N,2);d=Ql(d.ra,2);a=Jf(a.Ya());a.round();e=Tm(e,!1);return{uf:b,Eb:c,cc:f,Zb:g,Ab:h,dc:k,$b:n,$:m,ec:v,ac:r,ra:d,position:a,fc:e}},Pn=function(a,b){On(a.g,b,function(){return{uf:0,Eb:void 0,cc:-1,Zb:-1,Ab:-1,dc:-1,$b:-1,$:-1,ec:-1,ac:-1,ra:-1,position:void 0,fc:[]}});a.g[b]=Nn(a)},On=function(a,b,c){for(var d=a.length;d<b+1;)a.push(c()),d++},Sn=function(a,b,c){var d=a.Rd[b];if(null!=d)return d;d=Qn(a,b);var e=Nb(function(f){return f==b});a=Rn(a, d,d,c,En[Ob[e]]);"fully_viewable_audible_half_duration_impression"==b&&(a.std="csm");return a},Tn=function(a,b,c){var d=[b];if(a!=b||c!=b)d.unshift(a),d.push(c);return d},Rn=function(a,b,c,d,e){if(a.ab)return{"if":0};var f=Jf(a.Ya());f.round();var g=N.D(),h=M.D(),k=a.va(),n=a.ca?a.ca.ga():"ns",m={};m["if"]=g.l?1:void 0;m.sdk=a.B?a.B:void 0;m.t=a.qf;m.p=[f.top,f.left,f.bottom,f.right];m.tos=Jm(k.h,!1);m.mtos=Tm(k);m.mcvt=k.W.l;m.ps=void 0;m.vht=vn(k,Dl(),2==a.fa);m.mut=k.ea.l;m.a=Gn(a.pa.volume);m.mv= Gn(k.A);m.fs=a.tb?1:0;m.ft=k.H.g;m.at=k.B.g;m.as=0<k.o?1:0;m.atos=Jm(k.g);m.ssb=Jm(k.ba,!1);m.amtos=Mm(k.g,!1);m.uac=a.ea;m.vpt=k.l.g;"nio"==n&&(m.nio=1,m.avms="nio");m.gmm="4";m.gdr=Kn(a,k.l.g,!0)?1:0;m.efpf=a.wa;if("gsv"==n||"nis"==n)f=a.ca,0<f.B&&(m.nnut=f.B);m.tcm=In(a);m.nmt=a.Y;m.bt=a.U;m.pst=a.Z;m.vpaid=a.H;m.dur=a.l;m.vmtime=a.I;m.is=a.ha.l;1<=a.g.length&&(m.i0=a.g[0].Eb,m.a0=[a.g[0].Ab],m.c0=[a.g[0].$],m.ss0=[a.g[0].ra],f=a.g[0].position,m.p0=f?Cn(f):void 0);2<=a.g.length&&(m.i1=a.g[1].Eb, m.a1=Tn(a.g[1].cc,a.g[1].Ab,a.g[1].Zb),m.c1=Tn(a.g[1].dc,a.g[1].$,a.g[1].$b),m.ss1=Tn(a.g[1].ec,a.g[1].ra,a.g[1].ac),f=a.g[1].position,m.p1=f?Cn(f):void 0,m.mtos1=a.g[1].fc);3<=a.g.length&&(m.i2=a.g[2].Eb,m.a2=Tn(a.g[2].cc,a.g[2].Ab,a.g[2].Zb),m.c2=Tn(a.g[2].dc,a.g[2].$,a.g[2].$b),m.ss2=Tn(a.g[2].ec,a.g[2].ra,a.g[2].ac),f=a.g[2].position,m.p2=f?Cn(f):void 0,m.mtos2=a.g[2].fc);4<=a.g.length&&(m.i3=a.g[3].Eb,m.a3=Tn(a.g[3].cc,a.g[3].Ab,a.g[3].Zb),m.c3=Tn(a.g[3].dc,a.g[3].$,a.g[3].$b),m.ss3=Tn(a.g[3].ec, a.g[3].ra,a.g[3].ac),f=a.g[3].position,m.p3=f?Cn(f):void 0,m.mtos3=a.g[3].fc);m.cs=rn(a.ha);b&&(m.ic=qn(a.ha),m.dvpt=k.l.h,m.dvs=Om(k.h,.5),m.dfvs=Om(k.h,1),m.davs=Om(k.g,.5),m.dafvs=Om(k.g,1),c&&(k.l.h=0,Pm(k.h),Pm(k.g)),a.bb()&&(m.dtos=k.M,m.dav=k.F,m.dtoss=a.yc+1,c&&(k.M=0,k.F=0,a.yc++)),m.dat=k.B.h,m.dft=k.H.h,c&&(k.B.h=0,k.H.h=0));m.ps=[g.o.width,g.o.height];m.bs=[g.g.getWidth(),g.g.getHeight()];m.scs=[g.B.width,g.B.height];m.dom=g.domain;a.wb&&(m.vds=a.wb);if(0<a.A.length||a.fb)b=xb(a.A),a.fb&& b.push(a.fb),m.pings=lb(b,function(v){return v.toString()});b=lb(kb(a.A,function(v){return v.A()}),function(v){return v.B()});yb(b);m.ces=b;a.h&&(m.vmer=a.h);a.C&&(m.vmmk=a.C);a.N&&(m.vmiec=a.N);m.avms=a.ca?a.ca.ga():"ns";a.ca&&Tb(m,a.ca.Na());d?(m.c=Ql(a.pa.$,2),m.ss=Ql(a.pa.ra,2)):m.tth=Dl()-Al;m.mc=Ql(k.I,2);m.nc=Ql(k.C,2);m.mv=Gn(k.A);m.nv=Gn(k.o);m.lte=Ql(a.Ic,2);d=Jn(a,e);Tm(k);m.qmtos=Tm(d);m.qnc=Ql(d.C,2);m.qmv=Gn(d.A);m.qnv=Gn(d.o);m.qas=0<d.o?1:0;m.qi=a.la;m.avms||(m.avms="geo");m.psm=k.T.h; m.psv=k.T.g;m.psfv=k.Z.g;m.psa=k.Y.g;h=Nk(h.V);h.length&&(m.veid=h);a.o&&Tb(m,ln(a.o));return m},Qn=function(a,b){if(sb(Kl,b))return!0;var c=a.ia[b];return void 0!==c?(a.ia[b]=!0,!c):!1};var Un=Xa(),Xn=function(){this.g={};var a=D();Vn(this,a,document);var b=Wn();try{if("1"==b){for(var c=a.parent;c!=a.top;c=c.parent)Vn(this,c,c.document);Vn(this,a.top,a.top.document)}}catch(d){}},Wn=function(){var a=document.documentElement;try{if(!uf(D().top))return"2";var b=[],c=D(a.ownerDocument);for(a=c;a!=c.top;a=a.parent)if(a.frameElement)b.push(a.frameElement);else break;return b&&0!=b.length?"1":"0"}catch(d){return"2"}},Vn=function(a,b,c){Pl(c,"mousedown",function(){return Yn(a)},301);Pl(b, "scroll",function(){return Zn(a)},302);Pl(c,"touchmove",function(){return $n(a)},303);Pl(c,"mousemove",function(){return ao(a)},304);Pl(c,"keydown",function(){return bo(a)},305)},Yn=function(a){Cb(a.g,function(b){1E5<b.l||++b.l})},Zn=function(a){Cb(a.g,function(b){1E5<b.g||++b.g})},$n=function(a){Cb(a.g,function(b){1E5<b.g||++b.g})},bo=function(a){Cb(a.g,function(b){1E5<b.h||++b.h})},ao=function(a){Cb(a.g,function(b){1E5<b.o||++b.o})};var co=function(){this.g=[];this.h=[]},eo=function(a,b){return pb(a.g,function(c){return c.la==b})},fo=function(a,b){return b?pb(a.g,function(c){return c.ua.Sa==b}):null},go=function(a,b){return pb(a.h,function(c){return 2==c.xa()&&c.la==b})},io=function(){var a=ho;return 0==a.g.length?a.h:0==a.h.length?a.g:wb(a.h,a.g)};co.prototype.reset=function(){this.g=[];this.h=[]}; var jo=function(a,b){a=1==b.xa()?a.g:a.h;var c=qb(a,function(d){return d==b});return-1!=c?(a.splice(c,1),b.ca&&b.ca.Kb(),b.X(),!0):!1},ko=function(a){var b=ho;if(jo(b,a)){switch(a.xa()){case 0:var c=function(){return null};case 2:c=function(){return go(b,a.la)};break;case 1:c=function(){return eo(b,a.la)}}for(var d=c();d;d=c())jo(b,d)}},lo=function(a){var b=ho;a=kb(a,function(c){return!fo(b,c.ua.Sa)});b.g.push.apply(b.g,fa(a))},mo=function(a){var b=ho,c=[];y(a,function(d){ob(b.g,function(e){return e.ua.Sa=== d.ua.Sa&&e.la===d.la})||(b.g.push(d),c.push(d))})};Ka(co);var ho=co.D();var no=function(){this.g=this.h=null},oo=function(a,b){if(null==a.h)return!1;var c=function(d,e){b(d,e)};a.g=pb(a.h,function(d){return null!=d&&d.ed()});a.g&&(a.g.init(c)?km(a.g.g):b(a.g.g.rb(),a.g));return null!=a.g};Ka(no);var qo=function(a){a=po(a);pm.call(this,a.length?a[a.length-1]:new gm(C,0));this.l=a;this.h=null};t(qo,pm);l=qo.prototype;l.ga=function(){return(this.h?this.h:this.g).ga()};l.Na=function(){return(this.h?this.h:this.g).Na()};l.Ha=function(){return(this.h?this.h:this.g).Ha()};l.init=function(a){var b=!1;y(this.l,function(c){c.initialize()&&(b=!0)});b&&(this.o=a,jm(this.g,this));return b};l.X=function(){y(this.l,function(a){a.X()});pm.prototype.X.call(this)};l.ed=function(){return ob(this.l,function(a){return a.F()})}; l.zb=function(){return ob(this.l,function(a){return a.F()})};l.Lb=function(a,b,c){return new zn(a,this.g,b,c)};l.Qa=function(a){this.h=a.h};var po=function(a){if(!a.length)return[];a=kb(a,function(c){return null!=c&&c.F()});for(var b=1;b<a.length;b++)jm(a[b-1],a[b]);return a};var ro={threshold:[0,.3,.5,.75,1]},so=function(a,b,c,d){om.call(this,a,b,c,d);this.F=this.K=this.C=this.B=this.o=null};t(so,zn);so.prototype.sc=function(){var a=this;this.F||(this.F=Dl());if(ul(298,function(){return to(a)}))return!0;im(this.h,"msf");return!1};so.prototype.Kb=function(){if(this.o&&this.l)try{this.o.unobserve(this.l),this.B?(this.B.unobserve(this.l),this.B=null):this.C&&(this.C.disconnect(),this.C=null)}catch(a){}}; var uo=function(a){return a.o&&a.o.takeRecords?a.o.takeRecords():[]},to=function(a){if(!a.l)return!1;var b=a.l,c=a.h.g.ma,d=M.D().g.g;a.o=new c.IntersectionObserver(gl(d,function(e){return vo(a,e)}),ro);d=gl(d,function(){a.o.unobserve(b);a.o.observe(b);vo(a,uo(a))});c.ResizeObserver?(a.B=new c.ResizeObserver(d),a.B.observe(b)):c.MutationObserver&&(a.C=new u.MutationObserver(d),a.C.observe(b,{attributes:!0,childList:!0,characterData:!0,subtree:!0}));a.o.observe(b);vo(a,uo(a));return!0},vo=function(a, b){try{if(b.length){a.K||(a.K=Dl());var c=wo(b),d=$f(a.l,a.h.g.ma),e=d.x,f=d.y;a.g=new E(Math.round(f),Math.round(e)+c.boundingClientRect.width,Math.round(f)+c.boundingClientRect.height,Math.round(e));var g=Vl(c.intersectionRect);a.A=Kf(g,a.g.left-g.left,a.g.top-g.top)}}catch(h){a.Kb(),wl(299,h)}},wo=function(a){return nb(a,function(b,c){return b.time>c.time?b:c},a[0])};l=so.prototype;l.Ma=function(){var a=uo(this);0<a.length&&vo(this,a);zn.prototype.Ma.call(this)};l.wc=function(){};l.Cd=function(){return!1}; l.od=function(){};l.Na=function(){var a={};return Object.assign(this.h.Na(),(a.niot_obs=this.F,a.niot_cbk=this.K,a))};l.ga=function(){return"nio"};var xo=function(a){a=void 0===a?C:a;pm.call(this,new gm(a,2))};t(xo,pm);xo.prototype.ga=function(){return"nio"};xo.prototype.zb=function(){return!N.D().h&&null!=this.g.g.ma.IntersectionObserver};xo.prototype.Lb=function(a,b,c){return new so(a,this.g,b,c)};var zo=function(){var a=yo();gm.call(this,C.top,a,"geo")};t(zo,gm);zo.prototype.Z=function(){return N.D().g};zo.prototype.F=function(){var a=yo();this.J!==a&&(this.g!=this&&a>this.g.J&&(this.g=this,hm(this)),this.J=a);return 2==a};var yo=function(){M.D();var a=N.D();return a.l||a.h?0:2};Ka(zo);var Ao=function(){};Ka(Ao);var Bo=function(){this.done=!1;this.g={pe:0,ld:0,yh:0,ud:0,Ec:-1,xe:0,we:0,ye:0};this.B=null;this.A=!1;this.l=null;this.C=0;this.h=new em(this)},Eo=function(){var a=Co;a.A||(a.A=!0,Do(a,function(b){for(var c=[],d=0;d<arguments.length;++d)c[d-0]=arguments[d];return a.o.apply(a,fa(c))}),a.o())};Bo.prototype.ba=function(){Fo(this,io(),!1)}; var Go=function(){Ao.D();var a=no.D();null!=a.g&&a.g.g?km(a.g.g):am(N.D())},Fo=function(a,b,c){if(!a.done&&(a.h.cancel(),0!=b.length)){a.l=null;try{Go();var d=Dl(),e=M.D();e.A=d;if(null!=no.D().g)for(e=0;e<b.length;e++)en(b[e],d,c);else ll(nl,"",{strategy_not_selected:1,bin:e.h},!0,void 0);for(d=0;d<b.length;d++)fn(b[d]);++a.g.ud;M.D()}finally{c?y(b,function(f){f.pa.$=0}):fm(a.h)}}},Do=function(a,b){if(!a.B){b=vl(142,b);$k();var c=Ag(Je);c&&Pe(Je,c,b,{capture:!1})&&(a.B=b)}}; Bo.prototype.o=function(){var a=dm(),b=Dl();a?(Cl||(yl=b,y(ho.g,function(c){var d=c.va();d.U=vn(d,b,1!=c.fa)})),Cl=!0):(this.C=Ho(this,b),Cl=!1,Al=b,y(ho.g,function(c){c.Ub&&(c.va().J=b)}));Fo(this,io(),!a)}; var Io=function(){var a=no.D();if(null!=a.g){var b=a.g;y(io(),function(c){return cn(c,b)})}},Ho=function(a,b){a=a.C;Cl&&(a+=b-yl);return a},Jo=function(a){var b=Co;a=void 0===a?function(){return{}}:a;rl.Sc("av-js");nl.g=.01;tl([function(c){var d=M.D(),e={};e=(e.bin=d.h,e.type="error",e);d=Mk(d.V);if(!b.l){var f=C.document,g=0<=zl?Dl()-zl:-1,h=Dl();-1==b.g.Ec&&(g=h);var k=N.D(),n=M.D(),m=Mk(n.V),v=io();try{if(0<v.length){var r=k.g;r&&(m.bs=[r.getWidth(),r.getHeight()]);var w=k.o;w&&(m.ps=[w.width, w.height]);C.screen&&(m.scs=[C.screen.width,C.screen.height])}else m.url=encodeURIComponent(C.location.href.substring(0,512)),f.referrer&&(m.referrer=encodeURIComponent(f.referrer.substring(0,512)));m.tt=g;m.pt=zl;m.bin=n.h;void 0!==C.google_osd_load_pub_page_exp&&(m.olpp=C.google_osd_load_pub_page_exp);m.deb=[1,b.g.pe,b.g.ld,b.g.ud,b.g.Ec,0,b.h.h,b.g.xe,b.g.we,b.g.ye].join("-");m.tvt=Ho(b,h);k.h&&(m.inapp=1);if(null!==C&&C!=C.top){0<v.length&&(m.iframe_loc=encodeURIComponent(C.location.href.substring(0, 512)));var B=k.J;m.is=[B.getWidth(),B.getHeight()]}}catch(La){m.error=1}b.l=m}w=b.l;r={};for(var L in w)r[L]=w[L];L=M.D().g;if(1==Lk(L.l,"prf")){w=new el;B=L.g;f=0;-1<B.g&&(f=B.l.g.now()-B.g);w=Ce(w,1,B.o+f,0);B=L.g;w=Ce(w,5,-1<B.g?B.h+1:B.h,0);w=Ce(w,2,L.h.g.l(),0);w=Ce(w,3,L.h.g.h(),0);w=Ce(w,4,L.h.g.g(),0);L={};B=new be;f=ze(w,1);if(0!==f&&(g=f,null!=g)){ld(B.g,9);f=B.g;k=g;k=(g=0>k?1:0)?-k:k;if(0===k)hd=0<1/k?0:2147483648,gd=0;else if(isNaN(k))hd=2147483647,gd=4294967295;else if(1.7976931348623157E308< k)hd=(g<<31|2146435072)>>>0,gd=0;else if(2.2250738585072014E-308>k)k/=Math.pow(2,-1074),hd=(g<<31|k/4294967296)>>>0,gd=k>>>0;else{n=k;h=0;if(2<=n)for(;2<=n&&1023>h;)h++,n/=2;else for(;1>n&&-1022<h;)n*=2,h--;k*=Math.pow(2,-h);hd=(g<<31|h+1023<<20|1048576*k&1048575)>>>0;gd=4503599627370496*k>>>0}md(f,gd);md(f,hd)}f=xe(w,2,0);0!==f&&ge(B,2,f);f=xe(w,3,0);0!==f&&ge(B,3,f);f=xe(w,4,0);0!==f&&ge(B,4,f);f=xe(w,5,0);0!==f&&fe(B,5,f);w=ee(B);L=(L.pf=Yd(w),L)}else L={};Tb(r,L);Tb(c,e,d,r,a());if(e=Am())d={}, Tb(c,(d.v=encodeURIComponent(e),d))}])};Ka(Bo);var Co=Bo.D();var Ko=null,Lo="",Mo=!1,No=function(){var a=Ko||C;if(!a)return"";var b=[];if(!a.location||!a.location.href)return"";b.push("url="+encodeURIComponent(a.location.href.substring(0,512)));a.document&&a.document.referrer&&b.push("referrer="+encodeURIComponent(a.document.referrer.substring(0,512)));return b.join("&")};var Oo=function(a){return function(b){return void 0===b[a]?0:b[a]}},Qo=function(){var a=[0,2,4];return function(b){b=b.tos;if(Array.isArray(b)){for(var c=Array(b.length),d=0;d<b.length;d++)c[d]=0<d?c[d-1]+b[d]:b[d];return void 0!==a?Po(c,a):c}}},Ro=function(a,b,c,d){c=void 0===c?!0:c;d=void 0===d?function(){return!0}:d;return function(e){var f=e[a];if(Array.isArray(f)&&d(e))return Po(f,b,c)}},So=function(a,b){return function(c){return b(c)?c[a]:void 0}},To=function(a){return function(b){for(var c= 0;c<a.length;c++)if(a[c]===b.e||void 0===a[c]&&!b.hasOwnProperty("e"))return!0;return!1}},Po=function(a,b,c){return void 0===c||c?kb(a,function(d,e){return sb(b,e)}):lb(b,function(d,e,f){return a.slice(0<e?f[e-1]+1:0,d+1).reduce(function(g,h){return g+h},0)})};var Uo=To([void 0,1,2,3,4,8,16]),Vo=To([void 0,4,8,16]),Wo={sv:"sv",cb:"cb",e:"e",nas:"nas",msg:"msg","if":"if",sdk:"sdk",p:"p",p0:So("p0",Vo),p1:So("p1",Vo),p2:So("p2",Vo),p3:So("p3",Vo),cp:"cp",tos:"tos",mtos:"mtos",amtos:"amtos",mtos1:Ro("mtos1",[0,2,4],!1,Vo),mtos2:Ro("mtos2",[0,2,4],!1,Vo),mtos3:Ro("mtos3",[0,2,4],!1,Vo),mcvt:"mcvt",ps:"ps",scs:"scs",bs:"bs",vht:"vht",mut:"mut",a:"a",a0:So("a0",Vo),a1:So("a1",Vo),a2:So("a2",Vo),a3:So("a3",Vo),ft:"ft",dft:"dft",at:"at",dat:"dat",as:"as",vpt:"vpt", gmm:"gmm",std:"std",efpf:"efpf",swf:"swf",nio:"nio",px:"px",nnut:"nnut",vmer:"vmer",vmmk:"vmmk",vmiec:"vmiec",nmt:"nmt",tcm:"tcm",bt:"bt",pst:"pst",vpaid:"vpaid",dur:"dur",vmtime:"vmtime",dtos:"dtos",dtoss:"dtoss",dvs:"dvs",dfvs:"dfvs",dvpt:"dvpt",fmf:"fmf",vds:"vds",is:"is",i0:"i0",i1:"i1",i2:"i2",i3:"i3",ic:"ic",cs:"cs",c:"c",c0:So("c0",Vo),c1:So("c1",Vo),c2:So("c2",Vo),c3:So("c3",Vo),mc:"mc",nc:"nc",mv:"mv",nv:"nv",qmt:So("qmtos",Uo),qnc:So("qnc",Uo),qmv:So("qmv",Uo),qnv:So("qnv",Uo),raf:"raf", rafc:"rafc",lte:"lte",ces:"ces",tth:"tth",femt:"femt",femvt:"femvt",emc:"emc",emuc:"emuc",emb:"emb",avms:"avms",nvat:"nvat",qi:"qi",psm:"psm",psv:"psv",psfv:"psfv",psa:"psa",pnk:"pnk",pnc:"pnc",pnmm:"pnmm",pns:"pns",ptlt:"ptlt",pngs:"pings",veid:"veid",ssb:"ssb",ss0:So("ss0",Vo),ss1:So("ss1",Vo),ss2:So("ss2",Vo),ss3:So("ss3",Vo),dc_rfl:"urlsigs",obd:"obd",omidp:"omidp",omidr:"omidr",omidv:"omidv",omida:"omida",omids:"omids",omidpv:"omidpv",omidam:"omidam",omidct:"omidct",omidia:"omidia"},Xo={c:Oo("c"), at:"at",atos:Ro("atos",[0,2,4]),ta:function(a,b){return function(c){if(void 0===c[a])return b}}("tth","1"),a:"a",dur:"dur",p:"p",tos:Qo(),j:"dom",mtos:Ro("mtos",[0,2,4]),gmm:"gmm",gdr:"gdr",ss:Oo("ss"),vsv:db("w2"),t:"t"},Yo={atos:"atos",avt:Ro("atos",[2]),davs:"davs",dafvs:"dafvs",dav:"dav",ss:Oo("ss"),t:"t"},Zo={a:"a",tos:Qo(),at:"at",c:Oo("c"),mtos:Ro("mtos",[0,2,4]),dur:"dur",fs:"fs",p:"p",vpt:"vpt",vsv:db("ias_w2"),dom:"dom",gmm:"gmm",gdr:"gdr",t:"t"},$o={tos:Qo(),at:"at",c:Oo("c"),mtos:Ro("mtos", [0,2,4]),p:"p",vpt:"vpt",vsv:db("dv_w4"),gmm:"gmm",gdr:"gdr",dom:"dom",t:"t",mv:"mv",qmpt:Ro("qmtos",[0,2,4]),qvs:function(a,b){return function(c){var d=c[a];if("number"===typeof d)return lb(b,function(e){return 0<d&&d>=e?1:0})}}("qnc",[1,.5,0]),qmv:"qmv",qa:"qas",a:"a"};var bp=function(a,b){var c={sv:"898",cb:"j"};c.nas=ho.g.length;c.msg=a;void 0!==b&&(a=ap(b))&&(c.e=Ll[a]);return c},cp=function(a){return 0==a.lastIndexOf("custom_metric_viewable",0)},ap=function(a){var b=cp(a)?"custom_metric_viewable":a.toLowerCase();return Nb(function(c){return c==b})};var dp={Tf:"visible",Af:"audible",$g:"time",bh:"timetype"},ep={visible:function(a){return/^(100|[0-9]{1,2})$/.test(a)},audible:function(a){return"0"==a||"1"==a},timetype:function(a){return"mtos"==a||"tos"==a},time:function(a){return/^(100|[0-9]{1,2})%$/.test(a)||/^([0-9])+ms$/.test(a)}},fp=function(){this.g=void 0;this.h=!1;this.l=0;this.o=-1;this.B="tos"},gp=function(a){try{var b=a.split(",");return b.length>Jb(dp).length?null:nb(b,function(c,d){d=d.toLowerCase().split("=");if(2!=d.length||void 0=== ep[d[0]]||!ep[d[0]](d[1]))throw Error("Entry ("+d[0]+", "+d[1]+") is invalid.");c[d[0]]=d[1];return c},{})}catch(c){return null}},hp=function(a,b){if(void 0==a.g)return 0;switch(a.B){case "mtos":return a.h?Nm(b.g,a.g):Nm(b.h,a.g);case "tos":return a.h?Lm(b.g,a.g):Lm(b.h,a.g)}return 0};var ip=function(a,b,c,d){xn.call(this,b,d);this.C=a;this.J=c};t(ip,xn);ip.prototype.B=function(){return this.C};ip.prototype.A=function(){return!0};ip.prototype.o=function(a){var b=a.va(),c=a.getDuration();return ob(this.J,function(d){if(void 0!=d.g)var e=hp(d,b);else b:{switch(d.B){case "mtos":e=d.h?b.B.l:b.l.g;break b;case "tos":e=d.h?b.B.g:b.l.g;break b}e=0}0==e?d=!1:(d=-1!=d.l?d.l:void 0!==c&&0<c?d.o*c:-1,d=-1!=d&&e>=d);return d})};var jp=function(a){xn.call(this,"fully_viewable_audible_half_duration_impression",a)};t(jp,xn);jp.prototype.o=function(a){var b=Lm(a.va().g,1);return Kn(a,b)};var kp=function(a,b){xn.call(this,a,b)};t(kp,xn);kp.prototype.o=function(a){return a.va().bb()};var lp=function(){this.h=this.o=this.A=this.B=this.l=this.g=""};var mp=function(){},np=function(a,b,c,d,e){var f={};if(void 0!==a)if(null!=b)for(var g in b){var h=b[g];g in Object.prototype||null!=h&&(f[g]="function"===typeof h?h(a):a[h])}else Tb(f,a);void 0!==c&&Tb(f,c);a=xm(vm(new tm,f));0<a.length&&void 0!==d&&void 0!==e&&(e=e(a),a+="&"+d+"="+e);return a};var op=function(){};t(op,mp);op.prototype.g=function(a){var b=new lp;b.g=np(a,Wo);b.l=np(a,Yo);return b};var pp=function(a,b,c){Bn.call(this,a,b,c)};t(pp,Bn);pp.prototype.o=function(){var a=Ia("ima.admob.getViewability"),b=Lk(this.V,"queryid");"function"===typeof a&&b&&a(b)};pp.prototype.ga=function(){return"gsv"};var qp=function(a){a=void 0===a?C:a;pm.call(this,new gm(a,2))};t(qp,pm);qp.prototype.ga=function(){return"gsv"};qp.prototype.zb=function(){var a=N.D();M.D();return a.h&&!1};qp.prototype.Lb=function(a,b,c){return new pp(this.g,b,c)};var rp=function(a,b,c){Bn.call(this,a,b,c)};t(rp,Bn);rp.prototype.o=function(){var a=this,b=Ia("ima.bridge.getNativeViewability"),c=Lk(this.V,"queryid");"function"===typeof b&&c&&b(c,function(d){Pb(d)&&a.B++;var e=d.opt_nativeViewVisibleBounds||{},f=d.opt_nativeViewHidden;a.g=Wl(d.opt_nativeViewBounds||{});var g=a.h.l;g.g=f?Jf(An):Wl(e);a.timestamp=d.opt_nativeTime||-1;N.D().g=g.g;d=d.opt_nativeVolume;void 0!==d&&(g.volume=d)})};rp.prototype.ga=function(){return"nis"};var sp=function(a){a=void 0===a?C:a;pm.call(this,new gm(a,2))};t(sp,pm);sp.prototype.ga=function(){return"nis"};sp.prototype.zb=function(){var a=N.D();M.D();return a.h&&!1};sp.prototype.Lb=function(a,b,c){return new rp(this.g,b,c)};var tp=function(){gm.call(this,C,2,"mraid");this.aa=0;this.L=this.M=!1;this.C=null;this.h=Ml(this.ma);this.l.g=new E(0,0,0,0);this.ea=!1};t(tp,gm);tp.prototype.F=function(){return null!=this.h.Aa};tp.prototype.Y=function(){var a={};this.aa&&(a.mraid=this.aa);this.M&&(a.mlc=1);a.mtop=this.h.lf;this.C&&(a.mse=this.C);this.ea&&(a.msc=1);a.mcp=this.h.Tb;return a}; tp.prototype.A=function(a,b){for(var c=[],d=1;d<arguments.length;++d)c[d-1]=arguments[d];try{return this.h.Aa[a].apply(this.h.Aa,c)}catch(e){wl(538,e,.01,function(f){f.method=a})}};var up=function(a,b,c){a.A("addEventListener",b,c)}; tp.prototype.initialize=function(){var a=this;if(this.H)return!this.Db();this.H=!0;if(2===this.h.Tb)return this.C="ng",im(this,"w"),!1;if(1===this.h.Tb)return this.C="mm",im(this,"w"),!1;N.D().F=!0;this.ma.document.readyState&&"complete"==this.ma.document.readyState?vp(this):Pl(this.ma,"load",function(){$k().setTimeout(vl(292,function(){return vp(a)}),100)},292);return!0}; var vp=function(a){M.D().B=!!a.A("isViewable");up(a,"viewableChange",wp);"loading"===a.A("getState")?up(a,"ready",xp):yp(a)},yp=function(a){"string"===typeof a.h.Aa.AFMA_LIDAR?(a.M=!0,zp(a)):(a.h.Tb=3,a.C="nc",im(a,"w"))},zp=function(a){a.L=!1;var b=1==Lk(M.D().V,"rmmt"),c=!!a.A("isViewable");(b?!c:1)&&$k().setTimeout(vl(524,function(){a.L||(Ap(a),wl(540,Error()),a.C="mt",im(a,"w"))}),500);Bp(a);up(a,a.h.Aa.AFMA_LIDAR,Cp)},Bp=function(a){var b=1==Lk(M.D().V,"sneio"),c=void 0!==a.h.Aa.AFMA_LIDAR_EXP_1, d=void 0!==a.h.Aa.AFMA_LIDAR_EXP_2;(b=b&&d)&&(a.h.Aa.AFMA_LIDAR_EXP_2=!0);c&&(a.h.Aa.AFMA_LIDAR_EXP_1=!b)},Ap=function(a){a.A("removeEventListener",a.h.Aa.AFMA_LIDAR,Cp);a.M=!1};tp.prototype.T=function(){var a=N.D(),b=Dp(this,"getMaxSize");a.g=new E(0,b.width,b.height,0)};tp.prototype.U=function(){N.D().B=Dp(this,"getScreenSize")}; var Dp=function(a,b){if("loading"===a.A("getState"))return new Ve(-1,-1);b=a.A(b);if(!b)return new Ve(-1,-1);a=parseInt(b.width,10);b=parseInt(b.height,10);return isNaN(a)||isNaN(b)?new Ve(-1,-1):new Ve(a,b)};tp.prototype.X=function(){Ap(this);gm.prototype.X.call(this)}; var xp=function(){try{var a=tp.D();a.A("removeEventListener","ready",xp);yp(a)}catch(b){wl(541,b)}},Cp=function(a,b){try{var c=tp.D();c.L=!0;var d=a?new E(a.y,a.x+a.width,a.y+a.height,a.x):new E(0,0,0,0);var e=Dl(),f=dm();var g=new Fl(e,f,c);g.g=d;g.volume=b;c.Qa(g)}catch(h){wl(542,h)}},wp=function(a){var b=M.D(),c=tp.D();a&&!b.B&&(b.B=!0,c.ea=!0,c.C&&im(c,"w",!0))};Ka(tp);var Fp=function(){this.l=this.I=!1;this.g=null;this.o=new op;this.h=null;var a={};this.N=(a.start=this.Oe,a.firstquartile=this.Je,a.midpoint=this.Le,a.thirdquartile=this.Pe,a.complete=this.He,a.pause=this.Nc,a.resume=this.Ld,a.skip=this.Ne,a.viewable_impression=this.Pa,a.mute=this.ub,a.unmute=this.ub,a.fullscreen=this.Ke,a.exitfullscreen=this.Ie,a.fully_viewable_audible_half_duration_impression=this.Pa,a.measurable_impression=this.Pa,a.abandon=this.Nc,a.engagedview=this.Pa,a.impression=this.Pa,a.creativeview= this.Pa,a.progress=this.ub,a.custom_metric_viewable=this.Pa,a.bufferstart=this.Nc,a.bufferfinish=this.Ld,a);a={};this.U=(a.overlay_resize=this.Me,a.abandon=this.Cc,a.close=this.Cc,a.collapse=this.Cc,a.overlay_unmeasurable_impression=function(b){return Sn(b,"overlay_unmeasurable_impression",dm())},a.overlay_viewable_immediate_impression=function(b){return Sn(b,"overlay_viewable_immediate_impression",dm())},a.overlay_unviewable_impression=function(b){return Sn(b,"overlay_unviewable_impression",dm())}, a.overlay_viewable_end_of_session_impression=function(b){return Sn(b,"overlay_viewable_end_of_session_impression",dm())},a);M.D().h=3;Ep(this)};Fp.prototype.A=function(a){bn(a,!1);ko(a)};Fp.prototype.J=function(){};var Gp=function(a,b,c,d){a=a.C(null,d,!0,b);a.B=c;lo([a]);return a}; Fp.prototype.C=function(a,b,c,d){var e=this;this.h||(this.h=this.sd());b=c?b:-1;a=null==this.h||this.l?new Fn(C,a,b,7):new Fn(C,a,b,7,new xn("measurable_impression",this.h),Hp(this));a.la=d;Jk(a.V);Kk(a.V,"queryid",a.la);a.Oc("");gn(a,function(f){for(var g=[],h=0;h<arguments.length;++h)g[h-0]=arguments[h];return e.M.apply(e,fa(g))},function(f){for(var g=[],h=0;h<arguments.length;++h)g[h-0]=arguments[h];return e.T.apply(e,fa(g))});(d=no.D().g)&&cn(a,d);a.ua.Sa&&Ao.D();return a}; var Ip=function(a,b,c){sk(b);var d=a.h;y(b,function(e){var f=lb(e.l,function(g){var h=gp(g);if(null==h)g=null;else if(g=new fp,null!=h.visible&&(g.g=h.visible/100),null!=h.audible&&(g.h=1==h.audible),null!=h.time){var k="mtos"==h.timetype?"mtos":"tos",n=ec(h.time,"%")?"%":"ms";h=parseInt(h.time,10);"%"==n&&(h/=100);"ms"==n?(g.l=h,g.o=-1):(g.l=-1,g.o=h);g.B=void 0===k?"tos":k}return g});ob(f,function(g){return null==g})||Ln(c,new ip(e.id,e.g,f,d))})},Hp=function(a){a=a.h;return[new kp("viewable_impression", a),new jp(a)]},Jp=function(){var a=[],b=M.D();a.push(zo.D());Lk(b.V,"mvp_lv")&&a.push(tp.D());b=[new qp,new sp];b.push(new qo(a));b.push(new xo(C));return b},Lp=function(a){if(!a.I){a.I=!0;try{var b=Dl(),c=M.D(),d=N.D();zl=b;c.o=79463069;"o"!==a.g&&(Ko=gg(C).ma);if(al()){Co.g.ld=0;Co.g.Ec=Dl()-b;var e=Jp(),f=no.D();f.h=e;oo(f,function(){Kp()})?Co.done||(Io(),jm(f.g.g,a),Eo()):d.l?Kp():Eo()}else Mo=!0}catch(g){throw ho.reset(),g;}}},Mp=function(a){Co.h.cancel();Lo=a;Co.done=!0},Np=function(a){if(a.g)return a.g; var b=no.D().g;if(b)switch(b.ga()){case "nis":a.g="n";break;case "gsv":a.g="m"}a.g||(a.g="h");return a.g},Op=function(a,b,c){if(null==a.h)return b.wb|=4,!1;a=a.h.report(c,b);b.wb|=a;return 0==a};Fp.prototype.sb=function(a){switch(a.Ha()){case 0:if(a=no.D().g)a=a.g,tb(a.B,this),a.K&&this.Da()&&mm(a);Kp();break;case 2:Eo()}};Fp.prototype.Qa=function(){};Fp.prototype.Da=function(){return!1};var Kp=function(){var a=[new xo(C)],b=no.D();b.h=a;oo(b,function(){Mp("i")})?Co.done||(Io(),Eo()):Mp("i")}; Fp.prototype.T=function(a,b){a.ab=!0;switch(a.xa()){case 1:Pp(this,a,b);break;case 2:this.Qc(a)}this.Rc(a)};var Pp=function(a,b,c){if(!b.sa){var d=Sn(b,"start",dm());a=a.o.g(d).g;var e={id:"lidarv"};e.r=c;e.v="898v";rf(a,function(f,g){return e[f]="mtos"==f||"tos"==f?g:encodeURIComponent(g)});c=No();rf(c,function(f,g){return e[f]=encodeURIComponent(g)});c="//pagead2.googlesyndication.com/pagead/gen_204?"+xm(vm(new tm,e));Bm(c);b.sa=!0}};l=Fp.prototype;l.Oe=function(a){Pn(a,0);return Sn(a,"start",dm())}; l.ub=function(a,b,c){Fo(Co,[a],!dm());return this.Pa(a,b,c)};l.Pa=function(a,b,c){return Sn(a,c,dm())};l.Je=function(a){return Qp(a,"firstquartile",1)};l.Le=function(a){a.aa=!0;return Qp(a,"midpoint",2)};l.Pe=function(a){return Qp(a,"thirdquartile",3)};l.He=function(a){var b=Qp(a,"complete",4);0!=a.fa&&(a.fa=3);return b};var Qp=function(a,b,c){Fo(Co,[a],!dm());Pn(a,c);4!=c&&On(a.M,c,a.Vb);return Sn(a,b,dm())};l=Fp.prototype; l.Ld=function(a,b,c){b=dm();2!=a.fa||b||(a.va().J=Dl());Fo(Co,[a],!b);2==a.fa&&(a.fa=1);return Sn(a,c,b)};l.Ne=function(a,b){b=this.ub(a,b||{},"skip");0!=a.fa&&(a.fa=3);return b};l.Ke=function(a,b){bn(a,!0);return this.ub(a,b||{},"fullscreen")};l.Ie=function(a,b){bn(a,!1);return this.ub(a,b||{},"exitfullscreen")};l.Nc=function(a,b,c){b=a.va();b.U=vn(b,Dl(),1!=a.fa);Fo(Co,[a],!dm());1==a.fa&&(a.fa=2);return Sn(a,c,dm())};l.Me=function(a){Fo(Co,[a],!dm());return a.h()}; l.Cc=function(a){Fo(Co,[a],!dm());this.Jd(a);0!=a.fa&&(a.fa=3);return a.h()};var Ep=function(a){Jo(function(){var b=Rp();null!=a.g&&(b.sdk=a.g);var c=no.D();null!=c.g&&(b.avms=c.g.ga());return b})},Sp=function(a,b,c,d){var e=fo(ho,c);null!==e&&e.la!==b&&(a.A(e),e=null);e||(b=a.C(c,Dl(),!1,b),0==ho.h.length&&(M.D().o=79463069),mo([b]),e=b,e.B=Np(a),d&&(e.Ta=d));return e};Fp.prototype.M=function(){};var Up=function(a,b){b.C=0;for(var c in Hl)null==a[c]&&(b.C|=Hl[c]);Tp(a,"currentTime");Tp(a,"duration")}; l=Fp.prototype;l.Qc=function(){};l.Jd=function(){};l.fd=function(){};l.Rc=function(){};l.sd=function(){};var Tp=function(a,b){var c=a[b];void 0!==c&&0<c&&(a[b]=Math.floor(1E3*c))},Rp=function(){var a=N.D(),b={};return b.sv="898",b["if"]=a.l?"1":"0",b.nas=String(ho.g.length),b};var Vp=Xa(),Wp=!1,Xp=!1,Yp=!1,Zp=function(a){return!a||"function"!==typeof a||0>String(Function.prototype.toString).indexOf("[native code]")?!1:0<=String(a).indexOf("[native code]")&&!0||!1},$p=function(a){return!!(1<<a&Vp)},aq=[function(a){return!(!a.chrome||!a.chrome.webstore)},function(a){return!!a.document.documentMode},function(a){return!!a.document.fonts.ready},function(){return $p(0)},function(a){return!!a.ActiveXObject},function(a){return!!a.chrome},function(a){return!!a.navigator.serviceWorker}, function(a){return!!a.opera},function(a){return!!a.sidebar},function(){return!+"\v1"},function(){return $p(1)},function(a){return!a.ActiveXObject},function(a){return"-ms-ime-align"in a.document.documentElement.style},function(a){return"-ms-scroll-limit"in a.document.documentElement.style},function(a){return"-webkit-font-feature-settings"in a.document.body.style},function(){return $p(2)},function(a){return"ActiveXObject"in a},function(a){return"MozAppearance"in a.document.documentElement.style},function(a){return"_phantom"in a},function(a){return"callPhantom"in a},function(a){return"content"in a.document.createElement("template")},function(a){return"getEntriesByType"in a.performance},function(){return $p(3)},function(a){return"image-rendering"in a.document.body.style},function(a){return"object-fit"in a.document.body.style},function(a){return"open"in a.document.createElement("details")},function(a){return"orientation"in a.screen},function(a){return"performance"in a},function(a){return"shape-image-threshold"in a.document.body.style}, function(){return $p(4)},function(a){return"srcset"in a.document.createElement("img")},function(){return Xp},function(){return Yp},function(){return $p(5)},function(a){a=a.document.createElement("div");a.style.width="1px";a.style.width="-webkit-min-content";a.style.width="min-content";return"1px"!=a.style.width},function(a){a=a.document.createElement("div");a.style.width="1px";a.style.width="calc(1px - 1px)";a.style.width="-webkit-calc(1px - 1px)";return"1px"!=a.style.width},function(){var a=!1;eval('var DummyFunction1 = function(x){ "use strict"; var a = 12; b = a + x*35; }'); try{DummyFunction1()}catch(b){a=!0}return a},function(){var a=!1;try{DummyFunction2()}catch(b){a=!0}return a},function(){return!1},function(){return $p(6)},function(a){var b=a.document.createElement("canvas");b.width=b.height=1;b=b.getContext("2d");b.globalCompositeOperation="multiply";b.fillStyle="rgb(0,255,255)";b.fillRect(0,0,1,1);b.fill();b.fillStyle="rgb(255,255,0)";b.fillRect(0,0,1,1);b.fill();b=b.getImageData(0,0,1,1).data;return b[0]==b[2]&&b[1]==b[3]||Zp(a.navigator.vibrate)},function(a){a= a.document.createElement("canvas");a.width=a.height=1;a=a.getContext("2d");a.globalCompositeOperation="multiply";a.fillStyle="rgb(0,255,255)";a.fillRect(0,0,1,1);a.fill();a.fillStyle="rgb(255,255,0)";a.fillRect(0,0,1,1);a.fill();a=a.getImageData(0,0,1,1).data;return a[0]==a[2]&&a[1]==a[3]},function(a){return Zp(a.document.createElement("div").matches)},function(a){a=a.document.createElement("input");a.setAttribute("type","range");return"text"!==a.type},function(a){return a.CSS.supports("image-rendering", "pixelated")},function(a){return a.CSS.supports("object-fit","contain")},function(){return $p(7)},function(a){return a.CSS.supports("object-fit","inherit")},function(a){return a.CSS.supports("shape-image-threshold","0.9")},function(a){return a.CSS.supports("word-break","keep-all")},function(){return eval("1 == [for (item of [1,2,3]) item][0]")},function(a){return Zp(a.CSS.supports)},function(){return Zp(Intl.Collator)},function(a){return Zp(a.document.createElement("dialog").show)},function(){return $p(8)}, function(a){return Zp(a.document.createElement("div").animate([{transform:"scale(1)",easing:"ease-in"},{transform:"scale(1.3)",easing:"ease-in"}],{duration:1300,iterations:1}).reverse)},function(a){return Zp(a.document.createElement("div").animate)},function(a){return Zp(a.document.documentElement.webkitRequestFullScreen)},function(a){return Zp(a.navigator.getBattery)},function(a){return Zp(a.navigator.permissions.query)},function(){return!1},function(){return $p(9)},function(){return Zp(webkitRequestAnimationFrame)}, function(a){return Zp(a.BroadcastChannel.call)},function(a){return Zp(a.FontFace)},function(a){return Zp(a.Gamepad)},function(){return $p(10)},function(a){return Zp(a.MutationEvent)},function(a){return Zp(a.MutationObserver)},function(a){return Zp(a.crypto.getRandomValues)},function(a){return Zp(a.document.body.createShadowRoot)},function(a){return Zp(a.document.body.webkitCreateShadowRoot)},function(a){return Zp(a.fetch)},function(){return $p(11)},function(a){return Zp(a.navigator.serviceWorker.register)}, function(a){return Zp(a.navigator.webkitGetGamepads)},function(a){return Zp(a.speechSynthesis.speak)},function(a){return Zp(a.webkitRTCPeerConnection)},function(a){return a.CSS.supports("--fake-var","0")},function(){return $p(12)},function(a){return a.CSS.supports("cursor","grab")},function(a){return a.CSS.supports("cursor","zoom-in")},function(a){return a.CSS.supports("image-orientation","270deg")},function(){return $p(13)},function(a){return a.CSS.supports("position","sticky")},function(a){return void 0=== a.document.createElement("style").scoped},function(a){return a.performance.getEntriesByType("resource")instanceof Array},function(){return"undefined"==typeof InstallTrigger},function(){return"object"==typeof(new Intl.Collator).resolvedOptions()},function(a){return"boolean"==typeof a.navigator.onLine},function(){return $p(14)},function(a){return"undefined"==typeof a.navigator.Ch},function(a){return"number"==typeof a.performance.now()},function(){return 0==(new Uint16Array(1))[0]},function(a){return-1== a.ActiveXObject.toString().indexOf("native")},function(a){return-1==Object.prototype.toString.call(a.HTMLElement).indexOf("Constructor")}],bq=[function(a){a=a.document.createElement("div");var b=null,c=["{45EA75A0-A269-11D1-B5BF-0000F8051515}","{3AF36230-A269-11D1-B5BF-0000F8051515}","{89820200-ECBD-11CF-8B85-00AA005B4383}"];try{a.style.behavior="url(#default#clientcaps)"}catch(e){}for(var d=0;d<c.length;d++){try{b=a.getComponentVersion(c[d],"componentid").replace(/,/g,".")}catch(e){}if(b)return b.split(".")[0]}return!1}, function(){return(new Date).getTimezoneOffset()},function(a){return(a.innerWidth||a.document.documentElement.clientWidth||a.document.body.clientWidth)/(a.innerHeight||a.document.documentElement.clientHeight||a.document.body.clientHeight)},function(a){return(a.outerWidth||a.document&&a.document.body&&a.document.body.offsetWidth)/(a.outerHeight||a.document&&a.document.body&&a.document.body.offsetHeight)},function(a){return a.screen.availWidth/a.screen.availHeight},function(a){return a.screen.width/ a.screen.height}],cq=[function(a){return a.navigator.userAgent},function(a){return a.navigator.platform},function(a){return a.navigator.vendor}],eq=function(){try{dq()}catch(d){}var a="a=1&b="+Vp+"&",b=[],c=99;y(aq,function(d,e){var f=!1;try{f=d(C)}catch(g){}b[e/32>>>0]|=f<<e%32});y(b,function(d,e){a+=String.fromCharCode(c+e)+"="+(d>>>0).toString(16)+"&"});c=105;y(bq,function(d){var e="false";try{e=d(C)}catch(f){}a+=String.fromCharCode(c++)+"="+e+"&"});y(cq,function(d){var e="";try{e=Zd(d(C))}catch(f){}a+= String.fromCharCode(c++)+"="+e+"&"});return a.slice(0,-1)},dq=function(){if(!Wp){var a=function(){Xp=!0;C.document.removeEventListener("webdriver-evaluate",a,!0)};C.document.addEventListener("webdriver-evaluate",a,!0);var b=function(){Yp=!0;C.document.removeEventListener("webdriver-evaluate-response",b,!0)};C.document.addEventListener("webdriver-evaluate-response",b,!0);Wp=!0}};var fq=function(){this.blockSize=-1;this.blockSize=64;this.g=Array(4);this.o=Array(this.blockSize);this.l=this.h=0;this.reset()};Ya(fq,ok);fq.prototype.reset=function(){this.g[0]=1732584193;this.g[1]=4023233417;this.g[2]=2562383102;this.g[3]=271733878;this.l=this.h=0}; var gq=function(a,b,c){c||(c=0);var d=Array(16);if("string"===typeof b)for(var e=0;16>e;++e)d[e]=b.charCodeAt(c++)|b.charCodeAt(c++)<<8|b.charCodeAt(c++)<<16|b.charCodeAt(c++)<<24;else for(e=0;16>e;++e)d[e]=b[c++]|b[c++]<<8|b[c++]<<16|b[c++]<<24;b=a.g[0];c=a.g[1];e=a.g[2];var f=a.g[3];var g=b+(f^c&(e^f))+d[0]+3614090360&4294967295;b=c+(g<<7&4294967295|g>>>25);g=f+(e^b&(c^e))+d[1]+3905402710&4294967295;f=b+(g<<12&4294967295|g>>>20);g=e+(c^f&(b^c))+d[2]+606105819&4294967295;e=f+(g<<17&4294967295|g>>> 15);g=c+(b^e&(f^b))+d[3]+3250441966&4294967295;c=e+(g<<22&4294967295|g>>>10);g=b+(f^c&(e^f))+d[4]+4118548399&4294967295;b=c+(g<<7&4294967295|g>>>25);g=f+(e^b&(c^e))+d[5]+1200080426&4294967295;f=b+(g<<12&4294967295|g>>>20);g=e+(c^f&(b^c))+d[6]+2821735955&4294967295;e=f+(g<<17&4294967295|g>>>15);g=c+(b^e&(f^b))+d[7]+4249261313&4294967295;c=e+(g<<22&4294967295|g>>>10);g=b+(f^c&(e^f))+d[8]+1770035416&4294967295;b=c+(g<<7&4294967295|g>>>25);g=f+(e^b&(c^e))+d[9]+2336552879&4294967295;f=b+(g<<12&4294967295| g>>>20);g=e+(c^f&(b^c))+d[10]+4294925233&4294967295;e=f+(g<<17&4294967295|g>>>15);g=c+(b^e&(f^b))+d[11]+2304563134&4294967295;c=e+(g<<22&4294967295|g>>>10);g=b+(f^c&(e^f))+d[12]+1804603682&4294967295;b=c+(g<<7&4294967295|g>>>25);g=f+(e^b&(c^e))+d[13]+4254626195&4294967295;f=b+(g<<12&4294967295|g>>>20);g=e+(c^f&(b^c))+d[14]+2792965006&4294967295;e=f+(g<<17&4294967295|g>>>15);g=c+(b^e&(f^b))+d[15]+1236535329&4294967295;c=e+(g<<22&4294967295|g>>>10);g=b+(e^f&(c^e))+d[1]+4129170786&4294967295;b=c+(g<< 5&4294967295|g>>>27);g=f+(c^e&(b^c))+d[6]+3225465664&4294967295;f=b+(g<<9&4294967295|g>>>23);g=e+(b^c&(f^b))+d[11]+643717713&4294967295;e=f+(g<<14&4294967295|g>>>18);g=c+(f^b&(e^f))+d[0]+3921069994&4294967295;c=e+(g<<20&4294967295|g>>>12);g=b+(e^f&(c^e))+d[5]+3593408605&4294967295;b=c+(g<<5&4294967295|g>>>27);g=f+(c^e&(b^c))+d[10]+38016083&4294967295;f=b+(g<<9&4294967295|g>>>23);g=e+(b^c&(f^b))+d[15]+3634488961&4294967295;e=f+(g<<14&4294967295|g>>>18);g=c+(f^b&(e^f))+d[4]+3889429448&4294967295;c= e+(g<<20&4294967295|g>>>12);g=b+(e^f&(c^e))+d[9]+568446438&4294967295;b=c+(g<<5&4294967295|g>>>27);g=f+(c^e&(b^c))+d[14]+3275163606&4294967295;f=b+(g<<9&4294967295|g>>>23);g=e+(b^c&(f^b))+d[3]+4107603335&4294967295;e=f+(g<<14&4294967295|g>>>18);g=c+(f^b&(e^f))+d[8]+1163531501&4294967295;c=e+(g<<20&4294967295|g>>>12);g=b+(e^f&(c^e))+d[13]+2850285829&4294967295;b=c+(g<<5&4294967295|g>>>27);g=f+(c^e&(b^c))+d[2]+4243563512&4294967295;f=b+(g<<9&4294967295|g>>>23);g=e+(b^c&(f^b))+d[7]+1735328473&4294967295; e=f+(g<<14&4294967295|g>>>18);g=c+(f^b&(e^f))+d[12]+2368359562&4294967295;c=e+(g<<20&4294967295|g>>>12);g=b+(c^e^f)+d[5]+4294588738&4294967295;b=c+(g<<4&4294967295|g>>>28);g=f+(b^c^e)+d[8]+2272392833&4294967295;f=b+(g<<11&4294967295|g>>>21);g=e+(f^b^c)+d[11]+1839030562&4294967295;e=f+(g<<16&4294967295|g>>>16);g=c+(e^f^b)+d[14]+4259657740&4294967295;c=e+(g<<23&4294967295|g>>>9);g=b+(c^e^f)+d[1]+2763975236&4294967295;b=c+(g<<4&4294967295|g>>>28);g=f+(b^c^e)+d[4]+1272893353&4294967295;f=b+(g<<11&4294967295| g>>>21);g=e+(f^b^c)+d[7]+4139469664&4294967295;e=f+(g<<16&4294967295|g>>>16);g=c+(e^f^b)+d[10]+3200236656&4294967295;c=e+(g<<23&4294967295|g>>>9);g=b+(c^e^f)+d[13]+681279174&4294967295;b=c+(g<<4&4294967295|g>>>28);g=f+(b^c^e)+d[0]+3936430074&4294967295;f=b+(g<<11&4294967295|g>>>21);g=e+(f^b^c)+d[3]+3572445317&4294967295;e=f+(g<<16&4294967295|g>>>16);g=c+(e^f^b)+d[6]+76029189&4294967295;c=e+(g<<23&4294967295|g>>>9);g=b+(c^e^f)+d[9]+3654602809&4294967295;b=c+(g<<4&4294967295|g>>>28);g=f+(b^c^e)+d[12]+ 3873151461&4294967295;f=b+(g<<11&4294967295|g>>>21);g=e+(f^b^c)+d[15]+530742520&4294967295;e=f+(g<<16&4294967295|g>>>16);g=c+(e^f^b)+d[2]+3299628645&4294967295;c=e+(g<<23&4294967295|g>>>9);g=b+(e^(c|~f))+d[0]+4096336452&4294967295;b=c+(g<<6&4294967295|g>>>26);g=f+(c^(b|~e))+d[7]+1126891415&4294967295;f=b+(g<<10&4294967295|g>>>22);g=e+(b^(f|~c))+d[14]+2878612391&4294967295;e=f+(g<<15&4294967295|g>>>17);g=c+(f^(e|~b))+d[5]+4237533241&4294967295;c=e+(g<<21&4294967295|g>>>11);g=b+(e^(c|~f))+d[12]+1700485571& 4294967295;b=c+(g<<6&4294967295|g>>>26);g=f+(c^(b|~e))+d[3]+2399980690&4294967295;f=b+(g<<10&4294967295|g>>>22);g=e+(b^(f|~c))+d[10]+4293915773&4294967295;e=f+(g<<15&4294967295|g>>>17);g=c+(f^(e|~b))+d[1]+2240044497&4294967295;c=e+(g<<21&4294967295|g>>>11);g=b+(e^(c|~f))+d[8]+1873313359&4294967295;b=c+(g<<6&4294967295|g>>>26);g=f+(c^(b|~e))+d[15]+4264355552&4294967295;f=b+(g<<10&4294967295|g>>>22);g=e+(b^(f|~c))+d[6]+2734768916&4294967295;e=f+(g<<15&4294967295|g>>>17);g=c+(f^(e|~b))+d[13]+1309151649& 4294967295;c=e+(g<<21&4294967295|g>>>11);g=b+(e^(c|~f))+d[4]+4149444226&4294967295;b=c+(g<<6&4294967295|g>>>26);g=f+(c^(b|~e))+d[11]+3174756917&4294967295;f=b+(g<<10&4294967295|g>>>22);g=e+(b^(f|~c))+d[2]+718787259&4294967295;e=f+(g<<15&4294967295|g>>>17);g=c+(f^(e|~b))+d[9]+3951481745&4294967295;a.g[0]=a.g[0]+b&4294967295;a.g[1]=a.g[1]+(e+(g<<21&4294967295|g>>>11))&4294967295;a.g[2]=a.g[2]+e&4294967295;a.g[3]=a.g[3]+f&4294967295},hq=function(a,b){if(void 0===c)var c=b.length;for(var d=c-a.blockSize, e=a.o,f=a.h,g=0;g<c;){if(0==f)for(;g<=d;)gq(a,b,g),g+=a.blockSize;if("string"===typeof b)for(;g<c;){if(e[f++]=b.charCodeAt(g++),f==a.blockSize){gq(a,e);f=0;break}}else for(;g<c;)if(e[f++]=b[g++],f==a.blockSize){gq(a,e);f=0;break}}a.h=f;a.l+=c};var iq=function(){this.h=null};t(iq,op);iq.prototype.g=function(a){var b=op.prototype.g.call(this,a);var c=Vp=Xa();var d=$p(5);c=(Xp?!d:d)?c|2:c&-3;d=$p(2);c=(Yp?!d:d)?c|8:c&-9;c={s1:(c>>>0).toString(16)};this.h||(this.h=eq());b.B=this.h;b.A=np(a,Xo,c,"h",jq("kArwaWEsTs"));b.o=np(a,Zo,{},"h",jq("b96YPMzfnx"));b.h=np(a,$o,{},"h",jq("yb8Wev6QDg"));return b}; var jq=function(a){return function(b){var c=new fq;hq(c,b+a);var d=Array((56>c.h?c.blockSize:2*c.blockSize)-c.h);d[0]=128;for(b=1;b<d.length-8;++b)d[b]=0;var e=8*c.l;for(b=d.length-8;b<d.length;++b)d[b]=e&255,e/=256;hq(c,d);d=Array(16);for(b=e=0;4>b;++b)for(var f=0;32>f;f+=8)d[e++]=c.g[b]>>>f&255;return cb(d).slice(-8)}};var kq=function(a,b){this.l=a;this.o=b};kq.prototype.report=function(a,b){var c=this.g(b);if("function"===typeof c){var d={};d=(d.sv="898",d.cb="j",d.e=lq(a),d);var e=Sn(b,a,dm());Tb(d,e);b.Rd[a]=e;d=2==b.xa()?zm(d).join("&"):this.o.g(d).g;try{return c(b.la,d,a),0}catch(f){return 2}}else return 1};var lq=function(a){var b=cp(a)?"custom_metric_viewable":a;a=Nb(function(c){return c==b});return Ll[a]};kq.prototype.g=function(){return Ia(this.l)};var mq=function(a,b,c){kq.call(this,a,b);this.h=c};t(mq,kq);mq.prototype.g=function(a){if(!a.Ta)return kq.prototype.g.call(this,a);if(this.h[a.Ta])return function(){};wl(393,Error());return null};var nq=function(){Fp.call(this);this.F=void 0;this.H=null;this.K=!1;this.B={};this.L=0;this.o=new iq};t(nq,Fp);nq.prototype.J=function(a,b){var c=this,d=no.D();if(null!=d.g)switch(d.g.ga()){case "nis":var e=oq(this,a,b);break;case "gsv":e=pq(this,a,b);break;case "exc":e=qq(this,a)}e||(b.opt_overlayAdElement?e=void 0:b.opt_adElement&&(e=Sp(this,a,b.opt_adElement,b.opt_osdId)));e&&1==e.xa()&&(e.F==Ja&&(e.F=function(f){return c.fd(f)}),rq(this,e,b));return e}; var rq=function(a,b,c){c=c.opt_configurable_tracking_events;null!=a.h&&Array.isArray(c)&&Ip(a,c,b)}; nq.prototype.fd=function(a){a.h=0;a.N=0;if("h"==a.B||"n"==a.B){if(M.D().l)var b=Ia("ima.bridge.getVideoMetadata");else if(a.Ta&&sq(this)){var c=this.B[a.Ta];c?b=function(e){return tq(c,e)}:null!==c&&wl(379,Error())}else b=Ia("ima.common.getVideoMetadata");if("function"===typeof b)try{var d=b(a.la)}catch(e){a.h|=4}else a.h|=2}else if("b"==a.B)if(b=Ia("ytads.bulleit.getVideoMetadata"),"function"===typeof b)try{d=b(a.la)}catch(e){a.h|=4}else a.h|=2;else if("ml"==a.B)if(b=Ia("ima.common.getVideoMetadata"), "function"===typeof b)try{d=b(a.la)}catch(e){a.h|=4}else a.h|=2;else a.h|=1;a.h||(void 0===d?a.h|=8:null===d?a.h|=16:Pb(d)?a.h|=32:null!=d.errorCode&&(a.N=d.errorCode,a.h|=64));null==d&&(d={});Up(d,a);Xl(d.volume)&&Xl(this.F)&&(d.volume*=this.F);return d}; var pq=function(a,b,c){var d=eo(ho,b);d||(d=c.opt_nativeTime||-1,d=Gp(a,b,Np(a),d),c.opt_osdId&&(d.Ta=c.opt_osdId));return d},oq=function(a,b,c){var d=eo(ho,b);d||(d=Gp(a,b,"n",c.opt_nativeTime||-1));return d},qq=function(a,b){var c=eo(ho,b);c||(c=Gp(a,b,"h",-1));return c};nq.prototype.sd=function(){if(sq(this))return new mq("ima.common.triggerExternalActivityEvent",this.o,this.B);var a=uq(this);return null!=a?new kq(a,this.o):null}; var uq=function(a){var b=M.D();switch(Np(a)){case "b":return"ytads.bulleit.triggerExternalActivityEvent";case "n":return"ima.bridge.triggerExternalActivityEvent";case "h":if(b.l)return"ima.bridge.triggerExternalActivityEvent";case "m":case "ml":return"ima.common.triggerExternalActivityEvent"}return null};nq.prototype.Qc=function(a){!a.g&&a.ab&&Op(this,a,"overlay_unmeasurable_impression")&&(a.g=!0)}; nq.prototype.Jd=function(a){a.Md&&(a.bb()?Op(this,a,"overlay_viewable_end_of_session_impression"):Op(this,a,"overlay_unviewable_impression"),a.Md=!1)}; var vq=function(a,b,c,d){c=void 0===c?{}:c;var e={};Tb(e,{opt_adElement:void 0,opt_fullscreen:void 0},c);if(e.opt_bounds)return a.o.g(bp("ol",d));if(void 0!==d)if(void 0!==ap(d))if(Mo)b=bp("ue",d);else if(Lp(a),"i"==Lo)b=bp("i",d),b["if"]=0;else if(b=a.J(b,e)){b:{"i"==Lo&&(b.ab=!0,a.Rc(b));c=e.opt_fullscreen;void 0!==c&&bn(b,!!c);var f;if(c=!N.D().h&&!$l())$k(),c=0===zg(Je);if(f=c){switch(b.xa()){case 1:Pp(a,b,"pv");break;case 2:a.Qc(b)}Mp("pv")}c=d.toLowerCase();if(f=!f)c:{if(Lk(M.D().V,"ssmol")&& (f=a.l,"loaded"===c))break c;f=sb(Il,c)}if(f&&0==b.fa){"i"!=Lo&&(Co.done=!1);f=void 0!==e?e.opt_nativeTime:void 0;Bl=f="number"===typeof f?f:Dl();b.Ub=!0;var g=dm();b.fa=1;b.ia={};b.ia.start=!1;b.ia.firstquartile=!1;b.ia.midpoint=!1;b.ia.thirdquartile=!1;b.ia.complete=!1;b.ia.resume=!1;b.ia.pause=!1;b.ia.skip=!1;b.ia.mute=!1;b.ia.unmute=!1;b.ia.viewable_impression=!1;b.ia.measurable_impression=!1;b.ia.fully_viewable_audible_half_duration_impression=!1;b.ia.fullscreen=!1;b.ia.exitfullscreen=!1;b.yc= 0;g||(b.va().J=f);Fo(Co,[b],!g)}(f=b.ib[c])&&pn(b.ha,f);sb(Jl,c)&&!b.ab&&b.fb&&0!=b.fa&&(f=b.fb,f.g||(f.g=yn(f,b)));switch(b.xa()){case 1:var h=cp(c)?a.N.custom_metric_viewable:a.N[c];break;case 2:h=a.U[c]}if(h&&(d=h.call(a,b,e,d),void 0!==d)){e=bp(void 0,c);Tb(e,d);d=e;break b}d=void 0}3==b.fa&&a.A(b);b=d}else b=bp("nf",d);else b=void 0;else Mo?b=bp("ue"):(b=a.J(b,e))?(d=bp(),Tb(d,Rn(b,!0,!1,!1)),b=d):b=bp("nf");return"string"===typeof b?a.o.g(void 0):a.o.g(b)}; nq.prototype.M=function(a){this.l&&1==a.xa()&&wq(this,a)};nq.prototype.Rc=function(a){this.l&&1==a.xa()&&wq(this,a)};var wq=function(a,b){var c;if(b.Ta&&sq(a)){var d=a.B[b.Ta];d?c=function(f,g){xq(d,f,g)}:null!==d&&wl(379,Error())}else c=Ia("ima.common.triggerViewabilityMeasurementUpdate");if("function"===typeof c){var e=Mn(b);e.nativeVolume=a.F;c(b.la,e)}},yq=function(a,b,c){a.B[b]=c},sq=function(a){return M.D().l||"h"!=Np(a)&&"m"!=Np(a)?!1:0!=a.L}; nq.prototype.C=function(a,b,c,d){a=Fp.prototype.C.call(this,a,b,c,d);this.K&&(b=this.H,null==a.o&&(a.o=new kn),b.g[a.la]=a.o,a.o.B=Un);return a};nq.prototype.A=function(a){a&&1==a.xa()&&this.K&&delete this.H.g[a.la];return Fp.prototype.A.call(this,a)};var zq=function(a){var b={};return b.viewability=a.g,b.googleViewability=a.l,b.moatInit=a.B,b.moatViewability=a.A,b.integralAdsViewability=a.o,b.doubleVerifyViewability=a.h,b},Aq=function(a,b,c){c=void 0===c?{}:c;a=vq(nq.D(),b,c,a);return zq(a)};Ka(nq); var Bq=new lp;Bq.B="stopped";Bq.g="stopped";Bq.l="stopped";Bq.A="stopped";Bq.o="stopped";Bq.h="stopped";Object.freeze(Bq);var Cq=vl(193,Aq,void 0,Rp);x("Goog_AdSense_Lidar_sendVastEvent",Cq,void 0);var Dq=vl(194,function(a,b){b=void 0===b?{}:b;a=vq(nq.D(),a,b);return zq(a)});x("Goog_AdSense_Lidar_getViewability",Dq,void 0);var Eq=vl(195,function(){return cl()});x("Goog_AdSense_Lidar_getUrlSignalsArray",Eq,void 0);var Fq=vl(196,function(){return Wg(cl())}); x("Goog_AdSense_Lidar_getUrlSignalsList",Fq,void 0);var Hq=function(a){ue(this,a,Gq,null)};t(Hq,pe);var Gq=[3];var Jq=function(a){ue(this,a,Iq,null)};t(Jq,pe);var Kq=function(a,b){return Be(a,1,b)},Lq=function(a,b){return Be(a,2,b)},Mq=function(a,b){return Be(a,3,b)},Nq=function(a,b){Be(a,4,b)},Iq=[1,2,3,4];var Oq=function(a){ue(this,a,null,null)};t(Oq,pe);var Qq=function(a){ue(this,a,Pq,null)};t(Qq,pe);Qq.prototype.getVersion=function(){return xe(this,1,0)}; var Rq=function(a,b){return Ce(a,1,b,0)},Sq=function(a,b){return Ge(a,2,b)},Tq=function(a,b){return Ge(a,3,b)},Uq=function(a,b){return Ce(a,4,b,0)},Vq=function(a,b){return Ce(a,5,b,0)},Wq=function(a,b){return Ce(a,6,b,0)},Xq=function(a,b){return Ce(a,7,b,"")},Yq=function(a,b){return Ce(a,8,b,0)},Zq=function(a,b){return Ce(a,9,b,0)},$q=function(a,b){return Ce(a,10,b,!1)},ar=function(a,b){return Ce(a,11,b,!1)},br=function(a,b){return Be(a,12,b)},cr=function(a,b){return Be(a,13,b)},dr=function(a,b){return Be(a, 14,b)},er=function(a,b){return Ce(a,15,b,!1)},fr=function(a,b){return Ce(a,16,b,"")},gr=function(a,b){return Be(a,17,b)},hr=function(a,b){return Be(a,18,b)},ir=function(a,b){a.g||(a.g={});b=b||[];for(var c=oe([]),d=0;d<b.length;d++)c[d]=Fe(b[d]);a.g[19]=b;return Ae(a,19,c)},Pq=[12,13,14,17,18,19];var jr=function(a){ue(this,a,null,null)};t(jr,pe);var kr="a".charCodeAt(),lr=Ib({og:0,ng:1,kg:2,fg:3,lg:4,gg:5,mg:6,ig:7,jg:8,eg:9,hg:10}),mr=Ib({qg:0,rg:1,pg:2});var nr=function(a){if(/[^01]/.test(a))throw Error("Input bitstring "+a+" is malformed!");this.h=a;this.g=0},pr=function(a){a=or(a,36);var b=new Oq;b=Ce(b,1,Math.floor(a/10),0);return Ce(b,2,a%10*1E8,0)},qr=function(a){return String.fromCharCode(kr+or(a,6))+String.fromCharCode(kr+or(a,6))},tr=function(a){var b=or(a,16);return!0===!!or(a,1)?(a=rr(a),a.forEach(function(c){if(c>b)throw Error("ID "+c+" is past MaxVendorId "+b+"!");}),a):sr(a,b)},ur=function(a){for(var b=[],c=or(a,12);c--;){var d=or(a, 6),e=or(a,2),f=rr(a),g=b,h=g.push,k=new Hq;d=Ce(k,1,d,0);e=Ce(d,2,e,0);f=Be(e,3,f);h.call(g,f)}return b},rr=function(a){for(var b=or(a,12),c=[];b--;){var d=!0===!!or(a,1),e=or(a,16);if(d)for(d=or(a,16);e<=d;e++)c.push(e);else c.push(e)}c.sort(function(f,g){return f-g});return c},sr=function(a,b,c){for(var d=[],e=0;e<b;e++)if(or(a,1)){var f=e+1;if(c&&-1===c.indexOf(f))throw Error("ID: "+f+" is outside of allowed values!");d.push(f)}return d},or=function(a,b){if(a.g+b>a.h.length)throw Error("Requested length "+ b+" is past end of string.");var c=a.h.substring(a.g,a.g+b);a.g+=b;return parseInt(c,2)};nr.prototype.skip=function(a){this.g+=a};var vr=function(a){try{var b=ae(a).map(function(f){return f.toString(2).padStart(8,"0")}).join(""),c=new nr(b);if(3!==or(c,3))return null;var d=Lq(Kq(new Jq,sr(c,24,lr)),sr(c,24,lr)),e=or(c,6);0!==e&&Nq(Mq(d,sr(c,e)),sr(c,e));return d}catch(f){return null}};var wr=function(a){try{var b=ae(a).map(function(d){return d.toString(2).padStart(8,"0")}).join(""),c=new nr(b);return ir(hr(gr(fr(er(dr(cr(br(ar($q(Zq(Yq(Xq(Wq(Vq(Uq(Tq(Sq(Rq(new Qq,or(c,6)),pr(c)),pr(c)),or(c,12)),or(c,12)),or(c,6)),qr(c)),or(c,12)),or(c,6)),!!or(c,1)),!!or(c,1)),sr(c,12,mr)),sr(c,24,lr)),sr(c,24,lr)),!!or(c,1)),qr(c)),tr(c)),tr(c)),ur(c))}catch(d){return null}};var yr=function(a){if(!a)return null;var b=a.split(".");if(4<b.length)return null;a=wr(b[0]);if(!a)return null;var c=new jr;a=Ge(c,1,a);b.shift();b=q(b);for(c=b.next();!c.done;c=b.next())switch(c=c.value,xr(c)){case 1:case 2:break;case 3:c=vr(c);if(!c)return null;Ge(a,2,c);break;default:return null}return a},xr=function(a){try{var b=ae(a).map(function(c){return c.toString(2).padStart(8,"0")}).join("");return or(new nr(b),3)}catch(c){return-1}};var zr=function(a,b){var c={};if(Array.isArray(b)&&0!==b.length){b=q(b);for(var d=b.next();!d.done;d=b.next())d=d.value,c[d]=-1!==a.indexOf(d)}else for(a=q(a),d=a.next();!d.done;d=a.next())c[d.value]=!0;delete c[0];return c};var Ar=function(a,b){this.g=a;this.defaultValue=void 0===b?!1:b},Br=function(a,b){this.g=a;this.defaultValue=void 0===b?0:b};var Cr=new Ar(1936,!0),Dr=new Ar(1930),Er=new Br(360261971),Fr=new Br(1921,72),Gr=new Br(1920,24),Hr=new Br(1917,-1),Ir=new Br(1916,.001),Jr=new Ar(373442741),Kr=new Ar(1928),Lr=new Ar(1941),Mr=new Ar(370946349),Nr=new Ar(374326588),Or=new Ar(377105258),Pr=new Ar(1942);var Rr=function(a){ue(this,a,Qr,null)};t(Rr,pe);var Qr=[6];var Sr=function(a){ue(this,a,null,null)};t(Sr,pe);var Tr=function(a){ue(this,a,null,null)};t(Tr,pe);var Ur=function(a){this.g=a||{cookie:""}};l=Ur.prototype; l.set=function(a,b,c){var d=!1;if("object"===typeof c){var e=c.xh;d=c.kf||!1;var f=c.domain||void 0;var g=c.path||void 0;var h=c.Ed}if(/[;=\s]/.test(a))throw Error('Invalid cookie name "'+a+'"');if(/[;\r\n]/.test(b))throw Error('Invalid cookie value "'+b+'"');void 0===h&&(h=-1);this.g.cookie=a+"="+b+(f?";domain="+f:"")+(g?";path="+g:"")+(0>h?"":0==h?";expires="+(new Date(1970,1,1)).toUTCString():";expires="+(new Date(Date.now()+1E3*h)).toUTCString())+(d?";secure":"")+(null!=e?";samesite="+e:"")}; l.get=function(a,b){for(var c=a+"=",d=(this.g.cookie||"").split(";"),e=0,f;e<d.length;e++){f=gc(d[e]);if(0==f.lastIndexOf(c,0))return f.substr(c.length);if(f==a)return""}return b};l.remove=function(a,b,c){var d=void 0!==this.get(a);this.set(a,"",{Ed:0,path:b,domain:c});return d};l.Xa=function(){return Vr(this).keys};l.Oa=function(){return Vr(this).values}; var Vr=function(a){a=(a.g.cookie||"").split(";");for(var b=[],c=[],d,e,f=0;f<a.length;f++)e=gc(a[f]),d=e.indexOf("="),-1==d?(b.push(""),c.push(e)):(b.push(e.substring(0,d)),c.push(e.substring(d+1)));return{keys:b,values:c}};var Wr=function(a){return(a=(new Ur(a)).get("DATA_USE_CONSENT",""))?a:null},Xr=function(a){var b=(b=(new Ur(a)).get("FCCDCF",""))?b:null;try{var c=b?Ie(Sr,b):null}catch(d){c=null}if(!c)return Wr(a);c=De(c,Tr,3);if(!c||null==A(c,1))return Wr(a);a=A(c,2);b=Date.now();if(a){if(b<a||b>a+33696E6)return null}else return null;return A(c,1)};var Zr=function(a){ue(this,a,Yr,null)};t(Zr,pe);var Yr=[1,2,3,4];var $r=/^((market|itms|intent|itms-appss):\/\/)/i;var as=function(a,b){this.g=a[u.Symbol.iterator]();this.h=b;this.l=0};as.prototype[Symbol.iterator]=function(){return this};as.prototype.next=function(){var a=this.g.next();return{value:a.done?void 0:this.h.call(void 0,a.value,this.l++),done:a.done}};var bs=function(a,b){return new as(a,b)};var gs=function(a){if(a instanceof cs||a instanceof ds||a instanceof es)return a;if("function"==typeof a.next)return new cs(function(){return fs(a)});if("function"==typeof a[Symbol.iterator])return new cs(function(){return a[Symbol.iterator]()});if("function"==typeof a.nb)return new cs(function(){return fs(a.nb())});throw Error("Not an iterator or iterable.");},fs=function(a){if(!(a instanceof jn))return a;var b=!1;return{next:function(){for(var c;!b;)try{c=a.next();break}catch(d){if(d!==hn)throw d; b=!0}return{value:c,done:b}}}},cs=function(a){this.g=a};cs.prototype.nb=function(){return new ds(this.g())};cs.prototype[Symbol.iterator]=function(){return new es(this.g())};cs.prototype.l=function(){return new es(this.g())};var ds=function(a){this.h=a};t(ds,jn);ds.prototype.g=function(){var a=this.h.next();if(a.done)throw hn;return a.value};ds.prototype.next=function(){return ds.prototype.g.call(this)};ds.prototype[Symbol.iterator]=function(){return new es(this.h)};ds.prototype.l=function(){return new es(this.h)}; var es=function(a){cs.call(this,function(){return a});this.h=a};t(es,cs);es.prototype.next=function(){return this.h.next()};var hs=function(a,b){this.h={};this.g=[];this.l=this.size=0;var c=arguments.length;if(1<c){if(c%2)throw Error("Uneven number of arguments");for(var d=0;d<c;d+=2)this.set(arguments[d],arguments[d+1])}else if(a)if(a instanceof hs)for(c=a.Xa(),d=0;d<c.length;d++)this.set(c[d],a.get(c[d]));else for(d in a)this.set(d,a[d])};hs.prototype.Oa=function(){is(this);for(var a=[],b=0;b<this.g.length;b++)a.push(this.h[this.g[b]]);return a};hs.prototype.Xa=function(){is(this);return this.g.concat()}; hs.prototype.has=function(a){return js(this.h,a)};hs.prototype.remove=function(a){js(this.h,a)?(delete this.h[a],--this.size,this.l++,this.g.length>2*this.size&&is(this),a=!0):a=!1;return a};var is=function(a){if(a.size!=a.g.length){for(var b=0,c=0;b<a.g.length;){var d=a.g[b];js(a.h,d)&&(a.g[c++]=d);b++}a.g.length=c}if(a.size!=a.g.length){var e={};for(c=b=0;b<a.g.length;)d=a.g[b],js(e,d)||(a.g[c++]=d,e[d]=1),b++;a.g.length=c}};l=hs.prototype;l.get=function(a,b){return js(this.h,a)?this.h[a]:b}; l.set=function(a,b){js(this.h,a)||(this.size+=1,this.g.push(a),this.l++);this.h[a]=b};l.forEach=function(a,b){for(var c=this.Xa(),d=0;d<c.length;d++){var e=c[d],f=this.get(e);a.call(b,f,e,this)}};l.keys=function(){return gs(this.nb(!0)).l()};l.values=function(){return gs(this.nb(!1)).l()};l.entries=function(){var a=this;return bs(this.keys(),function(b){return[b,a.get(b)]})}; l.nb=function(a){is(this);var b=0,c=this.l,d=this,e=new jn;e.g=function(){if(c!=d.l)throw Error("The map has changed since the iterator was created");if(b>=d.g.length)throw hn;var f=d.g[b++];return a?f:d.h[f]};e.next=e.g.bind(e);return e};var js=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};var O=function(a,b){this.g=this.A=this.o="";this.J=null;this.K=this.h="";this.B=!1;var c;a instanceof O?(this.B=void 0!==b?b:a.B,ks(this,a.o),this.A=a.A,this.g=a.g,ls(this,a.J),this.h=a.h,ms(this,ns(a.l)),this.K=a.F()):a&&(c=String(a).match(pf))?(this.B=!!b,ks(this,c[1]||"",!0),this.A=os(c[2]||""),this.g=os(c[3]||"",!0),ls(this,c[4]),this.h=os(c[5]||"",!0),ms(this,c[6]||"",!0),this.K=os(c[7]||"")):(this.B=!!b,this.l=new ps(null,this.B))}; O.prototype.toString=function(){var a=[],b=this.o;b&&a.push(qs(b,rs,!0),":");var c=this.g;if(c||"file"==b)a.push("//"),(b=this.A)&&a.push(qs(b,rs,!0),"@"),a.push(encodeURIComponent(String(c)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),c=this.J,null!=c&&a.push(":",String(c));if(c=this.h)this.g&&"/"!=c.charAt(0)&&a.push("/"),a.push(qs(c,"/"==c.charAt(0)?ts:us,!0));(c=this.l.toString())&&a.push("?",c);(c=this.F())&&a.push("#",qs(c,vs));return a.join("")}; O.prototype.resolve=function(a){var b=this.H(),c=!!a.o;c?ks(b,a.o):c=!!a.A;c?b.A=a.A:c=!!a.g;c?b.g=a.g:c=null!=a.J;var d=a.h;if(c)ls(b,a.J);else if(c=!!a.h){if("/"!=d.charAt(0))if(this.g&&!this.h)d="/"+d;else{var e=b.h.lastIndexOf("/");-1!=e&&(d=b.h.substr(0,e+1)+d)}e=d;if(".."==e||"."==e)d="";else if(-1!=e.indexOf("./")||-1!=e.indexOf("/.")){d=0==e.lastIndexOf("/",0);e=e.split("/");for(var f=[],g=0;g<e.length;){var h=e[g++];"."==h?d&&g==e.length&&f.push(""):".."==h?((1<f.length||1==f.length&&""!= f[0])&&f.pop(),d&&g==e.length&&f.push("")):(f.push(h),d=!0)}d=f.join("/")}else d=e}c?b.h=d:c=""!==a.l.toString();c?ms(b,ns(a.l)):c=!!a.K;c&&(b.K=a.F());return b};O.prototype.H=function(){return new O(this)}; var ks=function(a,b,c){a.o=c?os(b,!0):b;a.o&&(a.o=a.o.replace(/:$/,""))},ls=function(a,b){if(b){b=Number(b);if(isNaN(b)||0>b)throw Error("Bad port number "+b);a.J=b}else a.J=null},ms=function(a,b,c){b instanceof ps?(a.l=b,ws(a.l,a.B)):(c||(b=qs(b,xs)),a.l=new ps(b,a.B))},ys=function(a,b,c){a.l.set(b,c);return a};O.prototype.F=function(){return this.K}; var os=function(a,b){return a?b?decodeURI(a.replace(/%25/g,"%2525")):decodeURIComponent(a):""},qs=function(a,b,c){return"string"===typeof a?(a=encodeURI(a).replace(b,zs),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null},zs=function(a){a=a.charCodeAt(0);return"%"+(a>>4&15).toString(16)+(a&15).toString(16)},rs=/[#\/\?@]/g,us=/[#\?:]/g,ts=/[#\?]/g,xs=/[#\?@]/g,vs=/#/g,ps=function(a,b){this.h=this.g=null;this.l=a||null;this.o=!!b},As=function(a){a.g||(a.g=new hs,a.h=0,a.l&&rf(a.l,function(b,c){a.add(Vc(b), c)}))};ps.prototype.add=function(a,b){As(this);this.l=null;a=Bs(this,a);var c=this.g.get(a);c||this.g.set(a,c=[]);c.push(b);this.h+=1;return this};ps.prototype.remove=function(a){As(this);a=Bs(this,a);return this.g.has(a)?(this.l=null,this.h-=this.g.get(a).length,this.g.remove(a)):!1};var Cs=function(a,b){As(a);b=Bs(a,b);return a.g.has(b)};l=ps.prototype;l.forEach=function(a,b){As(this);this.g.forEach(function(c,d){c.forEach(function(e){a.call(b,e,d,this)},this)},this)}; l.Xa=function(){As(this);for(var a=this.g.Oa(),b=this.g.Xa(),c=[],d=0;d<b.length;d++)for(var e=a[d],f=0;f<e.length;f++)c.push(b[d]);return c};l.Oa=function(a){As(this);var b=[];if("string"===typeof a)Cs(this,a)&&(b=b.concat(this.g.get(Bs(this,a))));else{a=this.g.Oa();for(var c=0;c<a.length;c++)b=b.concat(a[c])}return b};l.set=function(a,b){As(this);this.l=null;a=Bs(this,a);Cs(this,a)&&(this.h-=this.g.get(a).length);this.g.set(a,[b]);this.h+=1;return this}; l.get=function(a,b){if(!a)return b;a=this.Oa(a);return 0<a.length?String(a[0]):b};l.toString=function(){if(this.l)return this.l;if(!this.g)return"";for(var a=[],b=this.g.Xa(),c=0;c<b.length;c++){var d=b[c],e=encodeURIComponent(String(d));d=this.Oa(d);for(var f=0;f<d.length;f++){var g=e;""!==d[f]&&(g+="="+encodeURIComponent(String(d[f])));a.push(g)}}return this.l=a.join("&")}; var ns=function(a){var b=new ps;b.l=a.l;a.g&&(b.g=new hs(a.g),b.h=a.h);return b},Bs=function(a,b){b=String(b);a.o&&(b=b.toLowerCase());return b},ws=function(a,b){b&&!a.o&&(As(a),a.l=null,a.g.forEach(function(c,d){var e=d.toLowerCase();d!=e&&(this.remove(d),this.remove(e),0<c.length&&(this.l=null,this.g.set(Bs(this,e),xb(c)),this.h+=c.length))},a));a.o=b};var Ds="://secure-...imrworldwide.com/ ://cdn.imrworldwide.com/ ://aksecure.imrworldwide.com/ ://[^.]*.moatads.com ://youtube[0-9]+.moatpixel.com ://pm.adsafeprotected.com/youtube ://pm.test-adsafeprotected.com/youtube ://e[0-9]+.yt.srs.doubleverify.com www.google.com/pagead/xsul www.youtube.com/pagead/slav".split(" "),Es=/\bocr\b/,Fs=0,Gs={},Hs=function(a){if(fc($c(a)))return!1;if(0<=a.indexOf("://pagead2.googlesyndication.com/pagead/gen_204?id=yt3p&sr=1&"))return!0;try{var b=new O(a)}catch(c){return null!= pb(Ds,function(d){return 0<a.search(d)})}return b.F().match(Es)?!0:null!=pb(Ds,function(c){return null!=a.match(c)})},Ls=function(a){if(a&&(a=Is(a),!fc(a))){var b='javascript:"<body><img src=\\""+'+a+'+"\\"></body>"';Js(function(c){Ks(c?b:'javascript:"<body><object data=\\""+'+a+'+"\\" type=\\"text/html\\" width=1 height=1 style=\\"visibility:hidden;\\"></body>"')})}},Ks=function(a){var b=gf("IFRAME",{src:a,style:"display:none"});a=Xe(b).body;var c=pj(function(){Hi(d);hf(b)},15E3);var d=yi(b,["load", "error"],function(){pj(function(){u.clearTimeout(c);hf(b)},5E3)});a.appendChild(b)},Js=function(a){var b=Gs.imageLoadingEnabled;if(null!=b)a(b);else{var c=!1;Ms(function(d,e){delete Gs[e];c||(c=!0,null==Gs.imageLoadingEnabled&&(Gs.imageLoadingEnabled=d),a(d))})}},Ms=function(a){var b=new Image,c=""+Fs++;Gs[c]=b;b.onload=function(){clearTimeout(d);a(!0,c)};var d=setTimeout(function(){a(!1,c)},300);b.src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},Ns=function(a){if(a){var b= ef(document,"OBJECT");b.data=a;b.width="1";b.height="1";b.style.visibility="hidden";var c=""+Fs++;Gs[c]=b;b.onload=b.onerror=function(){delete Gs[c]};document.body.appendChild(b)}},Os=function(a){if(a){var b=new Image,c=""+Fs++;Gs[c]=b;b.onload=b.onerror=function(){delete Gs[c]};b.src=a}},Ps=function(a){a&&Js(function(b){b?Os(a):Ns(a)})},Is=function(a){if(!(a instanceof tc))if(a="object"==typeof a&&a.Ra?a.Ga():String(a),xc.test(a))a=new tc(a,sc);else{a=String(a);a=a.replace(/(%0A|%0D)/g,"");var b= a.match(wc);a=b&&vc.test(b[1])?new tc(a,sc):null}a=uc(a||zc);if("about:invalid#zClosurez"===a)return"";if(!(a instanceof Lc)){b="object"==typeof a;var c=null;b&&a.Dc&&(c=a.zc());a=Nc(oc(b&&a.Ra?a.Ga():String(a)),c)}a=Mc(a).toString();return encodeURIComponent(String(Wg(a)))};var Qs="ad_type vpos mridx pos vad_type videoad_start_delay".split(" ");var Rs=function(a){var b=a.pb,c=a.height,d=a.width,e=void 0===a.Ja?!1:a.Ja;this.A=a.vb;this.g=b;this.o=c;this.K=d;this.B=e};Rs.prototype.getHeight=function(){return this.o};Rs.prototype.getWidth=function(){return this.K};var Ss=function(a){var b=a.tf,c=a.re,d=a.sf,e=a.qe;Rs.call(this,{vb:a.vb,pb:a.pb,height:a.height,width:a.width,Ja:void 0===a.Ja?!1:a.Ja});this.J=b;this.l=c;this.C=d;this.h=e};t(Ss,Rs);var Ts=function(a){var b=a.Xe;Rs.call(this,{vb:a.vb,pb:a.pb,height:a.height,width:a.width,Ja:void 0===a.Ja?!1:a.Ja});this.h=b};t(Ts,Rs);Ts.prototype.getMediaUrl=function(){return this.h};/* Math.uuid.js (v1.4) http://www.broofa.com mailto:[email protected] Copyright (c) 2010 Robert Kieffer Dual licensed under the MIT and GPL licenses. */ var Us="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),Vs=function(){for(var a=Array(36),b=0,c,d=0;36>d;d++)8==d||13==d||18==d||23==d?a[d]="-":14==d?a[d]="4":(2>=b&&(b=33554432+16777216*Math.random()|0),c=b&15,b>>=4,a[d]=Us[19==d?c&3|8:c]);return a.join("")};function Ws(a,b){for(var c=[],d=1;d<arguments.length;++d)c[d-1]=arguments[d];return new (Function.prototype.bind.apply(a,[null].concat(fa(c))))};var P={},Xs=(P[18]=-1,P[22]=-1,P[43]=350,P[44]=350,P[45]=350,P[59]=-1,P[133]=350,P[134]=350,P[135]=350,P[136]=350,P[140]=50,P[141]=50,P[160]=350,P[242]=150,P[243]=150,P[244]=150,P[245]=150,P[249]=50,P[250]=50,P[251]=50,P[278]=150,P[342]=-1,P[343]=-1,P[344]=-1,P[345]=-1,P[346]=-1,P[347]=-1,P),Q={},Ys=(Q[18]=!1,Q[22]=!1,Q[43]=!0,Q[44]=!0,Q[45]=!0,Q[59]=!1,Q[133]=!0,Q[134]=!0,Q[135]=!0,Q[136]=!0,Q[140]=!0,Q[141]=!0,Q[160]=!0,Q[242]=!0,Q[243]=!0,Q[244]=!0,Q[245]=!0,Q[249]=!0,Q[250]=!0,Q[251]=!0,Q[278]= !0,Q[342]=!1,Q[343]=!1,Q[344]=!1,Q[345]=!1,Q[346]=!1,Q[347]=!1,Q),R={},Zs=(R[18]="video/mp4",R[22]="video/mp4",R[43]="video/webm",R[44]="video/webm",R[45]="video/webm",R[59]="video/mp4",R[133]="video/mp4",R[134]="video/mp4",R[135]="video/mp4",R[136]="video/mp4",R[140]="audio/mp4",R[141]="audio/mp4",R[160]="video/mp4",R[242]="video/webm",R[243]="video/webm",R[244]="video/webm",R[245]="video/webm",R[249]="audio/webm",R[250]="audio/webm",R[251]="audio/webm",R[278]="video/webm",R[342]="video/mp4",R[343]= "video/mp4",R[344]="video/mp4",R[345]="video/mp4",R[346]="video/mp4",R[347]="video/mp4",R),T={},$s=(T[18]="avc1.42001E, mp4a.40.2",T[22]="avc1.64001F, mp4a.40.2",T[43]="vp8, vorbis",T[44]="vp8, vorbis",T[45]="vp8, vorbis",T[59]="avc1.4D001F, mp4a.40.2",T[133]="avc1.4D401E",T[134]="avc1.4D401E",T[135]="avc1.4D401E",T[136]="avc1.4D401E",T[140]="mp4a.40.2",T[141]="mp4a.40.2",T[160]="avc1.4D401E",T[242]="vp9",T[243]="vp9",T[244]="vp9",T[245]="vp9",T[249]="opus",T[250]="opus",T[251]="opus",T[278]="vp9", T[342]="avc1.42E01E, mp4a.40.2",T[343]="avc1.42E01E, mp4a.40.2",T[344]="avc1.42E01E, mp4a.40.2",T[345]="avc1.42E01E, mp4a.40.2",T[346]="avc1.42E01E, mp4a.40.2",T[347]="avc1.4D001F, mp4a.40.2",T);var at=function(){};at.prototype.g=null;var ct=function(a){var b;(b=a.g)||(b={},bt(a)&&(b[0]=!0,b[1]=!0),b=a.g=b);return b};var dt,et=function(){};Ya(et,at);var ft=function(a){return(a=bt(a))?new ActiveXObject(a):new XMLHttpRequest},bt=function(a){if(!a.h&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var b=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],c=0;c<b.length;c++){var d=b[c];try{return new ActiveXObject(d),a.h=d}catch(e){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed");}return a.h};dt=new et;var gt=function(a){K.call(this);this.headers=new hs;this.I=a||null;this.h=!1;this.H=this.g=null;this.N="";this.o=0;this.l=this.M=this.A=this.L=!1;this.F=0;this.C=null;this.aa="";this.U=this.W=!1;this.T=null};Ya(gt,K);var ht=/^https?$/i,it=["POST","PUT"];gt.prototype.Y=function(a){this.T=a}; var mt=function(a,b,c,d){if(a.g)throw Error("[goog.net.XhrIo] Object is active with another request="+a.N+"; newUri="+b);c=c?c.toUpperCase():"GET";a.N=b;a.o=0;a.L=!1;a.h=!0;a.g=a.I?ft(a.I):ft(dt);a.H=a.I?ct(a.I):ct(dt);a.g.onreadystatechange=Va(a.Z,a);try{a.M=!0,a.g.open(c,String(b),!0),a.M=!1}catch(g){jt(a);return}b=d||"";d=new hs(a.headers);var e=d.Xa().find(function(g){return"content-type"==g.toLowerCase()}),f=u.FormData&&b instanceof u.FormData;!sb(it,c)||e||f||d.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); d.forEach(function(g,h){this.g.setRequestHeader(h,g)},a);a.aa&&(a.g.responseType=a.aa);"withCredentials"in a.g&&a.g.withCredentials!==a.W&&(a.g.withCredentials=a.W);if("setTrustToken"in a.g&&a.T)try{a.g.setTrustToken(a.T)}catch(g){}try{kt(a),0<a.F&&(a.U=lt(a.g),a.U?(a.g.timeout=a.F,a.g.ontimeout=Va(a.ba,a)):a.C=pj(a.ba,a.F,a)),a.A=!0,a.g.send(b),a.A=!1}catch(g){jt(a)}},lt=function(a){return ud&&Ld(9)&&"number"===typeof a.timeout&&void 0!==a.ontimeout}; gt.prototype.ba=function(){"undefined"!=typeof Ha&&this.g&&(this.o=8,this.dispatchEvent("timeout"),this.abort(8))};var jt=function(a){a.h=!1;a.g&&(a.l=!0,a.g.abort(),a.l=!1);a.o=5;nt(a);ot(a)},nt=function(a){a.L||(a.L=!0,a.dispatchEvent("complete"),a.dispatchEvent("error"))};gt.prototype.abort=function(a){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.o=a||7,this.dispatchEvent("complete"),this.dispatchEvent("abort"),ot(this))}; gt.prototype.O=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),ot(this,!0));gt.za.O.call(this)};gt.prototype.Z=function(){this.Za()||(this.M||this.A||this.l?pt(this):this.ea())};gt.prototype.ea=function(){pt(this)}; var pt=function(a){if(a.h&&"undefined"!=typeof Ha&&(!a.H[1]||4!=qt(a)||2!=rt(a)))if(a.A&&4==qt(a))pj(a.Z,0,a);else if(a.dispatchEvent("readystatechange"),4==qt(a)){a.h=!1;try{var b=rt(a);a:switch(b){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var c=!0;break a;default:c=!1}var d;if(!(d=c)){var e;if(e=0===b){var f=String(a.N).match(pf)[1]||null;if(!f&&u.self&&u.self.location){var g=u.self.location.protocol;f=g.substr(0,g.length-1)}e=!ht.test(f?f.toLowerCase():"")}d=e}d?(a.dispatchEvent("complete"), a.dispatchEvent("success")):(a.o=6,nt(a))}finally{ot(a)}}},ot=function(a,b){if(a.g){kt(a);var c=a.g,d=a.H[0]?Ja:null;a.g=null;a.H=null;b||a.dispatchEvent("ready");try{c.onreadystatechange=d}catch(e){}}},kt=function(a){a.g&&a.U&&(a.g.ontimeout=null);a.C&&(u.clearTimeout(a.C),a.C=null)};gt.prototype.Gc=function(){return!!this.g}; var qt=function(a){return a.g?a.g.readyState:0},rt=function(a){try{return 2<qt(a)?a.g.status:-1}catch(b){return-1}},tt=function(a){try{return a.g?a.g.responseText:""}catch(b){return""}},ut=function(a){if(a.g){a:{a=a.g.responseText;if(u.JSON)try{var b=u.JSON.parse(a);break a}catch(c){}b=Tg(a)}return b}},vt=function(a,b){if(a.g&&4==qt(a))return a=a.g.getResponseHeader(b),null===a?void 0:a};var wt=/\/itag\/(\d+)\//;function xt(a){var b=parseInt(tf(a,"itag"),10);return b?b:(a=a.match(wt))&&2==a.length?parseInt(a[1],10):null}function yt(a){var b=Zs[a];a=$s[a];b?(b=$c(b).toLowerCase(),b=a?b+'; codecs="'+$c(a)+'"':b):b="";return b}function zt(a,b){if("function"===typeof CustomEvent)return new CustomEvent(a,{detail:b});var c=document.createEvent("CustomEvent");c.initCustomEvent(a,!1,!0,b);return c};var At=-1;var Bt=function(){this.g=Date.now()};Bt.prototype.reset=function(){this.g=Date.now()};var Ct=function(a){a=a.g+5E3-Date.now();return 0<a?a:0};var Dt="ad.doubleclick.net bid.g.doubleclick.net ggpht.com google.co.uk google.com googleads.g.doubleclick.net googleads4.g.doubleclick.net googleadservices.com googlesyndication.com googleusercontent.com gstatic.com gvt1.com prod.google.com pubads.g.doubleclick.net s0.2mdn.net static.doubleclick.net surveys.g.doubleclick.net youtube.com ytimg.com".split(" "),Et=["c.googlesyndication.com"]; function Ft(a,b){b=void 0===b?window.location.protocol:b;var c=!1;Gt(a,Et)?c=!1:b.includes("https")&&Gt(a,Dt)&&(c=!0);if(c){b=new O(a);if("https"==b.o)return a;G(F.D(),"htp","1");ks(b,"https");return b.toString()}return a}function Gt(a,b){return(new RegExp("^https?://([a-z0-9-]{1,63}\\.)*("+b.join("|").replace(/\./g,"\\.")+")(:[0-9]+)?([/?#]|$)","i")).test(a)};var Ht=function(a){return(a=a.exec(Dc))?a[1]:""};(function(){if(Pd)return Ht(/Firefox\/([0-9.]+)/);if(ud||vd||td)return Kd;if(Td)return od()?Ht(/CriOS\/([0-9.]+)/):Ht(/Chrome\/([0-9.]+)/);if(Ud&&!od())return Ht(/Version\/([0-9.]+)/);if(Qd||Rd){var a=/Version\/(\S+).*Mobile\/(\S+)/.exec(Dc);if(a)return a[1]+"."+a[2]}else if(Sd)return(a=Ht(/Android\s+([0-9.]+)/))?a:Ht(/Version\/([0-9.]+)/);return""})();var It=/OS (\S+) like/,Jt=/Android ([\d\.]+)/;function Kt(a,b){a=(a=a.exec(Dc))?a[1]:"";a=a.replace(/_/g,".");return 0<=rc(a,b)}var Lt=function(){return yd&&"ontouchstart"in document.documentElement},Mt=function(a){return Ed&&Kt(It,a)},Nt=function(a){return(a=void 0===a?null:a)&&"function"===typeof a.getAttribute?a.getAttribute("playsinline")?!0:!1:!1};var Ot=function(a){var b=Error.call(this,a);this.message=b.message;"stack"in b&&(this.stack=b.stack);this.errorCode=a};t(Ot,Error);var Pt=function(){if(!ud)return!1;try{return new ActiveXObject("MSXML2.DOMDocument"),!0}catch(a){return!1}},Qt=ud&&Pt();var U=function(a){J.call(this);this.o=a;this.h={}};Ya(U,J);var Rt=[];U.prototype.P=function(a,b,c,d){return St(this,a,b,c,d)};var St=function(a,b,c,d,e,f){Array.isArray(c)||(c&&(Rt[0]=c.toString()),c=Rt);for(var g=0;g<c.length;g++){var h=zi(b,c[g],d||a.handleEvent,e||!1,f||a.o||a);if(!h)break;a.h[h.key]=h}return a};U.prototype.Gb=function(a,b,c,d){return Tt(this,a,b,c,d)}; var Tt=function(a,b,c,d,e,f){if(Array.isArray(c))for(var g=0;g<c.length;g++)Tt(a,b,c[g],d,e,f);else{b=yi(b,c,d||a.handleEvent,e,f||a.o||a);if(!b)return a;a.h[b.key]=b}return a};U.prototype.Ua=function(a,b,c,d,e){if(Array.isArray(b))for(var f=0;f<b.length;f++)this.Ua(a,b[f],c,d,e);else c=c||this.handleEvent,d=Na(d)?!!d.capture:!!d,e=e||this.o||this,c=Ai(c),d=!!d,b=oi(a)?a.Cb(b,c,d,e):a?(a=Ci(a))?a.Cb(b,c,d,e):null:null,b&&(Hi(b),delete this.h[b.key])}; var Ut=function(a){Cb(a.h,function(b,c){this.h.hasOwnProperty(c)&&Hi(b)},a);a.h={}};U.prototype.O=function(){U.za.O.call(this);Ut(this)};U.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented");};var Vt=function(){};Vt.prototype.get=function(a){return Wt({url:a.url,timeout:a.timeout,withCredentials:void 0===a.withCredentials?!0:a.withCredentials,method:"GET",La:void 0===a.La?void 0:a.La})}; var Wt=function(a){var b=a.url,c=a.timeout,d=a.withCredentials,e=a.method,f=void 0===a.content?void 0:a.content,g=void 0===a.La?void 0:a.La,h=void 0===a.headers?{}:a.headers;return Xt({url:b,timeout:c,withCredentials:d,method:e,content:f,La:g,headers:h}).then(function(k){return Promise.resolve(k)},function(k){return k instanceof Error&&6==k.message&&d?Xt({url:b,timeout:c,withCredentials:!d,method:e,content:f,La:g,headers:h}):Promise.reject(k)})},Xt=function(a){var b=a.url,c=a.timeout,d=a.withCredentials, e=a.method,f=void 0===a.content?void 0:a.content,g=void 0===a.La?void 0:a.La;a=void 0===a.headers?{}:a.headers;var h=new gt;h.W=d;h.F=Math.max(0,Ct(c));h.Y&&g&&h.Y(g);for(var k in a)h.headers.set(k,a[k]);var n=new U;return new Promise(function(m,v){n.Gb(h,"success",function(){a:{if(Zl())try{ut(h);var r="application/json";break a}catch(Uc){r="application/xml";break a}r=vt(h,"Content-Type")||""}if(-1!=r.indexOf("application/json"))m(ut(h)||{});else{try{var w=h.g?h.g.responseXML:null}catch(Uc){w=null}if(null== w)if(w=tt(h),"undefined"!=typeof DOMParser)r=new DOMParser,w=Sf(w),w=r.parseFromString(Mc(w),"application/xml");else if(Qt){r=new ActiveXObject("MSXML2.DOMDocument");r.resolveExternals=!1;r.validateOnParse=!1;try{r.setProperty("ProhibitDTD",!0),r.setProperty("MaxXMLSize",2048),r.setProperty("MaxElementDepth",256)}catch(Uc){}r.loadXML(w);w=r}else throw Error("Your browser does not support loading xml documents");r=gh(Vh);var B;if(B=w&&w.documentElement)(B=w.documentElement)&&"VAST"!=!B.nodeName?(B= B.getAttribute("version"))?(B=parseInt(B,10),B=null==B||isNaN(B)?null:B):B=null:B=null,B=null==B||2>B||4<B?!1:!0;if(!B&&r){r={vastUrl:b.substring(0,200),responseText:tt(h).substring(0,200),status:rt(h),origin:window.location.origin};Zl()||(r.contentType=vt(h,"Content-Type"),r.acao=vt(h,"Access-Control-Allow-Origin"),r.acac=vt(h,"Access-Control-Allow-Credentials"));B=F.D();for(var L=q(Object.keys(r)),La=L.next();!La.done;La=L.next())La=La.value,G(B,La,r[La])}m(w)}n.X();h.X()});n.Gb(h,["error","timeout"], function(){v(new Ot(h.o,rt(h)));n.X();h.X()});mt(h,Ft(b),e,f)})};function Yt(a,b){return fc(b)?!1:(new RegExp(a)).test(b)}function Zt(a){var b={};a.split(",").forEach(function(c){var d=c.split("=");2==d.length&&(c=gc(d[0]),d=gc(d[1]),0<c.length&&(b[c]=d))});return b} function $t(a){var b="af am ar_eg ar_sa ar_xb ar be bg bn ca cs da de_at de_cn de el en_au en_ca en_gb en_ie en_in en_sg en_xa en_xc en_za en es_419 es_ar es_bo es_cl es_co es_cr es_do es_ec es_gt es_hn es_mx es_ni es_pa es_pe es_pr es_py es_sv es_us es_uy es_ve es et eu fa fi fil fr_ca fr_ch fr gl gsw gu he hi hr hu id in is it iw ja kn ko ln lo lt lv ml mo mr ms nb ne nl no pl pt_br pt_pt pt ro ru sk sl sr_latn sr sv sw ta te th tl tr uk ur vi zh_cn zh_hk zh_tw zh zu".split(" ");if(!a)return null; a=a.toLowerCase().replace("-","_");if(b.includes(a))return a;a=(a=a.match(/^\w{2,3}([-_]|$)/))?a[0].replace(/[_-]/g,""):"";return b.includes(a)?a:null};var bu=function(a){O.call(this,a);this.C=new Map;a=this.h;var b=a.indexOf(";"),c=null;0<=b?(this.h=a.substring(0,b),c=a.substring(b+1)):this.h=a;au(this,c)};t(bu,O);bu.prototype.toString=function(){return cu(this,O.prototype.toString.call(this))};bu.prototype.F=function(){return""}; var au=function(a,b){fc($c(b))||b.split(";").forEach(function(c){var d=c.indexOf("=");if(!(0>=d)){var e=Vc(c.substring(0,d));c=Vc(c.substring(d+1));d=a.C.get(e);null!=d?d.includes(c)||d.push(c):d=[$c(c)];a.C.set(e,d)}},a)},du=function(a){if(fc($c("ord")))return null;a=a.C.get("ord");return null!=a?a:null},eu=function(a,b){fc($c("ord"))||(b=b.map($c),a.C.set("ord",b))},cu=function(a,b){b=[$c(b)];b.push.apply(b,fa(fu(a)));return b.join(";")},fu=function(a){var b=du(a);null==b?b=[$c(Date.now())]:fc($c("ord"))|| a.C.delete("ord");var c=[];a.C.forEach(function(d,e){d.forEach(function(f){c.push(e+"="+f)})});c.push("ord="+b[0]);eu(a,b);return c};bu.prototype.H=function(){return new bu(this.toString())};var gu,hu,iu,ju=function(){return u.navigator?u.navigator.userAgent:""},ku=-1!=ju().indexOf("(iPad")||-1!=ju().indexOf("(Macintosh")||-1!=ju().indexOf("(iPod")||-1!=ju().indexOf("(iPhone");function lu(a){var b=$b("_blank"),c="";ud&&(c="");if(!fc($c(a))){a=a instanceof tc||!$r.test(a)?a:new tc(a,sc);var d=window;a=a instanceof tc?a:yc(a);d=d||u;b=b instanceof Yb?Zb(b):b||"";void 0!==c?d.open(uc(a),b,c,void 0):d.open(uc(a),b)}};var mu={AUTOPLAY_DISALLOWED:"autoplayDisallowed",Bf:"beginFullscreen",Cf:"canPlay",Df:"canPlayThrough",CLICK:"click",DURATION_CHANGE:"durationChange",Pf:"end",Qf:"endFullscreen",Rf:"error",Vf:"focusSkipButton",ae:"loadStart",LOADED:"loaded",xg:"mediaLoadTimeout",yg:"mediaPlaybackTimeout",tc:"pause",Jg:"play",Lg:"playing",Tg:"seeked",Ug:"seeking",Vg:"skip",ke:"skipShown",uc:"start",eh:"timeUpdate",ah:"timedMetadata",oe:"volumeChange",ph:"waiting"};var ou=function(a){this.g=a;this.h=nu(a)},nu=function(a){return new Map(a.h.split("/").reduce(function(b,c,d){d%2?b[b.length-1].push(c):b.push([c]);return b},[]))},pu=function(a,b){var c=a.g.l.get(b);return c?c:(a=a.h.get(b))?a:null};function qu(){return!!window.MediaSource}function ru(a){return[43,44,45].includes(a)&&Pd?!1:Ys[a]?(a=yt(a),!!a&&qu()&&MediaSource.isTypeSupported(a)):!1};var tu=function(){};var uu=["doubleclick.net"]; function vu(){if(od())return!1;if(z("Android")){if(void 0===iu){a:{if(void 0===gu){if(ku){var a=-1!=ju().indexOf("Safari");var b=(new O(window.location.href)).l.Oa("js");b:{if((b=b.length?b[0]:"")&&0==b.lastIndexOf("afma-",0)){var c=b.lastIndexOf("v");if(-1<c&&(b=b.substr(c+1).match(/^(\d+\.\d+\.\d+|^\d+\.\d+|^\d+)(-.*)?$/))){b=b[1];break b}}b="0.0.0"}if(!a||"0.0.0"!==b){a=gu=!0;break a}}gu=!1}a=gu}a||(void 0===hu&&(hu=-1!=ju().indexOf("afma-sdk-a")?!0:!1),a=hu);iu=a}return iu?!0:nf()?!1:wu()}a=z("Macintosh")|| z("Linux")||z("Windows")||z("CrOS");return(gh(Xh)||gh(Zh)||gh(Yh))&&a&&Ic()?wu():!1}function wu(){var a=!1,b=(new O(window.location.href)).g;uu.forEach(function(c){b.includes(c)&&(a=!0)});return a}function xu(a){for(var b=0,c=0;c<a.length;c++)b=Math.imul(31,b)+a.charCodeAt(c)|0;return b.toString()};var yu,Bu=function(a,b,c){if("number"===typeof a)var d={name:zu(a)};else d=a,a=Au(a.name);this.code=a;this.g=d;b="Error "+b+": "+(this.g.name||"");c&&(b+=", "+c);ab.call(this,b)};Ya(Bu,ab); var Cu={me:1,Dg:2,NOT_FOUND_ERR:3,Td:4,Wd:5,Eg:6,le:7,ABORT_ERR:8,je:9,gh:10,TIMEOUT_ERR:11,ie:12,INVALID_ACCESS_ERR:13,INVALID_STATE_ERR:14},Du=(u.g||u.h||Cu).me,Eu=(u.g||u.h||Cu).NOT_FOUND_ERR,Fu=(u.g||u.h||Cu).Td,Gu=(u.g||u.h||Cu).Wd,Hu=(u.g||u.h||Cu).le,Iu=(u.g||u.h||Cu).ABORT_ERR,Ju=(u.g||u.h||Cu).je,Ku=(u.g||u.h||Cu).TIMEOUT_ERR,Lu=(u.g||u.h||Cu).ie,Mu=(u.DOMException||Cu).INVALID_ACCESS_ERR,Nu=(u.DOMException||Cu).INVALID_STATE_ERR,Au=function(a){switch(a){case "UnknownError":return Du;case "NotFoundError":return Eu; case "ConstraintError":return Fu;case "DataError":return Gu;case "TransactionInactiveError":return Hu;case "AbortError":return Iu;case "ReadOnlyError":return Ju;case "TimeoutError":return Ku;case "QuotaExceededError":return Lu;case "InvalidAccessError":return Mu;case "InvalidStateError":return Nu;default:return Du}},zu=function(a){switch(a){case Du:return"UnknownError";case Eu:return"NotFoundError";case Fu:return"ConstraintError";case Gu:return"DataError";case Hu:return"TransactionInactiveError"; case Iu:return"AbortError";case Ju:return"ReadOnlyError";case Ku:return"TimeoutError";case Lu:return"QuotaExceededError";case Mu:return"InvalidAccessError";case Nu:return"InvalidStateError";default:return"UnknownError"}},Ou=function(a,b){return"error"in a?new Bu(a.error,b):new Bu({name:"UnknownError"},b)},Pu=function(a,b){if("name"in a)return b=b+": "+a.message,new Bu(a,b);if("code"in a){var c=zu(a.code);b=b+": "+a.message;return new Bu({name:c},b)}return new Bu({name:"UnknownError"},b)};var Qu=function(a){this.g=a},Ru=u.IDBKeyRange||u.webkitIDBKeyRange;/* Portions of this code are from MochiKit, received by The Closure Authors under the MIT license. All other code is Copyright 2005-2009 The Closure Authors. All Rights Reserved. */ var Su=function(){this.A=[];this.B=this.o=!1;this.l=void 0;this.F=this.I=this.J=!1;this.C=0;this.h=null;this.K=0};Su.prototype.cancel=function(a){if(this.o)this.l instanceof Su&&this.l.cancel();else{if(this.h){var b=this.h;delete this.h;a?b.cancel(a):(b.K--,0>=b.K&&b.cancel())}this.F=!0;this.o||Tu(this,new Uu(this))}};Su.prototype.H=function(a,b){this.J=!1;Vu(this,a,b)};var Vu=function(a,b,c){a.o=!0;a.l=c;a.B=!b;Wu(a)},Yu=function(a){if(a.o){if(!a.F)throw new Xu(a);a.F=!1}}; Su.prototype.g=function(a){Yu(this);Vu(this,!0,a)};var Tu=function(a,b){Yu(a);Vu(a,!1,b)},$u=function(a,b){return Zu(a,b,null,void 0)},Zu=function(a,b,c,d){a.A.push([b,c,d]);a.o&&Wu(a);return a};Su.prototype.then=function(a,b,c){var d,e,f=new $i(function(g,h){e=g;d=h});Zu(this,e,function(g){g instanceof Uu?f.cancel():d(g)});return f.then(a,b,c)};Su.prototype.$goog_Thenable=!0; var av=function(a){return ob(a.A,function(b){return"function"===typeof b[1]})},Wu=function(a){if(a.C&&a.o&&av(a)){var b=a.C,c=bv[b];c&&(u.clearTimeout(c.g),delete bv[b]);a.C=0}a.h&&(a.h.K--,delete a.h);b=a.l;for(var d=c=!1;a.A.length&&!a.J;){var e=a.A.shift(),f=e[0],g=e[1];e=e[2];if(f=a.B?g:f)try{var h=f.call(e||null,b);void 0!==h&&(a.B=a.B&&(h==b||h instanceof Error),a.l=b=h);if(Yi(b)||"function"===typeof u.Promise&&b instanceof u.Promise)d=!0,a.J=!0}catch(k){b=k,a.B=!0,av(a)||(c=!0)}}a.l=b;d&&(h= Va(a.H,a,!0),d=Va(a.H,a,!1),b instanceof Su?(Zu(b,h,d),b.I=!0):b.then(h,d));c&&(b=new cv(b),bv[b.g]=b,a.C=b.g)},Xu=function(){ab.call(this)};Ya(Xu,ab);Xu.prototype.message="Deferred has already fired";Xu.prototype.name="AlreadyCalledError";var Uu=function(){ab.call(this)};Ya(Uu,ab);Uu.prototype.message="Deferred was canceled";Uu.prototype.name="CanceledError";var cv=function(a){this.g=u.setTimeout(Va(this.l,this),0);this.h=a};cv.prototype.l=function(){delete bv[this.g];throw this.h;};var bv={};var dv=function(){K.call(this)};Ya(dv,K);dv.prototype.g=null;dv.prototype.next=function(a){if(a)this.g["continue"](a);else this.g["continue"]()};dv.prototype.remove=function(){var a=new Su;try{var b=this.g["delete"]()}catch(c){return Tu(a,Pu(c,"deleting via cursor")),a}b.onsuccess=function(){a.g()};b.onerror=function(c){Tu(a,Ou(c.target,"deleting via cursor"))};return a}; var ev=function(a,b){var c=new dv;try{var d=a.openCursor(b?b.g:null)}catch(e){throw c.X(),Pu(e,a.name);}d.onsuccess=function(e){c.g=e.target.result||null;c.g?c.dispatchEvent("n"):c.dispatchEvent("c")};d.onerror=function(){c.dispatchEvent("e")};return c};var fv=function(a){this.g=a},gv=function(a,b,c){var d=new Su;try{var e=a.g.get(c)}catch(f){return b+=" with key "+Qg(c),Tu(d,Pu(f,b)),d}e.onsuccess=function(f){d.g(f.target.result)};e.onerror=function(f){b+=" with key "+Qg(c);Tu(d,Ou(f.target,b))};return d};fv.prototype.get=function(a){return gv(this,"getting from index "+this.g.name,a)};var hv=function(a,b){return ev(a.g,b)};var iv=function(a){this.g=a},jv=function(a,b,c,d,e){var f=new Su;try{var g=e?a.g[b](d,e):a.g[b](d)}catch(h){return c+=Qg(d),e&&(c+=", with key "+Qg(e)),Tu(f,Pu(h,c)),f}g.onsuccess=function(h){f.g(h.target.result)};g.onerror=function(h){c+=Qg(d);e&&(c+=", with key "+Qg(e));Tu(f,Ou(h.target,c))};return f};iv.prototype.add=function(a,b){return jv(this,"add","adding into "+this.g.name+" with value ",a,b)}; iv.prototype.remove=function(a){var b=new Su;try{var c=this.g["delete"](a instanceof Qu?a.g:a)}catch(e){return c="removing from "+this.g.name+" with key "+Qg(a),Tu(b,Pu(e,c)),b}c.onsuccess=function(){b.g()};var d=this;c.onerror=function(e){var f="removing from "+d.g.name+" with key "+Qg(a);Tu(b,Ou(e.target,f))};return b}; iv.prototype.get=function(a){var b=new Su;try{var c=this.g.get(a)}catch(e){return c="getting from "+this.g.name+" with key "+Qg(a),Tu(b,Pu(e,c)),b}c.onsuccess=function(e){b.g(e.target.result)};var d=this;c.onerror=function(e){var f="getting from "+d.g.name+" with key "+Qg(a);Tu(b,Ou(e.target,f))};return b};var kv=function(a){try{return new fv(a.g.index("timestamp"))}catch(b){throw Pu(b,"getting index timestamp");}};var lv=function(a,b){K.call(this);this.g=a;this.l=b;this.h=new U(this);this.h.P(this.g,"complete",Va(this.dispatchEvent,this,"complete"));this.h.P(this.g,"abort",Va(this.dispatchEvent,this,"abort"));this.h.P(this.g,"error",this.Yd)};Ya(lv,K);l=lv.prototype;l.Yd=function(a){a.target instanceof Bu?this.dispatchEvent({type:"error",target:a.target}):this.dispatchEvent({type:"error",target:Ou(a.target,"in transaction")})}; l.objectStore=function(a){try{return new iv(this.g.objectStore(a))}catch(b){throw Pu(b,"getting object store "+a);}};l.commit=function(a){if(this.g.commit||!a)try{this.g.commit()}catch(b){throw Pu(b,"cannot commit the transaction");}};l.wait=function(){var a=new Su;yi(this,"complete",Va(a.g,a));var b=yi(this,"abort",function(){Hi(c);Tu(a,new Bu(Iu,"waiting for transaction to complete"))});var c=yi(this,"error",function(e){Hi(b);Tu(a,e.target)});var d=this.l;return $u(a,function(){return d})}; l.abort=function(){this.g.abort()};l.O=function(){lv.za.O.call(this);this.h.X()};var mv=function(a){K.call(this);this.g=a;this.h=new U(this);this.h.P(this.g,"abort",Va(this.dispatchEvent,this,"abort"));this.h.P(this.g,"error",this.Zd);this.h.P(this.g,"versionchange",this.Ae);this.h.P(this.g,"close",Va(this.dispatchEvent,this,"close"))};Ya(mv,K);l=mv.prototype;l.Mc=!0;l.Zd=function(a){a=(a=a.target)&&a.error;this.dispatchEvent({type:"error",errorCode:a&&a.severity})};l.Ae=function(a){this.dispatchEvent(new nv(a.oldVersion,a.newVersion))}; l.close=function(){this.Mc&&(this.g.close(),this.Mc=!1)};l.getVersion=function(){return Number(this.g.version)};var ov=function(a){var b=["MediaSourceVideoChunk"];try{var c=a.g.transaction(b,"readwrite");return new lv(c,a)}catch(d){throw Pu(d,"creating transaction");}};mv.prototype.O=function(){mv.za.O.call(this);this.h.X()};var nv=function(a,b){ki.call(this,"versionchange");this.oldVersion=a;this.newVersion=b};Ya(nv,ki);var pv=function(a){var b=new Su;void 0==yu&&(yu=u.indexedDB||u.mozIndexedDB||u.webkitIndexedDB||u.moz_indexedDB);var c=yu.open("VideoChunkPersistentStorage",5);c.onsuccess=function(d){d=new mv(d.target.result);b.g(d)};c.onerror=function(d){Tu(b,Ou(d.target,"opening database VideoChunkPersistentStorage"))};c.onupgradeneeded=function(d){if(a){var e=new mv(d.target.result);a(new nv(d.oldVersion,d.newVersion),e,new lv(d.target.transaction,e))}};c.onblocked=function(){};return b};var qv={nh:"videoId",ug:"itag",Wg:"source",Xg:"startIndex"},rv=function(){K.call(this);this.g=null};t(rv,K);rv.prototype.initialize=function(){var a=this;return Promise.resolve(pv(this.h)).then(function(b){return a.g=b},function(b){G(F.D(),"codf",b.message)})};var tv=function(a){return null!==a.g&&a.g.Mc};rv.prototype.close=function(){var a=this;return(new Promise(function(b){return uv(a,b)})).then(function(){return vv()}).then(function(){return a.g.close()})}; var vv=function(){return"storage"in navigator&&"estimate"in navigator.storage?navigator.storage.estimate().then(function(a){G(F.D(),"csue",String(a.usage))}):Promise.resolve(void 0)},zv=function(a,b){b=wv(b);if(!b)return Promise.resolve(null);var c=xv(b);return yv(a,c,b.lmt)},Bv=function(a,b,c,d){if(c=wv(c)){var e=xv(c),f=c.startIndex;Av(a,{cacheId:e,startIndex:f,endIndex:f+b.byteLength-1,lmt:c.lmt,timestamp:new Date(Date.now()),isLastVideoChunk:d,video:b})}else Promise.resolve(void 0)}; rv.prototype.h=function(a,b){if(b.g.objectStoreNames.contains("MediaSourceVideoChunk"))try{b.g.deleteObjectStore("MediaSourceVideoChunk")}catch(d){throw Pu(d,"deleting object store MediaSourceVideoChunk");}a={keyPath:"cacheId"};try{var c=new iv(b.g.createObjectStore("MediaSourceVideoChunk",a))}catch(d){throw Pu(d,"creating object store MediaSourceVideoChunk");}b={unique:!1};try{c.g.createIndex("timestamp","timestamp",b)}catch(d){throw Pu(d,"creating new index timestamp with key path timestamp");}}; var uv=function(a,b){var c=new Date(Date.now());c.setDate(c.getDate()-30);c=new Qu(Ru.upperBound(c,void 0));var d=hv(kv(ov(a.g).objectStore("MediaSourceVideoChunk")),c),e=d.P("n",function(){d.remove();d.next()});yi(d,"c",function(){Hi(e);b()})},wv=function(a){var b=new ou(a);a=pu(b,"id");var c=pu(b,"itag"),d=pu(b,"source"),e=pu(b,"lmt");(b=b.g.l.get("range"))?(b=b.split("-")[0],b=!b||isNaN(b)?null:parseInt(b,10)):b=null;var f=[];a?c?d?e?null===b&&f.push("startIndex"):f.push("lmt"):f.push("source"): f.push("itag"):f.push("videoId");return 0<f.length?(G(F.D(),"civp",f.join("-")),null):{videoId:a,itag:c,source:d,lmt:e,startIndex:b+0}},xv=function(a){var b=Object.keys(qv).sort().map(function(c){return a[qv[c]]}).join(",");return xu(b)},yv=function(a,b,c){var d=ov(a.g).objectStore("MediaSourceVideoChunk");return Promise.resolve(d.get(b)).then(function(e){if(!e)return G(F.D(),"cenf","1"),null;if(e.lmt!==c)return G(F.D(),"cdl","1"),d.remove(b).then(null,function(f){G(F.D(),"crdlvf",f.message)}),null; G(F.D(),"cefml","1");return{endIndex:e.endIndex,isLastVideoChunk:e.isLastVideoChunk,video:e.video}},function(e){G(F.D(),"cgvf",e.message)})},Av=function(a,b){a=ov(a.g).objectStore("MediaSourceVideoChunk");Promise.resolve(jv(a,"put","putting into "+a.g.name+" with value",b,void 0)).then(function(){G(F.D(),"cavs","1")},function(c){G(F.D(),"cavf",c.message)})};var Cv=function(a){K.call(this);var b=this;this.F=new O(a);this.H=this.g=this.l=this.h=0;this.o=(this.C=vu())?Ws(rv):null;ii(this,function(){hi(b.o)});this.I=this.C?this.o.initialize():null;this.A=null};t(Cv,K); var Ev=function(a){Ba(function(b){if(1==b.g)return 2===a.g&&(a.g=1),sa(b,Dv(a),4);var c=3<a.H;if(c&&null!==a.A){var d=zt("media_source_error",{code:0<a.l?MediaError.MEDIA_ERR_NETWORK:MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED,message:'Response code "'+a.A+'" with '+a.h+" bytes requested and "+a.l+" bytes loaded"});a.dispatchEvent(d)}a.l<a.h&&3!==a.g&&!c?b.g=1:(3!==a.g&&(a.g=0),b.g=0)})},Dv=function(a){var b;return Ba(function(c){switch(c.g){case 1:b=a.l+"-"+(a.h-1);ys(a.F,"range",b);if(!a.C){c.g=2;break}return sa(c, a.I,3);case 3:return c.return(Fv(a));case 2:return c.h=4,sa(c,Gv(a),6);case 6:c.g=0;c.h=0;break;case 4:ta(c),a.H++,c.g=0}})},Fv=function(a){var b;return Ba(function(c){switch(c.g){case 1:return sa(c,zv(a.o,a.F),2);case 2:if(b=c.A){b.isLastVideoChunk&&(a.g=3);Hv(a,b.video,0);c.g=0;break}c.h=4;return sa(c,Gv(a),6);case 6:c.g=0;c.h=0;break;case 4:ta(c),a.H++,c.g=0}})},Gv=function(a){return new Promise(function(b,c){var d=new XMLHttpRequest,e=0,f=a.h-a.l;d.addEventListener("load",function(){H("lvlcl"); if(400<=d.status)return G(F.D(),"lvlxes",d.status.toString()),a.A=d.status,c();var g=d.response;g.byteLength<f&&(a.g=3);var h=Hv(a,g,e);e+=h;a.C&&0<g.byteLength&&Bv(a.o,g,a.F,g.byteLength<f);b()});d.addEventListener("timeout",function(){H("lvlct");a.A=d.status;c()});d.addEventListener("error",function(){H("lvlce");a.A=d.status;c()});d.addEventListener("progress",function(){if(400<=d.status)a.A=d.status;else{var g=Hv(a,d.response,e);e+=g}});d.responseType="arraybuffer";d.open("get",a.F.toString()); d.send(null)})},Hv=function(a,b,c){if(null===b)return 0;b=b.slice(c);a.l+=b.byteLength;a.dispatchEvent({type:"progress",te:b});return b.byteLength};Cv.prototype.O=function(){this.C&&tv(this.o)&&this.o.close();K.prototype.O.call(this)};var Iv=function(){};Iv.prototype.g=function(a,b,c){return 0===c?1E6:5E3>b-a?3E5:0};var Jv=function(a,b,c,d){this.url=a;this.mimeType=b;this.g=c;this.h=void 0===d?null:d};var Mv=function(a){K.call(this);var b=this;this.h=a;this.o=this.h.map(function(c){return Ws(Cv,c.url)});this.da=Ws(MediaSource);this.g=[];this.l=window.URL.createObjectURL(this.da);this.H=0;this.F=!1;this.C=function(){return Kv(b)};this.da.addEventListener("sourceopen",this.C);this.I=Lv(this);this.A=0};t(Mv,K); var Lv=function(a){for(var b=[],c=0;c<a.h.length;++c)b.push(new Iv);return b},Kv=function(a){H("msms_oso");for(var b={},c=0;c<a.h.length;b={yb:b.yb,xb:b.xb},++c){var d=a.h[c];G(F.D(),"msms_mime"+c,d.mimeType);G(F.D(),"msms_cs"+c,d.g.toString());b.yb=a.da.addSourceBuffer(d.mimeType);b.xb=a.o[c];b.xb.P("progress",function(e){return function(f){var g=e.xb;f=f.te;0!==f.byteLength&&e.yb.appendBuffer(f);3===g.g&&(a.H++,a.H===a.g.length&&Nv(a))}}(b));b.xb.P("media_source_error",function(e){a.dispatchEvent(e)}); b.yb?a.g.push(b.yb):H("msms_sbf"+c)}G(F.D(),"msms_ns",a.g.length.toString());a.F=!0;Ov(a)},Nv=function(a){Promise.all(a.g.map(function(b){return new Promise(function(c){b.updating?b.addEventListener("updateend",function(){c()}):c()})})).then(function(){return a.da.endOfStream()})},Ov=function(a){if(a.F)for(var b=0;b<a.h.length;++b){var c=a.o[b],d=a.g[b];d=0===d.buffered.length?0:1E3*d.buffered.end(0);d=a.I[b].g(a.A,d,c.h);0!==d&&(1===c.g?(c.h+=d,c.g=2):0===c.g&&(c.h+=d,c.g=1,Ev(c)))}}; Mv.prototype.O=function(){this.l&&window.URL.revokeObjectURL(this.l);for(var a=q(this.o),b=a.next();!b.done;b=a.next())b.value.X();this.da.removeEventListener("sourceopen",this.C);K.prototype.O.call(this)};var Pv=/\/pagead\/conversion|\/pagead\/adview|\/pagead\/gen_204|\/activeview?|csi.gstatic.com\/csi|google.com\/pagead\/xsul|google.com\/ads\/measurement\/l|googleads.g.doubleclick.net\/pagead\/ide_cookie|googleads.g.doubleclick.net\/xbbe\/pixel/,Qv=/outstream.min.js/,Rv=/outstream.min.css/,Sv=/fonts.gstatic.com/,Tv=/googlevideo.com\/videoplayback|c.2mdn.net\/videoplayback|gcdn.2mdn.net\/videoplayback/,Uv=/custom.elements.min.js/; function Vv(a,b){var c=0,d=0,e=0,f=0,g=0,h=0,k=0,n=!1,m=!1;if("function"===typeof Ia("performance.getEntriesByType",u)&&"transferSize"in u.PerformanceResourceTiming.prototype){var v=u.performance.getEntriesByType("resource");v=q(v);for(var r=v.next();!r.done;r=v.next())r=r.value,Pv.test(r.name)||(f+=1,r.transferSize?(c+=r.transferSize,r.encodedBodySize&&r.transferSize<r.encodedBodySize&&(h+=1,e+=r.encodedBodySize,Qv.test(r.name)&&(n=!0),Rv.test(r.name)&&(m=!0)),Tv.test(r.name)&&(d+=r.transferSize)): 0==r.transferSize&&0==r.encodedBodySize?Uv.test(r.name)?c+=6686:Sv.test(r.name)||(k+=1,Rg(F.D(),{event_name:"unmeasurable_asset",resource_name:r.name,encoded_body_size:r.encodedBodySize,transfer_size:r.transferSize})):(g+=1,e+=r.encodedBodySize,Qv.test(r.name)&&(n=!0),Rv.test(r.name)&&(m=!0)));v=0;if(a.duration){for(r=0;r<a.buffered.length;r++)v+=a.buffered.end(r)-a.buffered.start(r);v=Math.min(v,a.duration)}Rg(F.D(),{event_name:b,asset_bytes:c,video_bytes:d,cached_data_bytes:e,js_cached:n,css_cached:m, num_assets:f,num_assets_cached:g,num_assets_cache_validated:h,num_assets_unmeasurable:k,video_played_seconds:a.currentTime.toFixed(2),video_muted:a.muted,video_seconds_loaded:v.toFixed(2)})}else G(F.D(),"error","reporting_timing_not_supported")};function Wv(a){var b=F.D(),c=a.getVideoPlaybackQuality&&a.getVideoPlaybackQuality();c?(a=a.currentTime,G(b,"vqdf",String(c.droppedVideoFrames)),G(b,"vqtf",String(c.totalVideoFrames)),G(b,"vqfr",String(Math.round(c.totalVideoFrames/a)))):G(b,"vqu","1")};var Xv=function(){};Xv.prototype.toString=function(){return"video_mute"};var Yv=new Xv;var Zv=function(a){J.call(this);this.B=1;this.l=[];this.o=0;this.g=[];this.h={};this.F=!!a};Ya(Zv,J);Zv.prototype.C=function(a){var b=this.g[a];b&&(b=this.h[b],0!=this.o?(this.l.push(a),this.g[a+1]=Ja):(b&&tb(b,a),delete this.g[a],delete this.g[a+1],delete this.g[a+2]))}; Zv.prototype.A=function(a,b){var c=this.h[a];if(c){for(var d=Array(arguments.length-1),e=1,f=arguments.length;e<f;e++)d[e-1]=arguments[e];if(this.F)for(e=0;e<c.length;e++){var g=c[e];$v(this.g[g+1],this.g[g+2],d)}else{this.o++;try{for(e=0,f=c.length;e<f;e++)g=c[e],this.g[g+1].apply(this.g[g+2],d)}finally{if(this.o--,0<this.l.length&&0==this.o)for(;c=this.l.pop();)this.C(c)}}}};var $v=function(a,b,c){Wi(function(){a.apply(b,c)})}; Zv.prototype.O=function(){Zv.za.O.call(this);this.g.length=0;this.h={};this.l.length=0};var aw=function(a){J.call(this);this.g=new Zv(a);ji(this,this.g)};Ya(aw,J);var bw=function(a,b){a=a.g;var c=Yv.toString(),d=a.h[c];d||(d=a.h[c]=[]);var e=a.B;a.g[e]=c;a.g[e+1]=b;a.g[e+2]=void 0;a.B=e+3;d.push(e)};var cw=function(){J.call(this);this.g=new U(this);ji(this,this.g)};t(cw,J);var dw=function(a,b){cw.call(this,b);bw(b,function(c){c?a.show():a.g.mode="hidden"})};t(dw,cw);var ew=function(){K.call(this);this.h=new U(this);ji(this,this.h)};t(ew,K);var gw=function(a,b,c){c=void 0===c?!0:c;ew.call(this);a.setAttribute("crossorigin","anonymous");var d=gf("TRACK");d.setAttribute("kind","captions");d.setAttribute("src",b);d.setAttribute("default","");a.appendChild(d);this.g=a.textTracks[0];fw(this);c?this.show():this.g.mode="hidden"};t(gw,ew);var fw=function(a){var b=a.g;b.addEventListener("cuechange",function(){for(var c=b.cues,d=0;d<c.length;d++){var e=c[d];e.align="center";e.position="auto"}},{once:!0})}; gw.prototype.show=function(){this.g.mode="showing"};function hw(a,b){if("undefined"!==typeof ReportingObserver){var c=function(e){e=q(e);for(var f=e.next();!f.done;f=e.next())f=f.value,a(f)&&b(f)},d=new ReportingObserver(c,{buffered:!0});u.addEventListener("unload",function(){c(d.takeRecords(),d);d.disconnect()});d.observe()}} function iw(a){a=void 0===a?null:a;hw(function(b){return b.body&&"HeavyAdIntervention"===b.body.id},function(b){var c=b.body,d=F.D();G(d,"ham",c.message);c.message.includes("Ad was removed because its CPU usage exceeded the limit")?G(d,"hacpu","true"):c.message.includes("Ad was removed because its network usage exceeded the limit")&&G(d,"habytes","true");a&&a(b)})};var jw=function(a){K.call(this);this.g=a;this.o=this.A=!1;this.C=this.F=0;this.h=new oj(1E3);ji(this,this.h);zi(this.h,"tick",this.H,!1,this);zi(this.g,"pause",this.l,!1,this);zi(this.g,"playing",this.l,!1,this);zi(this.g,"ended",this.l,!1,this);zi(this.g,"timeupdate",this.l,!1,this)};t(jw,K);jw.prototype.l=function(a){switch(a.type){case "playing":kw(this);break;case "pause":case "ended":this.h.kb&&this.h.stop();break;case "timeupdate":!this.A&&0<this.g.currentTime&&(this.A=!0,kw(this))}}; var kw=function(a){!a.h.kb&&a.A&&(a.F=1E3*a.g.currentTime,a.C=Date.now(),a.o=!1,a.h.start())};jw.prototype.H=function(){var a=Date.now(),b=1E3*this.g.currentTime;b-this.F<.5*(a-this.C)?this.o||(this.o=!0,this.dispatchEvent("playbackStalled")):this.o=!1;this.F=b;this.C=a};var lw="autoplay controls crossorigin demuxedaudiosrc demuxedvideosrc loop muted playsinline poster preload src webkit-playsinline x-webkit-airplay".split(" "),mw="autoplay buffered controls crossOrigin currentSrc currentTime defaultMuted defaultPlaybackRate disableRemotePlayback duration ended loop muted networkState onerror onwaitingforkey paused played playsinline poster preload preservesPitch mozPreservesPitch webkitPreservesPitch readyState seekable videoWidth videoHeight volume textTracks canPlayType captureStream getVideoPlaybackQuality load pause play setSinkId oncanplay oncanplaythrough onload onplay onpause onended onfullscreenchange onfullscreenerror addEventListener dispatchEvent removeEventListener requestFullscreen".split(" "), nw={childList:!0},ow=HTMLElement;/^\s*class\s*\{\s*\}\s*$/.test(function(){}.toString())||(ow=function(){return u.Reflect.construct(HTMLElement,[],this.__proto__.constructor)},Object.setPrototypeOf(ow,HTMLElement),Object.setPrototypeOf(ow.prototype,HTMLElement.prototype)); var pw=function(a){if(null!==a){a=q(a);for(var b=a.next();!b.done;b=a.next())if(b=b.value,b.nodeName==="TRACK".toString())return b}return null},qw=function(a,b){this.code=a;this.message=void 0===b?"":b},rw=function(a){qw.call(this,MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED,void 0===a?"":a)};t(rw,qw); var ww=function(){var a=ow.call(this)||this;G(F.D(),"ulv","1");a.da=null;a.Hd="";a.md=null;a.R=gf("VIDEO");tw(a);a.Pd=new aw;uw(a);a.Sb=null;vw(a);a.attachShadow({mode:"open"});a.shadowRoot.appendChild(a.R);iw(function(){G(F.D(),"has",a.src||a.qb);G(F.D(),"hat",String(a.R.currentTime))});a.jc=!1;a.Kd=!1;a.Hb=null;return a};t(ww,ow); ww.prototype.attributeChangedCallback=function(a,b,c){switch(a){case "src":xw(this,c);break;case "demuxedaudiosrc":case "demuxedvideosrc":yw(this);break;case "muted":this.R[a]=""===c?!0:!!c;zw(this,a,c);break;default:zw(this,a,c)}}; var zw=function(a,b,c){c!==a.R.getAttribute(b)&&(null===c?a.R.removeAttribute(b):a.R.setAttribute(b,c))},Aw=function(a){a.da&&(a.R.removeEventListener("timeupdate",a.Hb),a.da.X(),a.da=null)},Bw=function(a,b){a.md=b;a.R.dispatchEvent(new Event("error"))},tw=function(a){Cw(a);Dw(a);a.R.addEventListener("loadedmetadata",function(){var b=a.R.videoWidth,c=a.R.videoHeight,d=cg(a),e=d.width,f=d.height;0<b&&0<c&&0<e&&0<f&&(d=d.width/d.height,b/=c,.97<=Math.min(b,d)/Math.max(b,d)?Vf(a.R,{"object-fit":"cover"}): Vf(a.R,{"object-fit":"contain"}))});a.R.addEventListener("play",function(){a.Kd||(Vv(a.R,"first_play"),a.Kd=!0)});a.R.addEventListener("pause",function(){a.jc||(Vv(a.R,"first_pause"),Wv(a.R),a.jc=!0)});zi(u,"unload",function(){a.jc||(Vv(a.R,"first_pause"),Wv(a.R),a.jc=!0)});a.R.addEventListener("stalled",function(){G(F.D(),"ves","1")});(new jw(a.R)).P("playbackStalled",function(){return G(F.D(),"pbs","1")});a.R.addEventListener("media_source_error",function(b){Aw(a);b=b.detail;Bw(a,new qw(b.code, b.message))});Ew(a)},vw=function(a){var b=pw(a.childNodes);b&&Fw(a,b);null===a.Sb&&Gw(a)},Gw=function(a){if(u.MutationObserver){var b=new MutationObserver(function(c){c=q(c);for(var d=c.next();!d.done;d=c.next())if(d=d.value,"childList"===d.type&&(d=pw(d.addedNodes))){Fw(a,d);b.disconnect();break}});b.observe(a,nw)}},uw=function(a){a.R.addEventListener("volumechange",function(){a.Pd.g.A(Yv.toString(),a.R.muted)})},Fw=function(a,b){if(null===a.Sb&&b.hasAttribute("src")){var c=b.getAttribute("src"); a.Sb=new gw(a.R,c,b.hasAttribute("default"));new dw(a.Sb,a.Pd);c.includes("kind=asr")&&G(F.D(),"act","1")}},xw=function(a,b){if(b!==a.Hd){var c=(a.Hd=b)?xt(b):null,d=!!c&&ru(c);G(F.D(),"umsem",d?"1":"0");d?(b=Ws(Jv,b,yt(c),1E3*Xs[c],null),a.da=Ws(Mv,[b]),a.da.P("media_source_error",function(e){e=zt("media_source_error",e.detail);a.R.dispatchEvent(e)}),a.Hb=function(){var e=a.da;e.A=1E3*a.R.currentTime;Ov(e)},a.R.addEventListener("timeupdate",a.Hb),a.R.src=a.da.l):(Aw(a),a.R.src=b);a.R.load()}},yw= function(a){a.src&&Bw(a,new qw(MediaError.MEDIA_ERR_ABORTED,"Setting demuxed src after src is already set."));if(!a.Bb&&!a.qb&&a.da)Aw(a),a.R.src="about:blank",a.R.load();else if(a.Bb&&a.qb){var b=xt(a.Bb),c=xt(a.qb);if(c&&ru(c))if(b&&ru(b)){var d=!!c&&ru(c)&&!!b&&ru(b);G(F.D(),"umsed",d?"1":"0");c=Ws(Jv,a.qb,yt(c),-1,null);b=Ws(Jv,a.Bb,yt(b),-1,null);a.da=Ws(Mv,[c,b]);a.da.P("media_source_error",function(e){e=zt("media_source_error",e.detail);a.R.dispatchEvent(e)});a.Hb=function(){var e=a.da;e.A= 1E3*a.R.currentTime;Ov(e)};a.R.addEventListener("timeupdate",a.Hb);a.R.src=a.da.l;a.R.load()}else Bw(a,new rw('Audio itag "'+b+'" not supported.'));else Bw(a,new rw('Video itag "'+c+'" not supported.'))}},Cw=function(a){for(var b={},c=q(mw),d=c.next();!d.done;b={Ba:b.Ba,rc:b.rc},d=c.next())b.Ba=d.value,b.Ba in a.R&&("function"===typeof a.R[b.Ba]?(b.rc=a.R[b.Ba].bind(a.R),Object.defineProperty(a,b.Ba,{set:function(e){return function(f){a.R[e.Ba]=f}}(b),get:function(e){return function(){return e.rc}}(b)})): Object.defineProperty(a,b.Ba,{set:function(e){return function(f){a.R[e.Ba]=f}}(b),get:function(e){return function(){return a.R[e.Ba]}}(b)}))},Dw=function(a){Object.defineProperty(a,"error",{set:function(){},get:function(){return a.R.error?a.R.error:a.md}})},Ew=function(a){a.R.style.width=ag();a.R.style.height=ag()}; da.Object.defineProperties(ww.prototype,{Bb:{configurable:!0,enumerable:!0,set:function(a){this.setAttribute("demuxedaudiosrc",a)},get:function(){return this.getAttribute("demuxedaudiosrc")}},qb:{configurable:!0,enumerable:!0,set:function(a){this.setAttribute("demuxedvideosrc",a)},get:function(){return this.getAttribute("demuxedvideosrc")}},src:{configurable:!0,enumerable:!0,set:function(a){this.setAttribute("src",a)},get:function(){return this.getAttribute("src")}}}); da.Object.defineProperties(ww,{observedAttributes:{configurable:!0,enumerable:!0,get:function(){return lw}}});u.customElements&&(u.customElements.get("lima-video")||u.customElements.define("lima-video",ww));function Hw(){var a=Ws(rv);a.initialize().then(function(b){b&&(b=zt("initialized"),a.dispatchEvent(b))});return a} var Jw=function(a,b,c,d,e){J.call(this);this.L=a;this.T=new O(b.url);this.h=c;this.o=e;this.I=b.g;this.wa=d;(this.W=b.h)||this.T.l.remove("alr");G(F.D(),"sl_dv"+this.o,(null!=this.W).toString());this.Y=!this.W;this.ob=0;this.g=new XMLHttpRequest;this.aa=this.U=this.Ob=this.F=this.l=0;this.Z=.1;this.C=[];this.N=!1;this.ba=this.sa=this.ea=null;this.Va=!1;this.Pb=this.M=this.A=this.lb=this.jb=null;this.H=!1;if(this.B=vu())this.A=Hw(),ji(this,this.A);Iw(this)};t(Jw,J); var Kw=function(a,b){b=zt("media_source_error",b);a.L.dispatchEvent(b)},Lw=function(a,b){Kw(a,{code:1<a.l?MediaError.MEDIA_ERR_NETWORK:MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED,message:b})},Iw=function(a){a.ea=function(){Mw(a);if(a.Y){var b=a.g.responseText;a.N=!b||b.length<a.I;a.U=0;H("sl_cc"+a.o+"_"+a.l);a.F++;Nw(a)}};a.sa=function(){return Mw(a)};a.ba=function(){H("sl_ec"+a.o+"_"+a.l);Lw(a,"Failed to load chunk "+a.l+" for stream "+a.o)};a.g.addEventListener("load",a.ea);a.g.addEventListener("progress", a.sa);a.g.addEventListener("error",a.ba);a.h.addEventListener("updateend",function(){a.h.buffered.length&&(a.Ob=a.h.buffered.end(0),a.B?a.H&&!a.h.updating&&a.l===a.F&&(H("sl_lc"+a.o),a.wa()):a.N&&!a.h.updating&&a.l===a.F&&(H("sl_lc"+a.o),a.wa()));!a.Va&&1<a.L.buffered.length&&(G(F.D(),"dbr","1"),a.Va=!0)});a.h.addEventListener("update",function(){a.C.length&&!a.h.updating&&a.h.appendBuffer(a.C.shift())});a.h.addEventListener("error",function(){H("msb_err"+a.o);Kw(a,{code:MediaError.MEDIA_ERR_DECODE, message:"Error on SourceBuffer "+a.o})});a.B?(tv(a.A)?Ow(a):a.jb=zi(a.A,"initialized",function(){Ow(a)}),a.lb=zi(a.A,"get_video_succeeded",function(){Nw(a)})):Ow(a)},Qw=function(a){H("sl_rc"+a.o+"-"+a.l);var b=Pw(a);a.g.open("get",b);a.g.overrideMimeType("text/plain; charset=x-user-defined");a.g.send(null);a.B&&(a.M=null,a.Pb=b)},Mw=function(a){if(400<=a.g.status)Lw(a,'Response code "'+a.g.status+'" on loading chunk '+a.l+" for stream "+a.o);else{if(!a.Y){var b=a.g.getResponseHeader("content-type"); if(b&&0<=b.indexOf("text/plain")){a.g.readyState===XMLHttpRequest.DONE&&(a.T=new O(a.g.response),a.l=0,a.F=0,a.ob++,Ow(a));return}a.Y=!0;H("sl_redc"+a.o);G(F.D(),"sl_tr"+a.o,a.ob.toString())}a.T.l.remove("alr");if(a.g.readyState===XMLHttpRequest.LOADING||a.g.readyState===XMLHttpRequest.DONE)b=Rw(a,a.U),a.U=a.g.response.length,a.aa+=b.byteLength,Sw(a,b);if(a.B&&a.g.readyState===XMLHttpRequest.DONE&&(b=Rw(a,0),0<b.byteLength)){var c=a.g.responseText;a.H=!c||c.length<a.I;Bv(a.A,b,new O(a.Pb),a.H)}}}, Sw=function(a,b){0<b.byteLength&&(a.h.updating||a.C.length?a.C.push(b):a.h.appendBuffer(b))},Rw=function(a,b){a=a.g.response;for(var c=new Uint8Array(a.length-b),d=0;d<c.length;d++)c[d]=a.charCodeAt(d+b)&255;return c.buffer},Nw=function(a){var b=At;-1!=b&&b<a.aa+a.I?(a.L.pause(),At=-1,b=!1):(b=a.F===a.l&&!a.h.updating&&!a.C.length,b=a.B?!a.H&&b&&a.L.currentTime>=a.Z:!a.N&&b&&a.L.currentTime>=a.Z);b&&(a.Z=a.Ob+.1,Ow(a))},Pw=function(a){var b=a.B&&a.M?a.M+1:a.l*a.I;return ys(a.T,"range",b+"-"+(b+a.I- 1)).toString()},Ow=function(a){if(a.B){var b=new O(Pw(a));zv(a.A,b).then(function(c){c?(a.M=parseInt(c.endIndex,10),a.H=c.isLastVideoChunk,Sw(a,c.video),c=zt("get_video_succeeded"),a.A.dispatchEvent(c),a.F++):Qw(a);a.l++})}else Qw(a),a.l++};Jw.prototype.O=function(){this.B&&tv(this.A)&&this.A.close();this.g.removeEventListener("load",this.ea);this.g.removeEventListener("progress",this.sa);this.g.removeEventListener("error",this.ba);Hi(this.jb);Hi(this.lb);J.prototype.O.call(this)};var Uw=function(a,b){J.call(this);var c=this;this.o=a;this.F=b;this.da=new MediaSource;this.C=[];this.h=[];this.g=this.l=null;this.B=!1;this.A=function(){return Tw(c)};this.da.addEventListener("sourceopen",this.A)};t(Uw,J); var Vw=function(a){a.l&&a.o.removeEventListener("timeupdate",a.l)},Tw=function(a){H("msmsw_oso");a.l=function(){if(!a.B)for(var e=q(a.h),f=e.next();!f.done;f=e.next())Nw(f.value)};a.o.addEventListener("timeupdate",a.l);for(var b=0;b<a.F.length;b++){var c=a.F[b];G(F.D(),"msmsw_mime"+b,c.mimeType);G(F.D(),"msmsw_cs"+b,c.g.toString());var d=a.da.addSourceBuffer(c.mimeType);d?(a.C.push(d),c=Ws(Jw,a.o,c,d,function(){a:if(!a.B){for(var e=q(a.h),f=e.next();!f.done;f=e.next())if(f=f.value,f.B?!f.H||f.h.updating|| f.C.length:!f.N||f.h.updating||f.C.length)break a;a.da.endOfStream();a.B=!0;Vw(a)}},b),a.h.push(c)):H("msmsw_sbf"+b)}G(F.D(),"msmsw_ns",a.C.length.toString())};Uw.prototype.O=function(){this.g&&window.URL.revokeObjectURL(this.g);for(var a=q(this.h),b=a.next();!b.done;b=a.next())b.value.X();Vw(this);this.da.removeEventListener("sourceopen",this.A);J.prototype.O.call(this)};var Ww=function(){throw Error("Do not instantiate directly");};Ww.prototype.g=null;Ww.prototype.getContent=function(){return this.content};Ww.prototype.toString=function(){return this.content};var Xw=function(){Ww.call(this)};Ya(Xw,Ww);var Yw=function(a){function b(c){this.content=c}b.prototype=a.prototype;return function(c,d){c=new b(String(c));void 0!==d&&(c.g=d);return c}}(Xw);var Zw={rgb:!0,rgba:!0,alpha:!0,rect:!0,image:!0,"linear-gradient":!0,"radial-gradient":!0,"repeating-linear-gradient":!0,"repeating-radial-gradient":!0,"cubic-bezier":!0,matrix:!0,perspective:!0,rotate:!0,rotate3d:!0,rotatex:!0,rotatey:!0,steps:!0,rotatez:!0,scale:!0,scale3d:!0,scalex:!0,scaley:!0,scalez:!0,skew:!0,skewx:!0,skewy:!0,translate:!0,translate3d:!0,translatex:!0,translatey:!0,translatez:!0},$w=function(a){a=gc(a);if(""==a)return null;var b=String(a.substr(0,4)).toLowerCase();if(0==("url("< b?-1:"url("==b?0:1))return null;if(0<a.indexOf("(")){if(/"|'/.test(a))return null;b=/([\-\w]+)\(/g;for(var c;c=b.exec(a);)if(!(c[1].toLowerCase()in Zw))return null}return a};function ax(a){var b=u.CSSStyleDeclaration;return b&&b.prototype&&b.prototype[a]||null}var bx=ax("getPropertyValue"),cx=ax("setProperty");function dx(a,b,c,d){if(a)return a.apply(b,d);if(ud&&10>document.documentMode){if(!b[c].call)throw Error("IE Clobbering detected");}else if("function"!=typeof b[c])throw Error("Clobbering detected");return b[c].apply(b,d)};var ex={"-webkit-border-horizontal-spacing":!0,"-webkit-border-vertical-spacing":!0},gx=function(a){if(!a)return Cc;var b=document.createElement("div").style;fx(a).forEach(function(c){var d=xd&&c in ex?c:c.replace(/^-(?:apple|css|epub|khtml|moz|mso?|o|rim|wap|webkit|xv)-(?=[a-z])/i,"");0!=d.lastIndexOf("--",0)&&0!=d.lastIndexOf("var",0)&&(c=dx(bx,a,a.getPropertyValue?"getPropertyValue":"getAttribute",[c])||"",c=$w(c),null!=c&&dx(cx,b,b.setProperty?"setProperty":"setAttribute",[d,c]))});return new Bc(b.cssText|| "",Ac)},fx=function(a){Ma(a)?a=xb(a):(a=Jb(a),tb(a,"cssText"));return a};var hx=function(){if(window.MutationObserver){var a=[];(new MutationObserver(function(){a.forEach(function(b){return b()});a=[]})).observe(document.createTextNode(""),{characterData:!0})}};"function"===typeof Promise&&-1<String(Promise).indexOf("[native code]")||hx();var ix="abort canplay canplaythrough durationchange emptied loadstart loadeddata loadedmetadata progress ratechange seeked seeking stalled suspend waiting".split(" ");var jx=function(a){this.g=a},kx=function(a,b){return Lb(a.g,b)&&(a=a.g[b],"boolean"===typeof a)?a:!1},lx=function(a){if(Lb(a.g,"forceExperimentIds")){a=a.g.forceExperimentIds;var b=[],c=0;Array.isArray(a)&&a.forEach(function(d){"number"===typeof d&&(b[c++]=d)});return b}return null};var V=function(){this.K="always";this.M=4;this.A=1;this.g=0;this.J=!0;this.o="en";this.L=!1;this.U=this.T="";this.B=null;this.Y=this.N=-1;this.W=this.I=this.C="";this.F=!1;this.h=!0;this.Z=Vs();this.H={};try{this.ba=Xk(void 0)[0]}catch(a){}},mx=function(a){a=$c(a);fc(a)||(a=a.substring(0,20));return a};l=V.prototype;l.setCompanionBackfill=function(a){this.K=a};l.getCompanionBackfill=function(){return this.K};l.setNumRedirects=function(a){this.M=a};l.getNumRedirects=function(){return this.M}; l.setPpid=function(a){this.aa=a};l.getPpid=function(){return this.aa};l.setVpaidAllowed=function(a){"boolean"===typeof a&&(this.A=a?1:0)};l.setVpaidMode=function(a){this.A=a};l.getVpaidMode=function(){return this.A};l.setAutoPlayAdBreaks=function(a){this.J=a};l.isAutoPlayAdBreaks=function(){return this.J};l.setIsVpaidAdapter=function(a){this.L=a};l.Fb=function(){return this.L};l.setLocale=function(a){if(a=$t(a))this.o=a};l.De=function(){return this.o};l.setPlayerType=function(a){this.T=mx(a)}; l.getPlayerType=function(){return this.T};l.setPlayerVersion=function(a){this.U=mx(a)};l.getPlayerVersion=function(){return this.U};var nx=function(a){if(null==a.B){var b={};var c=(new O(D().location.href)).l;if(Cs(c,"tcnfp"))try{b=JSON.parse(c.get("tcnfp"))}catch(d){}a.B=new jx(b)}return a.B};l=V.prototype;l.setPageCorrelator=function(a){this.N=a};l.setStreamCorrelator=function(a){this.Y=a};l.setDisableCustomPlaybackForIOS10Plus=function(a){this.F=a};l.getDisableCustomPlaybackForIOS10Plus=function(){return this.F}; l.Re=function(){return this.h};l.setCookiesEnabled=function(a){null!=a&&(this.h=a)};l.setDisableFlashAds=function(){};l.getDisableFlashAds=function(){return!0};l.setFeatureFlags=function(a){this.H=a};l.getFeatureFlags=function(){return this.H};V.prototype.getFeatureFlags=V.prototype.getFeatureFlags;V.prototype.setFeatureFlags=V.prototype.setFeatureFlags;V.prototype.getDisableFlashAds=V.prototype.getDisableFlashAds;V.prototype.setDisableFlashAds=V.prototype.setDisableFlashAds; V.prototype.setCookiesEnabled=V.prototype.setCookiesEnabled;V.prototype.isCookiesEnabled=V.prototype.Re;V.prototype.getDisableCustomPlaybackForIOS10Plus=V.prototype.getDisableCustomPlaybackForIOS10Plus;V.prototype.setDisableCustomPlaybackForIOS10Plus=V.prototype.setDisableCustomPlaybackForIOS10Plus;V.prototype.setStreamCorrelator=V.prototype.setStreamCorrelator;V.prototype.setPageCorrelator=V.prototype.setPageCorrelator;V.prototype.getPlayerVersion=V.prototype.getPlayerVersion; V.prototype.setPlayerVersion=V.prototype.setPlayerVersion;V.prototype.getPlayerType=V.prototype.getPlayerType;V.prototype.setPlayerType=V.prototype.setPlayerType;V.prototype.getLocale=V.prototype.De;V.prototype.setLocale=V.prototype.setLocale;V.prototype.isVpaidAdapter=V.prototype.Fb;V.prototype.setIsVpaidAdapter=V.prototype.setIsVpaidAdapter;V.prototype.isAutoPlayAdBreaks=V.prototype.isAutoPlayAdBreaks;V.prototype.setAutoPlayAdBreaks=V.prototype.setAutoPlayAdBreaks;V.prototype.getVpaidMode=V.prototype.getVpaidMode; V.prototype.setVpaidMode=V.prototype.setVpaidMode;V.prototype.setVpaidAllowed=V.prototype.setVpaidAllowed;V.prototype.getPpid=V.prototype.getPpid;V.prototype.setPpid=V.prototype.setPpid;V.prototype.getNumRedirects=V.prototype.getNumRedirects;V.prototype.setNumRedirects=V.prototype.setNumRedirects;V.prototype.getCompanionBackfill=V.prototype.getCompanionBackfill;V.prototype.setCompanionBackfill=V.prototype.setCompanionBackfill;var W=new V;var ox=function(a){ue(this,a,null,null)};t(ox,pe);var px=function(){var a={};this.g=function(b,c){return null!=a[b]?a[b]:c};this.h=function(b,c){return null!=a[b]?a[b]:c}};Ka(px);var qx=function(a){return px.D().g(a.g,a.defaultValue)},rx=function(a){return px.D().h(a.g,a.defaultValue)};var sx=function(a){void 0!==a.addtlConsent&&"string"!==typeof a.addtlConsent&&(a.addtlConsent=void 0);void 0!==a.gdprApplies&&"boolean"!==typeof a.gdprApplies&&(a.gdprApplies=void 0);return void 0!==a.tcString&&"string"!==typeof a.tcString||void 0!==a.listenerId&&"number"!==typeof a.listenerId?2:a.cmpStatus&&"error"!==a.cmpStatus?0:3},tx=function(a,b){b=void 0===b?500:b;J.call(this);this.h=a;this.g=null;this.B={};this.A=0;this.o=b;this.l=null};t(tx,J); tx.prototype.O=function(){this.B={};this.l&&(Qe(this.h,"message",this.l),delete this.l);delete this.B;delete this.h;delete this.g;J.prototype.O.call(this)}; var vx=function(a){return"function"===typeof a.h.__tcfapi||null!=ux(a)},yx=function(a,b){var c={internalErrorState:0},d=fb(function(){return b(c)}),e=0;-1!==a.o&&(e=setTimeout(function(){e=0;c.tcString="tcunavailable";c.internalErrorState=1;d()},a.o));wx(a,"addEventListener",function(f){f&&(c=f,c.internalErrorState=sx(c),xx(c)&&(0!=c.internalErrorState&&(c.tcString="tcunavailable"),wx(a,"removeEventListener",null,c.listenerId),e&&(clearTimeout(e),e=0),d()))})}; tx.prototype.addEventListener=function(a){var b={},c=fb(function(){return a(b)}),d=0;-1!==this.o&&(d=setTimeout(function(){b.tcString="tcunavailable";b.internalErrorState=1;c()},this.o));var e=function(f,g){clearTimeout(d);f?(b=f,b.internalErrorState=sx(b),g&&0===b.internalErrorState||(b.tcString="tcunavailable",g||(b.internalErrorState=3))):(b.tcString="tcunavailable",b.internalErrorState=3);a(b)};try{wx(this,"addEventListener",e)}catch(f){b.tcString="tcunavailable",b.internalErrorState=3,d&&(clearTimeout(d), d=0),c()}};tx.prototype.removeEventListener=function(a){a&&a.listenerId&&wx(this,"removeEventListener",null,a.listenerId)}; var wx=function(a,b,c,d){c||(c=function(){});if("function"===typeof a.h.__tcfapi)a=a.h.__tcfapi,a(b,2,c,d);else if(ux(a)){zx(a);var e=++a.A;a.B[e]=c;a.g&&(c={},a.g.postMessage((c.__tcfapiCall={command:b,version:2,callId:e,parameter:d},c),"*"))}else c({},!1)},ux=function(a){if(a.g)return a.g;a.g=Gf(a.h,"__tcfapiLocator");return a.g},zx=function(a){a.l||(a.l=function(b){try{var c=("string"===typeof b.data?JSON.parse(b.data):b.data).__tcfapiReturn;a.B[c.callId](c.returnValue,c.success)}catch(d){}},Pe(a.h, "message",a.l))},xx=function(a){if(!1===a.gdprApplies)return!0;void 0===a.internalErrorState&&(a.internalErrorState=sx(a));return"error"===a.cmpStatus||0!==a.internalErrorState||"loaded"===a.cmpStatus&&("tcloaded"===a.eventStatus||"useractioncomplete"===a.eventStatus)?!0:!1};function Ax(a){var b={};(new O(a)).l.forEach(function(c,d){b[d]=c});return b} var Bx=function(a){this.Dd=a.isGdprLoader||!1;this.uspString=a.uspString||"";var b=a.gdprApplies;this.h="boolean"==typeof b?b?"1":"0":"number"!=typeof b||1!==b&&0!==b?"string"!=typeof b||"1"!==b&&"0"!==b?"":"1"==b?"1":"0":1==b?"1":"0";this.g=a.tcString||"";/^[\.\w_-]*$/.test(this.g)||(this.g=encodeURIComponent(this.g))},Cx=function(a,b){a=void 0===a?{}:a;b=void 0===b?{}:b;this.g=a;this.h=new Bx(b)},Dx=function(a,b){var c=new O(a);var d=c.h;(c=ec(c.g,"googleads.g.doubleclick.net")&&Yt("/pagead/(live/)?ads", d))||(d=new bu(a),c=d.g,d=cu(d,d.h),c=!ec(c,".g.doubleclick.net")&&ec(c,"doubleclick.net")&&Yt("/(ad|pfad)[x|i|j]?/",d));c||(c=new O(a),d=c.h,c=ec(c.g,"doubleclick.net")&&Yt("/gampad/(live/)?ads",d));(c=c||"bid.g.doubleclick.net"==(new O(a)).g)||(c=new O(a),d=c.h,c="ad.doubleclick.net"===c.g&&Yt("/dv3/adv",d));c||(c=new O(a),d=c.h,"pubads.g.doubleclick.net"===c.g&&(Yt("/ssai/",d)||Yt("/ondemand/",d)));return new Cx(Ax(a),b)},Ex=function(a,b){if(a.g.hasOwnProperty(b))return a.g[b]},Fx=function(a){var b, c;if(!(b="1"==(null==(c=Ex(a,"ltd"))?void 0:c.toString()))){var d;b=null==(d=Ex(a,"gdpr"))?void 0:d.toString();d=a.h.h;d=("1"==d||"0"==d?d:void 0!=b?b:"").toLowerCase();if("true"===d||"1"===d)if(d=a.h.g,a=Ex(a,"gdpr_consent"),a=d&&"tcunavailable"!=d?d:"tcunavailable"==d?a||d:a||"","tcunavailable"===a)var e=!1;else{if((d=yr(a))&&a){var f=De(d,Qq,1);d=De(d,Jq,2)||new Jq;b=xe(f,9,0);c=xe(f,4,0);var g=xe(f,5,0),h=ye(f,10),k=ye(f,11),n=xe(f,16,""),m=ye(f,15),v={consents:zr(A(f,13),lr),legitimateInterests:zr(A(f, 14),lr)},r={consents:zr(A(f,17),void 0),legitimateInterests:zr(A(f,18),void 0)},w=zr(A(f,12),mr),B=Ee(f,Hq,19);f={};B=q(B);for(var L=B.next();!L.done;L=B.next()){L=L.value;var La=xe(L,1,0);f[La]=f[La]||{};for(var Uc=q(A(L,3)),Ad=Uc.next();!Ad.done;Ad=Uc.next())f[La][Ad.value]=xe(L,2,0)}a={tcString:a,tcfPolicyVersion:b,gdprApplies:!0,cmpId:c,cmpVersion:g,isServiceSpecific:h,useNonStandardStacks:k,publisherCC:n,purposeOneTreatment:m,purpose:v,vendor:r,specialFeatureOptins:w,publisher:{restrictions:f, consents:zr(A(d,1),lr),legitimateInterests:zr(A(d,2),lr),customPurposes:{consents:zr(A(d,3)),legitimateInterests:zr(A(d,4))}}}}else a=null;if(a){var Sa=void 0===Sa?!1:Sa;if(xx(a))if(!1===a.gdprApplies||"tcunavailable"===a.tcString||void 0===a.gdprApplies&&!Sa||"string"!==typeof a.tcString||!a.tcString.length)e=!0;else{e=void 0===e?"755":e;c:{if(a.publisher&&a.publisher.restrictions&&(Sa=a.publisher.restrictions["1"],void 0!==Sa)){Sa=Sa[void 0===e?"755":e];break c}Sa=void 0}0===Sa?e=!1:a.purpose&& a.vendor?(Sa=a.vendor.consents,(e=!(!Sa||!Sa[void 0===e?"755":e]))&&a.purposeOneTreatment&&("DE"===a.publisherCC||qx(Cr)&&"CH"===a.publisherCC)?e=!0:e&&(e=a.purpose.consents,e=!(!e||!e["1"]))):e=!0}else e=!1}else e=!1}else e=!0;b=!e}return b};var Gx="platform platformVersion architecture model uaFullVersion bitness".split(" "),Hx=function(){var a=window;return a.navigator&&a.navigator.userAgentData&&"function"===typeof a.navigator.userAgentData.getHighEntropyValues?a.navigator.userAgentData.getHighEntropyValues(Gx).then(function(b){var c=new Rr;c=Ae(c,1,b.platform);c=Ae(c,2,b.platformVersion);c=Ae(c,3,b.architecture);c=Ae(c,4,b.model);c=Ae(c,5,b.uaFullVersion);return Ae(c,9,b.bitness)}):null};var Jx=function(){new Cx;Vs();this.deviceId="";this.g=this.referrer=null;Ix(this)},Kx=function(){Jx.D();var a="h.3.467.0";W.Fb()&&(a+="/vpaid_adapter");return a},Ix=function(a){var b=Hx();b&&b.then(function(c){a.g=Zd(JSON.stringify(c.h&&Fe(c),He))})};Ka(Jx);var Mx=function(a){var b=nx(W);if(b&&kx(b,"forceCustomPlayback")||W.Fb())return!0;if((Cd||Lt())&&a)return!1;a=a&&(Cd||Lt()||Mt(10))&&(W.getDisableCustomPlaybackForIOS10Plus()||gh(Wh));return(Bd||Dd)&&!a||zd&&(!zd||!Kt(Jt,4))||Lx()?!0:!1},Nx=function(a){return null==a?!1:W.Fb()?!0:Ed||Cd||Lt()?Nt(a)?Cd||Lt()||Mt(10)&&W.getDisableCustomPlaybackForIOS10Plus()?!1:!0:!0:zd&&(!zd||!Kt(Jt,4))||Lx()?!0:!1},Ox=function(){var a=nx(W);return a&&kx(a,"disableOnScreenDetection")?!1:!Zl()},Lx=function(){return $l()|| (Jx.D(),!1)};var Px=function(){this.allowCustom=!0;this.creativeType=this.resourceType="All";this.sizeCriteria="SelectExactMatch";this.nearMatchPercent=90;this.adSlotIds=[]},Qx={IMAGE:"Image",FLASH:"Flash",ALL:"All"};x("module$contents$ima$CompanionAdSelectionSettings_CompanionAdSelectionSettings.CreativeType",Qx,void 0);var Rx={HTML:"Html",IFRAME:"IFrame",STATIC:"Static",ALL:"All"};x("module$contents$ima$CompanionAdSelectionSettings_CompanionAdSelectionSettings.ResourceType",Rx,void 0); var Sx={IGNORE:"IgnoreSize",SELECT_EXACT_MATCH:"SelectExactMatch",SELECT_NEAR_MATCH:"SelectNearMatch"};x("module$contents$ima$CompanionAdSelectionSettings_CompanionAdSelectionSettings.SizeCriteria",Sx,void 0);var Ux=function(a,b){b=void 0===b?new Px:b;this.h=a;this.g=b?b:new Px;this.A=Tx(Rx,this.g.resourceType)?this.g.resourceType:"All";this.l=Tx(Qx,this.g.creativeType)?this.g.creativeType:"All";this.C=Tx(Sx,this.g.sizeCriteria)?this.g.sizeCriteria:"SelectExactMatch";this.o=null!=this.g.adSlotIds?this.g.adSlotIds:[];this.B="number"===typeof this.g.nearMatchPercent&&0<this.g.nearMatchPercent&&100>=this.g.nearMatchPercent?this.g.nearMatchPercent:90},Xx=function(a,b){var c=[];b.forEach(function(d){a.g.allowCustom&& (!fc(d.getContent())&&(isNaN(d.g.sequenceNumber)||isNaN(d.g.mainAdSequenceNumber)||d.g.mainAdSequenceNumber==d.g.sequenceNumber)&&Vx(a,d)?c.push(d):(d=Wx(a,d),null!=d&&!fc(d.getContent())&&c.push(d)))});return c},Vx=function(a,b){var c;if(c="Flash"!=b.getContentType()){if(c="All"==a.A||a.A==b.g.resourceType)c=b.getContentType(),c=null==c?!0:"All"==a.l||a.l==c;c&&(c=b.xd(),c=0==a.o.length?!0:null!=c?a.o.includes(c):!1)}if(c)if(b=b.g.size,(c="IgnoreSize"==a.C)||(c=a.h,c=c==b?!0:c&&b?c.width==b.width&& c.height==b.height:!1),c)a=!0;else{if(c="SelectNearMatch"==a.C)c=b.width,b=b.height,c=c>a.h.width||b>a.h.height||c<a.B/100*a.h.width||b<a.B/100*a.h.height?!1:!0;a=c}else a=!1;return a},Wx=function(a,b){b=Yx(b);return null==b?null:b.find(function(c){return Vx(a,c)})||null},Tx=function(a,b){return null!=b&&Mb(a,b)};var X={},Zx=(X.creativeView="creativeview",X.start="start",X.midpoint="midpoint",X.firstQuartile="firstquartile",X.thirdQuartile="thirdquartile",X.complete="complete",X.mute="mute",X.unmute="unmute",X.pause="pause",X.rewind="rewind",X.resume="resume",X.fullscreen="fullscreen",X.exitFullscreen="exitfullscreen",X.expand="expand",X.collapse="collapse",X.close="close",X.acceptInvitation="acceptinvitation",X.userInteraction="userInteraction",X.adCanPlay="adCanPlay",X.adStarted="adStarted",X.abandon="abandon", X.acceptInvitationLinear="acceptinvitationlinear",X.engagedView="engagedview",X.instreamAdComplete="instreamAdComplete",X.skipShown="skipshown",X.skippableStateChanged="skippableStateChanged",X.skip="skip",X.progress="progress",X.publisher_invoked_skip="PUBLISHER_INVOKED_SKIP",X.annotation_start="annotation_start",X.annotation_click="annotation_click",X.annotation_close="annotation_close",X.cta_annotation_shown="cta_annotation_shown",X.cta_annotation_clicked="cta_annotation_clicked",X.cta_annotation_closed= "cta_annotation_closed",X.replay="replay",X.stop="stop",X.autoplayDisallowed="autoplayDisallowed",X.error="error",X.mediaLoadTimeout="mediaLoadTimeout",X.linearChanged="linearChanged",X.click="click",X.contentPauseRequested="contentPauseRequested",X.contentResumeRequested="contentResumeRequested",X.discardAdBreak="discardAdBreak",X.updateAdsRenderingSettings="updateAdsRenderingSettings",X.durationChange="durationChange",X.expandedChanged="expandedChanged",X.autoClose="autoClose",X.userClose="userClose", X.userRecall="userRecall",X.prefetched="prefetched",X.loaded="loaded",X.init="init",X.allAdsCompleted="allAdsCompleted",X.adMetadata="adMetadata",X.adBreakReady="adBreakReady",X.adBreakFetchError="adBreakFetchError",X.log="log",X.volumeChange="volumeChange",X.companionBackfill="companionBackfill",X.companionInitialized="companionInitialized",X.companionImpression="companionImpression",X.companionClick="companionClick",X.impression="impression",X.interaction="interaction",X.adProgress="adProgress", X.adBuffering="adBuffering",X.trackingUrlPinged="trackingUrlPinged",X.measurable_impression="measurable_impression",X.custom_metric_viewable="custom_metric_viewable",X.viewable_impression="viewable_impression",X.fully_viewable_audible_half_duration_impression="fully_viewable_audible_half_duration_impression",X.overlay_resize="overlay_resize",X.overlay_unmeasurable_impression="overlay_unmeasurable_impression",X.overlay_unviewable_impression="overlay_unviewable_impression",X.overlay_viewable_immediate_impression= "overlay_viewable_immediate_impression",X.overlay_viewable_end_of_session_impression="overlay_viewable_end_of_session_impression",X.externalActivityEvent="externalActivityEvent",X.adEvent="adEvent",X.configure="configure",X.remainingTime="remainingTime",X.destroy="destroy",X.resize="resize",X.volume="volume",X.authorIconClicked="videoAuthorIconClicked",X.authorNameClicked="videoAuthorClicked",X.videoClicked="videoClicked",X.videoIconClicked="videoIconClicked",X.learnMoreClicked="videoLearnMoreClicked", X.muteClicked="videoMuteClicked",X.titleClicked="videoTitleClicked",X.skipShown="SKIP_SHOWN",X.videoSkipClicked="SKIPPED",X.unmuteClicked="videoUnmuteClicked",X.vpaidEvent="vpaidEvent",X.show_ad="show_ad",X.video_card_endcap_collapse="video_card_endcap_collapse",X.video_card_endcap_dismiss="video_card_endcap_dismiss",X.video_card_endcap_impression="video_card_endcap_impression",X.mediaUrlPinged="mediaUrlPinged",X.breakStart="breakstart",X.breakEnd="breakend",X.omidReady="omidReady",X.omidUnavailable= "omidUnavailable",X.omidAdSessionCompleted="omidAdSessionCompleted",X.omidAdSessionAbandoned="omidAdSessionAbandoned",X.verificationNotExecuted="verificationNotExecuted",X.loadStart="loadStart",X.seeked="seeked",X.seeking="seeking",X);var $x=function(a){K.call(this);this.h=a||"goog_"+ad++;this.o=[];this.l=!1};t($x,K);$x.prototype.connect=function(){for(this.l=!0;0!=this.o.length;){var a=this.o.shift();this.sendMessage(a.name,a.type,a.data)}};var ay=function(a,b,c,d){a.l?a.sendMessage(b,c,d):a.o.push({name:b,type:c,data:d})};$x.prototype.sendMessage=function(){};function by(a){a=Ft(a,Zl()?"https":window.location.protocol);if(Zl())cy(a);else try{a&&(Hs(a)?Ls(a):Ps(a))}catch(b){}}function cy(a){(new Vt).get({url:a,timeout:new Bt}).then(function(){},function(){})};var dy=function(a,b,c){var d=Error.call(this);this.message=d.message;"stack"in d&&(this.stack=d.stack);this.l=b;this.g=c;this.o=a};t(dy,Error);l=dy.prototype;l.getAd=function(){return this.B};l.getInnerError=function(){return this.h};l.getMessage=function(){return this.l};l.getErrorCode=function(){return this.g};l.Bd=function(){return 1E3>this.g?this.g:900};l.getType=function(){return this.o}; l.toString=function(){return"AdError "+this.getErrorCode()+": "+this.getMessage()+(null!=this.getInnerError()?" Caused by: "+this.getInnerError():"")};var ey=function(a,b){this.message=a;this.errorCode=b};ey.prototype.getErrorCode=function(){return this.errorCode};ey.prototype.getMessage=function(){return this.message};var fy=new ey("Failed to initialize ad playback element before starting ad playback.",400),gy=new ey("The provided {0} information: {1} is invalid.",1101); function hy(a,b,c){var d=void 0===b?null:b;if(!(d instanceof dy)){var e=a.errorCode,f=a.message,g=Array.prototype.slice.call(arguments,2);if(0<g.length)for(var h=0;h<g.length;h++)f=f.replace(new RegExp("\\{"+h+"\\}","ig"),g[h]);e=new dy("adPlayError",f,e);e.h=d;d=e}return d};var iy=function(){this.errorMessage=this.info=this.error=this.Wc=null},jy=function(a,b){a.Wc=b;return a};iy.prototype.getError=function(){return this.error};var ky=function(a,b){a.errorMessage=b;return a};iy.prototype.getErrorMessage=function(){return this.errorMessage};var ly=function(){this.cache={}},py=function(){my||(ny=rx(Gr),oy=rx(Fr),my=new ly);return my},qy=function(a){var b=A(a,3);if(!b)return 3;if(void 0===A(a,2))return 4;a=Date.now();return a>b+36E5*oy?2:a>b+36E5*ny?1:0}; ly.prototype.get=function(a,b){var c=new iy;if(this.cache[a])return jy(c,this.cache[a]);var d="";try{d=b.getItem("_GESPSK-"+a)}catch(e){return c.error=6,ky(c,e.message)}if(!d)return new iy;b=null;try{b=Ie(Nj,d)}catch(e){return a=new iy,a.error=5,ky(a,e.message)}b&&(this.cache[a]=b);return jy(new iy,b)};ly.prototype.set=function(a,b){var c=A(a,1),d="_GESPSK-"+c,e=jy(new iy,a);try{b.setItem(d,JSON.stringify(a.h&&Fe(a),He))}catch(f){e.info=7,ky(e,f.message)}this.cache[c]=a;return e}; var my=null,ny=24,oy=72;var ry=function(){this.g=function(){return[]}};Ka(ry);function sy(a,b,c,d){c=void 0===c?null:c;d=void 0===d?{}:d;if(Math.random()<rx(Ir)){var e={},f=Object,g=f.assign;e.c=String(a);a=String;var h=window;if("number"!==typeof h.goog_pvsid)try{Object.defineProperty(h,"goog_pvsid",{value:Math.floor(Math.random()*Math.pow(2,52)),configurable:!1})}catch(k){}Qf(g.call(f,(e.pc=a(Number(h.goog_pvsid)||-1),e.em=c,e.lid=b,e.eids=ry.D().g().join(),e),d),"esp")}};function ty(a){if(!a)return null;var b=new Jj,c=rx(Hr),d=[],e=/^_GESPSK-(.+)$/;try{for(var f=0;f<a.length;f++){var g=(e.exec(a.key(f))||[])[1];g&&d.push(g)}}catch(k){}d=q(d);for(e=d.next();!e.done;e=d.next())if(e=e.value,f=py().get(e,a),f.getError())sy(f.getError(),e,f.getErrorMessage());else if(f=f.Wc)if(g=qy(f),0===g||1===g)if(g=A(f,2),0<=c&&g&&g.length>c)sy(12,e);else{var h=Nj;g=Ee(b,h,2);f=f?f:new h;h=A(b,2);g.push(f);h.push(Fe(f));sy(19,e)}if(!Ee(b,Nj,2).length)return null;a=new be;c=Ee(b,Kj, 1);0<c.length&&le(a,1,c,Mj);c=Ee(b,Nj,2);0<c.length&&le(a,2,c,Pj);return Yd(ee(a),void 0)};var uy=function(){this.g=[];this.h=[];this.l=[]};var vy=function(){var a=this;this.promise=new Promise(function(b,c){a.resolve=b;a.reject=c})};var wy=function(a){a=Error.call(this,a);this.message=a.message;"stack"in a&&(this.stack=a.stack);Object.setPrototypeOf(this,wy.prototype);this.name="InputError"};t(wy,Error);var yy=function(){var a=this;this.C=this.l=null;this.o=-1;this.h=new vy;this.g=!1;this.h.promise.then(function(){-1!==a.o&&(a.C=og()-a.o)},function(){})},zy=function(){yy.apply(this,arguments)};t(zy,yy);var Ay=function(a,b){a.g||(a.g=!0,a.l=b,a.h.resolve(b))},By=function(a){a.g||(a.g=!0,a.l=null,a.h.resolve(null))}; da.Object.defineProperties(zy.prototype,{promise:{configurable:!0,enumerable:!0,get:function(){return this.h.promise}},B:{configurable:!0,enumerable:!0,get:function(){return this.g}}});var Cy=function(a){yy.call(this);this.B=a};t(Cy,yy);da.Object.defineProperties(Cy.prototype,{value:{configurable:!0,enumerable:!0,get:function(){return this.B.l}},error:{configurable:!0,enumerable:!0,get:function(){return this.B.A}}});function Dy(a,b){return $a(this,function d(){var e,f,g;return za(d,function(h){if(1==h.g)return e=0<b?a.filter(function(k){return!k.nd}):a,sa(h,Promise.all(e.map(function(k){return k.td.promise})),2);if(3!=h.g){if(a.length===e.length)return h.return(0);f=a.filter(function(k){return k.nd});g=og();return sa(h,Promise.race([Promise.all(f.map(function(k){return k.td.promise})),new Promise(function(k){return void setTimeout(k,b)})]),3)}return h.return(og()-g)})})} var Ey=function(a,b){b=void 0===b?0:b;J.call(this);var c=this;this.id=a;this.F=b;this.g=new uy;this.C=!1;this.I=-1;ii(this,function(){var d=c.g;d.g.length=0;d.l.length=0;d.h.length=0})};t(Ey,J); Ey.prototype.start=function(){return $a(this,function b(){var c=this,d,e,f,g;return za(b,function(h){switch(h.g){case 1:if(c.C)return h.return();c.C=!0;h.h=2;return sa(h,Dy(c.g.h,c.F),4);case 4:c.I=h.A;if(c.Za()){h.g=5;break}for(var k=0,n=q(c.g.l),m=n.next();!m.done;m=n.next()){if(null===m.value.B.l)throw Error("missing input: "+c.id+"/"+k);++k}d=q(c.g.g);for(e=d.next();!e.done;e=d.next())f=e.value,f.o=og();return sa(h,c.A(),5);case 5:h.g=0;h.h=0;break;case 2:g=ta(h);if(c.Za())return h.return();if(!(g instanceof wy)&&g instanceof Error&&(c.L(c.id,g),c.g.g.length))for(k=new wy(g.message),n=q(c.g.g),m=n.next();!m.done;m=n.next())if(m=m.value,!m.B){var v=k;m.g=!0;m.A=v;m.h.reject(v)}h.g=0}})})};var Fy=function(a){var b=new zy;a.g.g.push(b);return b},Gy=function(a,b){a.g.h.push({nd:!1,td:b});return new Cy(b)};var Hy=function(a,b){Ey.call(this,a);this.id=a;this.L=b};t(Hy,Ey);var Iy=function(a,b,c,d){Hy.call(this,655,d);this.Fa=a;this.B=b;this.H=c;this.l=Fy(this);this.o=Fy(this);this.h=rx(Er)};t(Iy,Hy); Iy.prototype.A=function(){var a,b=py().get(this.Fa,this.H);if(b.getError())sy(b.getError(),this.Fa,b.getErrorMessage()),By(this.l),By(this.o);else{var c=Date.now();if(b=b.Wc)if(this.h&&(null==A(b,8)&&(sy(33,this.Fa),Oj(b,this.h)),null==A(b,7)&&(sy(34,this.Fa),Ae(b,7,Math.round(Date.now()/1E3/60)))),null!=A(b,3)||sy(35,this.Fa),this.h){var d=ve(b,8),e=null!==(a=A(b,7))&&void 0!==a?a:c;d<this.h&&Oj(b,Math.min(d+Number((this.h*(c/1E3/60-e)/60).toFixed(3)),this.h));1>ve(b,8)?(c={},sy(22,this.Fa,null, (c.t=String(e),c.cr=String(d),c.cs=String(qy(b)),c)),By(this.l),By(this.o)):(Ay(this.l,this.B),Ay(this.o,b))}else Ay(this.l,this.B),Ay(this.o,b);else Ay(this.l,this.B),b=this.o,d=new Nj,d=Ae(d,1,this.Fa),d=Oj(d,this.h),c=Ae(d,3,c),Ay(b,c)}};function Jy(a,b,c,d){sy(18,a);try{var e=og();rx(Er)&&(Oj(b,Number((ve(b,8)-1).toFixed(3))),Ae(b,7,Math.round(e/1E3/60)));return c().then(function(f){sy(29,a,null,{delta:String(og()-e)});Ae(b,3,Date.now());Ky(a,b,f,d);return b}).catch(function(f){Ky(a,b,A(b,2),d);sy(28,a,Ly(f));return b})}catch(f){return Ky(a,b,A(b,2),d),sy(1,a,Ly(f)),Promise.resolve(b)}} var Ky=function(a,b,c,d){"string"!==typeof c?sy(21,a):c||sy(20,a);Ae(b,2,c);b=py().set(b,d);b.getErrorMessage()?sy(b.info,a,b.getErrorMessage()):sy(27,a)},Ly=function(a){return"string"===typeof a?a:a instanceof Error?a.message:null};var My=function(a,b,c,d){Hy.call(this,658,d);this.H=c;this.h=Fy(this);this.l=Fy(this);this.o=Fy(this);this.B=Gy(this,a);this.M=Gy(this,b)};t(My,Hy); My.prototype.A=function(){var a=this;if(this.B.value){var b=function(g){Ay(a.h,{id:A(g,1),ue:A(g,2)})},c=this.B.value,d=this.M.value,e=A(d,1),f=qy(d);switch(f){case 0:sy(24,e);break;case 1:sy(25,e);break;case 2:sy(26,e);break;case 3:sy(9,e);break;case 4:sy(23,e)}switch(f){case 0:b(d);Ny(this);break;case 1:b(d);Ay(this.l,c);Ay(this.o,d);break;case 3:case 2:case 4:Ae(d,2,null),Jy(e,d,c,this.H).then(b),Ny(this)}}else By(this.h),Ny(this)};var Ny=function(a){By(a.l);By(a.o)};function Oy(){var a=window;var b=void 0===b?function(){}:b;return new Promise(function(c){var d=function(){c(b());Qe(a,"load",d)};Pe(a,"load",d)})};var Py=function(a,b,c,d){Hy.call(this,662,d);this.o=c;this.h=Gy(this,a);this.l=Gy(this,b)};t(Py,Hy);Py.prototype.A=function(){var a=this;this.l.value&&this.h.value&&Oy().then(function(){var b=a.l.value,c=A(b,1);Jy(c,b,a.h.value,a.o)})};var Qy=function(){J.apply(this,arguments);this.g=[]};t(Qy,J);Qy.prototype.O=function(){J.prototype.O.call(this);this.g.length=0};function Ry(a,b,c,d){return $a(this,function f(){var g,h,k,n,m;return za(f,function(v){if(1==v.g){g=new Iy(a,b,c,d);h=new My(g.l,g.o,c,d);k=new Py(h.l,h.o,c,d);n=new Qy;for(var r=q([g,h,k]),w=r.next();!w.done;w=r.next())w=w.value,ji(n,w),n.g.push(w);if(n.g.length)for(r=q(n.g),w=r.next();!w.done;w=r.next())w.value.start();return sa(v,h.h.promise,2)}m=v.A;return v.return(m?m:{id:a,ue:null})})})};function Sy(a,b,c,d){var e,f=null!==(e=a.encryptedSignalSource)&&void 0!==e?e:a.encryptedSignalSource={};return c?xf()===yf()||qx(Dr)?b.map(function(g){var h=g.Fa;if((g=Object.getOwnPropertyDescriptor(f,h))&&!g.configurable)return Promise.resolve(null);var k=!1;return new Promise(function(n){var m=f[h];Object.defineProperty(f,h,{set:function(v){if(!k){k=!0;if("function"===typeof v){var r={};sy(17,h,null,(r.api="0",r));v=Ry(h,v,c,d)}else sy(14,h),v=Promise.resolve(null);v.then(n)}}});m&&(f[h]=m)})}): (sy(16,""),[]):(sy(15,""),[])};function Ty(a){if(!a||Fx(a))return null;try{return window.localStorage}catch(b){return null}}function Uy(a,b){return(b=Ty(b))&&0!=a.length?Sy(u.googletag||(u.googletag={}),a,b,function(){}):null};var Vy=function(){K.call(this);this.H=!1;this.g=null;this.A=this.F=this.M=!1;this.h=0;this.o=[];this.C=!1;this.T=this.N=Infinity;this.l=0;this.L=new U(this);ji(this,this.L);this.I={}};t(Vy,K); var Xy=function(a,b){null==b||a.H||(a.g=b,Wy(a),a.H=!0)},Zy=function(a){null!=a.g&&a.H&&(Yy(a),a.H=!1,a.F=!1,a.A=!1,a.h=0,a.o=[],a.C=!1)},Wy=function(a){Yy(a);!(a.g instanceof K)&&"ontouchstart"in document.documentElement&&Ed?(a.I={touchstart:function(b){a.F=!0;a.h=b.touches.length;a.l&&(window.clearTimeout(a.l),a.l=0,a.M=!0);a.C=$y(a,b.touches)||1!=b.touches.length;a.C?(a.N=Infinity,a.T=Infinity):(a.N=b.touches[0].clientX,a.T=b.touches[0].clientY);b=b.touches;a.o=[];for(var c=0;c<b.length;c++)a.o.push(b[c].identifier)}, touchmove:function(b){a.h=b.touches.length;if(!Mt(8)||Math.pow(b.changedTouches[0].clientX-a.N,2)+Math.pow(b.changedTouches[0].clientY-a.T,2)>Math.pow(5,2))a.A=!0},touchend:function(b){return void az(a,b)}},Cb(a.I,function(b,c){a.g.addEventListener(c,b,!1)})):a.L.P(a.g,"click",a.U)},Yy=function(a){a.L.Ua(a.g,"click",a.U);Cb(a.I,function(b,c){this.g.removeEventListener(c,b,!1)},a);a.I={}},az=function(a,b){!a.F||1!=a.h||a.A||a.M||a.C||!$y(a,b.changedTouches)||(a.l=window.setTimeout(function(){return void bz(a)}, 300));a.h=b.touches.length;0==a.h&&(a.F=!1,a.A=!1,a.o=[]);a.M=!1};Vy.prototype.U=function(){bz(this)};var $y=function(a,b){for(var c=0;c<b.length;c++)if(a.o.includes(b[c].identifier))return!0;return!1},bz=function(a){a.l=0;a.dispatchEvent(new ki("click"))};Vy.prototype.O=function(){Zy(this);K.prototype.O.call(this)};var cz=function(a,b,c){this.h=c;0==b.length&&(b=[[]]);this.g=b.map(function(d){d=a.concat(d);for(var e=[],f=0,g=0;f<d.length;){var h=d[f++];if(128>h)e[g++]=String.fromCharCode(h);else if(191<h&&224>h){var k=d[f++];e[g++]=String.fromCharCode((h&31)<<6|k&63)}else if(239<h&&365>h){k=d[f++];var n=d[f++],m=d[f++];h=((h&7)<<18|(k&63)<<12|(n&63)<<6|m&63)-65536;e[g++]=String.fromCharCode(55296+(h>>10));e[g++]=String.fromCharCode(56320+(h&1023))}else k=d[f++],n=d[f++],e[g++]=String.fromCharCode((h&15)<<12| (k&63)<<6|n&63)}return new RegExp(e.join(""))})};cz.prototype.match=function(a){var b=this;return this.g.some(function(c){c=a.match(c);return null==c?!1:!b.h||1<=c.length&&"3.467.0"==c[1]||2<=c.length&&"3.467.0"==c[2]?!0:!1})}; var dz=[104,116,116,112,115,63,58,47,47,105,109,97,115,100,107,92,46,103,111,111,103,108,101,97,112,105,115,92,46,99,111,109,47,106,115,47,40,115,100,107,108,111,97,100,101,114,124,99,111,114,101,41,47],ez=[104,116,116,112,115,63,58,47,47,115,48,92,46,50,109,100,110,92,46,110,101,116,47,105,110,115,116,114,101,97,109,47,104,116,109,108,53,47],fz=[104,116,116,112,115,63,58,47,47,105,109,97,115,100,107,92,46,103,111,111,103,108,101,97,112,105,115,92,46,99,111,109,47,112,114,101,114,101,108,101,97,115, 101,47,106,115,47,91,48,45,57,93,43,92,46,91,48,45,57,92,46,93,43,47],gz=[[105,109,97,51,92,46,106,115],[105,109,97,51,95,100,101,98,117,103,92,46,106,115]],hz=[[98,114,105,100,103,101,40,91,48,45,57,93,43,92,46,91,48,45,57,92,46,93,43,41,40,95,40,91,97,45,122,48,45,57,93,41,123,50,44,51,125,41,123,48,44,50,125,92,46,104,116,109,108],[98,114,105,100,103,101,40,91,48,45,57,93,43,92,46,91,48,45,57,92,46,93,43,41,95,100,101,98,117,103,40,95,40,91,97,45,122,48,45,57,93,41,123,50,44,51,125,41,123,48,44, 50,125,92,46,104,116,109,108],[98,114,105,100,103,101,40,95,40,91,97,45,122,48,45,57,93,41,123,50,44,51,125,41,123,48,44,50,125,92,46,104,116,109,108]],iz=[[111,117,116,115,116,114,101,97,109,92,46,106,115],[111,117,116,115,116,114,101,97,109,95,100,101,98,117,103,92,46,106,115]],jz=new cz(dz,gz,!1),kz=new cz(dz,hz,!0),lz=new cz(ez,gz,!1),mz=new cz(ez,hz,!0),nz=new cz(fz,gz,!1),oz=new cz([104,116,116,112,115,63,58,47,47,40,112,97,103,101,97,100,50,124,116,112,99,41,92,46,103,111,111,103,108,101,115, 121,110,100,105,99,97,116,105,111,110,92,46,99,111,109,47,112,97,103,101,97,100,47,40,103,97,100,103,101,116,115,124,106,115,41,47],[],!1),pz=new cz(dz,[[100,97,105,95,105,102,114,97,109,101,40,91,48,45,57,93,43,92,46,91,48,45,57,92,46,93,43,41,40,95,40,91,97,45,122,48,45,57,93,41,123,50,44,51,125,41,123,48,44,50,125,92,46,104,116,109,108],[100,97,105,95,105,102,114,97,109,101,40,91,48,45,57,93,43,92,46,91,48,45,57,92,46,93,43,41,95,100,101,98,117,103,40,95,40,91,97,45,122,48,45,57,93,41,123,50,44, 51,125,41,123,48,44,50,125,92,46,104,116,109,108],[100,97,105,95,105,102,114,97,109,101,40,95,40,91,97,45,122,48,45,57,93,41,123,50,44,51,125,41,123,48,44,50,125,92,46,104,116,109,108]],!0),qz=new cz(dz,iz,!1),rz=new cz(fz,iz,!1),Fb={cg:jz,ag:kz,wg:lz,vg:mz,dg:nz,Zg:oz,bg:pz,Gg:qz,Hg:rz};function sz(a){for(var b=null,c=0;c<a.length;c++)if(b=a[c],Eb(function(d){return d.match(b.src)}))return b;return null};var tz=function(){var a=D(),b=document;return new O(a.parent==a?a.location.href:b.referrer)},uz=function(a,b){ys(a,"url","");try{var c=2083-a.toString().length-1;if(0>=c)return a.toString();for(var d=b.slice(0,c),e=encodeURIComponent(d),f=c;0<f&&e.length>c;)d=b.slice(0,f--),e=encodeURIComponent(d);ys(a,"url",d)}catch(g){}return a.toString()};var vz=function(){this.g=.01>Math.random();this.h=Math.floor(4503599627370496*Math.random())}; vz.prototype.report=function(a,b,c){b=void 0===b?{}:b;if(null==u.G_testRunner&&(this.g||(void 0===c?0:c))){b.lid=a;b.sdkv=Kx();a=kh().sort().join(",");fc($c(a))||(b.e=a);b=wz(this,b);var d=new O("http://pagead2.googlesyndication.com/pagead/gen_204");Cb(b,function(e,f){ys(d,f,null==e?"":"boolean"==typeof e?e?"t":"f":""+e)},this);b=tz();ks(d,b.o);b=d.toString();a=d.l.get("url");null!=a&&Gc()&&2083<b.length&&(b=uz(d,a));by(b)}};var wz=function(a,b){b.id="ima_html5";var c=tz();b.c=a.h;b.domain=c.g;return b}; Ka(vz);var xz=function(a,b,c,d,e){e=void 0===e?"":e;ki.call(this,a);this.ka=b;this.na=c;this.Mb=d;this.Gd=e};t(xz,ki);xz.prototype.toString=function(){return""};var yz=function(a){this.g=a};l=yz.prototype;l.getTotalAds=function(){return this.g.totalAds};l.getMaxDuration=function(){return this.g.maxDuration};l.getAdPosition=function(){return this.g.adPosition};l.getPodIndex=function(){return this.g.podIndex};l.getTimeOffset=function(){return this.g.timeOffset};l.getIsBumper=function(){return this.g.isBumper};yz.prototype.getIsBumper=yz.prototype.getIsBumper;yz.prototype.getTimeOffset=yz.prototype.getTimeOffset;yz.prototype.getPodIndex=yz.prototype.getPodIndex; yz.prototype.getAdPosition=yz.prototype.getAdPosition;yz.prototype.getMaxDuration=yz.prototype.getMaxDuration;yz.prototype.getTotalAds=yz.prototype.getTotalAds;var zz=function(a){this.g=a};l=zz.prototype;l.getContent=function(){return this.g.content};l.getContentType=function(){return this.g.contentType};l.getWidth=function(){return this.g.size.width};l.getHeight=function(){return this.g.size.height};l.xd=function(){return this.g.adSlotId};var Yx=function(a){return(a=a.g.backupCompanions)?a.map(function(b){return new zz(b)}):[]};zz.prototype.getAdSlotId=zz.prototype.xd;zz.prototype.getHeight=zz.prototype.getHeight;zz.prototype.getWidth=zz.prototype.getWidth; zz.prototype.getContentType=zz.prototype.getContentType;zz.prototype.getContent=zz.prototype.getContent;var Az=function(a,b){this.h=a;this.g=b};Az.prototype.getAdIdValue=function(){return this.h};Az.prototype.getAdIdRegistry=function(){return this.g};Az.prototype.getAdIdRegistry=Az.prototype.getAdIdRegistry;Az.prototype.getAdIdValue=Az.prototype.getAdIdValue;var Y=function(a){this.g=a};Y.prototype.getAdId=function(){return this.g.adId};Y.prototype.getCreativeAdId=function(){return this.g.creativeAdId};Y.prototype.getCreativeId=function(){return this.g.creativeId};var Bz=function(a){return a.g.adQueryId};l=Y.prototype;l.getAdSystem=function(){return this.g.adSystem};l.getAdvertiserName=function(){return this.g.advertiserName};l.getApiFramework=function(){return this.g.apiFramework};l.getWrapperAdIds=function(){return this.g.adWrapperIds}; l.getWrapperCreativeIds=function(){return this.g.adWrapperCreativeIds};l.getWrapperAdSystems=function(){return this.g.adWrapperSystems};l.isLinear=function(){return this.g.linear};l.isSkippable=function(){return this.g.skippable};l.getContentType=function(){return this.g.contentType};l.Ce=function(){return this.g.description};l.Ee=function(){return this.g.title};l.getDuration=function(){return this.g.duration};l.getVastMediaWidth=function(){return this.g.vastMediaWidth};l.getVastMediaHeight=function(){return this.g.vastMediaHeight}; l.getWidth=function(){return this.g.width};l.getHeight=function(){return this.g.height};l.getUiElements=function(){return this.g.uiElements};l.getMinSuggestedDuration=function(){return this.g.minSuggestedDuration};l.getAdPodInfo=function(){return new yz(this.g.adPodInfo)};l.getCompanionAds=function(a,b,c){var d=this.g.companions.map(function(e){return new zz(e)});return Xx(new Ux(new Ve(a,b),c),d)};l.getTraffickingParameters=function(){return Zt($c(this.g.traffickingParameters))}; l.getTraffickingParametersString=function(){return this.g.traffickingParameters};l.getVastMediaBitrate=function(){return this.g.vastMediaBitrate};l.getMediaUrl=function(){return this.g.mediaUrl};l.getSurveyUrl=function(){return this.g.surveyUrl};l.getDealId=function(){return this.g.dealId};l.Fe=function(){return(this.g.universalAdIds||[]).map(function(a){return new Az(a.adIdValue,a.adIdRegistry)})};l.getUniversalAdIdValue=function(){return this.g.universalAdIdValue};l.getUniversalAdIdRegistry=function(){return this.g.universalAdIdRegistry}; l.getSkipTimeOffset=function(){return this.g.skipTimeOffset};l.isUiDisabled=function(){return this.g.disableUi};Y.prototype.isUiDisabled=Y.prototype.isUiDisabled;Y.prototype.getSkipTimeOffset=Y.prototype.getSkipTimeOffset;Y.prototype.getUniversalAdIdRegistry=Y.prototype.getUniversalAdIdRegistry;Y.prototype.getUniversalAdIdValue=Y.prototype.getUniversalAdIdValue;Y.prototype.getUniversalAdIds=Y.prototype.Fe;Y.prototype.getDealId=Y.prototype.getDealId;Y.prototype.getSurveyUrl=Y.prototype.getSurveyUrl; Y.prototype.getMediaUrl=Y.prototype.getMediaUrl;Y.prototype.getVastMediaBitrate=Y.prototype.getVastMediaBitrate;Y.prototype.getTraffickingParametersString=Y.prototype.getTraffickingParametersString;Y.prototype.getTraffickingParameters=Y.prototype.getTraffickingParameters;Y.prototype.getCompanionAds=Y.prototype.getCompanionAds;Y.prototype.getAdPodInfo=Y.prototype.getAdPodInfo;Y.prototype.getMinSuggestedDuration=Y.prototype.getMinSuggestedDuration;Y.prototype.getUiElements=Y.prototype.getUiElements; Y.prototype.getHeight=Y.prototype.getHeight;Y.prototype.getWidth=Y.prototype.getWidth;Y.prototype.getVastMediaHeight=Y.prototype.getVastMediaHeight;Y.prototype.getVastMediaWidth=Y.prototype.getVastMediaWidth;Y.prototype.getDuration=Y.prototype.getDuration;Y.prototype.getTitle=Y.prototype.Ee;Y.prototype.getDescription=Y.prototype.Ce;Y.prototype.getContentType=Y.prototype.getContentType;Y.prototype.isSkippable=Y.prototype.isSkippable;Y.prototype.isLinear=Y.prototype.isLinear; Y.prototype.getWrapperAdSystems=Y.prototype.getWrapperAdSystems;Y.prototype.getWrapperCreativeIds=Y.prototype.getWrapperCreativeIds;Y.prototype.getWrapperAdIds=Y.prototype.getWrapperAdIds;Y.prototype.getApiFramework=Y.prototype.getApiFramework;Y.prototype.getAdvertiserName=Y.prototype.getAdvertiserName;Y.prototype.getAdSystem=Y.prototype.getAdSystem;Y.prototype.getCreativeId=Y.prototype.getCreativeId;Y.prototype.getCreativeAdId=Y.prototype.getCreativeAdId;Y.prototype.getAdId=Y.prototype.getAdId;var Cz=null,Dz=function(){K.call(this);this.g=null;this.F=new U(this);ji(this,this.F);this.h=new Map;this.o=new Map;this.l=this.A=!1;this.C=null},Ez;t(Dz,K);var Fz=function(){null==Cz&&(Cz=new Dz);return Cz},xq=function(a,b,c){var d={};d.queryId=b;d.viewabilityData=c;a.g&&ay(a.g,"activityMonitor","viewabilityMeasurement",d)};Dz.prototype.destroy=function(){this.F.Ua(this.g,"activityMonitor",this.H);this.l=!1;this.h.clear();this===Ez&&(Ez=null)};Dz.prototype.O=function(){this.destroy();K.prototype.O.call(this)}; Dz.prototype.init=function(a){if(!this.l){if(this.g=a||null)this.F.P(this.g,"activityMonitor",this.H),Gz(this);if(!(u.ima&&u.ima.video&&u.ima.video.client&&u.ima.video.client.tagged)){x("ima.video.client.sdkTag",!0,void 0);var b=u.document;a=ef(document,"SCRIPT");var c=dc(Zb($b("https://s0.2mdn.net/instream/video/client.js")));a.src=cc(c);Ke(a);a.async=!0;a.type="text/javascript";b=b.getElementsByTagName("script")[0];b.parentNode.insertBefore(a,b)}Ok();nq.D().L=W.g;this.A=!0;nq.D().l=!0;this.C=null; a=nq.D();b="h"==Np(a)||"b"==Np(a);c=!(M.D(),!1);b&&c&&(a.K=!0,a.H=new Xn);this.l=!0}}; var Iz=function(a){if(null==a)return!1;if((Bd||Dd)&&null!=a.webkitDisplayingFullscreen)return a.webkitDisplayingFullscreen;a=Hz(a);var b=window.screen.availHeight||window.screen.height;return 0>=(window.screen.availWidth||window.screen.width)-a.width&&42>=b-a.height},Hz=function(a){var b={left:a.offsetLeft,top:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight};try{"function"===typeof a.getBoundingClientRect&&kf(Xe(a),a)&&(b=a.getBoundingClientRect())}catch(c){}return b},Jz=function(a,b,c,d,e){e= void 0===e?{}:e;if(a.l){d&&null==e.opt_osdId&&(e.opt_osdId=d);if(a.C)return a.C(b,c,e);if(a=d?a.o.get(d):W.l)null==e.opt_fullscreen&&(e.opt_fullscreen=Iz(a)),null==e.opt_adElement&&(e.opt_adElement=a);return kk.gb(469,Wa(Aq,b,c,e),void 0)||{}}return{}},Kz=function(a,b){var c=String(Math.floor(1E9*Math.random()));a.o.set(c,b);if(gh($h))try{Hj(function(d){if(a.g){var e={};e.engagementString=d;ay(a.g,"activityMonitor","engagementData",e)}},function(){return b})}catch(d){}0!=W.g&&yq(nq.D(),c,a);return c}, Lz=function(a,b,c){if(c)a.h.get(c)==b&&a.h.delete(c);else{var d=[];a.h.forEach(function(e,f){e==b&&d.push(f)});d.forEach(a.h.delete,a.h)}},tq=function(a,b){a=a.h.get(b);return"function"===typeof a?a():{}},Gz=function(a){if("function"===typeof window.Goog_AdSense_Lidar_getUrlSignalsArray){var b={};b.pageSignals=window.Goog_AdSense_Lidar_getUrlSignalsArray();ay(a.g,"activityMonitor","pageSignals",b)}}; Dz.prototype.H=function(a){var b=a.na,c=b.queryId,d={},e=null;d.eventId=b.eventId;switch(a.ka){case "getPageSignals":Gz(this);break;case "reportVastEvent":e=b.vastEvent;a=b.osdId;var f={};f.opt_fullscreen=b.isFullscreen;b.isOverlay&&(f.opt_bounds=b.overlayBounds);d.viewabilityData=Jz(this,e,c,a,f);ay(this.g,"activityMonitor","viewability",d);break;case "fetchAdTagUrl":c={},c.eventId=b.eventId,a=b.osdId,Lb(b,"isFullscreen")&&(e=b.isFullscreen),Lb(b,"loggingId")&&(b=b.loggingId,c.loggingId=b,vz.D().report(43, {step:"beforeLookup",logid:b,time:Date.now()})),c.engagementString=Mz(this,a,e),this.g&&ay(this.g,"activityMonitor","engagement",c)}};var Mz=function(a,b,c){var d=b?a.o.get(b):W.l;a={};null!=c&&(a.fullscreen=c);c="";try{c=Gj(function(){return d},a)}catch(e){c="sdktle;"+Xc(e.name,12)+";"+Xc(e.message,40)}return c};x("ima.common.getVideoMetadata",function(a){return tq(Fz(),a)},void 0);x("ima.common.triggerViewabilityMeasurementUpdate",function(a,b){xq(Fz(),a,b)},void 0);var Nz=ud?dc(Zb($b('javascript:""'))):dc(Zb($b("about:blank")));cc(Nz);var Oz=ud?dc(Zb($b('javascript:""'))):dc(Zb($b("javascript:undefined")));cc(Oz);var Pz=function(a,b,c){b=void 0===b?null:b;c=void 0===c?null:c;ki.call(this,a);this.l=b;this.g=c};t(Pz,ki);Pz.prototype.getAd=function(){return this.l};Pz.prototype.getAdData=function(){return this.g};var Qz=function(){this.loadVideoTimeout=8E3;this.autoAlign=!0;this.bitrate=-1;this.uiElements=null;this.enablePreloading=this.disableClickThrough=!1;this.mimeTypes=null;this.useStyledNonLinearAds=this.useStyledLinearAds=this.useLearnMoreButton=this.restoreCustomPlaybackStateOnAdBreakComplete=!1;this.playAdsAfterTime=-1;this.useVideoAdUi=!0;this.disableUi=!1},Rz=function(a,b){var c={};Object.assign(c,a);b&&(c.disableClickThrough=!0);return c}; Qz.prototype.append=function(a){if(a){this.autoAlign=a.autoAlign||this.autoAlign;var b=ed(a.bitrate);"number"===typeof b&&!isNaN(b)&&0<b&&(this.bitrate=b);this.disableClickThrough=a.disableClickThrough||this.disableClickThrough;this.disableUi=a.disableUi||this.disableUi;this.enablePreloading=a.enablePreloading||this.enablePreloading;a.mimeTypes&&0!=a.mimeTypes.length&&(this.mimeTypes=a.mimeTypes);b=ed(a.playAdsAfterTime);"number"===typeof b&&!isNaN(b)&&0<b&&(this.playAdsAfterTime=b);this.restoreCustomPlaybackStateOnAdBreakComplete= a.restoreCustomPlaybackStateOnAdBreakComplete||this.restoreCustomPlaybackStateOnAdBreakComplete;b=ed(a.loadVideoTimeout);"number"===typeof b&&!isNaN(b)&&0<b&&(this.loadVideoTimeout=b);this.uiElements=a.uiElements||this.uiElements;this.useLearnMoreButton=a.useLearnMoreButton||this.useLearnMoreButton;this.useStyledLinearAds=a.useStyledLinearAds||this.useStyledLinearAds;this.useStyledNonLinearAds=a.useStyledNonLinearAds||this.useStyledNonLinearAds;this.useVideoAdUi=!1===a.useVideoAdUi?!1:this.useVideoAdUi}}; x("module$contents$ima$AdsRenderingSettings_AdsRenderingSettings.AUTO_SCALE",-1,void 0);var Sz=null,Tz=function(){K.call(this);this.g=new hs;this.h=null;this.o=new Map;this.l=new U(this);ji(this,this.l);this.A=new Map;this.H=null;this.F=-1;M.D().l=!0;Ox()};t(Tz,K); var Uz=function(){null==Sz&&(Sz=new Tz);return Sz},Vz=function(a,b){var c={};c.queryId=a;c.viewabilityString=b;Uz().dispatchEvent(new Pz("measurable_impression",null,c))},Wz=function(a,b){var c={};c.queryId=a;c.viewabilityString=b;Uz().dispatchEvent(new Pz("viewable_impression",null,c))},Xz=function(a,b,c){var d={};d.queryId=a;d.viewabilityString=b;d.eventName=c;Uz().dispatchEvent(new Pz("externalActivityEvent",null,d))}; Tz.prototype.destroy=function(){this.l.Ua(this.h,"activityMonitor",this.C);this.h=null}; Tz.prototype.C=function(a){var b=a.na;switch(a.ka){case "appStateChanged":nq.D();b=b.appState;a=N.D();a.K!=b&&(a.K=b,(a=no.D().g)&&lm(a.g,!b));break;case "externalActivityEvent":Xz(b.queryId,b.viewabilityString,b.eventName);break;case "measurableImpression":Vz(b.queryId,b.viewabilityString);break;case "viewableImpression":Wz(b.queryId,b.viewabilityString);break;case "engagementData":b=b.engagementString;Uz().H=b;Uz().F=Xa();break;case "viewability":a=b.queryId;var c=b.vastEvent;this.o.get(a)&&"start"== c&&this.o.get(a);a=b.eventId;clearTimeout(a);if(c=this.g.get(a))this.g.remove(a),c(b.viewabilityData);break;case "viewabilityMeasurement":nq.D();M.D();break;case "engagement":a=b.eventId;clearTimeout(a);c=this.g.get(a);if(vz.D().g){var d=-1;this.I&&(d=Xa()-this.I);var e=!1;c||(e=!0);Lb(b,"loggingId")&&vz.D().report(43,{step:"receivedResponse",time:Xa(),timeout:e,logid:b.loggingId,timediff:d})}c&&(this.g.remove(a),c(b.engagementString))}}; x("ima.bridge.getNativeViewability",function(a,b){Uz();b({})},void 0);x("ima.bridge.getVideoMetadata",function(a){return(a=Uz().A.get(a))?a():{}},void 0);x("ima.bridge.triggerViewEvent",Wz,void 0);x("ima.bridge.triggerMeasurableEvent",Vz,void 0);x("ima.bridge.triggerExternalActivityEvent",Xz,void 0);Object.entries({"application/dash+xml":1,"application/x-javascript":2,"application/x-mpegurl":3,"application/javascript":4,"audio/ogg":5,"audio/mp4":6,"audio/mpeg":7,"audio/wav":8,"text/javascript":9,"video/m4v":10,"video/ogg":11,"video/x-flv":12,"video/3gpp":13,"video/mpt2":14,"video/mp4":15,"video/mpeg":16,"video/quicktime":17,"video/webm":18});function Yz(a,b){return b instanceof RegExp?"__REGEXP"+b.toString():b}function Zz(a,b){return b&&0==b.toString().indexOf("__REGEXP")?(a=b.split("__REGEXP")[1].match(/\/(.*)\/(.*)?/),new RegExp(a[1],a[2]||"")):b}var $z=function(a,b){$x.call(this,b);this.A=a;this.g=null;this.C=new U(this);this.C.P(D(),"message",this.F)};t($z,$x);var aA=function(a){if(null==a||"string"!==typeof a||0!=a.lastIndexOf("ima://",0))return null;a=a.substr(6);try{return JSON.parse(a,Zz)}catch(b){return null}}; $z.prototype.sendMessage=function(a,b,c){if(null!=this.g&&null!=this.g.postMessage){var d=this.g,e=d.postMessage,f={};f.name=a;f.type=b;null!=c&&(f.data=c);f.sid=this.h;f.channel=this.A;a="ima://"+Wg(f,Yz);e.call(d,a,"*")}null!=this.g&&null==this.g.postMessage&&vz.D().report(11)};$z.prototype.O=function(){hi(this.C);this.g=null;$x.prototype.O.call(this)}; $z.prototype.F=function(a){a=a.g;var b=aA(a.data);if(bA(this,b)){if(null==this.g)this.g=a.source,this.l||this.connect();else if(this.g!=a.source)return;bA(this,b)&&this.dispatchEvent(new xz(b.name,b.type,b.data||{},b.sid,a.origin))}};var bA=function(a,b){if(null==b)return!1;var c=b.channel;if(null==c||c!=a.A)return!1;b=b.sid;return null==b||"*"!=a.h&&b!=a.h?!1:!0};var cA=dc(Zb($b("https://pagead2.googlesyndication.com/omsdk/releases/live/omweb-v1.js")));var dA={LOADED:"loaded",uc:"start",FIRST_QUARTILE:"firstQuartile",MIDPOINT:"midpoint",THIRD_QUARTILE:"thirdQuartile",COMPLETE:"complete",tc:"pause",kd:"resume",bd:"bufferStart",$c:"bufferFinish",SKIPPED:"skipped",oe:"volumeChange",Kg:"playerStateChange",zf:"adUserInteraction"};function eA(a,b){if(!b)throw Error("Value for "+a+" is undefined, null or blank.");if("string"!==typeof b&&!(b instanceof String))throw Error("Value for "+a+" is not a string.");if(""===b.trim())throw Error("Value for "+a+" is empty string.");}function fA(a,b){if(null==b)throw Error("Value for "+a+" is undefined or null");}function gA(a,b){if(null==b)throw Error(a+" must not be null or undefined.");if("number"!==typeof b||isNaN(b))throw Error("Value for "+a+" is not a number");};function hA(a,b){return a&&(a[b]||(a[b]={}))}function iA(a,b){var c;if(c=void 0===c?"undefined"===typeof omidExports?null:omidExports:c)a=a.split("."),a.slice(0,a.length-1).reduce(hA,c)[a[a.length-1]]=b};function jA(){return/\d+\.\d+\.\d+(-.*)?/.test("1.3.20-google_20210603")}function kA(){for(var a=["1","3","20"],b=["1","0","3"],c=0;3>c;c++){var d=parseInt(a[c],10),e=parseInt(b[c],10);if(d>e)break;else if(d<e)return!1}return!0};var lA=function(a,b,c,d){this.h=a;this.method=b;this.version=c;this.g=d},mA=function(a){return!!a&&void 0!==a.omid_message_guid&&void 0!==a.omid_message_method&&void 0!==a.omid_message_version&&"string"===typeof a.omid_message_guid&&"string"===typeof a.omid_message_method&&"string"===typeof a.omid_message_version&&(void 0===a.omid_message_args||void 0!==a.omid_message_args)},nA=function(a){return new lA(a.omid_message_guid,a.omid_message_method,a.omid_message_version,a.omid_message_args)},oA=function(a){var b= {};b=(b.omid_message_guid=a.h,b.omid_message_method=a.method,b.omid_message_version=a.version,b);void 0!==a.g&&(b.omid_message_args=a.g);return b};var pA=function(a){this.h=a};function qA(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(a){var b=16*Math.random()|0;return"y"===a?(b&3|8).toString(16):b.toString(16)})};function rA(a){for(var b=[],c=0;c<arguments.length;++c)b[c-0]=arguments[c];sA(function(){throw new (Function.prototype.bind.apply(Error,[null,"Could not complete the test successfully - "].concat(fa(b))));},function(){return console.error.apply(console,fa(b))})}function sA(a,b){"undefined"!==typeof jasmine&&jasmine?a():"undefined"!==typeof console&&console&&console.error&&b()};var tA=function(a){try{return a.frames?!!a.frames.omid_v1_present:!1}catch(b){return!1}};var uA=function(a){this.h=a;this.handleExportedMessage=uA.prototype.l.bind(this)};t(uA,pA);uA.prototype.sendMessage=function(a,b){b=void 0===b?this.h:b;if(!b)throw Error("Message destination must be defined at construction time or when sending the message.");b.handleExportedMessage(oA(a),this)};uA.prototype.l=function(a,b){mA(a)&&this.g&&this.g(nA(a),b)};var vA=eval("this"),wA=function(){if("undefined"!==typeof omidGlobal&&omidGlobal)return omidGlobal;if("undefined"!==typeof global&&global)return global;if("undefined"!==typeof window&&window)return window;if("undefined"!==typeof vA&&vA)return vA;throw Error("Could not determine global object context.");}();function xA(a){return null!=a&&"undefined"!==typeof a.top&&null!=a.top}function yA(a){if(a===wA)return!1;try{if("undefined"===typeof a.location.hostname)return!0}catch(b){return!0}return!1};var zA=function(a,b){this.h=b=void 0===b?wA:b;var c=this;a.addEventListener("message",function(d){if("object"===typeof d.data){var e=d.data;mA(e)&&d.source&&c.g&&c.g(nA(e),d.source)}})};t(zA,pA);zA.prototype.sendMessage=function(a,b){b=void 0===b?this.h:b;if(!b)throw Error("Message destination must be defined at construction time or when sending the message.");b.postMessage(oA(a),"*")};var AA=["omid","v1_SessionServiceCommunication"];function BA(a){return AA.reduce(function(b,c){return b&&b[c]},a)};iA("OmidSessionClient.Partner",function(a,b){eA("Partner.name",a);eA("Partner.version",b);this.name=a;this.version=b});var CA=function(a,b,c,d){d=void 0===d?"full":d;eA("VerificationScriptResource.resourceUrl",a);this.l=a;this.o=b;this.h=c;this.g=d};CA.prototype.toJSON=function(){return{accessMode:this.g,resourceUrl:this.l,vendorKey:this.o,verificationParameters:this.h}};iA("OmidSessionClient.VerificationScriptResource",CA);iA("OmidSessionClient.Context",function(a,b,c,d){c=void 0===c?null:c;d=void 0===d?null:d;fA("Context.partner",a);this.g=a;this.B=b;this.l=c;this.h=d;this.o=!1});var DA={sessionError:"reportError"},EA=Object.keys(dA).map(function(a){return dA[a]}),FA=["impressionOccurred"],GA=function(){var a=void 0===a?wA:a;this.g=a.omidSessionInterface};GA.prototype.sendMessage=function(a,b,c){"registerSessionObserver"==a&&(c=[b]);DA[a]&&(a=DA[a]);b=this.g;0<=FA.indexOf(a)&&(b=b.adEvents);0<=EA.indexOf(a)&&(b=b.mediaEvents);b=b[a];if(!b)throw Error("Unrecognized method name: "+a+".");b.apply(null,fa(c))};var JA=function(a,b,c){fA("AdSession.context",a);this.g=a;if(!b){var d;"undefined"===typeof d&&"undefined"!==typeof window&&window&&(d=window);d=xA(d)?d:wA;var e=void 0===e?tA:e;a:{b=q([d,xA(d)?d.top:wA]);for(var f=b.next();!f.done;f=b.next()){b:{var g=d;f=f.value;var h=e;if(!yA(f))try{var k=BA(f);if(k){var n=new uA(k);break b}}catch(m){}n=h(f)?new zA(g,f):null}if(g=n){b=g;break a}}b=null}}this.h=b;this.B=c||new GA;this.K=this.C=this.A=!1;this.J=this.o=null;this.l={};this.h&&(this.h.g=this.Ge.bind(this)); this.ya("setClientInfo","1.3.20-google_20210603",this.g.g.name,this.g.g.version);HA(this,a.B);(a=a.l)&&this.ya("setContentUrl",a);IA(this)},KA=function(a,b){a.sendMessage("registerSessionObserver",b)};l=JA.prototype;l.start=function(){this.ya("startSession",{customReferenceData:this.g.h,underEvaluation:this.g.o})};l.error=function(a,b){this.ya("sessionError",a,b)};l.ya=function(a,b){for(var c=[],d=1;d<arguments.length;++d)c[d-1]=arguments[d];this.sendMessage.apply(this,[a,null].concat(fa(c)))}; l.sendMessage=function(a,b,c){for(var d=[],e=2;e<arguments.length;++e)d[e-2]=arguments[e];if(this.h)e=qA(),b&&(this.l[e]=b),d=new lA(e,"SessionService."+a,"1.3.20-google_20210603",jA()&&kA()?d:JSON.stringify(d)),this.h.sendMessage(d);else if(null!=this.B.g)try{this.B.sendMessage(a,b,d)}catch(f){rA("Failed to communicate with SessionInterface with error:"),rA(f)}}; l.Ge=function(a){var b=a.method,c=a.h;a=a.g;if("response"===b&&this.l[c]){var d=jA()&&kA()?a?a:[]:a&&"string"===typeof a?JSON.parse(a):[];this.l[c].apply(this,d)}"error"===b&&window.console&&rA(a)};var HA=function(a,b){b&&(b=b.map(function(c){return c.toJSON()}),a.ya("injectVerificationScriptResources",b))},IA=function(a){KA(a,function(b){"sessionStart"===b.type&&(a.K=!0,a.o=b.data.creativeType,a.J=b.data.impressionType);"sessionFinish"===b.type&&(a.K=!1)})};iA("OmidSessionClient.AdSession",JA);var LA=function(a){fA("AdEvents.adSession",a);try{if(a.A)throw Error("AdEvents already registered.");a.A=!0;a.ya("registerAdEvents");this.g=a}catch(b){throw Error("AdSession already has an ad events instance registered");}};LA.prototype.loaded=function(a){a=void 0===a?null:a;var b=this.g;if("definedByJavaScript"===b.o)throw Error("Creative type has not been redefined");if("definedByJavaScript"===b.J)throw Error("Impression type has not been redefined");a?this.g.ya("loaded",a.toJSON()):this.g.ya("loaded")}; iA("OmidSessionClient.AdEvents",LA);var MA=function(a){fA("MediaEvents.adSession",a);try{if(a.C)throw Error("MediaEvents already registered.");a.C=!0;a.ya("registerMediaEvents");this.g=a}catch(b){throw Error("AdSession already has a media events instance registered");}};MA.prototype.start=function(a,b){gA("MediaEvents.start.duration",a);gA("MediaEvents.start.mediaPlayerVolume",b);if(0>b||1<b)throw Error("Value for MediaEvents.start.mediaPlayerVolume is outside the range [0,1]");this.g.ya("start",a,b)};MA.prototype.pause=function(){this.g.ya("pause")}; MA.prototype.resume=function(){this.g.ya("resume")};iA("OmidSessionClient.MediaEvents",MA);var PA=function(a,b){NA?a.srcdoc=b:(a=a.contentWindow)&&OA(a.document,b)},NA=xd&&"srcdoc"in ef(document,"IFRAME"),OA=function(a,b){a.open("text/html","replace");Rc(a,Sf(b));a.close()};function QA(a){return(a=lf(a))&&a.omidSessionInterface?a.omidSessionInterface:null}function RA(a,b){var c=gf("IFRAME",{name:b,sandbox:"allow-scripts allow-same-origin",style:"display: none"});a.appendChild(c);a="<script src="+cA.Ga()+">\x3c/script>";b=new Promise(function(d,e){c.addEventListener("load",function(){QA(c)?d(c):e()})});PA(c,a);return b};var SA=function(a,b){K.call(this);this.h=QA(a);this.g=b};t(SA,K);var UA=function(a){try{a.h.registerSessionObserver(function(b){"sessionStart"==b.type?TA(a,a.g):"sessionFinish"==b.type&&UA(a)})}catch(b){a.dispatchEvent(new Event("error"))}},TA=function(a,b){try{a.h.setVideoElement(b)}catch(c){a.dispatchEvent(new Event("error"))}};var VA=function(a){this.g=a};VA.prototype.getCuePoints=function(){return this.g};VA.prototype.getCuePoints=VA.prototype.getCuePoints;x("module$contents$ima$AdCuePoints_AdCuePoints.PREROLL",0,void 0);x("module$contents$ima$AdCuePoints_AdCuePoints.POSTROLL",-1,void 0);var WA=function(a){this.g=a;this.l="";this.h=-1;this.o=!1},YA=function(a,b){if(0<=a.h){var c=null==b?function(){}:b,d=function(){XA(a,c);a.g.removeEventListener("loadedmetadata",d,!1)};a.g.addEventListener("loadedmetadata",d,!1);a.g.src=a.l;a.g.load()}else null!=b&&b()},XA=function(a,b){var c=0<a.g.seekable.length;a.o?c?(a.g.currentTime=a.h,ZA(a),b()):setTimeout(function(){return XA(a,b)},100):(ZA(a),b())},ZA=function(a){a.h=-1;a.l="";a.o=!1};var $A=function(a){return 0<a.width&&0<a.height},aB=function(a){G(F.D(),"ps",a.width+"x"+a.height)},bB=function(a){K.call(this);this.g=a;this.ba=null;this.F=new WA(a);this.h=new U(this);ji(this,this.h);this.C=0;this.N=this.I=this.U=this.aa=this.M=!1;this.T=this.o=null;this.l=new Ve(this.g.offsetWidth,this.g.offsetHeight);this.A=null;this.Y=Iz(this.g);this.Z=!1};t(bB,K);l=bB.prototype;l.gd=function(){var a=this.F;a.l=a.g.currentSrc;a.o=0<a.g.seekable.length;a.h=a.g.ended?-1:a.g.currentTime}; l.Nb=function(a){YA(this.F,a)}; l.load=function(a,b){var c=F.D().g;c.U=!0;Eg(c);H("hvd_lc");$A(this.l)?aB(this.l):cB(this);dB(this);this.U=!1;if(b)if(H("hvd_ad"),b instanceof Ts){if(H("hvd_mad"),c=b.getMediaUrl()){H("hvd_admu");H("hvd_src");this.g.src=c;this.g.load();return}}else if(b instanceof Ss){H("hvd_dad");c=b.J;var d=b.l,e=b.C,f=b.h,g=b.A,h=b.g;if(c&&d&&e&&f&&g&&h&&(H("hvd_addu"),b.B)){H("hvd_admse");b=e+'; codecs="'+g+'"';f=f+'; codecs="'+h+'"';if(qu()&&qu()&&MediaSource.isTypeSupported(b)&&qu()&&MediaSource.isTypeSupported(f)){H("hvd_ymse"); H("hvd_mse");a=!1;try{-1!=window.location.search.indexOf("goog_limavideo=true")&&(a=!0)}catch(k){}u.customElements?a?a=!0:(gh(ai)&&vz.D().report(153,{limvid:"vd"}),a=gh(ai)||gh(Xh)||gh(Zh)||gh(Yh)?!0:!1):a=!1;a?(this.g.qb=c,this.g.Bb=d):(this.ba=new Uw(this.g,[new Jv(c,b,35E4,new tu),new Jv(d,f,82E3,new tu)]),ji(this,this.ba),a=this.g,c=this.ba,c.g||(c.g=window.URL.createObjectURL(c.da)),c=c.g,a.src=c);this.g.load();return}H("hvd_nmse")}}else H("hvd_uad");a?(H("hvd_src"),this.g.src=a):H("hvd_vn"); this.g.load()};l.setVolume=function(a){this.g.volume=Math.max(a,0);this.g.muted=0==a?!0:!1};l.getVolume=function(){return this.g.muted?0:this.g.volume};var eB=function(a){a.Z=!1;a.U||Gc()?(a.N=!1,a.o=a.g.play(),null!=a.o&&(a.T=null,a.o.then(function(){a.o=null;a.Fd(a.T);a.T=null}).catch(function(b){a.o=null;var c="";null!=b&&null!=b.name&&(c=b.name);"AbortError"==c||"NotAllowedError"==c?a.dispatchEvent("autoplayDisallowed"):a.ea()}))):a.N=!0}; bB.prototype.pause=function(){null==this.o&&(this.Z=!0,this.g.pause())};bB.prototype.getDuration=function(){return isNaN(this.g.duration)?-1:this.g.duration};bB.prototype.O=function(){this.A&&(this.g instanceof HTMLElement&&this.A.unobserve(this.g),this.A=null);fB(this);K.prototype.O.call(this)}; var gB=function(a){fB(a);a.h.P(a.g,ix,a.ob);a.h.P(a.g,"ended",a.Ye);a.h.P(a.g,"webkitbeginfullscreen",a.Pb);a.h.P(a.g,"webkitendfullscreen",a.wa);a.h.P(a.g,"loadedmetadata",a.Ze);a.h.P(a.g,"pause",a.bf);a.h.P(a.g,"playing",a.Fd);a.h.P(a.g,"timeupdate",a.cf);a.h.P(a.g,"volumechange",a.df);a.h.P(a.g,"error",a.ea);a.h.P(a.g,Sd||Ed&&!Mt(8)?"loadeddata":"canplay",a.$e);a.H=new Vy;a.h.P(a.H,"click",a.Va);Xy(a.H,a.g);a.W=new oj(1E3);a.h.P(a.W,"tick",a.jb);a.W.start()},fB=function(a){null!=a.H&&(Zy(a.H), a.H=null);null!=a.W&&a.W.X();Ut(a.h);dB(a)},dB=function(a){a.aa=!1;a.I=!1;a.M=!1;a.N=!1;a.C=0;a.o=null;a.T=null;hi(a.L)};bB.prototype.ob=function(a){this.dispatchEvent(a.type)}; var iB=function(a){if(!a.I){a.I=!0;a.dispatchEvent("start");try{if(gh(ai)&&u.customElements){var b=u.customElements.get("lima-video");a.g instanceof b?vz.D().report(153,{limvid:"limastart"}):vz.D().report(153,{limvid:"videostart"})}}catch(c){vz.D().report(153,{limvid:"startfail"})}b="function"===typeof a.g.getAttribute&&null!=a.g.getAttribute("playsinline");b=void 0===b?!1:b;(Cd||Lt()||Mt(10))&&(b||(Jx.D(),1))||(Jx.D(),pc(Dc,"Xbox"))||(Bd||Dd?0:(!zd||zd&&Kt(Jt,4))&&(Zl()?(Jx.D(),!1):!Lx()))||!zd|| zd&&Kt(Jt,3)||(Bd||Dd)&&!Mt(4)||hB(a)}};l=bB.prototype;l.Ze=function(){this.U=!0;this.N&&eB(this);this.N=!1};l.$e=function(){this.aa||(this.aa=!0,this.dispatchEvent("loaded"))};l.Fd=function(a){null!=this.o?this.T=a:(this.dispatchEvent("play"),Ed||Cd||Lt()||Sd||iB(this))}; l.cf=function(a){if(!this.I&&(Ed||Cd||Lt()||Sd)){if(0>=this.g.currentTime)return;if(Sd&&this.g.ended&&1==this.getDuration()){this.ea(a);return}iB(this)}if(Ed||pc(Dc,"Nintendo WiiU")){if(1.5<this.g.currentTime-this.C){this.M=!0;this.g.currentTime=this.C;return}this.M=!1;this.g.currentTime>this.C&&(this.C=this.g.currentTime)}this.dispatchEvent("timeUpdate")};l.df=function(){this.dispatchEvent("volumeChange")}; l.bf=function(){if(this.I&&Ed&&!this.Z&&(2>jB(this)||this.M)){this.L=new oj(250);this.h.P(this.L,"tick",this.lb);this.L.start();var a=!0}else a=!1;a||this.o||this.dispatchEvent("pause")};l.Ye=function(){var a=!0;if(Ed||pc(Dc,"Nintendo WiiU"))a=this.C>=this.g.duration-1.5;!this.M&&a&&this.dispatchEvent("end")};var hB=function(a){a.dispatchEvent("beginFullscreen")};bB.prototype.wa=function(){this.dispatchEvent("endFullscreen")};bB.prototype.ea=function(){this.dispatchEvent("error")}; bB.prototype.Va=function(){this.dispatchEvent("click")};var cB=function(a){"ResizeObserver"in window&&(a.A=new ResizeObserver(function(b){b=q(b);for(var c=b.next();!c.done;c=b.next())c=c.value,c.contentBoxSize?(c=Array.isArray(c.contentBoxSize)?c.contentBoxSize[0]:c.contentBoxSize,a.l.width=c.inlineSize,a.l.height=c.blockSize):(a.l.width=c.contentRect.width,a.l.height=c.contentRect.height),$A(a.l)&&(a.g instanceof HTMLElement&&a.A.unobserve(a.g),a.A=null,aB(a.l))}),a.g instanceof HTMLElement&&a.A.observe(a.g))}; bB.prototype.jb=function(){var a=new Ve(this.g.offsetWidth,this.g.offsetHeight),b=Iz(this.g);if(a.width!=this.l.width||a.height!=this.l.height)!this.Y&&b?hB(this):this.Y&&!b&&this.wa(),this.l=a,this.Y=b};bB.prototype.lb=function(){if(!this.g.ended&&this.g.paused&&(Ed||Td?this.g.currentTime<this.g.duration:1)){var a=this.g.duration-this.g.currentTime,b=jB(this);0<b&&(2<=b||2>a)&&(hi(this.L),eB(this))}else hi(this.L)}; var jB=function(a){var b;a:{for(b=a.g.buffered.length-1;0<=b;){if(a.g.buffered.start(b)<=a.g.currentTime){b=a.g.buffered.end(b);break a}b--}b=0}return b-a.g.currentTime};bB.prototype.Pb=function(){vz.D().report(139);hB(this)};var nB=function(a,b,c){J.call(this);var d=this;this.l=b;this.o=c;b=new U(this);ji(this,b);this.B="goog_"+ad++;this.g=this.h=null;RA(a,this.B).then(function(e){return void kB(d,e)}).catch(function(){return void lB(d)});b.P(this.l,"adsManager",function(e){"allAdsCompleted"==e.ka&&mB(d)})};t(nB,J); var kB=function(a,b){a.h=b;var c={};c=(c.frameName=a.B,c);ay(a.l,"omid","iframeReady",c);a.g=new SA(b,a.o);a.g.P("error",function(){return void lB(a)});UA(a.g)},lB=function(a){ay(a.l,"omid","iframeFailed");a.X()},mB=function(a){setTimeout(function(){a.X()},3E3)};nB.prototype.O=function(){this.h&&(hf(this.h),this.h=null);J.prototype.O.call(this)};var oB=function(a,b,c,d){J.call(this);this.o=a;this.l=b;this.g=c;this.C=d;this.h=new U(this);ji(this,this.h);this.h.P(this.o,d,this.A)};t(oB,J); var qB=function(a,b){var c=b.na;switch(b.ka){case "showVideo":c=a.l;null!=c.h&&c.h.show();break;case "hide":c=a.l;null!=c.h&&pB(c.h.g,!1);break;case "resizeAndPositionVideo":a=a.l.g;c=c.resizeAndPositionVideo;a.g.style.left=String(c.left)+"px";a.g.style.top=String(c.top)+"px";a.g.style.width=String(c.width)+"px";a.g.style.height=String(c.height)+"px";break;case "restoreSizeAndPositionVideo":c=a.l.g,c.g.style.width="100%",c.g.style.height="100%",c.g.style.left="0",c.g.style.right="0"}}; oB.prototype.A=function(a){var b=a.na;switch(a.ka){case "activate":a=this.l;var c=this.g;a.g!=c&&a.h&&a.o&&a.l&&(c.setVolume(a.g.getVolume()),c=a.g,a.g=a.l,a.l=c,c=a.h,a.h=a.o,a.o=c,pB(a.o.g,!1),null!=(c=a.J.H)&&(a=a.g.F.g,c.o=a,c.g&&(c=c.g,c.g=a,TA(c,a))));break;case "startTracking":a=this.g;c=this.B;this.h.P(a,Ib(mu),c);this.h.P(a,ix,c);gB(this.g);break;case "stopTracking":a=this.g;c=this.B;this.h.Ua(a,Ib(mu),c);this.h.Ua(a,ix,c);fB(this.g);break;case "exitFullscreen":a=this.g;(Bd||Dd)&&a.g.webkitDisplayingFullscreen&& a.g.webkitExitFullscreen();break;case "play":eB(this.g);break;case "pause":this.g.pause();break;case "load":gB(this.g);a=this.g;c=b.videoUrl;var d=b.muxedMediaUrl,e=b.muxedMimeType,f=b.muxedAudioCodec,g=b.muxedVideoCodec,h=b.demuxedAudioUrl,k=b.demuxedVideoUrl,n=b.demuxedAudioMimeType,m=b.demuxedVideoMimeType,v=b.demuxedAudioCodec,r=b.demuxedVideoCodec;b=b.mseCompatible;var w=null;k&&h&&b&&m&&n&&r&&v&&(w=new Ss({tf:k,re:h,Bh:null,rh:null,sf:m,qe:n,vb:r,pb:v,height:null,width:null,Ja:b,Ah:null,qh:null})); h=null;d&&e&&g&&f&&(h=new Ts({Xe:d,wh:null,mimeType:e,vb:g,pb:f,height:null,width:null,Ja:b,th:null}));w?a.load(c,w):h?a.load(c,h):a.load(c,null);break;case "unload":a=this.g;dB(a);a.U=!1;"removeAttribute"in a.g?a.g.removeAttribute("src"):a.g.src="";a.g.load();break;case "setCurrentTime":this.g.g.currentTime=b.currentTime;break;case "setVolume":this.g.setVolume(b.volume)}}; oB.prototype.B=function(a){var b={};switch(a.type){case "autoplayDisallowed":a="autoplayDisallowed";break;case "beginFullscreen":a="fullscreen";break;case "endFullscreen":a="exitFullscreen";break;case "click":a="click";break;case "end":a="end";break;case "error":a="error";break;case "loaded":a="loaded";break;case "mediaLoadTimeout":a="mediaLoadTimeout";break;case "pause":a="pause";b.ended=this.g.g.ended;break;case "play":a="play";break;case "skip":a="skip";break;case "start":a="start";b.volume=this.g.getVolume(); break;case "timeUpdate":a="timeupdate";b.currentTime=this.g.g.currentTime;b.duration=this.g.getDuration();break;case "volumeChange":a="volumeChange";b.volume=this.g.getVolume();break;case "loadedmetadata":a=a.type;b.duration=this.g.getDuration();break;case "abort":case "canplay":case "canplaythrough":case "durationchange":case "emptied":case "loadstart":case "loadeddata":case "progress":case "ratechange":case "seeked":case "seeking":case "stalled":case "suspend":case "waiting":a=a.type;break;default:return}ay(this.o, this.C,a,b)};var rB=function(a,b){J.call(this);this.h=b;this.l=new oB(a,b,this.h.g,"videoDisplay1");ji(this,this.l);this.g=null;var c=this.h.l;null!=c&&(this.g=new oB(a,b,c,"videoDisplay2"),ji(this,this.g))};t(rB,J);var sB=function(a,b,c,d){var e=document.createElement("IFRAME");e.id=b;e.name=b;e.width=String(c);e.height=String(d);e.allowTransparency="true";e.scrolling="no";e.marginWidth="0";e.marginHeight="0";e.frameBorder="0";e.style.border="0";e.style.verticalAlign="bottom";e.src="about:blank";a.appendChild(e);return e};function tB(){var a,b;return null==(a=D().googletag)?void 0:null==(b=a.companionAds)?void 0:b.call(a)}function uB(a){var b={};b.slotId=a.getSlotId().getId();var c=[];a=q(a.getSizes()||[]);for(var d=a.next();!d.done;d=a.next())if(d=d.value,"string"!==typeof d){var e={};c.push((e.adWidth=d.getWidth(),e.adHeight=d.getHeight(),e))}return b.adSizes=c,b} function vB(a){var b=tB();if(b&&a&&Array.isArray(a)){var c=new Map(b.getSlots().map(function(r){return[r.getSlotId().getId(),r]}));a=q(a);for(var d=a.next();!d.done;d=a.next()){var e=d.value,f=c.get(e.slotId);if(f&&!b.isSlotAPersistentRoadblock(f)){var g=e.adContent;if(g&&(d=Ze(f.getSlotId().getDomId()))){d.style.display="";var h=e.adWidth,k=e.adHeight;d.textContent="";if(e.friendlyIframeRendering)try{var n="google_companion_"+f.getSlotId().getId(),m=sB(d,n,h,k),v=m.contentWindow?m.contentWindow.document: m.contentDocument;wd&&v.open("text/html","replace");Rc(v,Sf(g));v.close()}catch(r){}else Qc(d,Sf(g)),d.style.width=h+"px",d.style.height=k+"px";b.slotRenderEnded(f,h,k);(e=e.onAdContentSet)&&e(d)}}}}};var wB=function(a,b,c,d,e,f){xz.call(this,a,b,c,d,e);this.g=f};t(wB,xz);var xB=function(a,b){K.call(this);this.o=a;this.l=b;this.g={};this.h=new U(this);ji(this,this.h);this.h.P(D(),"message",this.A)};t(xB,K);var yB=function(a,b){var c=b.g;a.g.hasOwnProperty(c)&&ay(a.g[c],b.type,b.ka,b.na)},zB=function(a,b,c,d){a.g.hasOwnProperty(b)||(c=new $z(b,c),a.h.P(c,a.o,function(e){this.dispatchEvent(new wB(e.type,e.ka,e.na,e.Mb,e.Gd,b))}),c.g=d,c.connect(),a.g[b]=c)};xB.prototype.O=function(){for(var a in this.g)hi(this.g[a]);K.prototype.O.call(this)}; xB.prototype.A=function(a){a=a.g;var b=aA(a.data);if(null!=b){var c=b.channel;if(this.l&&!this.g.hasOwnProperty(c)){var d=b.sid;zB(this,c,d,a.source);this.dispatchEvent(new wB(b.name,b.type,b.data||{},d,a.origin,c))}}};function AB(){return!!Ia("googletag.cmd",D())}function BB(){var a=Ia("googletag.console",D());return null!=a?a:null}var CB=function(){U.call(this);this.l=new xB("gpt",!0);ji(this,this.l);this.P(this.l,"gpt",this.A);this.g=null;AB()||D().top===D()||(this.g=new xB("gpt",!1),ji(this,this.g),this.P(this.g,"gpt",this.B))};t(CB,U); CB.prototype.A=function(a){var b=a.Gd,c="//imasdk.googleapis.com".match(pf);b=b.match(pf);if(c[3]==b[3]&&c[4]==b[4])if(null!=this.g)zB(this.g,a.g,a.Mb,D().parent),null!=this.g&&yB(this.g,a);else if(c=a.na,null!=c&&void 0!==c.scope){b=c.scope;c=c.args;var d;if("proxy"==b){var e=a.ka;"isGptPresent"==e?d=AB():"isConsolePresent"==e&&(d=null!=BB())}else if(AB())if("pubads"==b||"companionAds"==b){d=a.ka;var f=D().googletag;if(null!=f&&null!=f[b]&&(b=f[b](),null!=b&&(d=b[d],null!=d)))try{e=d.apply(b,c)}catch(g){}d= e}else if("console"==b){if(e=BB(),null!=e&&(b=e[a.ka],null!=b))try{b.apply(e,c)}catch(g){}}else null===b&&(e=a.ka,"googleGetCompanionAdSlots"==e?(e=tB())?(e=e.getSlots().map(uB),d=e.length?e:null):d=null:("googleSetCompanionAdContents"==e&&vB(c[0]),d=null));void 0!==d&&(a.na.returnValue=d,yB(this.l,a))}};CB.prototype.B=function(a){yB(this.l,a)};var DB=function(a,b){if(a.g){var c=a.g;hi(c.g[b]);delete c.g[b]}a.l&&(a=a.l,hi(a.g[b]),delete a.g[b])};var FB=function(a,b){var c=Array.prototype.slice.call(arguments),d=c.shift();if("undefined"==typeof d)throw Error("[goog.string.format] Template required");return d.replace(/%([0\- \+]*)(\d+)?(\.(\d+))?([%sfdiu])/g,function(e,f,g,h,k,n,m,v){if("%"==n)return"%";var r=c.shift();if("undefined"==typeof r)throw Error("[goog.string.format] Not enough arguments");arguments[0]=r;return EB[n].apply(null,arguments)})},EB={s:function(a,b,c){return isNaN(c)||""==c||a.length>=Number(c)?a:a=-1<b.indexOf("-",0)? a+Yc(" ",Number(c)-a.length):Yc(" ",Number(c)-a.length)+a},f:function(a,b,c,d,e){d=a.toString();isNaN(e)||""==e||(d=parseFloat(a).toFixed(e));var f=0>Number(a)?"-":0<=b.indexOf("+")?"+":0<=b.indexOf(" ")?" ":"";0<=Number(a)&&(d=f+d);if(isNaN(c)||d.length>=Number(c))return d;d=isNaN(e)?Math.abs(Number(a)).toString():Math.abs(Number(a)).toFixed(e);a=Number(c)-d.length-f.length;return d=0<=b.indexOf("-",0)?f+d+Yc(" ",a):f+Yc(0<=b.indexOf("0",0)?"0":" ",a)+d},d:function(a,b,c,d,e,f,g,h){return EB.f(parseInt(a, 10),b,c,d,0,f,g,h)}};EB.i=EB.d;EB.u=EB.d;var HB=function(a,b){K.call(this);this.l=new U(this);ji(this,this.l);this.M=this.L=null;this.I=!1;this.F="goog_"+ad++;this.A=new Map;var c=this.F,d=(Cf()?"https:":"http:")+FB("//imasdk.googleapis.com/js/core/bridge3.467.0_%s.html",W.o);a:{var e=window;try{do{try{if(0==e.location.href.indexOf(d)||0==e.document.referrer.indexOf(d)){var f=!0;break a}}catch(g){}e=e.parent}while(e!=e.top)}catch(g){}f=!1}f&&(d+="?f="+c);c=gf("IFRAME",{src:d+"#"+c,allowFullscreen:!0,allow:"autoplay;trust-token-redemption", style:"border:0; opacity:0; margin:0; padding:0; position:relative; color-scheme: light;"});this.l.Gb(c,"load",this.Z);a.appendChild(c);this.g=c;this.o=GB(this);this.C=b;this.h=null;this.N=new rB(this.o,this.C);ji(this,this.N);this.C.g&&this.l.P(this.o,"displayContainer",this.U);this.l.P(this.o,"mouse",this.W);this.l.P(this.o,"touch",this.Y);c=D();d=Ia("google.ima.gptProxyInstance",c);null!=d?c=d:(d=new CB,x("google.ima.gptProxyInstance",d,c),c=d);this.T=c;Lx()||(this.H=new nB(a,this.o,b.g.F.g),ji(this, this.H))};t(HB,K);var GB=function(a,b){b=void 0===b?"*":b;var c=a.A.get(b);null==c&&(c=new $z(a.F,b),a.I&&(c.g=lf(a.g),c.connect()),a.A.set(b,c));return c};HB.prototype.O=function(){null!==this.h&&(this.h.X(),this.h=null);this.A.forEach(function(a){hi(a)});this.A.clear();DB(this.T,this.F);hf(this.g);K.prototype.O.call(this)}; HB.prototype.W=function(a){var b=a.na,c=Zf(this.g),d=document.createEvent("MouseEvent");d.initMouseEvent(a.ka,!0,!0,window,b.detail,b.screenX,b.screenY,b.clientX+c.x,b.clientY+c.y,b.ctrlKey,b.altKey,b.shiftKey,b.metaKey,b.button,null);this.g.dispatchEvent(d)}; var IB=function(a,b){var c=Zf(a.g),d=!!("TouchEvent"in window&&0<TouchEvent.length);b=b.map(function(e){return d?new Touch({identifier:e.identifier,target:a.g,clientX:e.clientX,clientY:e.clientY,screenX:e.screenX,screenY:e.screenY,pageX:e.pageX+c.x,pageY:e.pageY+c.y}):document.createTouch(window,a.g,e.identifier,e.pageX+c.x,e.pageY+c.y,e.screenX,e.screenY)});return d?b:document.createTouchList.apply(document,b)}; HB.prototype.Y=function(a){var b=a.na,c=Zf(this.g);if("TouchEvent"in window&&0<TouchEvent.length)b={bubbles:!0,cancelable:!0,view:window,detail:b.detail,ctrlKey:b.ctrlKey,altKey:b.altKey,shiftKey:b.shiftKey,metaKey:b.metaKey,touches:IB(this,b.touches),targetTouches:IB(this,b.targetTouches),changedTouches:IB(this,b.changedTouches)},a=new TouchEvent(a.ka,b),this.g.dispatchEvent(a);else{var d=document.createEvent("TouchEvent");d.initTouchEvent(a.ka,!0,!0,window,b.detail,b.screenX,b.screenY,b.clientX+ c.x,b.clientY+c.y,b.ctrlKey,b.altKey,b.shiftKey,b.metaKey,IB(this,b.touches),IB(this,b.targetTouches),IB(this,b.changedTouches),b.scale,b.rotation);this.g.dispatchEvent(d)}};HB.prototype.U=function(a){switch(a.ka){case "showVideo":null==this.h?(this.h=new Vy,this.l.P(this.h,"click",this.aa)):Zy(this.h);Xy(this.h,JB(this.C));break;case "hide":null!==this.h&&(this.h.X(),this.h=null)}var b=this.N;qB(b.l,a);b.g&&qB(b.g,a)};HB.prototype.aa=function(){ay(this.o,"displayContainer","videoClick")}; HB.prototype.Z=function(){var a=this;this.L=rg();this.M=og();this.A.forEach(function(b){b.g=lf(a.g);b.connect()});this.I=!0};var LB=function(){K.call(this);this.buffered=new KB;this.F=new KB;this.A=new U(this);ji(this,this.A);this.src=this.C="";this.H=!1;this.l=null;var a=nx(W);if(a){a:{if(Lb(a.g,"videoElementFakeDuration")&&(a=a.g.videoElementFakeDuration,"number"===typeof a))break a;a=NaN}this.duration=a}};t(LB,K);var MB=function(){var a=["video/mp4"],b=["video/ogg"],c=new LB;c.canPlayType=function(d){return a.includes(d)?"probably":b.includes(d)?"maybe":""};c.width=0;c.height=0;c.offsetWidth=0;c.offsetHeight=0;return c}; l=LB.prototype;l.pause=function(){this.paused||(null.stop(),this.paused=!0,this.dispatchEvent("timeupdate"),this.dispatchEvent("pause"))}; l.load=function(){this.hd=0;this.paused=!0;this.dispatchEvent("loadstart");var a;isNaN(this.duration)?a=10+20*Math.random():a=this.duration;this.setProperty("duration",a);a=this.F;a.g.push(new NB(this.duration));a.length=a.g.length;a=this.buffered;a.g.push(new NB(this.duration));a.length=a.g.length;this.dispatchEvent("loadedmetadata");0<this.currentTime&&this.dispatchEvent("timeupdate");this.dispatchEvent("loadeddata");this.dispatchEvent("canplay");this.dispatchEvent("canplaythrough");this.dispatchEvent("progress")}; l.setProperty=function(a,b){switch(a){case "currentTime":a=Number(b);this.dispatchEvent("seeking");this.currentTime=a;this.dispatchEvent("seeked");a=Xa()-this.o;b=this.currentTime+a/1E3;this.o+=a;2<this.hd&&(this.currentTime=Math.min(b,this.duration));this.dispatchEvent("timeupdate");this.currentTime==this.duration&&(this.paused=!0,null.stop(),this.dispatchEvent("ended"));break;case "duration":this.duration=Number(b);this.dispatchEvent("durationchange");break;case "volume":this.volume=Number(b);this.dispatchEvent("volumechange"); break;default:throw"Property setter not implemented";}};l.setAttribute=function(a,b){null!=a&&OB.set(a,b)};l.getAttribute=function(a){return OB.get(a)};l.$d=function(a){var b=null,c=null;switch(a.type){case "loadeddata":b="Loaded";break;case "playing":b="Playing";c="#00f";break;case "pause":b="Paused";break;case "ended":b="Ended",c="#000"}b&&this.h&&(this.h.innerText=b);c&&this.g&&(this.g.style.backgroundColor=c)}; var OB=new hs,NB=function(a){this.startTime=0;this.endTime=a},KB=function(){this.length=0;this.g=[]};KB.prototype.start=function(a){return this.g[a].startTime};KB.prototype.end=function(a){return this.g[a].endTime};l=LB.prototype;l.hd=0;l.currentTime=0;l.duration=NaN;l.paused=!0;l.volume=1;l.muted=!1;Object.defineProperty(LB.prototype,"src",{get:function(){return LB.prototype.C},set:function(a){var b=LB.prototype;b.H&&null!=b.l?(b.l.reject(),b.l=null):b.C=a}});LB.prototype.o=0;LB.prototype.g=null; LB.prototype.h=null;var RB=function(a,b){J.call(this);this.o=a;this.l=this.g=null;this.h=PB();QB(this,b);iw(function(){G(F.D(),"haob","1")})};t(RB,J);RB.prototype.initialize=function(){this.h&&this.h.load()};RB.prototype.O=function(){hf(this.g);J.prototype.O.call(this)}; var QB=function(a,b){a.g=gf("DIV",{style:"display:none;"});a.o.appendChild(a.g);a.g.appendChild(a.h);b&&(a.l=gf("DIV",{style:"position:absolute;width:100%;height:100%;left:0px;top:0px"}),a.g.appendChild(a.l))},PB=function(){var a=nx(W);if(kx(a,"useVideoElementFake")){a=MB();var b=gf("DIV",{style:"position:absolute;width:100%;height:100%;top:0px;left:0px;"});for(c in a)b[c]=a[c];a.g=gf("DIV",{style:"position:absolute;width:100%;height:100%;top:0px;left:0px;background-color:#000"});a.h=gf("P",{style:"position:absolute;top:25%;margin-left:10px;font-size:24px;color:#fff;"}); a.g.appendChild(a.h);b.appendChild(a.g);a.A.P(a,["loadeddata","playing","pause","ended"],a.$d);var c=b}else{c=!1;try{-1!=window.location.search.indexOf("goog_limavideo=true")&&(c=!0)}catch(d){}u.customElements?c?a=!0:(gh(ai)&&vz.D().report(153,{limvid:"vw"}),a=gh(Zh)||gh(Xh)||gh(ai)||gh(Yh)?!0:!1):a=!1;if(a){c&&console.log("force lima video in wrapper");c=null;try{c=new ww}catch(d){c=gf("lima-video"),gh(ai)&&vz.D().report(153,{limvid:"firefail"})}c.style.backgroundColor="#000";c.style.height="100%"; c.style.width="100%";c.style.position="absolute";c.style.left="0";c.style.top="0"}else c=gf("VIDEO",{style:"background-color:#000;position:absolute;width:100%;height:100%;left:0;top:0;",title:Yw("Advertisement").toString()})}c.setAttribute("webkit-playsinline",!0);c.setAttribute("playsinline",!0);return c};RB.prototype.show=function(){pB(this.g,!0)};var pB=function(a,b){null!=a&&(a.style.display=b?"block":"none")};var UB=function(a,b,c){var d=a&&a.getRootNode?a.getRootNode({composed:!0}):a;if(null==a||!kf(Xe(d),d))throw hy(gy,null,"containerElement","element");d=!1;try{d=a&&a.getRootNode&&a.getRootNode()instanceof ShadowRoot}catch(e){}vz.D().report(152,{u:d});this.A=b;this.Z=Nx(this.A||null);this.Y=Nt(this.A||null);this.W=String(Math.floor(1E9*Math.random()));this.I=!1;this.H=a;this.U=null!=b;W.g=2;this.F=SB(b?b:null);d=gf("DIV",{style:"position:absolute"});a.insertBefore(d,a.firstChild);this.B=d;this.h=null; TB(this)&&b?a=new bB(b):(this.h=new RB(this.B,!0),a=new bB(this.h.h));this.g=a;this.l=this.o=null;if(a=this.h&&W.isAutoPlayAdBreaks())a=!(TB(this)||Bd||Dd||$l()||zd&&(!zd||!Kt(Jt,4)));a&&(this.o=new RB(this.B,!0),this.l=new bB(this.o.h));this.C=c||null;this.T=null!=this.C;TB(this)&&b?"function"!==typeof b.getBoundingClientRect?(c=this.B,W.l=c):c=b:c=this.B;this.K=c;this.J=new HB(this.B,this);this.N=new Ve(0,0);this.L="";b&&(b=b.src||b.currentSrc,b=b instanceof O?b.H():new O(b,void 0),200>b.toString().length? this.L=b.toString():200>b.g.length&&(this.L=b.g));this.M=new Map;this.M.set("videoDisplay1",this.g);this.l&&this.M.set("videoDisplay2",this.l)};UB.prototype.initialize=function(){this.I=!0;null!=this.h&&this.h.initialize();null!=this.o&&this.o.initialize()};UB.prototype.destroy=function(){var a=this;this.A=null;hi(this.h);hi(this.o);hi(this.J);this.g.Nb(function(){return hi(a.g)});null!=this.l&&this.l.Nb(function(){return hi(a.l)});hf(this.B)}; var JB=function(a){return a.T&&a.C?a.C:null!=a.h?a.h.l:null},TB=function(a){return Mx(a.F)&&a.U},SB=function(a){return null!=a&&"function"===typeof a.getAttribute&&null!=a.getAttribute("playsinline")?!0:!1};UB.prototype.destroy=UB.prototype.destroy;UB.prototype.initialize=UB.prototype.initialize;var VB=function(a){var b=Error.call(this);this.message=b.message;"stack"in b&&(this.stack=b.stack);this.g=a};t(VB,Error);l=VB.prototype;l.getInnerError=function(){var a=this.g.innerError;return a instanceof Object?new VB(a):null!=a?Error(a):null};l.getMessage=function(){return this.g.errorMessage};l.getErrorCode=function(){return this.g.errorCode};l.Bd=function(){var a=this.getErrorCode();return 1E3>a?a:900};l.getType=function(){return this.g.type}; l.toString=function(){return"AdError "+this.getErrorCode()+": "+this.getMessage()+(null!=this.getInnerError()?" Caused by: "+this.getInnerError():"")};VB.prototype.getType=VB.prototype.getType;VB.prototype.getVastErrorCode=VB.prototype.Bd;VB.prototype.getErrorCode=VB.prototype.getErrorCode;VB.prototype.getMessage=VB.prototype.getMessage;VB.prototype.getInnerError=VB.prototype.getInnerError;var WB={AD_LOAD:"adLoadError",AD_PLAY:"adPlayError"};x("module$contents$ima$AdError_AdError.Type",WB,void 0);var XB=function(a,b){b=void 0===b?null:b;ki.call(this,"adError");this.g=a;this.l=b};t(XB,ki);XB.prototype.getError=function(){return this.g};XB.prototype.getUserRequestContext=function(){return this.l};XB.prototype.getUserRequestContext=XB.prototype.getUserRequestContext;XB.prototype.getError=XB.prototype.getError;var YB={AD_ERROR:"adError"};x("module$contents$ima$AdErrorEvent_AdErrorEvent.Type",YB,void 0);var ZB=function(a,b,c){b=void 0===b?null:b;c=void 0===c?null:c;ki.call(this,a);this.l=b;this.g=c};t(ZB,ki);ZB.prototype.getAd=function(){return this.l};ZB.prototype.getAdData=function(){return this.g};ZB.prototype.getAdData=ZB.prototype.getAdData;ZB.prototype.getAd=ZB.prototype.getAd; var $B={AD_CAN_PLAY:"adCanPlay",yf:"adStarted",CONTENT_PAUSE_REQUESTED:"contentPauseRequested",CONTENT_RESUME_REQUESTED:"contentResumeRequested",CLICK:"click",VIDEO_CLICKED:"videoClicked",VIDEO_ICON_CLICKED:"videoIconClicked",cd:"engagedView",EXPANDED_CHANGED:"expandedChanged",STARTED:"start",AD_PROGRESS:"adProgress",AD_BUFFERING:"adBuffering",IMPRESSION:"impression",jd:"measurable_impression",VIEWABLE_IMPRESSION:"viewable_impression",dd:"fully_viewable_audible_half_duration_impression",de:"overlay_resize", ee:"overlay_unmeasurable_impression",fe:"overlay_unviewable_impression",he:"overlay_viewable_immediate_impression",ge:"overlay_viewable_end_of_session_impression",Uf:"externalActivityEvent",PAUSED:"pause",RESUMED:"resume",FIRST_QUARTILE:"firstQuartile",MIDPOINT:"midpoint",THIRD_QUARTILE:"thirdQuartile",COMPLETE:"complete",DURATION_CHANGE:"durationChange",USER_CLOSE:"userClose",ih:"userRecall",Ng:"prefetched",LOADED:"loaded",ALL_ADS_COMPLETED:"allAdsCompleted",SKIPPED:"skip",ke:"skipShown",LINEAR_CHANGED:"linearChanged", SKIPPABLE_STATE_CHANGED:"skippableStateChanged",AD_METADATA:"adMetadata",xf:"adBreakFetchError",AD_BREAK_READY:"adBreakReady",LOG:"log",VOLUME_CHANGED:"volumeChange",VOLUME_MUTED:"mute",INTERACTION:"interaction",Hf:"companionBackfill",fh:"trackingUrlPinged",kh:"video_card_endcap_collapse",lh:"video_card_endcap_dismiss",mh:"video_card_endcap_impression",Kf:"companionInitialized",Jf:"companionImpression",If:"companionClick",zg:"mediaUrlPinged",ae:"loadStart",Cg:"navigationRequested"}; x("module$contents$ima$AdEvent_AdEvent.Type",$B,void 0);var aC=function(a,b){b=void 0===b?null:b;ZB.call(this,"adMetadata",a);this.o=b};t(aC,ZB);aC.prototype.Be=function(){return this.o};aC.prototype.getAdCuePoints=aC.prototype.Be;var bC=function(a){this.adBreakDuration=a.adBreakDuration;this.adPosition=a.adPosition;this.currentTime=a.currentTime;this.duration=a.duration;this.totalAds=a.totalAds};var cC=function(a,b){K.call(this);this.l=a;this.A=b;this.h=this.l.currentTime;this.g=new oj(250);ji(this,this.g);this.o=new U(this);ji(this,this.o);St(this.o,this.g,"tick",this.C,!1,this)};t(cC,K);cC.prototype.Ya=function(){return this.h};cC.prototype.start=function(){dC(this);this.g.start()};cC.prototype.stop=function(){this.g.stop()};cC.prototype.C=function(){var a=this.l.currentTime;a!=this.Ya()&&(this.h=a,dC(this))}; var dC=function(a){var b={};b.currentTime=a.Ya();ay(a.A,"contentTimeUpdate","contentTimeUpdate",b)};var eC=function(a,b,c){K.call(this);this.h=a;this.g=null;this.I="";this.L=Cc;this.M=0;this.C=this.l=null;this.o=b;this.A=null;this.F="";this.H=c};t(eC,K); eC.prototype.init=function(a){this.F=a;a="about:blank";ud&&(a="");this.l=gf("IFRAME",{src:a,allowtransparency:!0,background:"transparent"});Vf(this.l,{display:"none",width:"0",height:"0"});a=this.h.H;a.appendChild(this.l);a=a.ownerDocument;a=a.defaultView||a.parentWindow;null==this.A&&(this.A=new U(this));this.A.P(a,"message",this.N);a='<body><script src="//imasdk.googleapis.com/js/sdkloader/loader.js">\x3c/script><script>loader = new VPAIDLoader(false, "'+(this.F+'");\x3c/script></body>');if(Td|| Pd||vd){var b=this.l.contentWindow;b&&OA(b.document,a)}else PA(this.l,a)}; eC.prototype.N=function(a){try{var b=a.g.data;try{var c=JSON.parse(b)}catch(La){return}var d=c.session;if(null!=d&&this.F==d)switch(c.type){case "friendlyReady":var e=fC(this);if(null!=e){this.g=e;this.I=e.currentSrc;var f=e.style.cssText;if(ud&&10>document.documentMode)var g=Cc;else{var h=document;"function"===typeof HTMLTemplateElement&&(h=ef(document,"TEMPLATE").content.ownerDocument);var k=h.implementation.createHTMLDocument("").createElement("DIV");k.style.cssText=f;g=gx(k.style)}this.L=g;this.M= e.currentTime}else{var n=this.h.H,m=this.h.N;var v="border: 0; margin: 0; padding: 0; position: absolute; width:"+(m.width+"px; ");v+="height:"+m.height+"px;";this.g=gf("VIDEO",{style:v,autoplay:!0});n.appendChild(this.g)}var r=this.h.H;e="border: 0; margin: 0; padding: 0;position: absolute; ";var w=cg(this.g);e+="width:"+w.width+"px; ";e+="height:"+w.height+"px;";this.C=gf("DIV",{style:e});r.appendChild(this.C);try{this.l.contentWindow.loader.initFriendly(this.g,this.C)}catch(La){gC(this)}ay(this.o, "vpaid","",b);break;case "becameLinear":this.g&&!of()&&!nf()&&Vf(this.g,{visibility:"visible"});ay(this.o,"vpaid","",b);break;case "becameNonlinear":hC(this);ay(this.o,"vpaid","",b);break;case "startAd":r={};if(this.g){h=this.g.paused;var B=0<this.g.currentTime;r.apl=B&&!h?"1":"0";r.ip=h?"1":"0";r.iavp=B?"1":"0"}else r.apl="n";vz.D().report(99,r);ay(this.o,"vpaid","",b);if(null!=fC(this)){var L=this.h;null!=L.h&&L.h.show()}break;default:ay(this.o,"vpaid","",b)}}catch(La){gC(this)}}; var gC=function(a){var b={type:"error"};b.session=a.F;a=Wg(b);window.postMessage(a,"*")},fC=function(a){return("videoDisplayUnknown"==a.H?a.h.g:a.h.M.get(a.H)).F.g},hC=function(a){a.g&&!of()&&!nf()&&Vf(a.g,{visibility:"hidden"})}; eC.prototype.O=function(){K.za.O.call(this);hi(this.A);this.A=null;hf(this.C);this.C=null;hf(this.l);this.l=null;var a=fC(this);if(null!=a){var b=this.L;a.style.cssText=b instanceof Bc&&b.constructor===Bc?b.g:"type_error:SafeStyle";of()||nf()?(a.src=this.I,a.currentTime=this.M):(a.removeAttribute("src"),a=this.h,null!=a.h&&pB(a.h.g,!1))}else hf(this.g),this.g=null};var iC=function(a,b){J.call(this);this.h=a;this.l=b;this.g=new Map};t(iC,J);var jC=function(a,b){try{var c=b.na,d=c.session;switch(c.vpaidEventType){case "createFriendlyIframe":b="videoDisplayUnknown";c.videoDisplayName&&(b=c.videoDisplayName);var e=c.session,f=new eC(a.h,a.l,b);a.g.set(e,f);f.init(e);break;case "vpaidNonLinear":var g=a.g.get(d);g&&hC(g);break;case "destroyFriendlyIframe":var h=a.g.get(d);h&&(h.X(),a.g.delete(d))}}catch(k){vz.D().report(125,{msg:k.message})}};iC.prototype.O=function(){this.g.forEach(function(a){return a.X()})};var kC=function(){this.g=[];this.h=[]},lC=function(a){return 0===a.g.length&&0===a.h.length};kC.prototype.remove=function(a){var b=this.g;b:{var c=b.length-1;0>c&&(c=Math.max(0,b.length+c));if("string"===typeof b)c="string"!==typeof a||1!=a.length?-1:b.lastIndexOf(a,c);else{for(;0<=c;c--)if(c in b&&b[c]===a)break b;c=-1}}0<=c?(ub(b,c),b=!0):b=!1;return b||tb(this.h,a)}; kC.prototype.Oa=function(){for(var a=[],b=this.g.length-1;0<=b;--b)a.push(this.g[b]);var c=this.h.length;for(b=0;b<c;++b)a.push(this.h[b]);return a};var Z=function(a,b,c,d,e,f,g){K.call(this);var h=this;this.I=a;this.g=b;this.M=c;this.jb=e;this.o=new Qz;this.C=g;this.N=!1;this.U=1;this.lb=d;this.ba=-1;this.l=this.h=null;this.H=new cC({currentTime:0},this.C);this.F=new kC;this.ea=this.Y=!1;this.Z=new Map;this.aa=this.wa=!1;this.Va=new iC(b,g);ji(this,this.Va);this.L=f&&null!=this.g.C;this.T=function(){var k=h.g.g,n=k.g.currentTime;k=k.getDuration();return{currentTime:n,duration:k,isPlaying:!0,volume:h.U}};this.W=new U(this);this.W.P(this.C,"adsManager", this.ob)};t(Z,K); Z.prototype.ob=function(a){var b=this,c=a.ka,d=a.na;switch(c){case "error":mC(this);nC(this,d);break;case "contentPauseRequested":vz.D().report(130);oC(this);pC(this,c,d);break;case "contentResumeRequested":qC(this,function(){return pC(b,c,d)});break;case "remainingTime":this.ba=d.remainingTime;break;case "skip":pC(this,c,d);break;case "log":pC(this,c,d,d.logData);break;case "companionBackfill":a=Ia("window.google_show_companion_ad");null!=a&&a();break;case "skipShown":this.N=!0;pC(this,c,d);break; case "interaction":pC(this,c,d,d.interactionData);break;case "vpaidEvent":jC(this.Va,a);break;case "skippableStateChanged":a=d.adData;null!=a.skippable&&(this.N=a.skippable);pC(this,c,d);break;case "volumeChange":a=d.adData;null!=a&&"number"===typeof a.volume&&(this.U=a.volume);pC(this,c,d);break;case "firstQuartile":pC(this,Zx.firstQuartile,d);pC(this,c,d);break;case "thirdQuartile":pC(this,Zx.thirdQuartile,d);pC(this,c,d);break;default:pC(this,c,d)}}; var pC=function(a,b,c,d){if(null==c.companions){var e=a.Z.get(c.adId);c.companions=null!=e?e:[]}var f=c.adData;if(e=null==f?null:new Y(f))a.h=e;switch(b){case "adBreakReady":case "mediaUrlPinged":b=new ZB(b,null,c);break;case "adMetadata":b=null;null!=c.adCuePoints&&(b=new VA(c.adCuePoints));b=new aC(e,b);break;case "allAdsCompleted":a.h=null;a.wa=!0;b=new ZB(b,e);break;case "contentPauseRequested":a.aa=!1;b=new ZB(b,e);break;case "contentResumeRequested":a.h=null;a.aa=!0;b=new ZB(b,e);break;case "loaded":a.ba= e.getDuration();a.N=!1;Ox()&&(d=a.I,c=a.jb,d.h.set(Bz(e),a.T),(0!=W.g?nq.D().l:d.A)&&Jz(d,"loaded",Bz(e),c));b=new ZB(b,e,f);break;case "start":a.Z.set(c.adId,c.companions);null!=JB(a.g)&&(null==a.l?(a.l=new Vy,a.W.P(a.l,"click",a.af)):Zy(a.l),Xy(a.l,JB(a.g)));b=new ZB(b,e);break;case "complete":null!=a.l&&Zy(a.l);Ox()&&Lz(a.I,a.T,Bz(e));a.h=null;a.Z.delete(c.adId);b=new ZB(b,e);break;case "log":c=null;null!=d&&null!=d.type?(f=d.type,f="adLoadError"==f||"adPlayError"==f):f=!1;f&&(c={adError:new VB(d)}); b=new ZB(b,e,c);break;case "interaction":b=new ZB(b,e,d);break;case "adProgress":b=new ZB(b,e,new bC(c));break;default:b=new ZB(b,e)}a.dispatchEvent(b);a.wa&&a.aa&&a.destroy()},nC=function(a,b){var c=new XB(new VB(b));a.Y?(a.dispatchEvent(c),Ox()&&a.h&&Lz(a.I,a.T,Bz(a.h)),a.h=null):a.F.h.push(c);a={error:b.errorCode,vis:zg(document)};vz.D().report(7,a)},rC=function(a,b,c){ay(a.C,"adsManager",b,c)},qC=function(a,b){vz.D().report(131);mC(a,b)},oC=function(a){var b=a.g.g;TB(a.g)&&a.o.restoreCustomPlaybackStateOnAdBreakComplete&& null!=b.gd&&b.gd()},mC=function(a,b){var c=a.g.g;TB(a.g)&&a.o.restoreCustomPlaybackStateOnAdBreakComplete&&null!=c.Nb?c.Nb(b):b&&b()};l=Z.prototype; l.init=function(a,b,c,d){if(lC(this.F)){var e=this.g,f=null;e.A&&null==d&&(f={vd:"setnull"});e.A&&e.A===d&&(f={vd:"match"});if(e.A&&e.A!==d){f=Nx(d||null);var g=Nt(d||null);f={vd:"diff",oc:e.Z,nc:f,oi:e.Y,ni:g}}!e.A&&d&&(f={vd:"new"});f&&(f.custVid=e.W,vz.D().report(93,f));null!=d&&(e.F=SB(d),Mx(e.F)&&(e.U=!0,hi(e.h),hi(e.o),hi(e.l),e.h=null,e.o=null,e.l=null,hi(e.g),e.g=new bB(d),"function"!==typeof d.getBoundingClientRect?(e.K=e.B,W.l=e.K):e.K=d,null!=(d=e.J.H)&&(e=e.g.F.g,d.o=e,d.g&&(d=d.g,d.g= e,TA(d,e)))));this.Y=!0;this.resize(a,b,c);e=Rz(this.o,this.L);rC(this,"init",{adsRenderingSettings:e,width:a,height:b,viewMode:c})}else{for(;!lC(this.F);)b=a=this.F,0===b.g.length&&(b.g=b.h,b.g.reverse(),b.h=[]),a=a.g.pop(),this.dispatchEvent(a);this.X()}};l.Te=function(){return TB(this.g)};l.Se=function(){return this.L};l.getRemainingTime=function(){return this.ba};l.getAdSkippableState=function(){return this.N};l.ze=function(){rC(this,"discardAdBreak")}; l.updateAdsRenderingSettings=function(a){if(null!=a){var b=this.o.bitrate,c=a.bitrate;vz.D().report(96,{init:this.Y?"1":"0",start:this.ea?"1":"0",old:b,"new":c,changed:b!=c?"1":"0"});this.o=a;a=Rz(this.o,this.L);rC(this,"updateAdsRenderingSettings",{adsRenderingSettings:a})}};l.skip=function(){rC(this,"skip")}; l.start=function(){if(this.M){(Bd||Dd)&&vz.D().report(50,{customPlayback:TB(this.g)});this.g.I||vz.D().report(26,{adtagurl:this.M,customPlayback:TB(this.g)});Ul(this.g.B)&&vz.D().report(30,{adtagurl:this.M,customPlayback:TB(this.g)});var a=this.g.C,b=this.g.B,c;if(c=a&&b&&!Ul(a))a=Hz(a),b=Hz(b),c=0<a.width&&0<a.height&&0<b.width&&0<b.height&&a.left<=b.left+b.width&&b.left<=a.left+a.width&&a.top<=b.top+b.height&&b.top<=a.top+a.height;c&&vz.D().report(31,{adtagurl:this.M,customPlayback:TB(this.g)})}if(!this.g.I&& !TB(this.g))throw hy(fy);b=this.g;b.T=this.L&&null!=b.C;this.g.J.g.style.opacity=1;null!=this.A&&1==this.getVolume()&&("boolean"===typeof this.A.muted&&this.A.muted?this.setVolume(0):"number"===typeof this.A.volume&&(b=this.A.volume,0<=b&&1>=b&&this.setVolume(this.A.volume)));this.ea=!0;rC(this,"start")};l.af=function(){if(!this.o.disableClickThrough&&null!=this.h){var a=this.h.g.clickThroughUrl;null!=a&&lu(a)}}; l.resize=function(a,b,c){var d=this.g,e=d.B;null!=e&&(-1==a?(e.style.right="0",e.style.left="0"):e.style.width=a+"px",-1==b?(e.style.bottom="0",e.style.top="0"):e.style.height=b+"px");e=d.J;e.g.width=-1==a?"100%":a;e.g.height=-1==b?"100%":b;try{e.g.offsetTop=e.g.offsetTop}catch(f){}d.N=new Ve(a,b);rC(this,"resize",{width:a,height:b,viewMode:c})};l.stop=function(){rC(this,"stop")};l.expand=function(){rC(this,"expand")};l.collapse=function(){rC(this,"collapse")};l.getVolume=function(){return this.U}; l.setVolume=function(a){this.U=a;this.g.g.setVolume(a);rC(this,"volume",{volume:a})};l.pause=function(){rC(this,"pause")};l.resume=function(){rC(this,"resume")};l.destroy=function(){this.X()};l.getCuePoints=function(){return this.lb};l.getCurrentAd=function(){return this.h};l.O=function(){rC(this,"destroy");null!=this.l&&this.l.X();this.W.X();var a=this.F;a.g=[];a.h=[];this.H&&(this.H.stop(),this.H.X());Ox()&&Lz(this.I,this.T);K.prototype.O.call(this)}; l.clicked=function(){vz.D().report(124,{api:"clicked"});var a=this.h&&this.h.g.clickThroughUrl;a&&this.h.isUiDisabled()&&lu(a);rC(this,"click")};l.focus=function(){ay(this.C,"userInteraction","focusUiElement")};Z.prototype.clicked=Z.prototype.clicked;Z.prototype.getCurrentAd=Z.prototype.getCurrentAd;Z.prototype.getCuePoints=Z.prototype.getCuePoints;Z.prototype.destroy=Z.prototype.destroy;Z.prototype.resume=Z.prototype.resume;Z.prototype.pause=Z.prototype.pause;Z.prototype.setVolume=Z.prototype.setVolume; Z.prototype.getVolume=Z.prototype.getVolume;Z.prototype.collapse=Z.prototype.collapse;Z.prototype.expand=Z.prototype.expand;Z.prototype.stop=Z.prototype.stop;Z.prototype.resize=Z.prototype.resize;Z.prototype.start=Z.prototype.start;Z.prototype.skip=Z.prototype.skip;Z.prototype.updateAdsRenderingSettings=Z.prototype.updateAdsRenderingSettings;Z.prototype.discardAdBreak=Z.prototype.ze;Z.prototype.getAdSkippableState=Z.prototype.getAdSkippableState;Z.prototype.getRemainingTime=Z.prototype.getRemainingTime; Z.prototype.isCustomClickTrackingUsed=Z.prototype.Se;Z.prototype.isCustomPlaybackUsed=Z.prototype.Te;Z.prototype.init=Z.prototype.init;var sC=function(a,b){ki.call(this,"adsManagerLoaded");this.g=a;this.l=b};t(sC,ki);sC.prototype.getAdsManager=function(a,b){a=a||{currentTime:null};var c=this.g;c.A=a;null!=a.currentTime&&(c.H=new cC(a,c.C),c.H.start());null!=b&&(c.o=b);return this.g};sC.prototype.getUserRequestContext=function(){return this.l};sC.prototype.getUserRequestContext=sC.prototype.getUserRequestContext;sC.prototype.getAdsManager=sC.prototype.getAdsManager;var tC={ADS_MANAGER_LOADED:"adsManagerLoaded"}; x("module$contents$ima$AdsManagerLoadedEvent_AdsManagerLoadedEvent.Type",tC,void 0);var uC=function(){this.videoPlayMuted=this.videoPlayActivation="unknown";this.videoContinuousPlay="0";this.nonLinearAdSlotHeight=this.nonLinearAdSlotWidth=this.linearAdSlotHeight=this.linearAdSlotWidth=this.liveStreamPrefetchSeconds=0;this.forceNonLinearFullSlot=!1;this.contentTitle=this.contentKeywords=this.contentDuration=null;this.vastLoadTimeout=5E3;this.omidAccessModeRules={};this.pageUrl=null};uC.prototype.setAdWillAutoPlay=function(a){this.videoPlayActivation=a?"auto":"click"}; uC.prototype.setAdWillPlayMuted=function(a){this.videoPlayMuted=a?"muted":"unmuted"};uC.prototype.setContinuousPlayback=function(a){this.videoContinuousPlay=a?"2":"1"};uC.prototype.setContinuousPlayback=uC.prototype.setContinuousPlayback;uC.prototype.setAdWillPlayMuted=uC.prototype.setAdWillPlayMuted;uC.prototype.setAdWillAutoPlay=uC.prototype.setAdWillAutoPlay;var vC=function(a){try{var b=new O(a);if(!b.g.includes(".cdn.ampproject.org"))return null;var c=b.h.split("/").slice(1);if("s"==c[1]&&3>c.length)return null;if(2>c.length)return a;var d="s"==c[1];c=d?c.slice(2):c.slice(1);var e=decodeURIComponent(c[0])+"/";return d?"https://"+e+c.slice(1).join("/"):"http://"+e+c.slice(1).join("/")}catch(f){return null}};var wC=function(a){var b=document;try{var c=Xr(b);var d=c?Ie(Zr,c):null}catch(e){d=null}if(!d)return 0;if(we(d,7))return 4;if(a){if(sb(A(d,3),a))return 2;if(sb(A(d,4),a))return 3}return 1};function xC(a){return qx(Jr)&&!a.navigator.cookieEnabled?!1:"null"!==a.origin}function yC(a,b,c){b=we(b,5)&&xC(c)?c.document.cookie:null;return null===b?null:(new Ur({cookie:b})).get(a)||""};var zC=function(){this.g=window;this.h=0};var AC=function(a,b,c){var d="script";d=void 0===d?"":d;var e=a.createElement("link");try{if(e.rel="preload",pc("preload","stylesheet")){e.href=cc(b).toString();var f=Tc('style[nonce],link[rel="stylesheet"][nonce]',e.ownerDocument&&e.ownerDocument.defaultView);f&&e.setAttribute("nonce",f)}else e.href=b instanceof bc?cc(b).toString():b instanceof tc?uc(b):uc(yc(b))}catch(g){return}d&&(e.as=d);c&&e.setAttribute("nonce",c);if(a=a.getElementsByTagName("head")[0])try{a.appendChild(e)}catch(g){}};var BC=/^\.google\.(com?\.)?[a-z]{2,3}$/,CC=/\.(cn|com\.bi|do|sl|ba|by|ma|am)$/,DC=u,FC=function(a){a="https://adservice"+(a+"/adsid/integrator.js");var b=["domain="+encodeURIComponent(u.location.hostname)];EC[3]>=Xa()&&b.push("adsid="+encodeURIComponent(EC[1]));return a+"?"+b.join("&")},EC,GC,HC=function(){DC=u;EC=DC.googleToken=DC.googleToken||{};var a=Xa();EC[1]&&EC[3]>a&&0<EC[2]||(EC[1]="",EC[2]=-1,EC[3]=-1,EC[4]="",EC[6]="");GC=DC.googleIMState=DC.googleIMState||{};a=GC[1];BC.test(a)&&!CC.test(a)|| (GC[1]=".google.com");Array.isArray(GC[5])||(GC[5]=[]);"boolean"!==typeof GC[6]&&(GC[6]=!1);Array.isArray(GC[7])||(GC[7]=[]);"number"!==typeof GC[8]&&(GC[8]=0)},IC={Ac:function(){return 0<GC[8]},ff:function(){GC[8]++},gf:function(){0<GC[8]&&GC[8]--},hf:function(){GC[8]=0},zh:function(){return!1},yd:function(){return GC[5]},qd:function(a){try{a()}catch(b){u.setTimeout(function(){throw b;},0)}},Id:function(){if(!IC.Ac()){var a=u.document,b=function(e){e=FC(e);a:{try{var f=Tc("script[nonce]",void 0); break a}catch(g){}f=void 0}AC(a,e,f);f=a.createElement("script");f.type="text/javascript";f.onerror=function(){return u.processGoogleToken({},2)};e=Tf(e);f.src=cc(e);Ke(f);try{(a.head||a.body||a.documentElement).appendChild(f),IC.ff()}catch(g){}},c=GC[1];b(c);".google.com"!=c&&b(".google.com");b={};var d=(b.newToken="FBT",b);u.setTimeout(function(){return u.processGoogleToken(d,1)},1E3)}}},JC=function(a){HC();var b=DC.googleToken[5]||0;a&&(0!=b||EC[3]>=Xa()?IC.qd(a):(IC.yd().push(a),IC.Id()));EC[3]>= Xa()&&EC[2]>=Xa()||IC.Id()},KC=function(a){u.processGoogleToken=u.processGoogleToken||function(b,c){var d=b;d=void 0===d?{}:d;c=void 0===c?0:c;b=d.newToken||"";var e="NT"==b,f=parseInt(d.freshLifetimeSecs||"",10),g=parseInt(d.validLifetimeSecs||"",10),h=d["1p_jar"]||"";d=d.pucrd||"";HC();1==c?IC.hf():IC.gf();var k=DC.googleToken=DC.googleToken||{},n=0==c&&b&&"string"===typeof b&&!e&&"number"===typeof f&&0<f&&"number"===typeof g&&0<g&&"string"===typeof h;e=e&&!IC.Ac()&&(!(EC[3]>=Xa())||"NT"==EC[1]); var m=!(EC[3]>=Xa())&&0!=c;if(n||e||m)e=Xa(),f=e+1E3*f,g=e+1E3*g,1E-5>Math.random()&&Of(u,"https://pagead2.googlesyndication.com/pagead/gen_204?id=imerr&err="+c),k[5]=c,k[1]=b,k[2]=f,k[3]=g,k[4]=h,k[6]=d,HC();if(n||!IC.Ac()){c=IC.yd();for(b=0;b<c.length;b++)IC.qd(c[b]);c.length=0}};JC(a)};var LC=function(a,b){b=void 0===b?500:b;J.call(this);this.h=a;this.B=b;this.g=null;this.o={};this.A=0;this.l=null};t(LC,J);LC.prototype.O=function(){this.o={};this.l&&(Qe(this.h,"message",this.l),delete this.l);delete this.o;delete this.h;delete this.g;J.prototype.O.call(this)}; var NC=function(a){var b;return"function"===typeof(null===(b=a.h)||void 0===b?void 0:b.__uspapi)||null!=MC(a)},PC=function(a,b){var c={};if(NC(a)){var d=fb(function(){return b(c)});OC(a,function(e,f){f&&(c=e);d()});setTimeout(d,a.B)}else b(c)},OC=function(a,b){var c,d;if("function"===typeof(null===(c=a.h)||void 0===c?void 0:c.__uspapi))(null===(d=a.h)||void 0===d?void 0:d.__uspapi)("getUSPData",1,b);else if(MC(a)){QC(a);var e=++a.A;a.o[e]=b;a.g&&(b={},a.g.postMessage((b.__uspapiCall={command:"getUSPData", version:1,callId:e},b),"*"))}},MC=function(a){if(a.g)return a.g;a.g=Gf(a.h,"__uspapiLocator");return a.g},QC=function(a){a.l||(a.l=function(b){var c;try{var d={};"string"===typeof b.data?d=JSON.parse(b.data):d=b.data;var e=d.__uspapiReturn;null===(c=a.o)||void 0===c?void 0:c[e.callId](e.returnValue,e.success)}catch(f){}},Pe(a.h,"message",a.l))};var RC=function(a){a=void 0===a?window:a;return!a.PeriodicSyncManager},SC={issuerOrigin:"https://adservice.google.com",issuancePath:"/tt/i",redemptionPath:"/tt/r",shouldRedeemToken:function(){var a=void 0===a?window:a;return!RC(a)||qx(Pr)?!0:!1},shouldRequestToken:function(){return!1}},TC=function(){var a=void 0===a?window:a;if(!RC(a)&&qx(Kr)||RC(a)&&qx(Lr)){a=a.navigator.userAgent;var b=/Chrome/.test(a);return/Android/.test(a)&&b}return!1},UC={issuerOrigin:"https://attestation.android.com",issuancePath:"/att/i", redemptionPath:"/att/r",shouldRedeemToken:function(){return TC()},shouldRequestToken:function(){return TC()}};var Hf=["A+b/H0b8RPXNaJgaNFpO0YOFuGK6myDQXlwnJB3SwzvNMfcndat4DZYMrP4ClJIzYWo3/yP2S+8FTZ/lpqbPAAEAAABueyJvcmlnaW4iOiJodHRwczovL2ltYXNkay5nb29nbGVhcGlzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2MjYyMjA3OTksImlzVGhpcmRQYXJ0eSI6dHJ1ZX0=","A9ZgbRtm4pU3oZiuNzOsKcC8ppFSZdcjP2qYcdQrFKVzkmiWH1kdYY1Mi9x7G8+PS8HV9Ha9Cz0gaMdKsiVZIgMAAAB7eyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2MjYyMjA3OTksImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9", "AxL6oBxcpn5rQDPKSAs+d0oxNyJYq2/4esBUh3Yx5z8QfcLu+AU8iFCXYRcr/CEEfDnkxxLTsvXPJFQBxHfvkgMAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2MjYyMjA3OTksImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9","A9KPtG5kl3oLTk21xqynDPGQ5t18bSOpwt0w6kGa6dEWbuwjpffmdUpR3W+faZDubGT+KIk2do0BX2ca16x8qAcAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2MjYyMjA3OTksImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9", "AookgM0K6zABiuRTZwpn+R95G2CKmUH/2+zf2kS/QpMlVZ6HTI6QekeLkrJyxeIi62p2ejcQTF464pkdlx0Nwg0AAABmeyJvcmlnaW4iOiJodHRwczovL3d3dy5nb29nbGUuY29tOjQ0MyIsImZlYXR1cmUiOiJUcnVzdFRva2VucyIsImV4cGlyeSI6MTYzNDA4MzE5OSwiaXNTdWJkb21haW4iOnRydWV9"],XC=function(a,b){a=void 0===a?function(){}:a;b=void 0===b?null:b;J.call(this);VC();this.l=b||qx(Nr)?[UC]:[SC,UC];this.g=a;if(document.hasTrustToken&&!qx(Mr))if(qx(Or)){if(!Array.isArray(window.goog_tt_state)){var c=WC(this);Object.defineProperty(window,"goog_tt_state", {configurable:!1,get:function(){return c.slice()}})}}else this.h=WC(this)};t(XC,J); var VC=function(){var a=void 0===a?window.document:a;If(a)},WC=function(a){var b=a.l.map(function(c){return{issuerOrigin:c.issuerOrigin,state:1}});qx(Or)||a.g(b);return b},YC=function(a,b,c){if(qx(Or)){if(a=window.goog_tt_state.find(function(e){return e.issuerOrigin===b}))a.state=c}else{var d=a.h.find(function(e){return e.issuerOrigin===b});d&&(d.state=c,a.g(a.h))}},ZC=function(){var a=window.goog_tt_state;return Array.isArray(a)&&a.some(function(b){return 1!=b.state})},$C=function(a,b){var c=""+ b.issuerOrigin+b.redemptionPath,d={keepalive:!0,redirect:"follow",method:"get",trustToken:{type:"token-redemption",issuer:b.issuerOrigin,refreshPolicy:"none"}};YC(a,b.issuerOrigin,2);return window.fetch(c,d).then(function(e){if(!e.ok)throw Error(e.status+": Network response was not ok!");YC(a,b.issuerOrigin,6)}).catch(function(e){e&&"NoModificationAllowedError"===e.name?YC(a,b.issuerOrigin,6):YC(a,b.issuerOrigin,5)})},aD=function(a,b,c){var d=""+b.issuerOrigin+b.issuancePath;YC(a,b.issuerOrigin,8); return window.fetch(d,{trustToken:{type:"token-request"}}).then(function(e){if(!e.ok)throw Error(e.status+": Network response was not ok!");YC(a,b.issuerOrigin,10);if(c)return $C(a,b)}).catch(function(e){if(e&&"NoModificationAllowedError"===e.name){if(YC(a,b.issuerOrigin,10),c)return $C(a,b)}else YC(a,b.issuerOrigin,9)})},bD=function(a){if(!(!document.hasTrustToken||qx(Mr)||qx(Or)&&ZC())){var b=[];a.l.forEach(function(c){var d=c.shouldRedeemToken(),e=c.shouldRequestToken();if(d||e){var f=document.hasTrustToken(c.issuerOrigin).then(function(g){if(g){if(d)return $C(a, c)}else{if(e)return aD(a,c,d);YC(a,c.issuerOrigin,3)}});b.push(f)}else YC(a,c.issuerOrigin,7)});window.Promise&&window.Promise.all&&window.Promise.all(b)}};(function(){if(!Eb(function(b){return b.match(D().location.href)})){var a=sz($e());null==a&&document.querySelectorAll&&(a=sz(document.querySelectorAll("script")));if(null==a)throw Error("IMA SDK is either not loaded from a google domain or is not a supported version.");}})(); var dD=function(a){K.call(this);var b=this,c=lx(nx(this.getSettings()));c&&0<c.length&&(jh.reset(),lh(new Nh(c)));this.F=new zC;this.g=a;this.H=new Map;this.l=this.g.J;this.I=new U(this);ji(this,this.I);this.L=new tx(window);this.M=new LC(window);this.o=null;this.A={};0!=W.g?(this.h=new Dz,ji(this,this.h)):this.h=Fz();Ox()&&(this.h.init(GB(this.l)),this.C=Kz(this.h,this.g.K),ii(this,function(){var d=b.C;b.h.o.delete(d);0!=W.g&&(nq.D().B[d]=null)}));gh(bi)&&cD(this)};t(dD,K);dD.prototype.destroy=function(){this.X()}; dD.prototype.getVersion=function(){return"h.3.467.0"};dD.prototype.requestAds=function(a,b){var c=this,d=[],e=null;vx(this.L)&&d.push(new Promise(function(g){yx(c.L,function(h){e=h;g()})}));var f=null;NC(this.M)&&d.push(new Promise(function(g){PC(c.M,function(h){f=h;g()})}));Promise.all(d).then(function(){eD(c,a,b,{Vc:e,Zc:f})})}; var eD=function(a,b,c,d){var e=b.adTagUrl;e&&vz.D().report(8,{adtagurl:e,customPlayback:TB(a.g),customClick:null!=a.g.C});var f="goog_"+ad++;a.H.set(f,c||null);var g=fD({adTagUrl:e,Dd:!1,Vc:d.Vc,Zc:d.Zc});a.o=Dx(e,g||{});gD(Fx(a.o))?hD().then(function(){iD(a,f,b,g)}):iD(a,f,b,g)};dD.prototype.getSettings=function(){return W};dD.prototype.contentComplete=function(){ay(GB(this.l),"adsLoader","contentComplete")};var gD=function(a){return a?!1:!Lx()}; dD.prototype.N=function(a){var b=a.ka;switch(b){case "adsLoaded":b=a.na;a=a.Mb;b=new Z(this.h,this.g,b.adTagUrl||"",b.adCuePoints,this.C,b.isCustomClickTrackingAllowed,GB(this.l,a));this.dispatchEvent(new sC(b,jD(this,a)));break;case "error":b=a.na;this.dispatchEvent(new XB(new VB(b),jD(this,a.Mb)));a={error:b.errorCode,vis:zg(document)};vz.D().report(7,a);break;case "cookieUpdate":a=a.na;if(null==a)break;var c=a.gfpCookie;if(c&&W.h){var d=new ox;Ae(d,5,!0);b=this.F;c=Ie(Qj,c);var e={Ed:A(c,2)-b.g.Date.now()/ 1E3,path:A(c,3),domain:A(c,4),kf:!1},f=A(c,1),g=b.g;we(d,5)&&xC(g)&&(new Ur(g.document)).set("__gads",f,e);we(d,5)&&.01>b.g.Math.random()&&(d=yC("__gads",d,b.g),Qf({domain:A(c,4),host:b.g.location.host,success:d===A(c,1)?"1":"0"},"gfp_cw_status"))}kD(this,a.encryptedSignalBidderIds||[]);break;case "trackingUrlPinged":this.dispatchEvent(new ZB(b,null,a.na))}}; var kD=function(a,b){0!=b.length&&(b=Uy(b.map(function(c){return{Fa:c}}),a.o))&&b.forEach(function(c){return c.then(function(d){d&&(d=ty(Ty(a.o)))&&(a.A.espSignals=d,lD(a))})})},lD=function(a){ay(GB(a.l),"adsLoader","signalsRefresh",a.A)},jD=function(a,b){var c=a.H.get(b);a.H.delete(b);return c},fD=function(a){var b=a.adTagUrl;if(b){var c=/iu=\/(\d+)\//.exec(Vc(b));(c=c&&2==c.length?c[1]:null)||(b=$c((new O(b)).l.get("client")),c=fc(b)?null:b);b=c}else b=null;b=b||"";var d=void 0===d?u:d;c=wC(b); if(0!=c)var e=c;else e=void 0===e?u:e,e=e.top,e=Ff(e,"googlefcInactive")?4:b&&Ff(e,"googlefcPA-"+b)?2:Ff(e,"googlefcNPA")?3:0;b=d;d=b=void 0===b?u:b;d=void 0===d?u:d;(d=!!d.googlefc)||(d=b.top,d=void 0===d?u.top:d,d=Ff(d,"googlefcPresent"));var f=void 0===f?u:f;f=Ff(f.top,"googlefcLoaded");b=a.Vc;c=a.Zc;var g={};return g.gfcPresent=d&&4!=e,g.gfcLoaded=f,g.gfcUserConsent=e,g.isGdprLoader=a.Dd,g.addtlConsent=b?b.addtlConsent:null,g.gdprApplies=b?b.gdprApplies:null,g.tcString=b?b.tcString:null,g.uspString= c?c.uspString:null,g},hD=function(){return new Promise(function(a){KC(function(){HC();W.C=EC[1]||"";HC();W.W=EC[6]||"";HC();W.I=EC[4]||"";a()})})},iD=function(a,b,c,d){var e={};e=(e.limaExperimentIds=kh().sort().join(","),e);var f=a.getSettings(),g=0!=W.g?nq.D().l:a.h.A;g=void 0===g?null:g;var h={};null!=g&&(h.activeViewPushUpdates=g);h.activityMonitorMode=f.g;h.adsToken=f.C;h.autoPlayAdBreaks=f.isAutoPlayAdBreaks();h.companionBackfill=f.getCompanionBackfill();h.cookiesEnabled=f.h;h.disableCustomPlaybackForIOS10Plus= f.getDisableCustomPlaybackForIOS10Plus();h.engagementDetection=!0;h.isFunctionalTest=!1;h.isVpaidAdapter=f.Fb();h["1pJar"]=f.I;h.numRedirects=f.getNumRedirects();h.pageCorrelator=f.N;h.persistentStateCorrelator=kg();h.playerType=f.getPlayerType();h.playerVersion=f.getPlayerVersion();h.ppid=f.getPpid();h.privacyControls=f.W;h.reportMediaRequests=!1;h.sessionId=f.Z;h.streamCorrelator=f.Y;h.testingConfig=nx(f).g;h.urlSignals=f.ba;h.vpaidMode=f.getVpaidMode();h.featureFlags=f.getFeatureFlags();g=c.adTagUrl; f={};f.contentMediaUrl=a.g.L;f.customClickTrackingProvided=null!=a.g.C;a:{var k=Tj();k=q(k);for(var n=k.next();!n.done;n=k.next())if(n=n.value,n.url&&n.url.includes("amp=1")){k=!0;break a}k=null!=window.context?0<parseInt(window.context.ampcontextVersion,10):null!=Wj().l}f.isAmp=k;a:{try{var m=window.top.location.href}catch(mD){m=2;break a}m=null==m?2:m==window.document.location.href?0:1}f.iframeState=m;f.imaHostingDomain=window.document.domain;f.imaHostingPageUrl=window.document.URL;if(Zl())m=window.location.href; else{n=Wj();m=n.h;k=n.g;n=n.l;var v=null;n&&(v=vC(n.url));m=v?v:m&&m.url?m.url:k&&k.url?k.url:""}f.topAccessiblePageUrl=m;f.referrer=window.document.referrer;f.domLoadTime=a.l.L;f.sdkImplLoadTime=a.l.M;f.supportsResizing=!TB(a.g);m=D().location.ancestorOrigins;f.topOrigin=m?0<m.length&&200>m[m.length-1].length?m[m.length-1]:"":null;f.osdId=a.C;f.usesCustomVideoPlayback=TB(a.g);f.usesInlinePlayback=a.g.F;k=a.g.H;m=[];v=n="";if(null!=k){n=k;v=!0;v=void 0===v?!1:v;for(var r=[],w=0;n&&25>w;++w){var B= "";void 0!==v&&v||(B=(B=9!==n.nodeType&&n.id)?"/"+B:"");a:{if(n&&n.nodeName&&n.parentElement){var L=n.nodeName.toString().toLowerCase();for(var La=n.parentElement.childNodes,Uc=0,Ad=0;Ad<La.length;++Ad){var Sa=La[Ad];if(Sa.nodeName&&Sa.nodeName.toString().toLowerCase()===L){if(n===Sa){L="."+Uc;break a}++Uc}}}L=""}r.push((n.nodeName&&n.nodeName.toString().toLowerCase())+B+L);n=n.parentElement}n=r.join();if(k){k=(k=k.ownerDocument)&&(k.defaultView||k.parentWindow)||null;v=[];if(k)try{var S=k.parent; for(r=0;S&&S!==k&&25>r;++r){var Zc=S.frames;for(w=0;w<Zc.length;++w)if(k===Zc[w]){v.push(w);break}k=S;S=k.parent}}catch(mD){}v=v.join()}else v=""}m.push(n,v);if(null!=g){for(S=0;S<Qs.length-1;++S)m.push(tf(g,Qs[S])||"");S=tf(g,"videoad_start_delay");Zc="";S&&(S=parseInt(S,10),Zc=0>S?"postroll":0==S?"preroll":"midroll");m.push(Zc)}else for(S=0;S<Qs.length;++S)m.push("");S=m.join(":");Zc=S.length;if(0==Zc)S=0;else{g=305419896;for(m=0;m<Zc;m++)g^=(g<<5)+(g>>2)+S.charCodeAt(m)&4294967295;S=0<g?g:4294967296+ g}f=(f.videoAdKey=S.toString(),f);S={};d=(S.consentSettings=d,S.imalibExperiments=e,S.settings=h,S.videoEnvironment=f,S);e={};e.adsResponse=c.adsResponse;e.videoPlayActivation=c.videoPlayActivation;e.videoPlayMuted=c.videoPlayMuted;e.videoContinuousPlay=c.videoContinuousPlay;e.adTagUrl=c.adTagUrl;e.contentDuration=c.contentDuration;e.contentKeywords=c.contentKeywords;e.contentTitle=c.contentTitle;e.linearAdSlotWidth=c.linearAdSlotWidth;e.linearAdSlotHeight=c.linearAdSlotHeight;e.nonLinearAdSlotWidth= c.nonLinearAdSlotWidth;e.nonLinearAdSlotHeight=c.nonLinearAdSlotHeight;e.forceNonLinearFullSlot=c.forceNonLinearFullSlot;e.liveStreamPrefetchSeconds=c.liveStreamPrefetchSeconds;e.vastLoadTimeout=c.vastLoadTimeout;e.omidAccessModeRules=c.omidAccessModeRules;e.pageUrl=c.pageUrl;Object.assign(d,e);if(a.o&&W.h){e=a.o;c=new ox;e=!Fx(e);Ae(c,5,e);e=a.F;if(0===e.h){if(yC("__gads",c,e.g))h=!0;else if(h=e.g,we(c,5)&&xC(h)&&(new Ur(h.document)).set("GoogleAdServingTest","Good",void 0),h="Good"===yC("GoogleAdServingTest", c,e.g))f=e.g,we(c,5)&&xC(f)&&(new Ur(f.document)).remove("GoogleAdServingTest");e.h=h?2:1}d.isBrowserCookieEnabled=2===e.h;c=yC("__gads",c,a.F.g);null!==c&&(d.gfpCookieValue=c)}d.trustTokenStatus=a.A.trustTokenStatus;if(c=ty(Ty(a.o)))a.A.espSignals=c,d.espSignals=c;d.isEapLoader=!1;b=GB(a.l,b);a.I.P(b,"adsLoader",a.N);ay(b,"adsLoader","requestAds",d)},cD=function(a){bD(new XC(function(b){a.A.trustTokenStatus=b;lD(a)}))};dD.prototype.contentComplete=dD.prototype.contentComplete; dD.prototype.getSettings=dD.prototype.getSettings;dD.prototype.requestAds=dD.prototype.requestAds;dD.prototype.getVersion=dD.prototype.getVersion;dD.prototype.destroy=dD.prototype.destroy;x("google.ima.AdCuePoints",VA,window);x("google.ima.AdDisplayContainer",UB,window); x("google.ima.AdError.ErrorCode",{DEPRECATED_ERROR_CODE:-1,VAST_MALFORMED_RESPONSE:100,VAST_SCHEMA_VALIDATION_ERROR:101,VAST_UNSUPPORTED_VERSION:102,VAST_TRAFFICKING_ERROR:200,VAST_UNEXPECTED_LINEARITY:201,VAST_UNEXPECTED_DURATION_ERROR:202,VAST_WRAPPER_ERROR:300,VAST_LOAD_TIMEOUT:301,VAST_TOO_MANY_REDIRECTS:302,VAST_NO_ADS_AFTER_WRAPPER:303,VIDEO_PLAY_ERROR:400,VAST_MEDIA_LOAD_TIMEOUT:402,VAST_LINEAR_ASSET_MISMATCH:403,VAST_PROBLEM_DISPLAYING_MEDIA_FILE:405,OVERLAY_AD_PLAYING_FAILED:500,NONLINEAR_DIMENSIONS_ERROR:501, Ig:502,jh:503,Lf:602,Gf:603,UNKNOWN_ERROR:900,VPAID_ERROR:901,FAILED_TO_REQUEST_ADS:1005,VAST_ASSET_NOT_FOUND:1007,VAST_EMPTY_RESPONSE:1009,UNKNOWN_AD_RESPONSE:1010,UNSUPPORTED_LOCALE:1011,ADS_REQUEST_NETWORK_ERROR:1012,INVALID_AD_TAG:1013,STREAM_INITIALIZATION_FAILED:1020,ASSET_FALLBACK_FAILED:1021,INVALID_ARGUMENTS:1101,Bg:1204,AUTOPLAY_DISALLOWED:1205,CONSENT_MANAGEMENT_PROVIDER_NOT_READY:1300,Yg:2002},window);x("google.ima.AdError.ErrorCode.VIDEO_ELEMENT_USED",-1,window); x("google.ima.AdError.ErrorCode.VIDEO_ELEMENT_REQUIRED",-1,window);x("google.ima.AdError.ErrorCode.VAST_MEDIA_ERROR",-1,window);x("google.ima.AdError.ErrorCode.ADSLOT_NOT_VISIBLE",-1,window);x("google.ima.AdError.ErrorCode.OVERLAY_AD_LOADING_FAILED",-1,window);x("google.ima.AdError.ErrorCode.VAST_MALFORMED_RESPONSE",-1,window);x("google.ima.AdError.ErrorCode.COMPANION_AD_LOADING_FAILED",-1,window);x("google.ima.AdError.Type",WB,window);x("google.ima.AdErrorEvent.Type",YB,window); x("google.ima.AdEvent.Type",$B,window);x("google.ima.AdsLoader",dD,window);x("google.ima.AdsManagerLoadedEvent.Type",tC,window);x("google.ima.CompanionAdSelectionSettings",Px,window);x("google.ima.CompanionAdSelectionSettings.CreativeType",Qx,void 0);x("google.ima.CompanionAdSelectionSettings.ResourceType",Rx,void 0);x("google.ima.CompanionAdSelectionSettings.SizeCriteria",Sx,void 0);x("google.ima.CustomContentLoadedEvent.Type.CUSTOM_CONTENT_LOADED","deprecated-event",window); x("ima.ImaSdkSettings",V,window);x("google.ima.settings",W,window);x("google.ima.ImaSdkSettings.CompanionBackfillMode",{ALWAYS:"always",ON_MASTER_AD:"on_master_ad"},void 0);x("google.ima.ImaSdkSettings.VpaidMode",{DISABLED:0,ENABLED:1,INSECURE:2},void 0);x("google.ima.AdsRenderingSettings",Qz,window);x("google.ima.AdsRenderingSettings.AUTO_SCALE",-1,window);x("google.ima.AdsRequest",uC,window);x("google.ima.VERSION","3.467.0",void 0); x("google.ima.OmidAccessMode",{LIMITED:"limited",DOMAIN:"domain",FULL:"full"},void 0);x("google.ima.UiElements",{AD_ATTRIBUTION:"adAttribution",COUNTDOWN:"countdown"},void 0);x("google.ima.ViewMode",{NORMAL:"normal",FULLSCREEN:"fullscreen"},void 0);})();
b
GS_PnP_restoration.py
import os import cv2 import numpy as np import matplotlib.pyplot as plt from utils import utils_sr import torch from argparse import ArgumentParser from utils.utils_restoration import rgb2y, psnr, array2tensor, tensor2array import sys from matplotlib.ticker import MaxNLocator class PnP_restoration(): def __init__(self, hparams): self.hparams = hparams self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.initialize_cuda_denoiser() def initialize_cuda_denoiser(self): ''' Initialize the denoiser model with the given pretrained ckpt ''' sys.path.append('../GS_denoising/') from lightning_GSDRUNet import GradMatch parser2 = ArgumentParser(prog='utils_restoration.py') parser2 = GradMatch.add_model_specific_args(parser2) parser2 = GradMatch.add_optim_specific_args(parser2) hparams = parser2.parse_known_args()[0] hparams.act_mode = self.hparams.act_mode_denoiser self.denoiser_model = GradMatch(hparams) checkpoint = torch.load(self.hparams.pretrained_checkpoint, map_location=self.device) self.denoiser_model.load_state_dict(checkpoint['state_dict']) self.denoiser_model.eval() for i, v in self.denoiser_model.named_parameters(): v.requires_grad = False self.denoiser_model = self.denoiser_model.to(self.device) if self.hparams.precision == 'double' : if self.denoiser_model is not None: self.denoiser_model.double() def initialize_prox(self, img, degradation): ''' calculus for future prox computatations :param img: degraded image :param degradation: 2D blur kernel for deblurring and SR, mask for inpainting ''' if self.hparams.degradation_mode == 'deblurring': self.k = degradation self.k_tensor = array2tensor(np.expand_dims(self.k, 2)).double().to(self.device) self.FB, self.FBC, self.F2B, self.FBFy = utils_sr.pre_calculate(img, self.k_tensor, 1) elif self.hparams.degradation_mode == 'SR': self.k = degradation self.k_tensor = array2tensor(np.expand_dims(self.k, 2)).double().to(self.device) self.FB, self.FBC, self.F2B, self.FBFy = utils_sr.pre_calculate(img, self.k_tensor, self.hparams.sf) elif self.hparams.degradation_mode == 'inpainting': self.M = array2tensor(degradation).double().to(self.device) self.My = self.M*img else: print('degradation mode not treated') def calculate_prox(self, img): ''' Calculation of the proximal mapping of the data term f :param img: input for the prox :return: prox_f(img) ''' if self.hparams.degradation_mode == 'deblurring': rho = torch.tensor([1/self.tau]).double().repeat(1, 1, 1, 1).to(self.device) px = utils_sr.data_solution(img.double(), self.FB, self.FBC, self.F2B, self.FBFy, rho, 1) elif self.hparams.degradation_mode == 'SR': rho = torch.tensor([1 / self.tau]).double().repeat(1, 1, 1, 1).to(self.device) px = utils_sr.data_solution(img.double(), self.FB, self.FBC, self.F2B, self.FBFy, rho, self.hparams.sf) elif self.hparams.degradation_mode == 'inpainting': if self.hparams.noise_level_img > 1e-2: px = (self.tau*self.My + img)/(self.tau*self.M+1) else : px = self.My + (1-self.M)*img else: print('degradation mode not treated') return px def calculate_F(self,x,s,img): ''' Calculation of the objective function value f + lamb*s :param x: Point where to evaluate F :param s: Precomputed regularization function value :param img: Degraded image :return: F(x) ''' if self.hparams.degradation_mode == 'deblurring': deg_x = utils_sr.imfilter(x.double(),self.k_tensor[0].double().flip(1).flip(2).expand(3,-1,-1,-1)) F = 0.5 * torch.norm(img - deg_x, p=2) ** 2 + self.hparams.lamb * s elif self.hparams.degradation_mode == 'SR': deg_x = utils_sr.imfilter(x.double(), self.k_tensor[0].double().flip(1).flip(2).expand(3, -1, -1, -1)) deg_x = deg_x[...,0::self.hparams.sf, 0::self.hparams.sf] F = 0.5 * torch.norm(img - deg_x, p=2) ** 2 + self.hparams.lamb * s elif self.hparams.degradation_mode == 'inpainting': deg_x = self.M*x.double() F = 0.5*torch.norm(img - deg_x, p=2) ** 2 + self.hparams.lamb * s else : print('degradation not implemented') return F.item() def restore(self, img, clean_img, degradation,extract_results=False): ''' Compute GS-PnP restoration algorithm :param img: Degraded image :param clean_img: ground-truth clean image :param degradation: 2D blur kernel for deblurring and SR, mask for inpainting :param extract_results: Extract information for subsequent image or curve saving ''' if extract_results: z_list, x_list, Dx_list, psnr_tab, s_list, Ds_list, F_list = [], [], [], [], [], [], [] # initalize parameters if self.hparams.tau is not None: self.tau = self.hparams.tau else: self.tau = 1 / self.hparams.lamb i = 0 # iteration counter img_tensor = array2tensor(img).to(self.device) # for GPU computations (if GPU available) self.initialize_prox(img_tensor, degradation) # prox calculus that can be done outside of the loop # Initialization of the algorithm if self.hparams.degradation_mode == 'SR' : x0 = cv2.resize(img, (img.shape[1] * self.hparams.sf, img.shape[0] * self.hparams.sf),interpolation=cv2.INTER_CUBIC) x0 = utils_sr.shift_pixel(x0, self.hparams.sf) x0 = array2tensor(x0).to(self.device) else: x0 = img_tensor x0 = self.calculate_prox(x0) if extract_results: # extract np images and PSNR values out_x = tensor2array(x0.cpu()) current_x_psnr = psnr(clean_img, out_x) if self.hparams.print_each_step: print('current x PSNR : ', current_x_psnr) psnr_tab.append(current_x_psnr) x_list.append(out_x) x = x0 diff_F = 1 F_old = 1 self.relative_diff_F_min = self.hparams.relative_diff_F_min while i < self.hparams.maxitr and abs(diff_F)/F_old > self.relative_diff_F_min: if self.hparams.inpainting_init : if i < self.hparams.n_init: self.sigma_denoiser = 50 self.relative_diff_F_min = 0 else : self.sigma_denoiser = self.hparams.sigma_denoiser self.relative_diff_F_min = self.hparams.relative_diff_F_min else : self.sigma_denoiser = self.hparams.sigma_denoiser x_old = x #Denoising of x_old and calculation of F_old Ds, f = self.denoiser_model.calculate_grad(x_old, self.sigma_denoiser / 255.) Ds = Ds.detach() f = f.detach() Dx = x_old - self.denoiser_model.hparams.weight_Ds * Ds s_old = 0.5 * (torch.norm(x_old.double() - f.double(), p=2) ** 2) F_old = self.calculate_F(x_old, s_old, img_tensor) backtracking_check = False while not backtracking_check: # Gradient step z = (1 - self.hparams.lamb * self.tau) * x_old + self.hparams.lamb * self.tau * Dx # Proximal step x = self.calculate_prox(z) # Calculation of Fnew f = self.denoiser_model.calculate_grad(x, self.sigma_denoiser / 255.)[1] f = f.detach() s = 0.5 * (torch.norm(x.double() - f.double(), p=2) ** 2) F_new = self.calculate_F(x,s,img_tensor) # Backtracking diff_x = (torch.norm(x - x_old, p=2) ** 2).item() diff_F = F_old - F_new if self.hparams.degradation_mode == 'inpainting': diff_F = 1 F_old = 1 if self.hparams.use_backtracking and diff_F < (self.hparams.gamma / self.tau) * diff_x and abs(diff_F)/F_old > self.relative_diff_F_min: backtracking_check = False self.tau = self.hparams.eta_tau * self.tau x = x_old else: backtracking_check = True # Logging if extract_results: out_z = tensor2array(z.cpu()) out_x = tensor2array(x.cpu()) current_z_psnr = psnr(clean_img, out_z) current_x_psnr = psnr(clean_img, out_x) if self.hparams.print_each_step: print('iteration : ', i) print('current z PSNR : ', current_z_psnr) print('current x PSNR : ', current_x_psnr) x_list.append(out_x) z_list.append(out_z) Dx_list.append(tensor2array(Dx.cpu())) Ds_list.append(torch.norm(Ds).cpu().item()) s_list.append(s.cpu().item()) F_list.append(F_new) psnr_tab.append(current_x_psnr) i += 1 # next iteration # post-processing gradient step if extract_results: Ds, f = self.denoiser_model.calculate_grad(x, self.sigma_denoiser / 255.) Ds = Ds.detach() f = f.detach() Dx = x - self.denoiser_model.hparams.weight_Ds * Ds.detach() s = 0.5 * (torch.norm(x.double() - f.double(), p=2) ** 2) else: Ds, _ = self.denoiser_model.calculate_grad(x, self.sigma_denoiser / 255.) Ds = Ds.detach() Dx = x - self.denoiser_model.hparams.weight_Ds * Ds z = (1 - self.hparams.lamb * self.tau) * x + self.hparams.lamb * self.tau * Dx if self.hparams.degradation_mode == 'inpainting': output_img = tensor2array(x.cpu()) else : output_img = tensor2array(z.cpu()) output_psnr = psnr(clean_img, output_img) output_psnrY = psnr(rgb2y(clean_img), rgb2y(output_img)) if extract_results: if self.hparams.print_each_step: print('current z PSNR : ', output_psnr) z_list.append(tensor2array(z.cpu())) Dx_list.append(tensor2array(Dx.cpu())) Ds_list.append(torch.norm(Ds).cpu().item()) s_list.append(s.cpu().item()) return output_img, output_psnr, output_psnrY, np.array(x_list), np.array(z_list), np.array(Dx_list), np.array(psnr_tab), np.array(Ds_list), np.array(s_list), np.array(F_list) else: return output_img, output_psnr, output_psnrY def initialize_curves(self): self.rprox = [] self.prox = [] self.conv = [] self.lip_algo = [] self.lip_D = [] self.PSNR = [] self.s = [] self.Ds = [] self.F = [] def update_curves(self, x_list, z_list, Dx_list, psnr_tab, Ds_list, s_list, F_list): prox_list = x_list self.F.append(F_list) self.s.append(s_list) self.Ds.append(Ds_list) self.prox.append(np.sqrt(np.array([np.sum(np.abs(prox_list[i + 1] - prox_list[i]) ** 2) for i in range(len(x_list[:-1]))]) / np.array([np.sum(np.abs(z_list[i + 1] - z_list[i]) ** 2) for i in range(len(z_list[:-1]))]))) rprox_list = 2 * prox_list - z_list self.rprox.append(np.sqrt(np.array([np.sum(np.abs(rprox_list[i + 1] - rprox_list[i]) ** 2) for i in range(len(rprox_list[:-1]))]) / np.array([np.sum(np.abs(z_list[i + 1] - z_list[i]) ** 2) for i in range(len(rprox_list[:-1]))]))) self.conv.append(np.array([np.sum(np.abs(x_list[k + 1] - x_list[k]) ** 2) for k in range(len(x_list) - 1)]) / np.sum(np.abs(x_list[0]) ** 2)) self.lip_algo.append(np.sqrt(np.array([np.sum(np.abs(x_list[k + 1] - x_list[k]) ** 2) for k in range(1, len(x_list) - 1)]) / np.array([np.sum(np.abs(x_list[k] - x_list[k - 1]) ** 2) for k in range(1, len(x_list[:-1]))]))) self.lip_D.append(np.sqrt(np.array([np.sum(np.abs(Dx_list[i + 1] - Dx_list[i]) ** 2) for i in range(len(Dx_list) - 1)]) / np.array([np.sum(np.abs(x_list[i + 1] - x_list[i]) ** 2) for i in range(len(x_list) - 1)]))) self.PSNR.append(psnr_tab) def save_curves(self, save_path): import matplotlib matplotlib.rcParams.update({'font.size': 15}) plt.figure(1) fig, ax = plt.subplots() ax.spines['right'].set_visible(False)
for i in range(len(self.PSNR)): plt.plot(self.PSNR[i], '*', label='im_' + str(i)) plt.legend() plt.grid() plt.savefig(os.path.join(save_path, 'PSNR.png')) plt.figure(2) fig, ax = plt.subplots() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) for i in range(len(self.F)): plt.plot(self.F[i], '-o', markersize=10) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.savefig(os.path.join(save_path, 'F.png')) plt.figure(3) fig, ax = plt.subplots() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) for i in range(len(self.conv)): plt.plot(self.conv[i], '-o', markersize=10) plt.semilogy() ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.savefig(os.path.join(save_path, 'conv_log.png'), bbox_inches="tight") self.conv2 = [[np.min(self.conv[i][:k]) for k in range(1, len(self.conv[i]))] for i in range(len(self.conv))] conv_rate = [self.conv2[i][0]*np.array([(1/k) for k in range(1,len(self.conv2[i]))]) for i in range(len(self.conv2))] plt.figure(4) fig, ax = plt.subplots() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) for i in range(len(self.conv2)): plt.plot(self.conv2[i], '-o', markersize=10, label='GS-PnP') plt.plot(conv_rate[i], '--', color='red', label=r'$\mathcal{O}(\frac{1}{K})$') plt.semilogy() plt.legend() ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.savefig(os.path.join(save_path, 'conv_log2.png'), bbox_inches="tight") plt.figure(5) fig, ax = plt.subplots() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) for i in range(len(self.lip_algo)): plt.plot(self.lip_algo[i], '-o', label='im_' + str(i)) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.grid() plt.savefig(os.path.join(save_path, 'lip_algo.png')) plt.figure(6) for i in range(len(self.lip_D)): plt.plot(self.lip_D[i], '-o', label='im_' + str(i)) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.grid() plt.savefig(os.path.join(save_path, 'lip_D.png')) def add_specific_args(parent_parser): parser = ArgumentParser(parents=[parent_parser], add_help=False) parser.add_argument('--denoiser_name', type=str, default='GS-DRUNet') parser.add_argument('--dataset_path', type=str, default='../datasets') parser.add_argument('--pretrained_checkpoint', type=str,default='../GS_denoising/ckpts/GSDRUNet.ckpt') parser.add_argument('--PnP_algo', type=str, default='HQS') parser.add_argument('--dataset_name', type=str, default='CBSD10') parser.add_argument('--sigma_denoiser', type=float) parser.add_argument('--noise_level_img', type=float, default=2.55) parser.add_argument('--maxitr', type=int, default=400) parser.add_argument('--lamb', type=float, default=0.1) parser.add_argument('--tau', type=float) parser.add_argument('--n_images', type=int, default=68) parser.add_argument('--weight_Ds', type=float, default=1.) parser.add_argument('--eta_tau', type=float, default=0.9) parser.add_argument('--gamma', type=float, default=0.1) parser.add_argument('--no_use_backtracking', dest='use_backtracking', action='store_false') parser.set_defaults(use_backtracking=True) parser.add_argument('--relative_diff_F_min', type=float, default=1e-6) parser.add_argument('--inpainting_init', dest='inpainting_init', action='store_true') parser.set_defaults(inpainting_init=False) parser.add_argument('--precision', type=str, default='simple') parser.add_argument('--n_init', type=int, default=10) parser.add_argument('--patch_size', type=int, default=256) parser.add_argument('--extract_curves', dest='extract_curves', action='store_true') parser.set_defaults(extract_curves=False) parser.add_argument('--extract_images', dest='extract_images', action='store_true') parser.set_defaults(extract_images=False) parser.add_argument('--print_each_step', dest='print_each_step', action='store_true') parser.set_defaults(print_each_step=False) parser.add_argument('--act_mode_denoiser', type=str, default='E') return parser
ax.spines['top'].set_visible(False)
test_sftp.py
import os import tempfile import time import unittest from qftplib.client import FTPClient class FTPTest(unittest.TestCase): host = os.environ.get('SFTP_HOST_TEST') user = os.environ.get('SFTP_USER_TEST') password = os.environ.get('SFTP_PASS_TEST') dir = os.environ.get('SFTP_DIR_TEST') port = 22 def test_name(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: assert str(sftp) == f'<FTPClient({self.host}, {self.user}, xxxx, port = {self.port}, protocol = sftp)>' def test_listdir(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: directory_files = sftp.listdir(self.dir) assert len(directory_files) > 0 def test_pwd_chdir(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: sftp.chdir(self.dir) assert sftp.pwd() == f'/home/{self.user}/{self.dir}' def test_rmdir_mkdir(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: sftp.chdir(self.dir) new_dir = str(int(time.time())) sftp.mkdir(new_dir) files = sftp.listdir('.') assert f'{new_dir}' in files sftp.rmdir(f'/home/{self.user}/{self.dir}/{new_dir}') files = sftp.listdir('.') assert f'{new_dir}' not in files def test_rename(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: sftp.chdir(self.dir) new_dir = str(int(time.time())) sftp.mkdir(new_dir) sftp.rename(f'/home/{self.user}/{self.dir}/{new_dir}', f'/home/{self.user}/{self.dir}/{new_dir}_renamed') files = sftp.listdir('.') assert f'{new_dir}_renamed' in files sftp.rmdir(f'/home/{self.user}/{self.dir}/{new_dir}_renamed') def test_put_delete(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp, tempfile.NamedTemporaryFile() as f: remotepath = os.path.join(self.dir, os.path.basename(f.name)) sftp.put(f.name, remotepath) sftp.delete(remotepath) files = sftp.listdir(self.dir) assert remotepath not in files
def test_get(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp, tempfile.NamedTemporaryFile(mode='w') as f: files = sftp.listdir(self.dir) filename = next((f for f in files if f.endswith('.csv') or f.endswith('.txt')), None) sftp.get(f'/home/{self.user}/{self.dir}/{filename}', f.name) assert os.path.exists(f.name) assert os.path.isfile(f.name)
bootstrap.js
/* =================================================== * bootstrap-transition.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#transitions * =================================================== * Copyright 2012 Twitter, 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. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) * ======================================================= */ $(function () { $.support.transition = (function () { var transitionEnd = (function () { var el = document.createElement('bootstrap') , transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } , name for (name in transEndEventNames){ if (el.style[name] !== undefined) { return transEndEventNames[name] } } }()) return transitionEnd && { end: transitionEnd } })() }) }(window.jQuery); /* ========================================================= * bootstrap-modal.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Copyright 2012 Twitter, 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. * ========================================================= */ !function ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden') }) } , removeBackdrop: function () { this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); /* ============================================================ * bootstrap-dropdown.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#dropdowns * ============================================================ * Copyright 2012 Twitter, 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. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* DROPDOWN CLASS DEFINITION * ========================= */ var toggle = '[data-toggle=dropdown]' , Dropdown = function (element) { var $el = $(element).on('click.dropdown.data-api', this.toggle) $('html').on('click.dropdown.data-api', function () { $el.parent().removeClass('open') }) } Dropdown.prototype = { constructor: Dropdown , toggle: function (e) { var $this = $(this) , $parent , isActive if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') clearMenus() if (!isActive) { $parent.toggleClass('open') } $this.focus() return false } , keydown: function (e) { var $this , $items , $active , $parent , isActive , index if (!/(38|40|27)/.test(e.keyCode)) return $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items .eq(index) .focus() } } function clearMenus() { $(toggle).each(function () { getParent($(this)).removeClass('open') }) } function getParent($this) { var selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = selector && $(selector) if (!$parent || !$parent.length) $parent = $this.parent() return $parent } /* DROPDOWN PLUGIN DEFINITION * ========================== */ var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown /* DROPDOWN NO CONFLICT * ==================== */ $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } /* APPLY TO STANDARD DROPDOWN ELEMENTS * =================================== */ $(document) .on('click.dropdown.data-api', clearMenus) .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('.dropdown-menu', function (e) { e.stopPropagation() }) .on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(window.jQuery); /* ============================================================= * bootstrap-scrollspy.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#scrollspy * ============================================================= * Copyright 2012 Twitter, 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. * ============================================================== */ !function ($) { "use strict"; // jshint ;_; /* SCROLLSPY CLASS DEFINITION * ========================== */ function ScrollSpy(element, options) { var process = $.proxy(this.process, this) , $element = $(element).is('body') ? $(window) : $(element) , href this.options = $.extend({}, $.fn.scrollspy.defaults, options) this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.$body = $('body') this.refresh() this.process() } ScrollSpy.prototype = { constructor: ScrollSpy , refresh: function () { var self = this , $targets this.offsets = $([]) this.targets = $([]) $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) , href = $el.data('target') || $el.attr('href') , $href = /^#\w/.test(href) && $(href) return ( $href && $href.length && [[ $href.position().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]] ) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } , process: function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset , scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight , maxScroll = scrollHeight - this.$scrollElement.height() , offsets = this.offsets , targets = this.targets , activeTarget = this.activeTarget , i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate ( i ) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } , activate: function (target) { var active , selector this.activeTarget = target $(this.selector) .parent('.active') .removeClass('active') selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' active = $(selector) .parent('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active.closest('li.dropdown').addClass('active') } active.trigger('activate') } } /* SCROLLSPY PLUGIN DEFINITION * =========================== */ var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('scrollspy') , options = typeof option == 'object' && option if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy $.fn.scrollspy.defaults = { offset: 10 } /* SCROLLSPY NO CONFLICT * ===================== */ $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } /* SCROLLSPY DATA-API * ================== */ $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(window.jQuery); /* ======================================================== * bootstrap-tab.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#tabs * ======================================================== * Copyright 2012 Twitter, 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. * ======================================================== */ !function ($) { "use strict"; // jshint ;_; /* TAB CLASS DEFINITION * ==================== */ var Tab = function (element) { this.element = $(element) } Tab.prototype = { constructor: Tab , show: function () { var $this = this.element , $ul = $this.closest('ul:not(.dropdown-menu)') , selector = $this.attr('data-target') , previous , $target , e if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ( $this.parent('li').hasClass('active') ) return previous = $ul.find('.active:last a')[0] e = $.Event('show', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown' , relatedTarget: previous }) }) } , activate: function ( element, container, callback) { var $active = container.find('> .active') , transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if ( element.parent('.dropdown-menu') ) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active.one($.support.transition.end, next) : next() $active.removeClass('in') } } /* TAB PLUGIN DEFINITION * ===================== */ var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tab') if (!data) $this.data('tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab /* TAB NO CONFLICT * =============== */ $.fn.tab.noConflict = function () { $.fn.tab = old return this } /* TAB DATA-API * ============ */ $(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(window.jQuery); /* ========================================================== * bootstrap-affix.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#affix * ========================================================== * Copyright 2012 Twitter, 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. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* AFFIX CLASS DEFINITION * ====================== */ var Affix = function (element, options) { this.options = $.extend({}, $.fn.affix.defaults, options) this.$window = $(window) .on('scroll.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.affix.data-api', $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this)) this.$element = $(element) this.checkPosition() } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() , scrollTop = this.$window.scrollTop() , position = this.$element.offset() , offset = this.options.offset , offsetBottom = offset.bottom , offsetTop = offset.top , reset = 'affix affix-top affix-bottom' , affix if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && scrollTop <= offsetTop ? 'top' : false if (this.affixed === affix) return this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : '')) } /* AFFIX PLUGIN DEFINITION * ======================= */ var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('affix') , options = typeof option == 'object' && option if (!data) $this.data('affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix $.fn.affix.defaults = { offset: 0 } /* AFFIX NO CONFLICT * ================= */ $.fn.affix.noConflict = function () { $.fn.affix = old return this } /* AFFIX DATA-API * ============== */ $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) , data = $spy.data() data.offset = data.offset || {} data.offsetBottom && (data.offset.bottom = data.offsetBottom) data.offsetTop && (data.offset.top = data.offsetTop) $spy.affix(data) }) }) }(window.jQuery); /* ========================================================== * bootstrap-alert.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#alerts * ========================================================== * Copyright 2012 Twitter, 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. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* ALERT CLASS DEFINITION * ====================== */ var dismiss = '[data-dismiss="alert"]' , Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) , selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) e && e.preventDefault() $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) $parent.trigger(e = $.Event('close')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent .trigger('closed') .remove() } $.support.transition && $parent.hasClass('fade') ? $parent.on($.support.transition.end, removeElement) : removeElement() } /* ALERT PLUGIN DEFINITION * ======================= */ var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('alert') if (!data) $this.data('alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert /* ALERT NO CONFLICT * ================= */ $.fn.alert.noConflict = function () { $.fn.alert = old return this } /* ALERT DATA-API * ============== */ $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery); /* ============================================================ * bootstrap-button.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#buttons * ============================================================ * Copyright 2012 Twitter, 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. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* BUTTON PUBLIC CLASS DEFINITION * ============================== */ var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.button.defaults, options) } Button.prototype.setState = function (state) { var d = 'disabled' , $el = this.$element , data = $el.data() , val = $el.is('input') ? 'val' : 'html' state = state + 'Text' data.resetText || $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d) }, 0) }
var $parent = this.$element.closest('[data-toggle="buttons-radio"]') $parent && $parent .find('.active') .removeClass('active') this.$element.toggleClass('active') } /* BUTTON PLUGIN DEFINITION * ======================== */ var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('button') , options = typeof option == 'object' && option if (!data) $this.data('button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.defaults = { loadingText: 'loading...' } $.fn.button.Constructor = Button /* BUTTON NO CONFLICT * ================== */ $.fn.button.noConflict = function () { $.fn.button = old return this } /* BUTTON DATA-API * =============== */ $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') }) }(window.jQuery); /* ============================================================= * bootstrap-collapse.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, 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. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.collapse.defaults, options) if (this.options.parent) { this.$parent = $(this.options.parent) } this.options.toggle && this.toggle() } Collapse.prototype = { constructor: Collapse , dimension: function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } , show: function () { var dimension , scroll , actives , hasData if (this.transitioning || this.$element.hasClass('in')) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) actives = this.$parent && this.$parent.find('> .accordion-group > .in') if (actives && actives.length) { hasData = actives.data('collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('collapse', null) } this.$element[dimension](0) this.transition('addClass', $.Event('show'), 'shown') $.support.transition && this.$element[dimension](this.$element[0][scroll]) } , hide: function () { var dimension if (this.transitioning || !this.$element.hasClass('in')) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') this.$element[dimension](0) } , reset: function (size) { var dimension = this.dimension() this.$element .removeClass('collapse') [dimension](size || 'auto') [0].offsetWidth this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') return this } , transition: function (method, startEvent, completeEvent) { var that = this , complete = function () { if (startEvent.type == 'show') that.reset() that.transitioning = 0 that.$element.trigger(completeEvent) } this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.transitioning = 1 this.$element[method]('in') $.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete() } , toggle: function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } } /* COLLAPSE PLUGIN DEFINITION * ========================== */ var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('collapse') , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.defaults = { toggle: true } $.fn.collapse.Constructor = Collapse /* COLLAPSE NO CONFLICT * ==================== */ $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } /* COLLAPSE DATA-API * ================= */ $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href , target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 , option = $(target).data('collapse') ? 'toggle' : $this.data() $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') $(target).collapse(option) }) }(window.jQuery); /* ========================================================== * bootstrap-carousel.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#carousel * ========================================================== * Copyright 2012 Twitter, 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. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* CAROUSEL CLASS DEFINITION * ========================= */ var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.prototype = { cycle: function (e) { if (!e) this.paused = false if (this.interval) clearInterval(this.interval); this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } , getActiveIndex: function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } , to: function (pos) { var activeIndex = this.getActiveIndex() , that = this if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) { return this.$element.one('slid', function () { that.to(pos) }) } if (activeIndex == pos) { return this.pause().cycle() } return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } , pause: function (e) { if (!e) this.paused = true if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle() } clearInterval(this.interval) this.interval = null return this } , next: function () { if (this.sliding) return return this.slide('next') } , prev: function () { if (this.sliding) return return this.slide('prev') } , slide: function (type, next) { var $active = this.$element.find('.item.active') , $next = next || $active[type]() , isCycling = this.interval , direction = type == 'next' ? 'left' : 'right' , fallback = type == 'next' ? 'first' : 'last' , that = this , e this.sliding = true isCycling && this.pause() $next = $next.length ? $next : this.$element.find('.item')[fallback]() e = $.Event('slide', { relatedTarget: $next[0] , direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) this.$element.one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } isCycling && this.cycle() return this } } /* CAROUSEL PLUGIN DEFINITION * ========================== */ var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('carousel') , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) $this.data('carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.defaults = { interval: 5000 , pause: 'hover' } $.fn.carousel.Constructor = Carousel /* CAROUSEL NO CONFLICT * ==================== */ $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } /* CAROUSEL DATA-API * ================= */ $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , options = $.extend({}, $target.data(), $this.data()) , slideIndex $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('carousel').pause().to(slideIndex).cycle() } e.preventDefault() }) }(window.jQuery); /* ============================================================= * bootstrap-typeahead.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#typeahead * ============================================================= * Copyright 2012 Twitter, 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. * ============================================================ */ !function($){ "use strict"; // jshint ;_; /* TYPEAHEAD PUBLIC CLASS DEFINITION * ================================= */ var Typeahead = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.typeahead.defaults, options) this.matcher = this.options.matcher || this.matcher this.sorter = this.options.sorter || this.sorter this.highlighter = this.options.highlighter || this.highlighter this.updater = this.options.updater || this.updater this.source = this.options.source this.$menu = $(this.options.menu) this.shown = false this.listen() } Typeahead.prototype = { constructor: Typeahead , select: function () { var val = this.$menu.find('.active').attr('data-value') this.$element .val(this.updater(val)) .change() return this.hide() } , updater: function (item) { return item } , show: function () { var pos = $.extend({}, this.$element.position(), { height: this.$element[0].offsetHeight }) this.$menu .insertAfter(this.$element) .css({ top: pos.top + pos.height , left: pos.left }) .show() this.shown = true return this } , hide: function () { this.$menu.hide() this.shown = false return this } , lookup: function (event) { var items this.query = this.$element.val() if (!this.query || this.query.length < this.options.minLength) { return this.shown ? this.hide() : this } items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source return items ? this.process(items) : this } , process: function (items) { var that = this items = $.grep(items, function (item) { return that.matcher(item) }) items = this.sorter(items) if (!items.length) { return this.shown ? this.hide() : this } return this.render(items.slice(0, this.options.items)).show() } , matcher: function (item) { return ~item.toLowerCase().indexOf(this.query.toLowerCase()) } , sorter: function (items) { var beginswith = [] , caseSensitive = [] , caseInsensitive = [] , item while (item = items.shift()) { if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item) else if (~item.indexOf(this.query)) caseSensitive.push(item) else caseInsensitive.push(item) } return beginswith.concat(caseSensitive, caseInsensitive) } , highlighter: function (item) { var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&') return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { return '<strong>' + match + '</strong>' }) } , render: function (items) { var that = this items = $(items).map(function (i, item) { i = $(that.options.item).attr('data-value', item) i.find('a').html(that.highlighter(item)) return i[0] }) items.first().addClass('active') this.$menu.html(items) return this } , next: function (event) { var active = this.$menu.find('.active').removeClass('active') , next = active.next() if (!next.length) { next = $(this.$menu.find('li')[0]) } next.addClass('active') } , prev: function (event) { var active = this.$menu.find('.active').removeClass('active') , prev = active.prev() if (!prev.length) { prev = this.$menu.find('li').last() } prev.addClass('active') } , listen: function () { this.$element .on('focus', $.proxy(this.focus, this)) .on('blur', $.proxy(this.blur, this)) .on('keypress', $.proxy(this.keypress, this)) .on('keyup', $.proxy(this.keyup, this)) if (this.eventSupported('keydown')) { this.$element.on('keydown', $.proxy(this.keydown, this)) } this.$menu .on('click', $.proxy(this.click, this)) .on('mouseenter', 'li', $.proxy(this.mouseenter, this)) .on('mouseleave', 'li', $.proxy(this.mouseleave, this)) } , eventSupported: function(eventName) { var isSupported = eventName in this.$element if (!isSupported) { this.$element.setAttribute(eventName, 'return;') isSupported = typeof this.$element[eventName] === 'function' } return isSupported } , move: function (e) { if (!this.shown) return switch(e.keyCode) { case 9: // tab case 13: // enter case 27: // escape e.preventDefault() break case 38: // up arrow e.preventDefault() this.prev() break case 40: // down arrow e.preventDefault() this.next() break } e.stopPropagation() } , keydown: function (e) { this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27]) this.move(e) } , keypress: function (e) { if (this.suppressKeyPressRepeat) return this.move(e) } , keyup: function (e) { switch(e.keyCode) { case 40: // down arrow case 38: // up arrow case 16: // shift case 17: // ctrl case 18: // alt break case 9: // tab case 13: // enter if (!this.shown) return this.select() break case 27: // escape if (!this.shown) return this.hide() break default: this.lookup() } e.stopPropagation() e.preventDefault() } , focus: function (e) { this.focused = true } , blur: function (e) { this.focused = false if (!this.mousedover && this.shown) this.hide() } , click: function (e) { e.stopPropagation() e.preventDefault() this.select() this.$element.focus() } , mouseenter: function (e) { this.mousedover = true this.$menu.find('.active').removeClass('active') $(e.currentTarget).addClass('active') } , mouseleave: function (e) { this.mousedover = false if (!this.focused && this.shown) this.hide() } } /* TYPEAHEAD PLUGIN DEFINITION * =========================== */ var old = $.fn.typeahead $.fn.typeahead = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('typeahead') , options = typeof option == 'object' && option if (!data) $this.data('typeahead', (data = new Typeahead(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.typeahead.defaults = { source: [] , items: 8 , menu: '<ul class="typeahead dropdown-menu"></ul>' , item: '<li><a href="#"></a></li>' , minLength: 1 } $.fn.typeahead.Constructor = Typeahead /* TYPEAHEAD NO CONFLICT * =================== */ $.fn.typeahead.noConflict = function () { $.fn.typeahead = old return this } /* TYPEAHEAD DATA-API * ================== */ $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) { var $this = $(this) if ($this.data('typeahead')) return $this.typeahead($this.data()) }) }(window.jQuery);
Button.prototype.toggle = function () {