file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
test_mixins.py
from mmdet.core import (bbox2roi, bbox_mapping, merge_aug_bboxes, merge_aug_masks, merge_aug_proposals, multiclass_nms) class RPNTestMixin(object): def simple_test_rpn(self, x, img_meta, rpn_test_cfg): rpn_outs = self.rpn_head(x) if len(rpn_outs) == 3: # bg_vector bg_vector = rpn_outs[-1] rpn_outs = rpn_outs[:-1] proposal_inputs = rpn_outs + (img_meta, rpn_test_cfg) proposal_list = self.rpn_head.get_bboxes(*proposal_inputs) return proposal_list, bg_vector else: proposal_inputs = rpn_outs + (img_meta, rpn_test_cfg) proposal_list = self.rpn_head.get_bboxes(*proposal_inputs) return proposal_list def aug_test_rpn(self, feats, img_metas, rpn_test_cfg, sync_bg=False): imgs_per_gpu = len(img_metas[0]) aug_proposals = [[] for _ in range(imgs_per_gpu)] bg_vectors = [] for x, img_meta in zip(feats, img_metas): if sync_bg: proposal_list, bg_vector = self.simple_test_rpn(x, img_meta, rpn_test_cfg) bg_vectors.append(bg_vector) else: proposal_list = self.simple_test_rpn(x, img_meta, rpn_test_cfg) for i, proposals in enumerate(proposal_list): aug_proposals[i].append(proposals) if sync_bg and bg_vectors: bg_vector_avg = torch.mean(torch.cat(bg_vectors, dim)) # reorganize the order of 'img_metas' to match the dimensions # of 'aug_proposals' aug_img_metas = [] for i in range(imgs_per_gpu): aug_img_meta = [] for j in range(len(img_metas)): aug_img_meta.append(img_metas[j][i]) aug_img_metas.append(aug_img_meta) # after merging, proposals will be rescaled to the original image size merged_proposals = [ merge_aug_proposals(proposals, aug_img_meta, rpn_test_cfg) for proposals, aug_img_meta in zip(aug_proposals, aug_img_metas) ] if sync_bg: return merged_proposals, bg_vector_avg else: return merged_proposals class BBoxTestMixin(object): def simple_test_bboxes(self, x, img_meta, proposals, rcnn_test_cfg, bg_vector=None, with_decoder=False, rescale=False): """Test only det bboxes without augmentation.""" rois = bbox2roi(proposals) roi_feats = self.bbox_roi_extractor( x[:len(self.bbox_roi_extractor.featmap_strides)], rois) if self.with_shared_head: roi_feats = self.shared_head(roi_feats) if with_decoder: cls_score, bbox_pred, _, _ = self.bbox_head(roi_feats, bg_vector=bg_vector) else: cls_score, bbox_pred = self.bbox_head(roi_feats, bg_vector=bg_vector) img_shape = img_meta[0]['img_shape'] scale_factor = img_meta[0]['scale_factor'] det_bboxes, det_labels = self.bbox_head.get_det_bboxes( rois, cls_score, bbox_pred, img_shape, scale_factor, rescale=rescale, cfg=rcnn_test_cfg) return det_bboxes, det_labels def aug_test_bboxes(self, feats, img_metas, proposal_list, rcnn_test_cfg, bg_vector=None, with_decoder=False): aug_bboxes = [] aug_scores = [] for x, img_meta in zip(feats, img_metas): # only one image in the batch img_shape = img_meta[0]['img_shape'] scale_factor = img_meta[0]['scale_factor'] flip = img_meta[0]['flip'] # TODO more flexible proposals = bbox_mapping(proposal_list[0][:, :4], img_shape, scale_factor, flip) rois = bbox2roi([proposals]) # recompute feature maps to save GPU memory roi_feats = self.bbox_roi_extractor( x[:len(self.bbox_roi_extractor.featmap_strides)], rois) if self.with_shared_head: roi_feats = self.shared_head(roi_feats) if with_decoder: cls_score, bbox_pred, _, _ = self.bbox_head(roi_feats, bg_vector=bg_vector) else: cls_score, bbox_pred = self.bbox_head(roi_feats, bg_vector=bg_vector) # cls_score, bbox_pred = self.bbox_head(roi_feats) bboxes, scores = self.bbox_head.get_det_bboxes( rois, cls_score, bbox_pred, img_shape, scale_factor, rescale=False, cfg=None) aug_bboxes.append(bboxes) aug_scores.append(scores) # after merging, bboxes will be rescaled to the original image size merged_bboxes, merged_scores = merge_aug_bboxes( aug_bboxes, aug_scores, img_metas, rcnn_test_cfg) det_bboxes, det_labels = multiclass_nms(merged_bboxes, merged_scores, rcnn_test_cfg.score_thr, rcnn_test_cfg.nms, rcnn_test_cfg.max_per_img) return det_bboxes, det_labels class MaskTestMixin(object): def simple_test_mask(self, x, img_meta, det_bboxes, det_labels, bg_vector=None, rescale=False): # image shape of the first image in the batch (only one) ori_shape = img_meta[0]['ori_shape'] scale_factor = img_meta[0]['scale_factor'] if det_bboxes.shape[0] == 0: segm_result = [[] for _ in range(self.mask_head.num_classes - 1)] else: # if det_bboxes is rescaled to the original image size, we need to # rescale it back to the testing scale to obtain RoIs. _bboxes = ( det_bboxes[:, :4] * scale_factor if rescale else det_bboxes) mask_rois = bbox2roi([_bboxes]) mask_feats = self.mask_roi_extractor( x[:len(self.mask_roi_extractor.featmap_strides)], mask_rois) if self.with_shared_head: mask_feats = self.shared_head(mask_feats) if self.gzsd_mode: seen_mask_pred, unseen_mask_pred = self.mask_head(mask_feats, bg_vector) mask_pred = torch.cat((seen_mask_pred, unseen_mask_pred[:, 1:, :, :]), 1) segm_result = self.mask_head.get_seg_masks(mask_pred, _bboxes, det_labels, self.test_cfg.rcnn, ori_shape, scale_factor, rescale)
# det_labels, # self.test_cfg.rcnn, # ori_shape, scale_factor, # rescale) # unseen_segm_result = self.mask_head.get_seg_masks(unseen_mask_pred, _bboxes, # det_labels, # self.test_cfg.rcnn, # ori_shape, scale_factor, # rescale) # if self.mask_head.num_classes == 66: # segm_result = [[] for i in range(65+15)] # for i in range(65): # segm_result[i] = seen_segm_result[i] # for i in range(66, 80): # segm_result[i] = unseen_segm_result[i] # if self.mask_head.num_classes == 48: # segm_result = [[] for i in range(48 + 17)] # for i in range(47): # segm_result[i] = seen_segm_result[i] # for i in range(48, 65): # segm_result[i] = unseen_segm_result[i] if not self.gzsd_mode: mask_pred = self.mask_head(mask_feats, bg_vector) segm_result = self.mask_head.get_seg_masks(mask_pred, _bboxes, det_labels, self.test_cfg.rcnn, ori_shape, scale_factor, rescale) return segm_result def aug_test_mask(self, feats, img_metas, det_bboxes, det_labels, bg_vector=None): if det_bboxes.shape[0] == 0: segm_result = [[] for _ in range(self.mask_head.num_classes - 1)] else: aug_masks = [] for x, img_meta in zip(feats, img_metas): img_shape = img_meta[0]['img_shape'] scale_factor = img_meta[0]['scale_factor'] flip = img_meta[0]['flip'] _bboxes = bbox_mapping(det_bboxes[:, :4], img_shape, scale_factor, flip) mask_rois = bbox2roi([_bboxes]) mask_feats = self.mask_roi_extractor( x[:len(self.mask_roi_extractor.featmap_strides)], mask_rois) if self.with_shared_head: mask_feats = self.shared_head(mask_feats) mask_pred = self.mask_head(mask_feats, bg_vector) # convert to numpy array to save memory aug_masks.append(mask_pred.sigmoid().cpu().numpy()) merged_masks = merge_aug_masks(aug_masks, img_metas, self.test_cfg.rcnn) ori_shape = img_metas[0][0]['ori_shape'] segm_result = self.mask_head.get_seg_masks( merged_masks, det_bboxes, det_labels, self.test_cfg.rcnn, ori_shape, scale_factor=1.0, rescale=False) return segm_result
# seen_segm_result = self.mask_head.get_seg_masks(seen_mask_pred, _bboxes,
variance.go
package math import ( "math" "github.com/MontFerret/ferret/pkg/runtime/core" "github.com/MontFerret/ferret/pkg/runtime/values" "github.com/MontFerret/ferret/pkg/runtime/values/types" ) func variance(input *values.Array, sample values.Int) values.Float
{ if input.Length() == 0 { return values.NewFloat(math.NaN()) } m, _ := mean(input) var err error var variance values.Float input.ForEach(func(value core.Value, idx int) bool { err = core.ValidateType(value, types.Int, types.Float) if err != nil { return false } n := values.Float(toFloat(value)) variance += (n - m) * (n - m) return true }) // When getting the mean of the squared differences // "sample" will allow us to know if it's a sample // or population and whether to subtract by one or not l := values.Float(input.Length() - (1 * sample)) return variance / l }
Inform6TaskProvider.ts
/** * The Inform 6 Task provider and other task-related functions. */ import path = require("path") import * as vscode from "vscode" import { TaskManager } from "./task-manager" export interface Inform6TaskDefinition extends vscode.TaskDefinition { /** * The type of an Inform 6 task is always `inform6`. */ type: "inform6", /** * The Inform file to compile. */ source: string, /** * The destination of the compiled story file. */ output?: string, /** * The additional ICL commands to pass to the compiler. */ iclCommands?: string[] } export class
implements vscode.TaskProvider { static readonly Inform6TaskType = "inform6" private taskManager: TaskManager constructor(taskManager: TaskManager) { this.taskManager = taskManager } async provideTasks(): Promise<vscode.Task[]> { // No tasks are auto-detected for the moment. // TODO: Maybe scan all Inform files in the workspace and create a task for each // one of them ? return [] } resolveTask(_task: vscode.Task): vscode.Task | undefined { // Check if the mandatory source is present. const source = _task.definition.source if (source) { return this.taskManager.getInform6Task({ type: "inform6", source: source, output: _task.definition.output || undefined, iclCommands: _task.definition.iclCommands || undefined }) } return undefined } }
Inform6TaskProvider
Link_down.py
import requests import sys import h5py import numpy as np import os def get(path, params=None, savedir=None): # make HTTP GET request to path headers = {"api-key":"27d44ba55cd115b10f2dd9153589aff0"} r = requests.get(path, params=params, headers=headers) # raise exception if response code is not HTTP SUCCESS (200) r.raise_for_status() if r.headers['content-type'] == 'application/json': return r.json() # parse json responses automatically if 'content-disposition' in r.headers: filename = r.headers['content-disposition'].split("filename=")[1] if savedir != None: filename = savedir + filename with open(filename, 'wb') as f: f.write(r.content) return filename # return the filename string
def HaloProgenitors(haloID): ''' haloID is the subhalo's ID in snap_099 return a dict = {'SnapNum' : SubfindID} ''' url = "http://www.tng-project.org/api/TNG100-1/snapshots/99/subhalos/%haloID/sublink/simple.json"%haloID try: sublink = get(url, savedir='/home/sublink/') except: print(sys.exc_info()[0]) return -1 f = sublink #Find halo's Subfind ID with redshift(ie:SnapNum), and save the dict in '/Raid0/zhouzb/diskHalo_Sublink/' snap_num = np.array(f['SnapNum']) subfind_ID = np.array(f['SubfindID']) Progenitors_dict = {} for i in range(len(snap_num)): Progenitors_dict['%d'%snap_num[i]] = subfind_ID[i] f.close() return Progenitors_dict ''' snap_91 z=0.1 snap_84 z=0.2 snap_78 z=0.3 snap_72 z=0.4 snap_67 z=0.5 snap_59 z=0.7 snap_50 z=1.0 snap_40 z=1.5 snap_33 z=2.0 ''' barred = np.load('F:/Linux/data/099fig/barredID.npy') snap = [99, 91, 84, 78, 72, 67, 59, 50, 40, 33] errorHalo = [] for haloID in barred: Prog_dict = HaloProgenitors(haloID) if Prog_dict == -1: print('halo: %d Network ERROR, Try next'%haloID) errorHalo.append(haloID) continue else: #Download stellar particles' information in all selected snapshot z for z in snap: print('Now download halo %d in snap_%d'%(haloID, z)) try: subID = Prog_dict['%d'%z] cutoff_url = 'http://www.tng-project.org/api/TNG100-1/snapshots/%d/subhalos/%d/cutout.hdf5?stars=Masses,Coordinates,Velocities,GFM_StellarFormationTime'%(z, subID) if os.path.isfile('F:/Linux/data/TNG/cutoff/disk_%d/cutout_%d.hdf5'%(z, subID)) == False: get(cutoff_url, savedir='F:/Linux/data/TNG/cutoff/disk_%d/'%z) except: print("halo %d in snap_%d Fail:"%(haloID, z), sys.exc_info()[0]) print("You need to reload this halo.") errorHalo.append(haloID) break else: print('halo %d in snap_%d downloaded'%(haloID, z)) print('halo %d in all snapshot download Completed'%haloID) if len(errorHalo) == 0: print('All done.') else: print('%d halo download faild'%len(errorHalo)) print("Error halo's ID were saved in '/Raid0/zhouzb/downError.log.npy'.") np.save('F:/Linux/data/TNG/errorID.npy', errorHalo)
return r
product.controller.ts
import { CtxUser } from 'src/lib/decorators/ctx-user.decorators'; import { Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, UseGuards, } from '@nestjs/common'; import { JwtAuthGuard } from 'src/lib/guards/auth.guard'; import { Product } from '../schemas/product.schema'; import { ProductService } from '../services/product.service'; import { UserDocument } from 'src/user/schemas/user.schema'; @UseGuards(JwtAuthGuard) @Controller('api/v1/products') export class ProductController { constructor(private readonly productService: ProductService) {} @Get() getProducts(@CtxUser() user: UserDocument) { return this.productService.findAll(user); } @Get('/removes') getProductsRemoves(@CtxUser() user: UserDocument) { return this.productService.findAllDeleted(user); }
@Post() async createProduct( @Res() res, @Body() createBody: Product, @CtxUser() user: UserDocument, ): Promise<Product> { const product = await this.productService.create(createBody, user); return res.status(HttpStatus.OK).json({ message: 'Product Successfully Created', product, }); } @Delete(':id') async deleteProduct(@Res() res, @Param('id') id: string): Promise<boolean> { const productDeleted = await this.productService.delete(id); return res.status(HttpStatus.OK).json({ message: 'Product Deleted Successfully', productDeleted, }); } @Put(':id') async updateProduct( @Res() res, @Param('id') id: string, @Body() createBody: Product, @CtxUser() user: UserDocument, ): Promise<Product> { const productUpdated = await this.productService.update( id, createBody, user, ); return res.status(HttpStatus.OK).json({ message: 'Product Updated Successfully', productUpdated, }); } @Put('restore/:id') async restoreProduct(@Res() res, @Param('id') id: string): Promise<Product> { const productRestored = await this.productService.restore(id); return res.status(HttpStatus.OK).json({ message: 'Product Restored Successfully', productRestored, }); } }
logs.py
#!/usr/bin/env python # encoding: utf-8 def build_log_urls(node, path): url = node.web_url_for( 'addon_view_or_download_file', path=path, provider='osfstorage' ) return { 'view': url, 'download': url + '?action=download' } class OsfStorageNodeLogger(object): def __init__(self, node, auth, path=None): self.node = node self.auth = auth self.path = path def log(self, action, extra=None, save=False): """Log an event. Wraps the Node#add_log method, automatically adding relevant parameters and prefixing log events with `"osf_storage_"`. :param str action: Log action. Should be a class constant from NodeLog. :param dict extra: Extra parameters to add to the ``params`` dict of the new NodeLog. """ params = { 'project': self.node.parent_id, 'node': self.node._primary_key, } # If logging a file-related action, add the file's view and download URLs if self.path: params.update({ 'urls': build_log_urls(self.node, self.path), 'path': self.path, }) if extra: params.update(extra) # Prefix the action with osf_storage_ self.node.add_log( action='osf_storage_{0}'.format(action), params=params, auth=self.auth, ) if save:
self.node.save()
MediumDetailsNoDateScreen.js
import React from 'react'; import { getRouteParams } from 'shoutem.navigation'; import { connectStyle } from '@shoutem/theme'; import { Caption, Tile, Title, View } from '@shoutem/ui'; import { ext } from '../const'; import { ArticleDetailsScreen } from './ArticleDetailsScreen'; export class MediumDetailsNoDateScreen extends ArticleDetailsScreen {
return ( <Tile styleName="text-centric md-gutter-bottom"> <Title>{article.title.toUpperCase()}</Title> <View styleName="horizontal md-gutter-top"> <Caption numberOfLines={1}>{article.newsAuthor}</Caption> </View> </Tile> ); } } export default connectStyle(ext('ArticleDetailsScreen'))( MediumDetailsNoDateScreen, );
renderHeader() { const { article } = getRouteParams(this.props);
config.go
package config import "github.com/acrossOcean/config/core" var defConf *core.Config func init() { defConf = core.NewConfig() } func AddPath(path string, morePath ...string) { defConf.AddPath(path, morePath...) } func SetReadOrder(readOrder core.ReadOrder, moreOrder ...core.ReadOrder) { defConf.SetReadOrder(readOrder, moreOrder...) } func WatchChange(isOpen bool) { defConf.WatchChange(isOpen) } func String(key string) (string, bool) { return defConf.String(key) } func DefaultString(key string, defaultVal string) string { return defConf.DefaultString(key, defaultVal) } func StringList(key string) ([]string, error) { return defConf.StringList(key) } func Int(key string) (int, bool) { return defConf.Int(key) } func DefaultInt(key string, defaultVal int) int { return defConf.DefaultInt(key, defaultVal) }
func Bool(key string) (bool, bool) { return defConf.Bool(key) } func DefaultBool(key string, defaultVal bool) bool { return defConf.DefaultBool(key, defaultVal) } func Int64(key string) (int64, bool) { return defConf.Int64(key) } func DefaultInt64(key string, defaultVal int64) int64 { return defConf.DefaultInt64(key, defaultVal) } func Get(key string) (interface{}, bool) { return defConf.Get(key) } func GetCurrentCache() map[string]map[string]interface{} { return defConf.GetCurrentCache() }
gen.go
package main import ( gen "github.com/whyrusleeping/cbor-gen" "github.com/filecoin-project/specs-actors/v7/actors/builtin" "github.com/filecoin-project/specs-actors/v7/actors/builtin/account" "github.com/filecoin-project/specs-actors/v7/actors/builtin/cron" init_ "github.com/filecoin-project/specs-actors/v7/actors/builtin/init" "github.com/filecoin-project/specs-actors/v7/actors/builtin/market" "github.com/filecoin-project/specs-actors/v7/actors/builtin/miner" "github.com/filecoin-project/specs-actors/v7/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/v7/actors/builtin/paych" "github.com/filecoin-project/specs-actors/v7/actors/builtin/power" "github.com/filecoin-project/specs-actors/v7/actors/builtin/reward" "github.com/filecoin-project/specs-actors/v7/actors/builtin/system" "github.com/filecoin-project/specs-actors/v7/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/v7/actors/util/smoothing" "github.com/filecoin-project/specs-actors/v7/support/vm" ) func main() { // Common types //if err := gen.WriteTupleEncodersToFile("./actors/runtime/proof/cbor_gen.go", "proof", //proof.SectorInfo{}, // Aliased from v0 //proof.SealVerifyInfo{}, // Aliased from v0 //proof.PoStProof{}, // Aliased from v0 //proof.WindowPoStVerifyInfo{}, // Aliased from v0 //proof.WinningPoStVerifyInfo{}, // Aliased from v0 //); err != nil { // panic(err) //} if err := gen.WriteTupleEncodersToFile("./actors/builtin/cbor_gen.go", "builtin", builtin.MinerAddrs{}, builtin.ConfirmSectorProofsParams{}, builtin.DeferredCronEventParams{}, // builtin.ApplyRewardParams{}, // Aliased from v2 ); err != nil { panic(err) } // if err := gen.WriteTupleEncodersToFile("./actors/states/cbor_gen.go", "states", // states.Actor{}, // ); err != nil { // panic(err) // } // Actors if err := gen.WriteTupleEncodersToFile("./actors/builtin/system/cbor_gen.go", "system", // actor state system.State{}, ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/account/cbor_gen.go", "account", // actor state account.State{}, ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/init/cbor_gen.go", "init", // actor state init_.State{}, // method params and returns //init_.ConstructorParams{}, // Aliased from v0 //init_.ExecParams{}, // Aliased from v0 //init_.ExecReturn{}, // Aliased from v0 ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/cron/cbor_gen.go", "cron", // actor state cron.State{}, cron.Entry{}, // method params and returns //cron.ConstructorParams{}, // Aliased from v0 ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/reward/cbor_gen.go", "reward", // actor state reward.State{}, // method params and returns //reward.AwardBlockRewardParams{}, // Aliased from v0 reward.ThisEpochRewardReturn{}, ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/multisig/cbor_gen.go", "multisig", // actor state multisig.State{}, //multisig.Transaction{}, // Aliased from v0 //multisig.ProposalHashData{}, // Aliased from v0 // method params and returns // multisig.ConstructorParams{}, // Aliased from v2 //multisig.ProposeParams{}, // Aliased from v0 //multisig.ProposeReturn{}, // Aliased from v0 //multisig.AddSignerParams{}, // Aliased from v0 //multisig.RemoveSignerParams{}, // Aliased from v0 //multisig.TxnIDParams{}, // Aliased from v0 //multisig.ApproveReturn{}, // Aliased from v0 //multisig.ChangeNumApprovalsThresholdParams{}, // Aliased from v0 //multisig.SwapSignerParams{}, // Aliased from v0 //multisig.LockBalanceParams{}, // Aliased from v0 ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/paych/cbor_gen.go", "paych", // actor state paych.State{}, paych.LaneState{}, // method params and returns //paych.ConstructorParams{}, // Aliased from v0 // paych.UpdateChannelStateParams{}, // Aliased from v2 //paych.SignedVoucher{}, // Aliased from v0 //paych.ModVerifyParams{}, // Aliased from v0 // other types //paych.Merge{}, // Aliased from v0 ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/power/cbor_gen.go", "power", // actors state power.State{}, power.Claim{}, power.CronEvent{}, // method params and returns power.CreateMinerParams{}, //power.CreateMinerReturn{}, // Aliased from v0 //power.EnrollCronEventParams{}, // Aliased from v0 //power.UpdateClaimedPowerParams{}, // Aliased from v0 power.CurrentTotalPowerReturn{}, // other types power.MinerConstructorParams{}, ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/market/cbor_gen.go", "market", // actor state market.State{}, // method params and returns //market.WithdrawBalanceParams{}, // Aliased from v0 // market.PublishStorageDealsParams{}, // Aliased from v0 market.PublishStorageDealsReturn{}, //market.ActivateDealsParams{}, // Aliased from v0 market.VerifyDealsForActivationParams{}, market.VerifyDealsForActivationReturn{}, market.SectorDataSpec{}, market.ComputeDataCommitmentParams{}, market.ComputeDataCommitmentReturn{}, //market.OnMinerSectorsTerminateParams{}, // Aliased from v0 // other types //market.DealProposal{}, // Aliased from v0 //market.ClientDealProposal{}, market.SectorDeals{}, market.SectorWeights{}, market.DealState{}, ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/miner/cbor_gen.go", "miner", // actor state miner.State{}, miner.MinerInfo{}, miner.Deadlines{}, miner.Deadline{}, miner.Partition{}, miner.ExpirationSet{}, miner.PowerPair{}, miner.SectorPreCommitOnChainInfo{}, miner.SectorPreCommitInfo{}, miner.SectorOnChainInfo{}, miner.WorkerKeyChange{}, miner.VestingFunds{}, miner.VestingFund{}, miner.WindowedPoSt{}, // method params and returns // miner.ConstructorParams{}, // in power actor //miner.SubmitWindowedPoStParams{}, // Aliased from v0 //miner.TerminateSectorsParams{}, // Aliased from v0 //miner.TerminateSectorsReturn{}, // Aliased from v0 //miner.ChangePeerIDParams{}, // Aliased from v0 //miner.ChangeMultiaddrsParams{}, // Aliased from v0 //miner.ProveCommitSectorParams{}, // Aliased from v0 miner.ProveCommitAggregateParams{}, //miner.ChangeWorkerAddressParams{}, // Aliased from v0 //miner.ExtendSectorExpirationParams{}, // Aliased from v0 //miner.DeclareFaultsParams{}, // Aliased from v0 //miner.DeclareFaultsRecoveredParams{}, // Aliased from v0 //miner.ReportConsensusFaultParams{}, // Aliased from v0 // miner.GetControlAddressesReturn{}, // Aliased from v2 //miner.CheckSectorProvenParams{}, // Aliased from v0 //miner.WithdrawBalanceParams{}, // Aliased from v0 //miner.CompactPartitionsParams{}, // Aliased from v0 //miner.CompactSectorNumbersParams{}, // Aliased from v0 //miner.CronEventPayload{}, // Aliased from v0 // miner.DisputeWindowedPoStParams{}, // Aliased from v3 miner.PreCommitSectorBatchParams{}, // other types //miner.FaultDeclaration{}, // Aliased from v0 //miner.RecoveryDeclaration{}, // Aliased from v0 //miner.ExpirationExtension{}, // Aliased from v0 //miner.TerminationDeclaration{}, // Aliased from v0 //miner.PoStPartition{}, // Aliased from v0 ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/builtin/verifreg/cbor_gen.go", "verifreg", // actor state verifreg.State{}, // method params and returns //verifreg.AddVerifierParams{}, // Aliased from v0
// other types ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./actors/util/smoothing/cbor_gen.go", "smoothing", smoothing.FilterEstimate{}, ); err != nil { panic(err) } if err := gen.WriteTupleEncodersToFile("./support/vm/cbor_gen.go", "vm", vm.ChainMessage{}, vm.StateInfo0{}, vm.StateRoot{}, ); err != nil { panic(err) } }
//verifreg.AddVerifiedClientParams{}, // Aliased from v0 //verifreg.UseBytesParams{}, // Aliased from v0 //verifreg.RestoreBytesParams{}, // Aliased from v0
json.rs
use crate::obj::objbytearray::PyByteArray; use crate::obj::objbytes::PyBytes; use crate::obj::objstr::PyString; use crate::py_serde; use crate::pyobject::{ItemProtocol, PyObjectRef, PyResult, TypeProtocol}; use crate::types::create_type; use crate::VirtualMachine; use serde_json; /// Implement json.dumps pub fn json_dumps(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> { let serializer = py_serde::PyObjectSerializer::new(vm, &obj); serde_json::to_string(&serializer).map_err(|err| vm.new_type_error(err.to_string())) } pub fn json_dump(obj: PyObjectRef, fs: PyObjectRef, vm: &VirtualMachine) -> PyResult
/// Implement json.loads pub fn json_loads(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let de_result = match_class!(obj, s @ PyString => py_serde::deserialize(vm, &mut serde_json::Deserializer::from_str(s.as_str())), b @ PyBytes => py_serde::deserialize(vm, &mut serde_json::Deserializer::from_slice(&b)), ba @ PyByteArray => py_serde::deserialize(vm, &mut serde_json::Deserializer::from_slice(&ba.inner.borrow().elements)), obj => { let msg = format!( "the JSON object must be str, bytes or bytearray, not {}", obj.class().name ); return Err(vm.new_type_error(msg)); } ); de_result.map_err(|err| { let module = vm .get_attribute(vm.sys_module.clone(), "modules") .unwrap() .get_item("json", vm) .unwrap(); let json_decode_error = vm.get_attribute(module, "JSONDecodeError").unwrap(); let json_decode_error = json_decode_error.downcast().unwrap(); let exc = vm.new_exception(json_decode_error, format!("{}", err)); vm.set_attr(&exc, "lineno", vm.ctx.new_int(err.line())) .unwrap(); vm.set_attr(&exc, "colno", vm.ctx.new_int(err.column())) .unwrap(); exc }) } pub fn json_load(fp: PyObjectRef, vm: &VirtualMachine) -> PyResult { let result = vm.call_method(&fp, "read", vec![])?; json_loads(result, vm) } pub fn make_module(vm: &VirtualMachine) -> PyObjectRef { let ctx = &vm.ctx; // TODO: Make this a proper type with a constructor let json_decode_error = create_type( "JSONDecodeError", &ctx.types.type_type, &ctx.exceptions.exception_type, ); py_module!(vm, "json", { "dumps" => ctx.new_rustfunc(json_dumps), "dump" => ctx.new_rustfunc(json_dump), "loads" => ctx.new_rustfunc(json_loads), "load" => ctx.new_rustfunc(json_load), "JSONDecodeError" => json_decode_error }) }
{ let result = json_dumps(obj, vm)?; vm.call_method(&fs, "write", vec![vm.new_str(result)])?; Ok(vm.get_none()) }
source_graph.rs
/* Things this doesn't currently support that it might need to later: - Import renames (use a::b as c) - these are silently ignored (!) - Imports that start with two colons (use ::a::b) - these are also silently ignored (!) - As of writing, flutter_rust_bridge doesn't support imports from outside the current crate, though that's outside the scope of the code in this file */ use std::{collections::HashMap, fmt::Debug, fs, path::PathBuf}; use cargo_metadata::MetadataCommand; use log::debug; use syn::{Ident, ItemEnum, ItemStruct, UseTree}; /// Represents a crate, including a map of its modules, imports, structs and /// enums. #[derive(Debug, Clone)] pub struct Crate { pub name: String, pub manifest_path: PathBuf, pub root_src_file: PathBuf, pub root_module: Module, } impl Crate { pub fn new(manifest_path: &str) -> Self { let mut cmd = MetadataCommand::new(); cmd.manifest_path(&manifest_path); let metadata = cmd.exec().unwrap(); let root_package = metadata.root_package().unwrap(); let root_src_file = { let lib_file = root_package .manifest_path .parent() .unwrap() .join("src/lib.rs"); let main_file = root_package .manifest_path .parent() .unwrap() .join("src/main.rs"); if lib_file.exists() { fs::canonicalize(lib_file).unwrap() } else if main_file.exists() { fs::canonicalize(main_file).unwrap() } else { panic!("No src/lib.rs or src/main.rs found for this Cargo.toml file"); } }; let source_rust_content = fs::read_to_string(&root_src_file).unwrap(); let file_ast = syn::parse_file(&source_rust_content).unwrap(); let mut result = Crate { name: root_package.name.clone(), manifest_path: fs::canonicalize(manifest_path).unwrap(), root_src_file: root_src_file.clone(), root_module: Module { visibility: Visibility::Public, file_path: root_src_file, module_path: vec!["crate".to_string()], source: Some(ModuleSource::File(file_ast)), scope: None, }, }; result.resolve(); result } /// Create a map of the modules for this crate pub fn resolve(&mut self) { self.root_module.resolve(); } } /// Mirrors syn::Visibility, but can be created without a token #[derive(Debug, Clone)] pub enum Visibility { Public, Crate, Restricted, // Not supported Inherited, // Usually means private } fn syn_vis_to_visibility(vis: &syn::Visibility) -> Visibility
#[derive(Debug, Clone)] pub struct Import { pub path: Vec<String>, pub visibility: Visibility, } #[derive(Debug, Clone)] pub enum ModuleSource { File(syn::File), ModuleInFile(Vec<syn::Item>), } #[derive(Clone)] pub struct Struct { pub ident: Ident, pub src: ItemStruct, pub visibility: Visibility, pub path: Vec<String>, } impl Debug for Struct { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Struct") .field("ident", &self.ident) .field("src", &"omitted") .field("visibility", &self.visibility) .field("path", &self.path) .finish() } } #[derive(Clone)] pub struct Enum { pub ident: Ident, pub src: ItemEnum, pub visibility: Visibility, pub path: Vec<String>, } impl Debug for Enum { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Enum") .field("ident", &self.ident) .field("src", &"omitted") .field("visibility", &self.visibility) .field("path", &self.path) .finish() } } #[derive(Debug, Clone)] pub struct ModuleScope { pub modules: Vec<Module>, pub enums: Vec<Enum>, pub structs: Vec<Struct>, pub imports: Vec<Import>, } #[derive(Clone)] pub struct Module { pub visibility: Visibility, pub file_path: PathBuf, pub module_path: Vec<String>, pub source: Option<ModuleSource>, pub scope: Option<ModuleScope>, } impl Debug for Module { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Module") .field("visibility", &self.visibility) .field("module_path", &self.module_path) .field("file_path", &self.file_path) .field("source", &"omitted") .field("scope", &self.scope) .finish() } } impl Module { pub fn resolve(&mut self) { self.resolve_modules(); self.resolve_imports(); } /// Maps out modules, structs and enums within the scope of this module fn resolve_modules(&mut self) { let mut scope_modules = Vec::new(); let mut scope_structs = Vec::new(); let mut scope_enums = Vec::new(); let items = match self.source.as_ref().unwrap() { ModuleSource::File(file) => &file.items, ModuleSource::ModuleInFile(items) => items, }; for item in items.iter() { match item { syn::Item::Struct(item_struct) => { scope_structs.push(Struct { ident: item_struct.ident.clone(), src: item_struct.clone(), visibility: syn_vis_to_visibility(&item_struct.vis), path: { let mut path = self.module_path.clone(); path.push(item_struct.ident.to_string()); path }, }); } syn::Item::Enum(item_enum) => { scope_enums.push(Enum { ident: item_enum.ident.clone(), src: item_enum.clone(), visibility: syn_vis_to_visibility(&item_enum.vis), path: { let mut path = self.module_path.clone(); path.push(item_enum.ident.to_string()); path }, }); } syn::Item::Mod(item_mod) => { let ident = item_mod.ident.clone(); let mut module_path = self.module_path.clone(); module_path.push(ident.to_string()); scope_modules.push(match &item_mod.content { Some(content) => { let mut child_module = Module { visibility: syn_vis_to_visibility(&item_mod.vis), file_path: self.file_path.clone(), module_path, source: Some(ModuleSource::ModuleInFile(content.1.clone())), scope: None, }; child_module.resolve(); child_module } None => { let folder_path = self.file_path.parent().unwrap().join(ident.to_string()); let folder_exists = folder_path.exists(); let file_path = if folder_exists { folder_path.join("mod.rs") } else { self.file_path .parent() .unwrap() .join(ident.to_string() + ".rs") }; let file_exists = file_path.exists(); let source = if file_exists { let source_rust_content = fs::read_to_string(&file_path).unwrap(); debug!("Trying to parse {:?}", file_path); Some(ModuleSource::File( syn::parse_file(&source_rust_content).unwrap(), )) } else { None }; let mut child_module = Module { visibility: syn_vis_to_visibility(&item_mod.vis), file_path, module_path, source, scope: None, }; if file_exists { child_module.resolve(); } child_module } }); } _ => {} } } self.scope = Some(ModuleScope { modules: scope_modules, enums: scope_enums, structs: scope_structs, imports: vec![], // Will be filled in by resolve_imports() }); } fn resolve_imports(&mut self) { let imports = &mut self.scope.as_mut().unwrap().imports; let items = match self.source.as_ref().unwrap() { ModuleSource::File(file) => &file.items, ModuleSource::ModuleInFile(items) => items, }; for item in items.iter() { if let syn::Item::Use(item_use) = item { let flattened_imports = flatten_use_tree(&item_use.tree); for import in flattened_imports { imports.push(Import { path: import, visibility: syn_vis_to_visibility(&item_use.vis), }); } } } } pub fn collect_structs<'a>(&'a self, container: &mut HashMap<String, &'a Struct>) { let scope = self.scope.as_ref().unwrap(); for scope_struct in &scope.structs { container.insert(scope_struct.ident.to_string(), scope_struct); } for scope_module in &scope.modules { scope_module.collect_structs(container); } } pub fn collect_enums<'a>(&'a self, container: &mut HashMap<String, &'a Enum>) { let scope = self.scope.as_ref().unwrap(); for scope_enum in &scope.enums { container.insert(scope_enum.ident.to_string(), scope_enum); } for scope_module in &scope.modules { scope_module.collect_enums(container); } } } fn flatten_use_tree_rename_abort_warning(use_tree: &UseTree) { debug!("WARNING: flatten_use_tree() found an import rename (use a::b as c). flatten_use_tree() will now abort."); debug!("WARNING: This happened while parsing {:?}", use_tree); debug!("WARNING: This use statement will be ignored."); } /// Takes a use tree and returns a flat list of use paths (list of string tokens) /// /// Example: /// use a::{b::c, d::e}; /// becomes /// [ /// ["a", "b", "c"], /// ["a", "d", "e"] /// ] /// /// Warning: As of writing, import renames (import a::b as c) are silently /// ignored. fn flatten_use_tree(use_tree: &UseTree) -> Vec<Vec<String>> { // Vec<(path, is_complete)> let mut result = vec![(vec![], false)]; let mut counter: usize = 0; loop { counter += 1; if counter > 10000 { panic!("flatten_use_tree: Use statement complexity limit exceeded. This is probably a bug."); } // If all paths are complete, break from the loop if result.iter().all(|result_item| result_item.1) { break; } let mut items_to_push = Vec::new(); for path_tuple in &mut result { let path = &mut path_tuple.0; let is_complete = &mut path_tuple.1; if *is_complete { continue; } let mut tree_cursor = use_tree; for path_item in path.iter() { match tree_cursor { UseTree::Path(use_path) => { let ident = use_path.ident.to_string(); if *path_item != ident { panic!("This ident did not match the one we already collected. This is a bug."); } tree_cursor = use_path.tree.as_ref(); } UseTree::Group(use_group) => { let mut moved_tree_cursor = false; for tree in use_group.items.iter() { match tree { UseTree::Path(use_path) => { if path_item == &use_path.ident.to_string() { tree_cursor = use_path.tree.as_ref(); moved_tree_cursor = true; break; } } // Since we're not matching UseTree::Group here, a::b::{{c}, {d}} might // break. But also why would anybody do that _ => unreachable!(), } } if !moved_tree_cursor { unreachable!(); } } _ => unreachable!(), } } match tree_cursor { UseTree::Name(use_name) => { path.push(use_name.ident.to_string()); *is_complete = true; } UseTree::Path(use_path) => { path.push(use_path.ident.to_string()); } UseTree::Glob(_) => { path.push("*".to_string()); *is_complete = true; } UseTree::Group(use_group) => { // We'll modify the first one in-place, and make clones for // all subsequent ones let mut first: bool = true; // Capture the path in this state, since we're about to // modify it let path_copy = path.clone(); for tree in use_group.items.iter() { let mut new_path_tuple = if first { None } else { let new_path = path_copy.clone(); items_to_push.push((new_path, false)); Some(items_to_push.iter_mut().last().unwrap()) }; match tree { UseTree::Path(use_path) => { let ident = use_path.ident.to_string(); if first { path.push(ident); } else { new_path_tuple.unwrap().0.push(ident); } } UseTree::Name(use_name) => { let ident = use_name.ident.to_string(); if first { path.push(ident); *is_complete = true; } else { let path_tuple = new_path_tuple.as_mut().unwrap(); path_tuple.0.push(ident); path_tuple.1 = true; } } UseTree::Glob(_) => { if first { path.push("*".to_string()); *is_complete = true; } else { let path_tuple = new_path_tuple.as_mut().unwrap(); path_tuple.0.push("*".to_string()); path_tuple.1 = true; } } UseTree::Group(_) => { panic!( "Directly-nested use groups ({}) are not supported by flutter_rust_bridge. Use {} instead.", "use a::{{b}, c}", "a::{b, c}" ); } // UseTree::Group(_) => panic!(), UseTree::Rename(_) => { flatten_use_tree_rename_abort_warning(use_tree); return vec![]; } } first = false; } } UseTree::Rename(_) => { flatten_use_tree_rename_abort_warning(use_tree); return vec![]; } } } for item in items_to_push { result.push(item); } } result.into_iter().map(|val| val.0).collect() }
{ match vis { syn::Visibility::Public(_) => Visibility::Public, syn::Visibility::Crate(_) => Visibility::Crate, syn::Visibility::Restricted(_) => Visibility::Restricted, syn::Visibility::Inherited => Visibility::Inherited, } }
etcd.go
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package etcd import ( "fmt" "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" etcdgeneric "k8s.io/kubernetes/pkg/registry/generic/etcd" "k8s.io/kubernetes/pkg/registry/namespace" "k8s.io/kubernetes/pkg/runtime" ) // rest implements a RESTStorage for namespaces against etcd type REST struct { *etcdgeneric.Etcd status *etcdgeneric.Etcd } // StatusREST implements the REST endpoint for changing the status of a namespace. type StatusREST struct { store *etcdgeneric.Etcd } // FinalizeREST implements the REST endpoint for finalizing a namespace. type FinalizeREST struct { store *etcdgeneric.Etcd } // NewREST returns a RESTStorage object that will work against namespaces. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST, *FinalizeREST) { prefix := "/namespaces" newListFunc := func() runtime.Object { return &api.NamespaceList{} } storageInterface := opts.Decorator( opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Namespaces), &api.Namespace{}, prefix, namespace.Strategy, newListFunc) store := &etcdgeneric.Etcd{ NewFunc: func() runtime.Object { return &api.Namespace{} }, NewListFunc: newListFunc, KeyRootFunc: func(ctx api.Context) string { return prefix }, KeyFunc: func(ctx api.Context, name string) (string, error) { return etcdgeneric.NoNamespaceKeyFunc(ctx, prefix, name) }, ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.Namespace).Name, nil },
}, QualifiedResource: api.Resource("namespaces"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, CreateStrategy: namespace.Strategy, UpdateStrategy: namespace.Strategy, ReturnDeletedObject: true, Storage: storageInterface, } statusStore := *store statusStore.UpdateStrategy = namespace.StatusStrategy finalizeStore := *store finalizeStore.UpdateStrategy = namespace.FinalizeStrategy return &REST{Etcd: store, status: &statusStore}, &StatusREST{store: &statusStore}, &FinalizeREST{store: &finalizeStore} } // Delete enforces life-cycle rules for namespace termination func (r *REST) Delete(ctx api.Context, name string, options *api.DeleteOptions) (runtime.Object, error) { nsObj, err := r.Get(ctx, name) if err != nil { return nil, err } namespace := nsObj.(*api.Namespace) // upon first request to delete, we switch the phase to start namespace termination if namespace.DeletionTimestamp.IsZero() { now := unversioned.Now() namespace.DeletionTimestamp = &now namespace.Status.Phase = api.NamespaceTerminating result, _, err := r.status.Update(ctx, namespace) return result, err } // prior to final deletion, we must ensure that finalizers is empty if len(namespace.Spec.Finalizers) != 0 { err = apierrors.NewConflict(api.Resource("namespaces"), namespace.Name, fmt.Errorf("The system is ensuring all content is removed from this namespace. Upon completion, this namespace will automatically be purged by the system.")) return nil, err } return r.Etcd.Delete(ctx, name, nil) } func (r *StatusREST) New() runtime.Object { return r.store.New() } // Update alters the status subset of an object. func (r *StatusREST) Update(ctx api.Context, obj runtime.Object) (runtime.Object, bool, error) { return r.store.Update(ctx, obj) } func (r *FinalizeREST) New() runtime.Object { return r.store.New() } // Update alters the status finalizers subset of an object. func (r *FinalizeREST) Update(ctx api.Context, obj runtime.Object) (runtime.Object, bool, error) { return r.store.Update(ctx, obj) }
PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { return namespace.MatchNamespace(label, field)
article-view.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { getArticleThunk } from '../store' import ParsedArticle from './parsed-article' // import history class
extends Component { constructor() { super() this.state = { parsedArray: [] } this.bbCodeParser = this.bbCodeParser.bind(this) // console.log(this.props.history.location.pathname) } componentDidMount() { this.props.getArticle(this.props.history.location.pathname) } bbCodeParser() { const content = this.props.article.content const imgRegex = /\[img([^\]]*)\]([^\[]*)\[\/img\]/g let match = imgRegex.exec(content) let parsedContentArray = [] while (match !== null) { let textObj = { type: 'text' } let imageObj = { captured: match[0] } imageObj.type = 'img' imageObj.float = match[1].trim() === 'float=right' ? 'right' : 'left' imageObj.url = match[2] imageObj.index = match.index if (parsedContentArray.length === 0) { textObj.begin = 0 } else { textObj.begin = parsedContentArray[parsedContentArray.length - 1].index + parsedContentArray[parsedContentArray.length - 1].captured.length } textObj.end = imageObj.index textObj.captured = content.slice(textObj.begin, textObj.end) parsedContentArray.push(textObj) parsedContentArray.push(imageObj) match = imgRegex.exec(content) } let textObj = { type: 'text' } if (parsedContentArray.length) { textObj.begin = parsedContentArray[parsedContentArray.length - 1].index + parsedContentArray[parsedContentArray.length - 1].captured.length textObj.end = content.length textObj.captured = content.slice(textObj.begin, textObj.end) } else { textObj.captured = content textObj.begin = 0 textObj.end = content ? content.length : 0 } parsedContentArray.push(textObj) return parsedContentArray } render() { let parsedContentArray = this.bbCodeParser() return ( <div className="articleView"> <h1>{this.props.article && this.props.article.title}</h1> <h4>by {this.props.article && (this.props.article.isAnonymous ? 'anonymous' : this.props.article.author)}</h4> <ParsedArticle className="parsedArticle" parsedContentArray={parsedContentArray} /> </div> ) } } const mapState = state => { return { article: state.article } } const mapDispatch = dispatch => { return { getArticle(url) { dispatch(getArticleThunk(url)) } } } export default connect(mapState, mapDispatch)(ArticleView)
ArticleView
elmo_lstm.py
""" A stacked bidirectional LSTM with skip connections between layers. """ from typing import Optional, Tuple, List import warnings import torch from torch.nn.utils.rnn import PackedSequence, pad_packed_sequence with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) import h5py import numpy from allennlp.modules.lstm_cell_with_projection import LstmCellWithProjection from allennlp.common.checks import ConfigurationError from allennlp.modules.encoder_base import _EncoderBase from allennlp.common.file_utils import cached_path class ElmoLstm(_EncoderBase): """ A stacked, bidirectional LSTM which uses [`LstmCellWithProjection`'s](./lstm_cell_with_projection.md) with highway layers between the inputs to layers. The inputs to the forward and backward directions are independent - forward and backward states are not concatenated between layers. Additionally, this LSTM maintains its `own` state, which is updated every time `forward` is called. It is dynamically resized for different batch sizes and is designed for use with non-continuous inputs (i.e inputs which aren't formatted as a stream, such as text used for a language modeling task, which is how stateful RNNs are typically used). This is non-standard, but can be thought of as having an "end of sentence" state, which is carried across different sentences. # Parameters input_size : `int`, required The dimension of the inputs to the LSTM. hidden_size : `int`, required The dimension of the outputs of the LSTM. cell_size : `int`, required. The dimension of the memory cell of the `LstmCellWithProjection`. num_layers : `int`, required The number of bidirectional LSTMs to use. requires_grad : `bool`, optional If True, compute gradient of ELMo parameters for fine tuning. recurrent_dropout_probability : `float`, optional (default = 0.0) The dropout probability to be used in a dropout scheme as stated in [A Theoretically Grounded Application of Dropout in Recurrent Neural Networks] (https://arxiv.org/abs/1512.05287). state_projection_clip_value : `float`, optional, (default = None) The magnitude with which to clip the hidden_state after projecting it. memory_cell_clip_value : `float`, optional, (default = None) The magnitude with which to clip the memory cell. """ def __init__( self, input_size: int, hidden_size: int, cell_size: int, num_layers: int, requires_grad: bool = False, recurrent_dropout_probability: float = 0.0, memory_cell_clip_value: Optional[float] = None, state_projection_clip_value: Optional[float] = None, ) -> None: super().__init__(stateful=True) # Required to be wrapped with a `PytorchSeq2SeqWrapper`. self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.cell_size = cell_size self.requires_grad = requires_grad forward_layers = [] backward_layers = [] lstm_input_size = input_size go_forward = True for layer_index in range(num_layers): forward_layer = LstmCellWithProjection( lstm_input_size, hidden_size, cell_size, go_forward, recurrent_dropout_probability, memory_cell_clip_value, state_projection_clip_value, ) backward_layer = LstmCellWithProjection( lstm_input_size, hidden_size, cell_size, not go_forward, recurrent_dropout_probability, memory_cell_clip_value, state_projection_clip_value, ) lstm_input_size = hidden_size self.add_module("forward_layer_{}".format(layer_index), forward_layer) self.add_module("backward_layer_{}".format(layer_index), backward_layer) forward_layers.append(forward_layer) backward_layers.append(backward_layer) self.forward_layers = forward_layers self.backward_layers = backward_layers def forward(self, inputs: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: """ # Parameters inputs : `torch.Tensor`, required. A Tensor of shape `(batch_size, sequence_length, hidden_size)`. mask : `torch.LongTensor`, required. A binary mask of shape `(batch_size, sequence_length)` representing the non-padded elements in each sequence in the batch. # Returns A `torch.Tensor` of shape (num_layers, batch_size, sequence_length, hidden_size), where the num_layers dimension represents the LSTM output from that layer. """ batch_size, total_sequence_length = mask.size() stacked_sequence_output, final_states, restoration_indices = self.sort_and_run_forward( self._lstm_forward, inputs, mask ) num_layers, num_valid, returned_timesteps, encoder_dim = stacked_sequence_output.size() # Add back invalid rows which were removed in the call to sort_and_run_forward. if num_valid < batch_size: zeros = stacked_sequence_output.new_zeros( num_layers, batch_size - num_valid, returned_timesteps, encoder_dim ) stacked_sequence_output = torch.cat([stacked_sequence_output, zeros], 1) # The states also need to have invalid rows added back. new_states = [] for state in final_states: state_dim = state.size(-1) zeros = state.new_zeros(num_layers, batch_size - num_valid, state_dim) new_states.append(torch.cat([state, zeros], 1)) final_states = new_states # It's possible to need to pass sequences which are padded to longer than the # max length of the sequence to a Seq2StackEncoder. However, packing and unpacking # the sequences mean that the returned tensor won't include these dimensions, because # the RNN did not need to process them. We add them back on in the form of zeros here. sequence_length_difference = total_sequence_length - returned_timesteps if sequence_length_difference > 0: zeros = stacked_sequence_output.new_zeros( num_layers, batch_size, sequence_length_difference, stacked_sequence_output[0].size(-1), ) stacked_sequence_output = torch.cat([stacked_sequence_output, zeros], 2) self._update_states(final_states, restoration_indices) # Restore the original indices and return the sequence. # Has shape (num_layers, batch_size, sequence_length, hidden_size) return stacked_sequence_output.index_select(1, restoration_indices) def _lstm_forward( self, inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, ) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ # Parameters inputs : `PackedSequence`, required. A batch first `PackedSequence` to run the stacked LSTM over. initial_state : `Tuple[torch.Tensor, torch.Tensor]`, optional, (default = None) A tuple (state, memory) representing the initial hidden state and memory of the LSTM, with shape (num_layers, batch_size, 2 * hidden_size) and (num_layers, batch_size, 2 * cell_size) respectively. # Returns output_sequence : `torch.FloatTensor` The encoded sequence of shape (num_layers, batch_size, sequence_length, hidden_size) final_states : `Tuple[torch.FloatTensor, torch.FloatTensor]` The per-layer final (state, memory) states of the LSTM, with shape (num_layers, batch_size, 2 * hidden_size) and (num_layers, batch_size, 2 * cell_size) respectively. The last dimension is duplicated because it contains the state/memory for both the forward and backward layers. """ if initial_state is None: hidden_states: List[Optional[Tuple[torch.Tensor, torch.Tensor]]] = [None] * len( self.forward_layers ) elif initial_state[0].size()[0] != len(self.forward_layers): raise ConfigurationError( "Initial states were passed to forward() but the number of " "initial states does not match the number of layers." ) else: hidden_states = list(zip(initial_state[0].split(1, 0), initial_state[1].split(1, 0))) inputs, batch_lengths = pad_packed_sequence(inputs, batch_first=True) forward_output_sequence = inputs backward_output_sequence = inputs final_states = [] sequence_outputs = [] for layer_index, state in enumerate(hidden_states): forward_layer = getattr(self, "forward_layer_{}".format(layer_index)) backward_layer = getattr(self, "backward_layer_{}".format(layer_index)) forward_cache = forward_output_sequence backward_cache = backward_output_sequence if state is not None: forward_hidden_state, backward_hidden_state = state[0].split(self.hidden_size, 2) forward_memory_state, backward_memory_state = state[1].split(self.cell_size, 2) forward_state = (forward_hidden_state, forward_memory_state) backward_state = (backward_hidden_state, backward_memory_state) else: forward_state = None backward_state = None forward_output_sequence, forward_state = forward_layer( forward_output_sequence, batch_lengths, forward_state ) backward_output_sequence, backward_state = backward_layer( backward_output_sequence, batch_lengths, backward_state ) # Skip connections, just adding the input to the output. if layer_index != 0:
sequence_outputs.append( torch.cat([forward_output_sequence, backward_output_sequence], -1) ) # Append the state tuples in a list, so that we can return # the final states for all the layers. final_states.append( ( torch.cat([forward_state[0], backward_state[0]], -1), torch.cat([forward_state[1], backward_state[1]], -1), ) ) stacked_sequence_outputs: torch.FloatTensor = torch.stack(sequence_outputs) # Stack the hidden state and memory for each layer into 2 tensors of shape # (num_layers, batch_size, hidden_size) and (num_layers, batch_size, cell_size) # respectively. final_hidden_states, final_memory_states = zip(*final_states) final_state_tuple: Tuple[torch.FloatTensor, torch.FloatTensor] = ( torch.cat(final_hidden_states, 0), torch.cat(final_memory_states, 0), ) return stacked_sequence_outputs, final_state_tuple def load_weights(self, weight_file: str) -> None: """ Load the pre-trained weights from the file. """ requires_grad = self.requires_grad with h5py.File(cached_path(weight_file), "r") as fin: for i_layer, lstms in enumerate(zip(self.forward_layers, self.backward_layers)): for j_direction, lstm in enumerate(lstms): # lstm is an instance of LSTMCellWithProjection cell_size = lstm.cell_size dataset = fin["RNN_%s" % j_direction]["RNN"]["MultiRNNCell"][ "Cell%s" % i_layer ]["LSTMCell"] # tensorflow packs together both W and U matrices into one matrix, # but pytorch maintains individual matrices. In addition, tensorflow # packs the gates as input, memory, forget, output but pytorch # uses input, forget, memory, output. So we need to modify the weights. tf_weights = numpy.transpose(dataset["W_0"][...]) torch_weights = tf_weights.copy() # split the W from U matrices input_size = lstm.input_size input_weights = torch_weights[:, :input_size] recurrent_weights = torch_weights[:, input_size:] tf_input_weights = tf_weights[:, :input_size] tf_recurrent_weights = tf_weights[:, input_size:] # handle the different gate order convention for torch_w, tf_w in [ [input_weights, tf_input_weights], [recurrent_weights, tf_recurrent_weights], ]: torch_w[(1 * cell_size) : (2 * cell_size), :] = tf_w[ (2 * cell_size) : (3 * cell_size), : ] torch_w[(2 * cell_size) : (3 * cell_size), :] = tf_w[ (1 * cell_size) : (2 * cell_size), : ] lstm.input_linearity.weight.data.copy_(torch.FloatTensor(input_weights)) lstm.state_linearity.weight.data.copy_(torch.FloatTensor(recurrent_weights)) lstm.input_linearity.weight.requires_grad = requires_grad lstm.state_linearity.weight.requires_grad = requires_grad # the bias weights tf_bias = dataset["B"][...] # tensorflow adds 1.0 to forget gate bias instead of modifying the # parameters... tf_bias[(2 * cell_size) : (3 * cell_size)] += 1 torch_bias = tf_bias.copy() torch_bias[(1 * cell_size) : (2 * cell_size)] = tf_bias[ (2 * cell_size) : (3 * cell_size) ] torch_bias[(2 * cell_size) : (3 * cell_size)] = tf_bias[ (1 * cell_size) : (2 * cell_size) ] lstm.state_linearity.bias.data.copy_(torch.FloatTensor(torch_bias)) lstm.state_linearity.bias.requires_grad = requires_grad # the projection weights proj_weights = numpy.transpose(dataset["W_P_0"][...]) lstm.state_projection.weight.data.copy_(torch.FloatTensor(proj_weights)) lstm.state_projection.weight.requires_grad = requires_grad
forward_output_sequence += forward_cache backward_output_sequence += backward_cache
demandprinter.py
import inspect import io import json import logging as logginglib import sys from datetime import datetime from typing import Any, Callable, Dict, List, Optional, Set, TextIO, Tuple from typing_extensions import Literal from hpc.autoscale import hpclogging as logging from hpc.autoscale.codeanalysis import hpcwrapclass from hpc.autoscale.hpctypes import Hostname from hpc.autoscale.job.demand import DemandResult from hpc.autoscale.node.node import Node OutputFormat = Literal["json", "table", "table_headerless"] @hpcwrapclass class DemandPrinter: def __init__( self, column_names: Optional[List[str]] = None, stream: Optional[TextIO] = None, output_format: OutputFormat = "table", long: bool = False, ) -> None: column_names_list: List[str] = [] if column_names: column_names_list = column_names self.__defaults = {} for n in range(len(column_names_list)): expr = column_names_list[n] if ":" in expr and "[" not in expr: column, default_value = expr.split(":", 1) column_names_list[n] = column self.__defaults[column] = default_value self.column_names = [x.lower() for x in column_names_list] self.stream = stream or sys.stdout self.output_format = output_format self.long = long def _calc_width(self, columns: List[str], rows: List[List[str]]) -> Tuple[int, ...]: maxes = [len(c) for c in columns] for row in rows: for n in range(len(row)): maxes[n] = max(len(row[n]), maxes[n]) return tuple(maxes) def _get_all_columns(self, compute_nodes: List[Node]) -> List[str]: columns = [] for attr_name in dir(Node): if not attr_name[0].isalpha(): continue attr = getattr(Node, attr_name) if hasattr(attr, "__call__"): continue columns.append(attr_name) if compute_nodes: all_available: Set[str] = set() for n in compute_nodes: all_available.update(n.available.keys()) columns += list(all_available) assert None not in columns columns = sorted(columns) return columns def print_columns(self, demand_result: DemandResult = None) -> None: columns = self.column_names if not columns: columns = self._get_all_columns( demand_result.compute_nodes if demand_result else [] ) columns = [c for c in columns if c != "hostname_required"] widths = self._calc_width(columns, []) formats = " ".join(["{:%d}" % x for x in widths]) assert len(widths) == len(columns), "{} != {}".format(len(widths), len(columns)) print(formats.format(*columns), file=self.stream) self.stream.flush() def print_demand(self, demand_result: DemandResult) -> None: rows = [] columns = self.column_names if not columns: columns = self._get_all_columns(demand_result.compute_nodes) if self.output_format == "json": columns = [c for c in columns if c not in ["hostname_required"]] else: columns = [ c for c in columns if c not in ["available", "node", "hostname_required"] ] columns = ["job_ids" if c == "assigned_job_ids" else c for c in columns] if "name" in columns: columns.remove("name") columns.insert(0, "name") short_columns = [c.split("@")[0] for c in columns] long_columns = [c.split("@")[-1] for c in columns] # sort by private ip or the node name def sort_by_ip_or_name(node: Node) -> Any: if node.private_ip: return tuple(map(int, node.private_ip.split("."))) name_toks = node.name.split("-") if name_toks[-1].isdigit(): node_index = int(name_toks[-1]) nodearray_ord = [ord(x) for x in node.nodearray] # 2**31 to make these come after private ips # then nodearray name, then index return tuple([2 ** 31] + nodearray_ord + [node_index]) return tuple([-1] + name_toks) ordered_nodes = sorted(demand_result.compute_nodes, key=sort_by_ip_or_name) for node in ordered_nodes: row: List[str] = [] rows.append(row) for column in long_columns: # TODO justify - this is a printing function, so this value could be lots of things etc. value: Any = None is_from_available = column.startswith("*") is_ratio = column.startswith("/") is_slice = "[" in column if is_from_available or is_ratio: column = column[1:] def _slice(v: str) -> str: return v slice = _slice if is_slice: slice_expr = column[column.index("[") :] column = column.split("[")[0] # TODO maybe parse this instead of eval-ing a lambda if self.long: slice = lambda v: v # noqa: E731 else: slice = eval( "lambda v: v%s if v is not None else v" % slice_expr ) if column == "hostname": hostname = node.hostname if not node.exists or not hostname: if node.private_ip: hostname = Hostname(str(node.private_ip)) else: hostname = Hostname("tbd") value = hostname elif column == "hostname_required": continue elif column == "job_ids": value = node.assignments elif hasattr(node, column): value = getattr(node, column) else: if is_from_available: value = node.available.get(column) elif is_ratio: value = "{}/{}".format( node.available.get(column), node.resources.get(column) ) elif column in node.resources: value = node.resources.get(column) else: value = node.metadata.get(column) if value is None: value = self.__defaults.get(column) # convert sets to lists, as sets are not json serializable if isinstance(value, set): value = list(value) elif isinstance(value, datetime): value = value.isoformat() # for json, we support lists, null, numbers etc. # for table* we will output a string for every value. if self.output_format != "json": if isinstance(value, list): value = ",".join(sorted(value)) elif isinstance(value, set): value = ",".join(sorted(list(value))) elif value is None: value = "" elif isinstance(value, float): value = "{:.1f}".format(value) elif not isinstance(value, str): value = str(value) else: if hasattr(value, "to_json"): value = value.to_json() elif hasattr(value, "keys"): value = dict(value) row.append(slice(value)) # remove / and slice expressions stripped_short_names = [c.lstrip("/").split("[")[0] for c in short_columns] if self.output_format != "json": stripped_short_names = [x.upper() for x in stripped_short_names] print_rows(stripped_short_names, rows, self.stream, self.output_format) def __str__(self) -> str: return "DemandPrinter(columns={}, output_format={}, stream={})".format( str(self.column_names), self.output_format, self.stream ) def __repr__(self) -> str: return str(self) def print_columns( demand_result: DemandResult, stream: Optional[TextIO] = None, output_format: OutputFormat = "table", long: bool = False, ) -> None: printer = DemandPrinter(None, stream=stream, output_format=output_format, long=long) printer.print_columns(demand_result) def print_demand( columns: List[str], demand_result: DemandResult, stream: Optional[TextIO] = None, output_format: OutputFormat = "table", log: bool = False, long: bool = False, ) -> None: if log: stream = logging_stream(stream or sys.stdout) printer = DemandPrinter( columns, stream=stream, output_format=output_format, long=long ) printer.print_demand(demand_result) def wrap_text_io(clz: Any) -> Callable[[TextIO, Optional[str]], TextIO]: members: Dict[str, Any] = {} for attr in dir(TextIO): if not attr[0].islower() and attr not in [ "__enter__", "__exit__", "__iter__", "__next__", ]: continue if attr in dir(clz): continue def make_member(mem_name: str) -> Any: is_function = inspect.isfunction(getattr(TextIO, mem_name)) if is_function: return lambda *args: getattr(args[0].wrapped, mem_name)(*args[1:]) else: return property(lambda *args: getattr(args[0].wrapped, mem_name)) members[attr] = make_member(attr) return type("LoggingStream", (clz,), members) class _LoggingStream: def __init__(self, wrapped: TextIO, logger_name: Optional[str] = None) -> None:
def write(self, s: str) -> int: self.line_buffer.write(s) return self.wrapped.write(s) def flush(self) -> None: buf = self.line_buffer.getvalue() if not buf: return fact = logginglib.getLogRecordFactory() logger = logging.getLogger(self.logger_name) created = None for line in buf.splitlines(keepends=False): record = fact( name="demandprinter", level=logging.INFO, pathname=__file__, lineno=1, msg=line, args=(), exc_info=None, created=created, ) created = created or record.created logger.handle(record) self.line_buffer = io.StringIO() def close(self) -> None: self.flush() self.wrapped.close() LoggingStream = wrap_text_io(_LoggingStream) def logging_stream(wrapped: TextIO, logger_name: Optional[str] = None) -> TextIO: logger_name = logger_name or "demand" return LoggingStream(wrapped, logger_name) class ExcludeDemandPrinterFilter(logginglib.Filter): def __init__(self, name: str = "") -> None: super().__init__(name) def filter(self, record: logginglib.LogRecord) -> bool: return record.name != "demandprinter" def calculate_column_widths( columns: List[str], rows: List[List[str]] ) -> Tuple[int, ...]: maxes = [len(c.split("@")[0]) for c in columns] for row in rows: for n in range(len(row)): maxes[n] = max(len(row[n]), maxes[n]) return tuple(maxes) def print_rows( columns: List[str], rows: List[List[str]], stream: Optional[TextIO] = None, output_format: str = "table", ) -> None: output_format = output_format or "table" stream = stream or sys.stdout short_names = [c.split("@")[0] for c in columns] if output_format.lower() == "json": json.dump( [dict(zip(short_names, row)) for row in rows], stream, indent=2, ) else: widths = calculate_column_widths(short_names, rows) formats = " ".join(["{:%d}" % x for x in widths]) if output_format == "table": print(formats.format(*short_names), file=stream) for row in rows: print(formats.format(*[str(r) for r in row]), file=stream) stream.flush()
self.line_buffer = io.StringIO() self.wrapped = wrapped self.logger_name = logger_name
cli.py
import argparse def add_common_args(parser: argparse.ArgumentParser): parser.add_argument( '--dry-run', action='store_true', default=False, help='If true, will not actually do any changes to i3 workspaces.') parser.add_argument( '--log-level', choices=('debug', 'info', 'warning', 'error', 'critical'), default='warning', help='Logging level for stderr and syslog.') def add_workspace_naming_args(parser: argparse.ArgumentParser) -> None:
parser.add_argument( '--window-icons-all-groups', action='store_true', default=False, help='If true, will add the icons of the open windows to workspaces' ' in all groups, and not just the active group. Also implies ' '--window-icons.') parser.add_argument( '--renumber-workspaces', action='store_true', default=False, help='If true, will renumber workspaces in every groups so that they ' 'are in numerical order, similar to tmux\'s renumber-windows option.')
convert.go
package internal import ( "reflect" "strings" ) // 这个是为了在JSON或者转成MAP更改其字段 // TS是用的驼峰 // Field 字符串转换 type Field func(string) string func base(data interface{}) (reflect.Type, reflect.Value, bool) { dv := reflect.ValueOf(data) dt := reflect.TypeOf(data) if dt.Kind() != reflect.Ptr { // 如果不是指针不能赋值 pdv := reflect.New(dt) pdv.Elem().Set(dv) dv = pdv dt = pdv.Type() } for dt.Kind() == reflect.Ptr { if dv.IsNil() { return dt, dv, false } dt = dt.Elem() dv = dv.Elem() } return dt, dv, true } func ToMapWithField(data interface{}, field Field) map[string]interface{} { dt, dv, ok := base(data) if !ok { return make(map[string]interface{}) } // 支持MAP\STRUCT if dt.Kind() == reflect.Struct { return structToMap(dv, field) } if dt.Kind() == reflect.Map { return mapToMap(dv, field) } // ARRAY\SLICE自行循环调用 return make(map[string]interface{}) } func ToSliceWithField(data interface{}, field Field) []interface{} { dt, dv, ok := base(data) if !ok { return make([]interface{}, 0) } if dt.Kind() == reflect.Array || dt.Kind() == reflect.Slice { return sliceToMap(dv, field) } return make([]interface{}, 0) } func ToWithField(data interface{}, field Field) interface{} { _, dv, ok := base(data) if !ok { return dv } rs, _ := selectMapFunc(dv, field) return rs } // 支持方法 func selectMapFunc(dv reflect.Value, field Field) (interface{}, bool) { kind := dv.Kind() for kind == reflect.Ptr { if dv.IsNil() { return nil, false } d
mField() mp := make(map[string]interface{}) if fn == 0 { return mp } dt := dv.Type() for i := 0; i < fn; i++ { fs := dt.Field(i) fv := dv.Field(i) if !fv.CanSet() { // 私有变量 continue } // 检测TAG tag := fs.Tag.Get("json") fd := fs.Name if tag != "" { jfd := strings.TrimSpace(strings.SplitN(tag, ",", 2)[0]) if jfd != "" { if jfd == "-" { // 忽略 continue } fd = jfd } } if field != nil { fd = field(fd) } if tmp, ok := selectMapFunc(fv, field); ok { mp[fd] = tmp continue } mp[fd] = fv.Interface() } return mp } // 该函数只是把内部做转换 func sliceToMap(dv reflect.Value, field Field) []interface{} { num := dv.Len() is := make([]interface{}, num) if num == 0 { return is } for i := 0; i < num; i++ { iv := dv.Index(i) tmp, ok := selectMapFunc(iv, field) if ok { is[i] = tmp continue } is[i] = iv.Interface() } return is } func mapToMap(dv reflect.Value, field Field) map[string]interface{} { it := dv.MapRange() mp := make(map[string]interface{}) for it.Next() { f := it.Key() if f.Kind() != reflect.String { continue } fd := f.String() if field != nil { fd = field(fd) } v := it.Value() if tmp, ok := selectMapFunc(v, field); ok { mp[fd] = tmp continue } mp[fd] = v.Interface() } return mp } // To 通用转换 func To(data interface{}) interface{} { return ToWithField(data, nil) } // ToMap 对结构体字段进行转换 // 依赖JSON TAG // NOTE 请调用方自行避免使用循环依赖, 与JSON保持一致,私有变量忽略 func ToMap(data interface{}) map[string]interface{} { return ToMapWithField(data, nil) } // ToSlice 对数组进行每个元素进行转换 func ToSlice(data interface{}) []interface{} { return ToSliceWithField(data, nil) } // 封装了一些通用的中间函数 // Origin 原始结果 func Origin(next Field) Field { return func(s string) string { if next != nil { s = next(s) } return s } } // Snake 转下划线 func Snake(next Field) Field { return func(s string) string { s = ToSnake(s) if next != nil { s = next(s) } return s } } // Came 转驼峰 func Came(next Field) Field { return func(s string) string { s = ToCame(s) if next != nil { s = next(s) } return s } } // Upper 转大写 func Upper(next Field) Field { return func(s string) string { s = strings.ToUpper(s) if next != nil { s = next(s) } return s } } // Lower 转小写 func Lower(next Field) Field { return func(s string) string { s = strings.ToLower(s) if next != nil { s = next(s) } return s } } // LcFirst 首字母小写 func LcFirst(next Field) Field { return func(s string) string { s = ToLcFirst(s) if next != nil { s = next(s) } return s } } // UcFirst 首字母大写 func UcFirst(next Field) Field { return func(s string) string { s = ToUcFirst(s) if next != nil { s = next(s) } return s } }
v = dv.Elem() kind = dv.Kind() } // 支持MAP\STRUCT\ARRAY if kind == reflect.Struct { return structToMap(dv, field), true } if kind == reflect.Map { return mapToMap(dv, field), true } if kind == reflect.Array || kind == reflect.Slice { return sliceToMap(dv, field), true } return nil, false } // 结构体转map func structToMap(dv reflect.Value, field Field) map[string]interface{} { fn := dv.Nu
version_test.go
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 version import ( "context" "fmt" "net/http" "testing" "github.com/stretchr/testify/assert" ) func TestGetVersionsGithub(t *testing.T) { // Ensure a clean environment. tests := []struct { Name string Path string ResponseBody string ExpectedErr string ExpectedVer string }{ { "RC releases are skipped", "/no_rc", `[ { "url": "https://api.github.com/repos/dapr/dapr/releases/44766923", "html_url": "https://github.com/dapr/dapr/releases/tag/v1.2.3-rc.1", "id": 44766926, "tag_name": "v1.2.3-rc.1", "target_commitish": "master", "name": "Dapr Runtime v1.2.3-rc.1", "draft": false, "prerelease": false }, { "url": "https://api.github.com/repos/dapr/dapr/releases/44766923", "html_url": "https://github.com/dapr/dapr/releases/tag/v1.2.2", "id": 44766923, "tag_name": "v1.2.2", "target_commitish": "master", "name": "Dapr Runtime v1.2.2", "draft": false, "prerelease": false } ] `, "", "1.2.2", }, { "Malformed JSON", "/malformed", "[", "unexpected end of JSON input", "", }, { "Only RCs", "/only_rcs", `[ { "url": "https://api.github.com/repos/dapr/dapr/releases/44766923", "html_url": "https://github.com/dapr/dapr/releases/tag/v1.2.3-rc.1", "id": 44766926, "tag_name": "v1.2.3-rc.1", "target_commitish": "master", "name": "Dapr Runtime v1.2.3-rc.1", "draft": false, "prerelease": false } ] `, "no releases", "", }, { "Empty json", "/empty", "[]", "no releases", "", }, } m := http.NewServeMux() s := http.Server{Addr: ":12345", Handler: m} for _, tc := range tests { body := tc.ResponseBody m.HandleFunc(tc.Path, func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, body) }) } go func() { s.ListenAndServe() }() for _, tc := range tests { t.Run(tc.Name, func(t *testing.T) { version, err := GetLatestReleaseGithub(fmt.Sprintf("http://localhost:12345%s", tc.Path)) assert.Equal(t, tc.ExpectedVer, version) if tc.ExpectedErr != "" { assert.EqualError(t, err, tc.ExpectedErr) } }) } t.Run("error on 404", func(t *testing.T) { version, err := GetLatestReleaseGithub("http://localhost:12345/non-existant/path") assert.Equal(t, "", version) assert.EqualError(t, err, "http://localhost:12345/non-existant/path - 404 Not Found") }) t.Run("error on bad addr", func(t *testing.T) { version, err := GetLatestReleaseGithub("http://a.super.non.existant.domain/") assert.Equal(t, "", version) assert.Error(t, err) }) s.Shutdown(context.Background()) } func TestGetVersionsHelm(t *testing.T) { // Ensure a clean environment. tests := []struct { Name string Path string ResponseBody string ExpectedErr string ExpectedVer string }{ { "RC releases are skipped", "/rcs_are_skiipped", `apiVersion: v1 entries: dapr: - apiVersion: v1 appVersion: 1.2.3-rc.1 created: "2021-06-17T03:13:24.179849371Z" description: A Helm chart for Dapr on Kubernetes digest: 60d8d17b58ca316cdcbdb8529cf9ba2c9e2e0834383c677cafbf99add86ee7a0 name: dapr urls: - https://dapr.github.io/helm-charts/dapr-1.2.3-rc.1.tgz version: 1.2.3-rc.1 - apiVersion: v1 appVersion: 1.2.2 created: "2021-06-17T03:13:24.179849371Z" description: A Helm chart for Dapr on Kubernetes digest: 60d8d17b58ca316cdcbdb8529cf9ba2c9e2e0834383c677cafbf99add86ee7a0 name: dapr urls: - https://dapr.github.io/helm-charts/dapr-1.2.2.tgz version: 1.2.2 `, "", "1.2.2", }, { "Malformed YAML", "/malformed", "[", "yaml: line 1: did not find expected node content", "", }, { "Empty YAML", "/empty", "", "no releases", "", }, { "Only RCs", "/only_rcs", `apiVersion: v1 entries: dapr: - apiVersion: v1 appVersion: 1.2.3-rc.1 created: "2021-06-17T03:13:24.179849371Z" description: A Helm chart for Dapr on Kubernetes digest: 60d8d17b58ca316cdcbdb8529cf9ba2c9e2e0834383c677cafbf99add86ee7a0 name: dapr urls: - https://dapr.github.io/helm-charts/dapr-1.2.3-rc.1.tgz version: 1.2.3-rc.1 `, "no releases", "", }, } m := http.NewServeMux() s := http.Server{Addr: ":12346", Handler: m} for _, tc := range tests { body := tc.ResponseBody m.HandleFunc(tc.Path, func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, body) }) } go func() { s.ListenAndServe() }() for _, tc := range tests { t.Run(tc.Name, func(t *testing.T) { version, err := GetLatestReleaseHelmChart(fmt.Sprintf("http://localhost:12346%s", tc.Path)) assert.Equal(t, tc.ExpectedVer, version) if tc.ExpectedErr != "" { assert.EqualError(t, err, tc.ExpectedErr) } }) } s.Shutdown(context.Background()) }
/* Copyright 2021 The Dapr Authors
delete_chartrepo_repo_charts_name_version_labels_id_responses.go
// Code generated by go-swagger; DO NOT EDIT. package products // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "github.com/go-openapi/runtime" strfmt "github.com/go-openapi/strfmt" ) // DeleteChartrepoRepoChartsNameVersionLabelsIDReader is a Reader for the DeleteChartrepoRepoChartsNameVersionLabelsID structure. type DeleteChartrepoRepoChartsNameVersionLabelsIDReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewDeleteChartrepoRepoChartsNameVersionLabelsIDOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewDeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 401: result := NewDeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 403: result := NewDeleteChartrepoRepoChartsNameVersionLabelsIDForbidden() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewDeleteChartrepoRepoChartsNameVersionLabelsIDNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 500: result := NewDeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } } // NewDeleteChartrepoRepoChartsNameVersionLabelsIDOK creates a DeleteChartrepoRepoChartsNameVersionLabelsIDOK with default headers values func NewDeleteChartrepoRepoChartsNameVersionLabelsIDOK() *DeleteChartrepoRepoChartsNameVersionLabelsIDOK { return &DeleteChartrepoRepoChartsNameVersionLabelsIDOK{} } /*DeleteChartrepoRepoChartsNameVersionLabelsIDOK handles this case with default header values. The label is successfully unmarked from the chart version. */ type DeleteChartrepoRepoChartsNameVersionLabelsIDOK struct { } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDOK) Error() string { return fmt.Sprintf("[DELETE /chartrepo/{repo}/charts/{name}/{version}/labels/{id}][%d] deleteChartrepoRepoChartsNameVersionLabelsIdOK ", 200) } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil }
func NewDeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest() *DeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest { return &DeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest{} } /*DeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest handles this case with default header values. Bad request */ type DeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest struct { } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest) Error() string { return fmt.Sprintf("[DELETE /chartrepo/{repo}/charts/{name}/{version}/labels/{id}][%d] deleteChartrepoRepoChartsNameVersionLabelsIdBadRequest ", 400) } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewDeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized creates a DeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized with default headers values func NewDeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized() *DeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized { return &DeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized{} } /*DeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized handles this case with default header values. Unauthorized */ type DeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized struct { } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized) Error() string { return fmt.Sprintf("[DELETE /chartrepo/{repo}/charts/{name}/{version}/labels/{id}][%d] deleteChartrepoRepoChartsNameVersionLabelsIdUnauthorized ", 401) } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewDeleteChartrepoRepoChartsNameVersionLabelsIDForbidden creates a DeleteChartrepoRepoChartsNameVersionLabelsIDForbidden with default headers values func NewDeleteChartrepoRepoChartsNameVersionLabelsIDForbidden() *DeleteChartrepoRepoChartsNameVersionLabelsIDForbidden { return &DeleteChartrepoRepoChartsNameVersionLabelsIDForbidden{} } /*DeleteChartrepoRepoChartsNameVersionLabelsIDForbidden handles this case with default header values. Operation is forbidden or quota exceeded */ type DeleteChartrepoRepoChartsNameVersionLabelsIDForbidden struct { } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDForbidden) Error() string { return fmt.Sprintf("[DELETE /chartrepo/{repo}/charts/{name}/{version}/labels/{id}][%d] deleteChartrepoRepoChartsNameVersionLabelsIdForbidden ", 403) } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewDeleteChartrepoRepoChartsNameVersionLabelsIDNotFound creates a DeleteChartrepoRepoChartsNameVersionLabelsIDNotFound with default headers values func NewDeleteChartrepoRepoChartsNameVersionLabelsIDNotFound() *DeleteChartrepoRepoChartsNameVersionLabelsIDNotFound { return &DeleteChartrepoRepoChartsNameVersionLabelsIDNotFound{} } /*DeleteChartrepoRepoChartsNameVersionLabelsIDNotFound handles this case with default header values. Not found */ type DeleteChartrepoRepoChartsNameVersionLabelsIDNotFound struct { } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDNotFound) Error() string { return fmt.Sprintf("[DELETE /chartrepo/{repo}/charts/{name}/{version}/labels/{id}][%d] deleteChartrepoRepoChartsNameVersionLabelsIdNotFound ", 404) } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewDeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError creates a DeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError with default headers values func NewDeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError() *DeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError { return &DeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError{} } /*DeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError handles this case with default header values. Internal server error occurred */ type DeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError struct { } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError) Error() string { return fmt.Sprintf("[DELETE /chartrepo/{repo}/charts/{name}/{version}/labels/{id}][%d] deleteChartrepoRepoChartsNameVersionLabelsIdInternalServerError ", 500) } func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil }
// NewDeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest creates a DeleteChartrepoRepoChartsNameVersionLabelsIDBadRequest with default headers values
workspace.go
package v1
} type WorkspaceStorageS3 struct { Host string `json:"host"` Port int `json:"path"` UseSSL bool `json:"useSSL"` BucketName string `json:"bucketName"` Credentials WorkspaceStorageS3Credentials `json:"credentials"` } type WorkspaceStorageS3Credentials struct { Secret WorkspaceStorageS3CredentialsS3 `json:"secret"` } type WorkspaceStorageS3CredentialsS3 struct { Name string `json:"name"` AccessKeyKey string `json:"accessKeyKey"` SecretKeyKey string `json:"secretKeyKey"` } type WorkspaceRepo struct { URL string `json:"url"` SSH WorkspaceRepoSSH `json:"ssh"` } type WorkspaceRepoSSH struct { Secret WorkspaceRepoSSHSecret `json:"secret"` } type WorkspaceRepoSSHSecret struct { Name string `json:"name"` Key string `json:"key"` }
type WorkspaceStorage struct { S3 WorkspaceStorageS3 `json:"s3"`
VoipUserMapper.ts
/* Copyright 2021 The Matrix.org Foundation C.I.C. 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 { Room } from 'matrix-js-sdk/src/models/room'; import { logger } from "matrix-js-sdk/src/logger"; import { EventType } from 'matrix-js-sdk/src/@types/event'; import { ensureVirtualRoomExists } from './createRoom'; import { MatrixClientPeg } from "./MatrixClientPeg"; import DMRoomMap from "./utils/DMRoomMap"; import CallHandler from './CallHandler'; import { VIRTUAL_ROOM_EVENT_TYPE } from "./call-types"; import { findDMForUser } from "./utils/direct-messages"; // Functions for mapping virtual users & rooms. Currently the only lookup // is sip virtual: there could be others in the future. export default class VoipUserMapper { // We store mappings of virtual -> native room IDs here until the local echo for the // account data arrives.
public static sharedInstance(): VoipUserMapper { if (window.mxVoipUserMapper === undefined) window.mxVoipUserMapper = new VoipUserMapper(); return window.mxVoipUserMapper; } private async userToVirtualUser(userId: string): Promise<string> { const results = await CallHandler.instance.sipVirtualLookup(userId); if (results.length === 0 || !results[0].fields.lookup_success) return null; return results[0].userid; } private async getVirtualUserForRoom(roomId: string): Promise<string | null> { const userId = DMRoomMap.shared().getUserIdForRoomId(roomId); if (!userId) return null; const virtualUser = await this.userToVirtualUser(userId); if (!virtualUser) return null; return virtualUser; } public async getOrCreateVirtualRoomForRoom(roomId: string): Promise<string | null> { const virtualUser = await this.getVirtualUserForRoom(roomId); if (!virtualUser) return null; const virtualRoomId = await ensureVirtualRoomExists(MatrixClientPeg.get(), virtualUser, roomId); MatrixClientPeg.get().setRoomAccountData(virtualRoomId, VIRTUAL_ROOM_EVENT_TYPE, { native_room: roomId, }); this.virtualToNativeRoomIdCache.set(virtualRoomId, roomId); return virtualRoomId; } /** * Gets the ID of the virtual room for a room, or null if the room has no * virtual room */ public async getVirtualRoomForRoom(roomId: string): Promise<Room | null> { const virtualUser = await this.getVirtualUserForRoom(roomId); if (!virtualUser) return null; return findDMForUser(MatrixClientPeg.get(), virtualUser); } public nativeRoomForVirtualRoom(roomId: string): string { const cachedNativeRoomId = this.virtualToNativeRoomIdCache.get(roomId); if (cachedNativeRoomId) { logger.log( "Returning native room ID " + cachedNativeRoomId + " for virtual room ID " + roomId + " from cache", ); return cachedNativeRoomId; } const virtualRoom = MatrixClientPeg.get().getRoom(roomId); if (!virtualRoom) return null; const virtualRoomEvent = virtualRoom.getAccountData(VIRTUAL_ROOM_EVENT_TYPE); if (!virtualRoomEvent || !virtualRoomEvent.getContent()) return null; const nativeRoomID = virtualRoomEvent.getContent()['native_room']; const nativeRoom = MatrixClientPeg.get().getRoom(nativeRoomID); if (!nativeRoom || nativeRoom.getMyMembership() !== 'join') return null; return nativeRoomID; } public isVirtualRoom(room: Room): boolean { if (this.nativeRoomForVirtualRoom(room.roomId)) return true; if (this.virtualToNativeRoomIdCache.has(room.roomId)) return true; // also look in the create event for the claimed native room ID, which is the only // way we can recognise a virtual room we've created when it first arrives down // our stream. We don't trust this in general though, as it could be faked by an // inviter: our main source of truth is the DM state. const roomCreateEvent = room.currentState.getStateEvents(EventType.RoomCreate, ""); if (!roomCreateEvent || !roomCreateEvent.getContent()) return false; // we only look at this for rooms we created (so inviters can't just cause rooms // to be invisible) if (roomCreateEvent.getSender() !== MatrixClientPeg.get().getUserId()) return false; const claimedNativeRoomId = roomCreateEvent.getContent()[VIRTUAL_ROOM_EVENT_TYPE]; return Boolean(claimedNativeRoomId); } public async onNewInvitedRoom(invitedRoom: Room): Promise<void> { if (!CallHandler.instance.getSupportsVirtualRooms()) return; const inviterId = invitedRoom.getDMInviter(); logger.log(`Checking virtual-ness of room ID ${invitedRoom.roomId}, invited by ${inviterId}`); const result = await CallHandler.instance.sipNativeLookup(inviterId); if (result.length === 0) { return; } if (result[0].fields.is_virtual) { const nativeUser = result[0].userid; const nativeRoom = findDMForUser(MatrixClientPeg.get(), nativeUser); if (nativeRoom) { // It's a virtual room with a matching native room, so set the room account data. This // will make sure we know where how to map calls and also allow us know not to display // it in the future. MatrixClientPeg.get().setRoomAccountData(invitedRoom.roomId, VIRTUAL_ROOM_EVENT_TYPE, { native_room: nativeRoom.roomId, }); // also auto-join the virtual room if we have a matching native room // (possibly we should only join if we've also joined the native room, then we'd also have // to make sure we joined virtual rooms on joining a native one) MatrixClientPeg.get().joinRoom(invitedRoom.roomId); } // also put this room in the virtual room ID cache so isVirtualRoom return the right answer // in however long it takes for the echo of setAccountData to come down the sync this.virtualToNativeRoomIdCache.set(invitedRoom.roomId, nativeRoom.roomId); } } }
private virtualToNativeRoomIdCache = new Map<string, string>();
utils.go
package utils import ( "errors" "os" "os/exec" "path/filepath" "runtime" "strings" "github.com/github/hub/ui" ) func Check(err error) { if err != nil
} func ConcatPaths(paths ...string) string { return strings.Join(paths, "/") } func BrowserLauncher() ([]string, error) { browser := os.Getenv("BROWSER") if browser == "" { browser = searchBrowserLauncher(runtime.GOOS) } if browser == "" { return nil, errors.New("Please set $BROWSER to a web launcher") } return strings.Split(browser, " "), nil } func searchBrowserLauncher(goos string) (browser string) { switch goos { case "darwin": browser = "open" case "windows": browser = "cmd /c start" default: candidates := []string{"xdg-open", "cygstart", "x-www-browser", "firefox", "opera", "mozilla", "netscape"} for _, b := range candidates { path, err := exec.LookPath(b) if err == nil { browser = path break } } } return browser } func DirName() (string, error) { dir, err := os.Getwd() if err != nil { return "", err } name := filepath.Base(dir) name = strings.Replace(name, " ", "-", -1) return name, nil } func IsOption(confirm, short, long string) bool { return strings.EqualFold(confirm, short) || strings.EqualFold(confirm, long) }
{ ui.Errorln(err) os.Exit(1) }
certs_test.go
/* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package bootstrapper import ( "os" "path/filepath" "testing" "k8s.io/minikube/pkg/minikube/command" "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/localpath" "k8s.io/minikube/pkg/minikube/tests" "k8s.io/minikube/pkg/util" ) func TestSetupCerts(t *testing.T) { tempDir := tests.MakeTempDir() defer os.RemoveAll(tempDir) k8s := config.KubernetesConfig{ APIServerName: constants.APIServerName, DNSDomain: constants.ClusterDNSDomain, ServiceCIDR: constants.DefaultServiceCIDR, } if err := os.Mkdir(filepath.Join(tempDir, "certs"), 0777); err != nil
if err := util.GenerateCACert( filepath.Join(tempDir, "certs", "mycert.pem"), filepath.Join(tempDir, "certs", "mykey.pem"), "Test Certificate", ); err != nil { t.Fatalf("error generating certificate: %v", err) } expected := map[string]string{ `sudo /bin/bash -c "test -f /usr/share/ca-certificates/mycert.pem || ln -s /etc/ssl/certs/mycert.pem /usr/share/ca-certificates/mycert.pem"`: "-", `sudo /bin/bash -c "test -f /usr/share/ca-certificates/minikubeCA.pem || ln -s /etc/ssl/certs/minikubeCA.pem /usr/share/ca-certificates/minikubeCA.pem"`: "-", } f := command.NewFakeCommandRunner() f.SetCommandToOutput(expected) var filesToBeTransferred []string for _, cert := range certs { filesToBeTransferred = append(filesToBeTransferred, filepath.Join(localpath.MiniPath(), cert)) } filesToBeTransferred = append(filesToBeTransferred, filepath.Join(localpath.MiniPath(), "ca.crt")) filesToBeTransferred = append(filesToBeTransferred, filepath.Join(localpath.MiniPath(), "certs", "mycert.pem")) if err := SetupCerts(f, k8s, config.Node{}); err != nil { t.Fatalf("Error starting cluster: %v", err) } for _, cert := range filesToBeTransferred { _, err := f.GetFileToContents(cert) if err != nil { t.Errorf("Cert not generated: %s", cert) } } }
{ t.Fatalf("error create certificate directory: %v", err) }
main.rs
use async_std::task; use std::time::{Duration, Instant}; #[async_std::main] async fn main() { const ITER_COUNT: i64 = 8192; let mut avg_join_complete_lat_ns: i64 = 0;
let mut avg_join_wait_lat_ns: i64 = 0; let mut avg_spawn_lat_ns: i64 = 0; for _ in 0..ITER_COUNT { let t0 = Instant::now(); let t1 = task::spawn(async { return Instant::now(); }).await; let t2 = Instant::now(); avg_join_complete_lat_ns += (t2 - t1).as_nanos() as i64; avg_spawn_lat_ns += (t1 - t0).as_nanos() as i64; } for _ in 0..ITER_COUNT { let ftr = task::spawn(async { std::thread::sleep(Duration::from_millis(1)); return Instant::now(); }); let t0 = ftr.await; let t1 = Instant::now(); avg_join_wait_lat_ns += (t1 - t0).as_nanos() as i64; } avg_join_complete_lat_ns /= ITER_COUNT; avg_join_wait_lat_ns /= ITER_COUNT; avg_spawn_lat_ns /= ITER_COUNT; println!("Average latency of {} tasks:", ITER_COUNT); println!("\tjoin complete: {}ns", avg_join_complete_lat_ns); println!("\tjoin wait: {}ns", avg_join_wait_lat_ns); println!("\tspawn: {}ns", avg_spawn_lat_ns); }
test_base_handler_without_unsafe.py
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com [email protected] from preggy import expect from tornado.testing import gen_test from tests.fixtures.images import ( default_image,
from thumbor.context import Context, ServerParameters from thumbor.importer import Importer from tests.handlers.test_base_handler import BaseImagingTestCase # pylint: disable=broad-except,abstract-method,attribute-defined-outside-init,line-too-long,too-many-public-methods # pylint: disable=too-many-lines class ImageOperationsWithoutUnsafeTestCase(BaseImagingTestCase): def get_context(self): cfg = Config(SECURITY_KEY="ACME-SEC") cfg.LOADER = "thumbor.loaders.file_loader" cfg.FILE_LOADER_ROOT_PATH = self.loader_path cfg.ALLOW_UNSAFE_URL = False importer = Importer(cfg) importer.import_modules() server = ServerParameters(8890, "localhost", "thumbor.conf", None, "info", None) server.security_key = "ACME-SEC" return Context(server, cfg, importer) @gen_test async def test_can_get_image_with_signed_url(self): response = await self.async_fetch( "/_wIUeSaeHw8dricKG2MGhqu5thk=/smart/image.jpg" ) expect(response.code).to_equal(200) expect(response.body).to_be_similar_to(default_image()) @gen_test async def test_getting_unsafe_image_fails(self): response = await self.async_fetch("/unsafe/smart/image.jpg") expect(response.code).to_equal(400)
) from thumbor.config import Config
schedulePanelFields.js
export const repeatPeriodField = { required: true, type: 'int', min: 1,
type: 'list', values: ['hours', 'days', 'weeks', 'months'] }
max: 50 }; export const repeatTimeUnitField = {
serialize.py
import datetime import json from twilio.base import values def iso8601_date(d): """ Return a string representation of a date that the Twilio API understands Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date """ if d == values.unset: return d elif isinstance(d, datetime.datetime): return str(d.date()) elif isinstance(d, datetime.date): return str(d) elif isinstance(d, str): return d def iso8601_datetime(d): """ Return a string representation of a date that the Twilio API understands Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date """ if d == values.unset: return d elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date): return d.strftime('%Y-%m-%dT%H:%M:%SZ') elif isinstance(d, str): return d def prefixed_collapsible_map(m, prefix): """ Return a dict of params corresponding to those in m with the added prefix """ if m == values.unset: return {} def flatten_dict(d, result=None, prv_keys=None): if result is None: result = {} if prv_keys is None: prv_keys = [] for k, v in d.items(): if isinstance(v, dict): flatten_dict(v, result, prv_keys + [k]) else: result['.'.join(prv_keys + [k])] = v return result if isinstance(m, dict): flattened = flatten_dict(m) return {'{}.{}'.format(prefix, k): v for k, v in flattened.items()} return {} def object(obj):
def map(lst, serialize_func): """ Applies serialize_func to every element in lst """ if not isinstance(lst, list): return lst return [serialize_func(e) for e in lst]
""" Return a jsonified string represenation of obj if obj is jsonifiable else return obj untouched """ if isinstance(obj, dict) or isinstance(obj, list): return json.dumps(obj) return obj
restores.go
package backup // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // RestoresClient is the open API 2.0 Specs for Azure RecoveryServices Backup service type RestoresClient struct { BaseClient } // NewRestoresClient creates an instance of the RestoresClient client. func NewRestoresClient(subscriptionID string) RestoresClient { return NewRestoresClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewRestoresClientWithBaseURI creates an instance of the RestoresClient client using a custom endpoint. Use this // when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewRestoresClientWithBaseURI(baseURI string, subscriptionID string) RestoresClient { return RestoresClient{NewWithBaseURI(baseURI, subscriptionID)} } // Trigger restores the specified backed up data. This is an asynchronous operation. To know the status of this API // call, use // GetProtectedItemOperationResult API. // Parameters: // vaultName - the name of the recovery services vault. // resourceGroupName - the name of the resource group where the recovery services vault is present. // fabricName - fabric name associated with the backed up items. // containerName - container name associated with the backed up items. // protectedItemName - backed up item to be restored. // recoveryPointID - recovery point ID which represents the backed up data to be restored. // parameters - resource restore request func (client RestoresClient) Trigger(ctx context.Context, vaultName string, resourceGroupName string, fabricName string, containerName string, protectedItemName string, recoveryPointID string, parameters RestoreRequestResource) (result autorest.Response, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/RestoresClient.Trigger") defer func() { sc := -1 if result.Response != nil { sc = result.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.TriggerPreparer(ctx, vaultName, resourceGroupName, fabricName, containerName, protectedItemName, recoveryPointID, parameters) if err != nil { err = autorest.NewErrorWithError(err, "backup.RestoresClient", "Trigger", nil, "Failure preparing request") return } resp, err := client.TriggerSender(req) if err != nil { result.Response = resp err = autorest.NewErrorWithError(err, "backup.RestoresClient", "Trigger", resp, "Failure sending request") return } result, err = client.TriggerResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "backup.RestoresClient", "Trigger", resp, "Failure responding to request") } return } // TriggerPreparer prepares the Trigger request. func (client RestoresClient) TriggerPreparer(ctx context.Context, vaultName string, resourceGroupName string, fabricName string, containerName string, protectedItemName string, recoveryPointID string, parameters RestoreRequestResource) (*http.Request, error) { pathParameters := map[string]interface{}{ "containerName": autorest.Encode("path", containerName), "fabricName": autorest.Encode("path", fabricName), "protectedItemName": autorest.Encode("path", protectedItemName), "recoveryPointId": autorest.Encode("path", recoveryPointID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vaultName": autorest.Encode("path", vaultName), } const APIVersion = "2019-05-13" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(),
autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // TriggerSender sends the Trigger request. The method will close the // http.Response Body if it receives an error. func (client RestoresClient) TriggerSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // TriggerResponder handles the response to the Trigger request. The method always // closes the http.Response Body. func (client RestoresClient) TriggerResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return }
autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/restore", pathParameters), autorest.WithJSON(parameters),
grid-core.esm.min.js
/** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ ' * @license MIT */ /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ ' * @license MIT */ /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */ var e,t=function(){function e(e,t,o,i){void 0===i&&(i=1),this.r=Math.min(1,Math.max(0,e||0)),this.g=Math.min(1,Math.max(0,t||0)),this.b=Math.min(1,Math.max(0,o||0)),this.a=Math.min(1,Math.max(0,i||0))}return e.fromString=function(t){if(t.indexOf("#")>=0)return e.fromHexString(t);var o=e.nameToHex[t];if(o)return e.fromHexString(o);if(t.indexOf("rgb")>=0)return e.fromRgbaString(t);throw new Error("Invalid color string: '"+t+"'")},e.fromHexString=function(t){var o=t.match(e.hexRe);if(o)return new e((i=parseInt(o[1],16))/255,(n=parseInt(o[2],16))/255,(r=parseInt(o[3],16))/255,(s=void 0!==o[4]?parseInt(o[4],16):255)/255);if(o=t.match(e.shortHexRe)){var i=parseInt(o[1],16),n=parseInt(o[2],16),r=parseInt(o[3],16),s=void 0!==o[4]?parseInt(o[4],16):15;return new e((i+=16*i)/255,(n+=16*n)/255,(r+=16*r)/255,(s+=16*s)/255)}throw new Error("Malformed hexadecimal color string: '"+t+"'")},e.fromRgbaString=function(t){var o=t.match(e.rgbRe);if(o)return new e(+o[1]/255,+o[2]/255,+o[3]/255);if(o=t.match(e.rgbaRe))return new e(+o[1]/255,+o[2]/255,+o[3]/255,+o[4]);throw new Error("Malformed rgb/rgba color string: '"+t+"'")},e.fromArray=function(t){if(4===t.length)return new e(t[0],t[1],t[2],t[3]);if(3===t.length)return new e(t[0],t[1],t[2]);throw new Error("The given array should contain 3 or 4 color components (numbers).")},e.fromHSB=function(t,o,i,n){void 0===n&&(n=1);var r=e.HSBtoRGB(t,o,i);return new e(r[0],r[1],r[2],n)},e.padHex=function(e){return 1===e.length?"0"+e:e},e.prototype.toHexString=function(){var t="#"+e.padHex(Math.round(255*this.r).toString(16))+e.padHex(Math.round(255*this.g).toString(16))+e.padHex(Math.round(255*this.b).toString(16));return this.a<1&&(t+=e.padHex(Math.round(255*this.a).toString(16))),t},e.prototype.toRgbaString=function(e){void 0===e&&(e=3);var t=[Math.round(255*this.r),Math.round(255*this.g),Math.round(255*this.b)],o=Math.pow(10,e);return 1!==this.a?(t.push(Math.round(this.a*o)/o),"rgba("+t.join(", ")+")"):"rgb("+t.join(", ")+")"},e.prototype.toString=function(){return 1===this.a?this.toHexString():this.toRgbaString()},e.prototype.toHSB=function(){return e.RGBtoHSB(this.r,this.g,this.b)},e.RGBtoHSB=function(e,t,o){var i=Math.min(e,t,o),n=Math.max(e,t,o),r=NaN;if(i!==n){var s=n-i,a=(n-e)/s,l=(n-t)/s,p=(n-o)/s;r=e===n?p-l:t===n?2+a-p:4+l-a,(r/=6)<0&&(r+=1)}return[360*r,0!==n?(n-i)/n:0,n]},e.HSBtoRGB=function(e,t,o){isNaN(e)&&(e=0),e=(e%360+360)%360/360;var i=0,n=0,r=0;if(0===t)i=n=r=o;else{var s=6*(e-Math.floor(e)),a=s-Math.floor(s),l=o*(1-t),p=o*(1-t*a),u=o*(1-t*(1-a));switch(s>>0){case 0:i=o,n=u,r=l;break;case 1:i=p,n=o,r=l;break;case 2:i=l,n=o,r=u;break;case 3:i=l,n=p,r=o;break;case 4:i=u,n=l,r=o;break;case 5:i=o,n=l,r=p}}return[i,n,r]},e.prototype.derive=function(t,o,i,n){var r=e.RGBtoHSB(this.r,this.g,this.b),s=r[2];0==s&&i>1&&(s=.05);var a=((r[0]+t)%360+360)%360,l=Math.max(Math.min(r[1]*o,1),0);s=Math.max(Math.min(s*i,1),0);var p=Math.max(Math.min(this.a*n,1),0),u=e.HSBtoRGB(a,l,s);return u.push(p),e.fromArray(u)},e.prototype.brighter=function(){return this.derive(0,1,1/.7,1)},e.prototype.darker=function(){return this.derive(0,1,.7,1)},e.hexRe=/\s*#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})?\s*$/,e.shortHexRe=/\s*#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])?\s*$/,e.rgbRe=/\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)\s*/,e.rgbaRe=/\s*rgba\((\d+),\s*(\d+),\s*(\d+),\s*([.\d]+)\)\s*/,e.nameToHex=Object.freeze({aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#00FFFF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000000",blanchedalmond:"#FFEBCD",blue:"#0000FF",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#00FFFF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgreen:"#006400",darkgrey:"#A9A9A9",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#FF00FF",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",gray:"#808080",green:"#008000",greenyellow:"#ADFF2F",grey:"#808080",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgreen:"#90EE90",lightgrey:"#D3D3D3",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#00FF00",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#FF00FF",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#663399",red:"#FF0000",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFFFFF",whitesmoke:"#F5F5F5",yellow:"#FFFF00",yellowgreen:"#9ACD32"}),e}(),o=function(){function e(){}return e.STEP_EVERYTHING=0,e.STEP_FILTER=1,e.STEP_SORT=2,e.STEP_MAP=3,e.STEP_AGGREGATE=4,e.STEP_PIVOT=5,e.ROW_BUFFER_SIZE=10,e.LAYOUT_INTERVAL=500,e.BATCH_WAIT_MILLIS=50,e.EXPORT_TYPE_DRAG_COPY="dragCopy",e.EXPORT_TYPE_CLIPBOARD="clipboard",e.EXPORT_TYPE_EXCEL="excel",e.EXPORT_TYPE_CSV="csv",e.KEY_BACKSPACE=8,e.KEY_TAB=9,e.KEY_NEW_LINE=10,e.KEY_ENTER=13,e.KEY_SHIFT=16,e.KEY_ESCAPE=27,e.KEY_SPACE=32,e.KEY_LEFT=37,e.KEY_UP=38,e.KEY_RIGHT=39,e.KEY_DOWN=40,e.KEY_DELETE=46,e.KEY_A=65,e.KEY_C=67,e.KEY_V=86,e.KEY_D=68,e.KEY_F2=113,e.KEY_PAGE_UP=33,e.KEY_PAGE_DOWN=34,e.KEY_PAGE_HOME=36,e.KEY_PAGE_END=35,e.ROW_MODEL_TYPE_INFINITE="infinite",e.ROW_MODEL_TYPE_VIEWPORT="viewport",e.ROW_MODEL_TYPE_CLIENT_SIDE="clientSide",e.ROW_MODEL_TYPE_SERVER_SIDE="serverSide",e.DEPRECATED_ROW_MODEL_TYPE_NORMAL="normal",e.ALWAYS="always",e.ONLY_WHEN_GROUPING="onlyWhenGrouping",e.PINNED_TOP="top",e.PINNED_BOTTOM="bottom",e.DOM_LAYOUT_NORMAL="normal",e.DOM_LAYOUT_PRINT="print",e.DOM_LAYOUT_AUTO_HEIGHT="autoHeight",e.GROUP_AUTO_COLUMN_ID="ag-Grid-AutoColumn",e.SOURCE_PASTE="paste",e.PINNED_RIGHT="right",e.PINNED_LEFT="left",e.SORT_ASC="asc",e.SORT_DESC="desc",e}(),i=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,n=/([^\s,]+)/g,r={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},s=/[&<>"']/g,a=function(){function e(){}var t;return e.doOnce=function(e,t){this.doOnceFlags[t]||(e(),this.doOnceFlags[t]=!0)},e.isLeftClick=function(e){return"buttons"in e?1==e.buttons:1==(e.which||e.button)},e.areEventsNear=function(e,t,o){if(0===o)return!1;var i=Math.abs(e.clientX-t.clientX),n=Math.abs(e.clientY-t.clientY);return Math.max(i,n)<=o},e.jsonEquals=function(e,t){return(e?JSON.stringify(e):null)===(t?JSON.stringify(t):null)},e.shallowCompare=function(e,t){if(this.missing(e)&&this.missing(t))return!0;if(this.missing(e)||this.missing(t))return!1;if(e.length!==t.length)return!1;for(var o=0;o<e.length;o++)if(e[o]!==t[o])return!1;return!0},e.getNameOfClass=function(e){var t=e.toString(),o=/function (.{1,})\(/.exec(t);return o&&o.length>1?o[1]:""},e.getValueUsingField=function(e,t,o){if(t&&e){if(o){for(var i=t.split("."),n=e,r=0;r<i.length;r++)if(n=n[i[r]],this.missing(n))return null;return n}return e[t]}},e.getElementSize=function(e){var t=window.getComputedStyle(e),o=t.height,i=t.width,n=t.paddingTop,r=t.paddingRight,s=t.paddingBottom,a=t.paddingLeft,l=t.marginTop,p=t.marginRight,u=t.marginBottom,c=t.marginLeft,d=t.boxSizing;return{height:parseFloat(o),width:parseFloat(i),paddingTop:parseFloat(n),paddingRight:parseFloat(r),paddingBottom:parseFloat(s),paddingLeft:parseFloat(a),marginTop:parseFloat(l),marginRight:parseFloat(p),marginBottom:parseFloat(u),marginLeft:parseFloat(c),boxSizing:d}},e.getInnerHeight=function(e){var t=this.getElementSize(e);return"border-box"===t.boxSizing?t.height-t.paddingTop-t.paddingBottom:t.height},e.getInnerWidth=function(e){var t=this.getElementSize(e);return"border-box"===t.boxSizing?t.width-t.paddingLeft-t.paddingRight:t.width},e.getAbsoluteHeight=function(e){var t=this.getElementSize(e),o=t.marginBottom+t.marginTop;return Math.ceil(e.offsetHeight+o)},e.getAbsoluteWidth=function(e){var t=this.getElementSize(e),o=t.marginLeft+t.marginRight;return Math.ceil(e.offsetWidth+o)},e.getScrollLeft=function(e,t){var o=e.scrollLeft;return t&&(o=Math.abs(o),this.isBrowserChrome()&&(o=e.scrollWidth-e.clientWidth-o)),o},e.cleanNumber=function(e){return"string"==typeof e&&(e=parseInt(e,10)),e="number"==typeof e?Math.floor(e):null},e.setScrollLeft=function(e,t,o){o&&((this.isBrowserSafari()||this.isBrowserChrome())&&(t=e.scrollWidth-e.clientWidth-t),this.isBrowserFirefox()&&(t*=-1)),e.scrollLeft=t},e.iterateNamedNodeMap=function(e,t){if(e)for(var o=0;o<e.length;o++){var i=e[o];t(i.name,i.value)}},e.iterateObject=function(e,t){e&&!this.missing(e)&&(Array.isArray(e)?e.forEach((function(e,o){return t(""+o,e)})):Object.keys(e).forEach((function(o){return t(o,e[o])})))},e.cloneObject=function(e){for(var t={},o=Object.keys(e),i=0;i<o.length;i++){var n=o[i],r=e[n];t[n]=r}return t},e.copyPropertiesIfPresent=function(e,t){for(var o=this,i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];i.forEach((function(i){return o.copyPropertyIfPresent(e,t,i)}))},e.copyPropertyIfPresent=function(e,t,o,i){var n=this.getProperty(e,o);void 0!==n&&this.setProperty(t,o,i?i(n):n)},e.getAllKeysInObjects=function(e){var t={};return e.forEach((function(e){e&&Object.keys(e).forEach((function(e){return t[e]=null}))})),Object.keys(t)},e.mergeDeep=function(t,o){this.exists(o)&&this.iterateObject(o,(function(o,i){var n=t[o];n!==i&&("object"==typeof n&&"object"==typeof i?e.mergeDeep(n,i):t[o]=i)}))},e.assign=function(e){for(var t=this,o=[],i=1;i<arguments.length;i++)o[i-1]=arguments[i];return o.forEach((function(o){t.exists(o)&&t.iterateObject(o,(function(t,o){e[t]=o}))})),e},e.flatten=function(e){return[].concat.apply([],e)},e.parseYyyyMmDdToDate=function(e,t){try{if(!e)return null;if(-1===e.indexOf(t))return null;var o=e.split(t);return 3!=o.length?null:new Date(Number(o[0]),Number(o[1])-1,Number(o[2]))}catch(e){return null}},e.serializeDateToYyyyMmDd=function(e,t){return e?e.getFullYear()+t+this.padStart(e.getMonth()+1,2)+t+this.padStart(e.getDate(),2):null},e.padStart=function(e,t){for(var o=e+"";o.length<t;)o="0"+o;return o},e.pushAll=function(e,t){this.missing(t)||this.missing(e)||t.forEach((function(t){return e.push(t)}))},e.createArrayOfNumbers=function(e,t){for(var o=[],i=e;i<=t;i++)o.push(i);return o},e.getFunctionParameters=function(e){var t=e.toString().replace(i,""),o=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(n);return null===o?[]:o},e.find=function(e,t,o){if(null==e)return null;if(!Array.isArray(e)){var i=this.values(e);return this.find(i,t,o)}for(var n=e,r=null,s=0;s<n.length;s++){var a=n[s];if("string"==typeof t){if(a[t]===o){r=a;break}}else if(t(a)){r=a;break}}return r},e.toStrings=function(e){return e.map((function(e){return null!=e&&e.toString?e.toString():null}))},e.findIndex=function(e,t){for(var o=0;o<e.length;o++)if(t(e[o],o,e))return o;return-1},e.isNode=function(e){return"function"==typeof Node?e instanceof Node:e&&"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},e.isElement=function(e){return"function"==typeof HTMLElement?e instanceof HTMLElement:e&&"object"==typeof e&&null!==e&&1===e.nodeType&&"string"==typeof e.nodeName},e.isNodeOrElement=function(e){return this.isNode(e)||this.isElement(e)},e.copyNodeList=function(e){for(var t=e?e.length:0,o=[],i=0;i<t;i++)o.push(e[i]);return o},e.isEventFromPrintableCharacter=function(t){var i=String.fromCharCode(t.charCode);if(this.isKeyPressed(t,o.KEY_NEW_LINE))return!1;if(t.altKey||t.ctrlKey)return!1;if(p.exists(t.key)){var n=1===t.key.length,r=e.isNumpadDelWithNumlockOnForEdgeOrIe(t);return n||r}return e.PRINTABLE_CHARACTERS.indexOf(i)>=0},e.isUserSuppressingKeyboardEvent=function(e,t,o,i,n){var r=e.getSuppressKeyboardEventFunc(),s=i.getColDef().suppressKeyboardEvent;if(!r&&!s)return!1;var a={event:t,editing:n,column:i,api:e.getApi(),node:o,data:o.data,colDef:i.getColDef(),context:e.getContext(),columnApi:e.getColumnApi()};if(s&&s(a))return!0;return!!r&&r(a)},e.getCellCompForEvent=function(e,t){for(var o=this.getTarget(t);o;){var i=e.getDomData(o,"cellComp");if(i)return i;o=o.parentElement}return null},e.addChangeListener=function(e,t){e.addEventListener("changed",t),e.addEventListener("paste",t),e.addEventListener("input",t),e.addEventListener("keydown",t),e.addEventListener("keyup",t)},e.makeNull=function(e){return null==e||""===e?null:e},e.missing=function(e){return!this.exists(e)},e.missingOrEmpty=function(e){return!e||this.missing(e)||0===e.length},e.missingOrEmptyObject=function(e){return this.missing(e)||0===Object.keys(e).length},e.exists=function(e,t){return void 0===t&&(t=!1),null!=e&&(""!==e||t)},e.firstExistingValue=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var o=0;o<e.length;o++){var i=e[o];if(p.exists(i))return i}return null},e.anyExists=function(e){if(e)for(var t=0;t<e.length;t++)if(this.exists(e[t]))return!0;return!1},e.existsAndNotEmpty=function(e){return null!=e&&this.exists(e)&&e.length>0},e.clearElement=function(e){for(;e&&e.firstChild;)e.removeChild(e.firstChild)},e.removeElement=function(e,t){this.removeFromParent(e.querySelector(t))},e.removeFromParent=function(e){e&&e.parentNode&&e.parentNode.removeChild(e)},e.isVisible=function(e){return null!==e.offsetParent},e.callIfPresent=function(e){e&&e()},e.loadTemplate=function(e){var t=document.createElement("div");return t.innerHTML=e,t.firstChild},e.appendHtml=function(e,t){e.lastChild?e.insertAdjacentHTML("afterbegin",t):e.innerHTML=t},e.addOrRemoveCssClass=function(e,t,o){o?this.addCssClass(e,t):this.removeCssClass(e,t)},e.radioCssClass=function(e,t,o){for(var i=e.parentElement.firstChild;i;)p.addOrRemoveCssClass(i,t,o?i!==e:i===e),i=i.nextSibling},e.addCssClass=function(e,t){var o=this;if(t&&0!==t.length)if(t.indexOf(" ")>=0)t.split(" ").forEach((function(t){return o.addCssClass(e,t)}));else if(e.classList)e.classList.contains(t)||e.classList.add(t);else if(e.className&&e.className.length>0){var i=e.className.split(" ");i.indexOf(t)<0&&(i.push(t),e.setAttribute("class",i.join(" ")))}else e.setAttribute("class",t)},e.removeCssClass=function(e,t){if(e.classList)e.classList.contains(t)&&e.classList.remove(t);else if(e.className&&e.className.length>0){var o=e.className.split(" ");if(o.indexOf(t)>=0){for(;o.indexOf(t)>=0;)o.splice(o.indexOf(t),1);e.setAttribute("class",o.join(" "))}}},e.containsClass=function(e,t){if(e.classList)return e.classList.contains(t);if(e.className){var o=e.className===t,i=e.className.indexOf(" "+t+" ")>=0,n=0===e.className.indexOf(t+" "),r=e.className.lastIndexOf(" "+t)===e.className.length-t.length-1;return o||i||n||r}return!1},e.getElementAttribute=function(e,t){return e.attributes&&e.attributes[t]?e.attributes[t].value:null},e.offsetHeight=function(e){return e&&e.clientHeight?e.clientHeight:0},e.offsetWidth=function(e){return e&&e.clientWidth?e.clientWidth:0},e.sortNumberArray=function(e){e.sort((function(e,t){return e-t}))},e.removeRepeatsFromArray=function(e,t){if(e)for(var o=e.length-2;o>=0;o--){var i=e[o]===t,n=e[o+1]===t;i&&n&&e.splice(o+1,1)}},e.removeFromArray=function(e,t){var o=e.indexOf(t);o>=0&&e.splice(o,1)},e.removeAllFromArray=function(e,t){t.forEach((function(t){var o=e.indexOf(t);o>=0&&e.splice(o,1)}))},e.insertIntoArray=function(e,t,o){e.splice(o,0,t)},e.insertArrayIntoArray=function(e,t,o){if(!this.missing(e)&&!this.missing(t))for(var i=t.length-1;i>=0;i--){var n=t[i];this.insertIntoArray(e,n,o)}},e.moveInArray=function(e,t,o){var i=this;t.forEach((function(t){i.removeFromArray(e,t)})),t.slice().reverse().forEach((function(t){i.insertIntoArray(e,t,o)}))},e.defaultComparator=function(e,t,o){void 0===o&&(o=!1);var i=null==e,n=null==t;if(e&&e.toNumber&&(e=e.toNumber()),t&&t.toNumber&&(t=t.toNumber()),i&&n)return 0;if(i)return-1;if(n)return 1;if("string"==typeof e){if(!o)return r(e,t);try{return e.localeCompare(t)}catch(o){return r(e,t)}}return e<t?-1:e>t?1:0;function r(e,t){return e>t?1:e<t?-1:0}},e.last=function(e){if(e&&e.length)return e[e.length-1]},e.compareArrays=function(e,t){if(this.missing(e)&&this.missing(t))return!0;if(this.missing(e)||this.missing(t)||!e||!t)return!1;if(e.length!==t.length)return!1;for(var o=0;o<e.length;o++)if(e[o]!==t[o])return!1;return!0},e.ensureDomOrder=function(e,t,o){o&&o.nextSibling===t||(o?o.nextSibling?e.insertBefore(t,o.nextSibling):e.appendChild(t):e.firstChild&&e.firstChild!==t&&e.insertAdjacentElement("afterbegin",t))},e.setDomChildOrder=function(e,t){for(var o=0;o<t.length;o++){var i=t[o],n=e.children[o];n!==i&&e.insertBefore(i,n)}},e.insertTemplateWithDomOrder=function(e,t,o){var i;return o?(o.insertAdjacentHTML("afterend",t),i=o.nextSibling):(e.firstChild?e.insertAdjacentHTML("afterbegin",t):e.innerHTML=t,i=e.firstChild),i},e.every=function(e,t){if(!e||0===e.length)return!0;for(var o=0;o<e.length;o++)if(!t(e[o]))return!1;return!0},e.toStringOrNull=function(e){return this.exists(e)&&e.toString?e.toString():null},e.formatSize=function(e){return"number"==typeof e?e+"px":e},e.formatNumberTwoDecimalPlacesAndCommas=function(e){return"number"!=typeof e?"":(Math.round(100*e)/100).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")},e.findLineByLeastSquares=function(e){var t=e.length;if(t<=1)return e;for(var o=0,i=0,n=0,r=0,s=0,a=0;a<t;a++)o+=a,i+=s=e[a],r+=a*a,n+=a*s;var l=(t*n-o*i)/(t*r-o*o),p=i/t-l*o/t,u=[];for(a=0;a<=t;a++)u.push(a*l+p);return u},e.formatNumberCommas=function(e){return"number"!=typeof e?"":e.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")},e.prependDC=function(e,t){this.exists(e.firstChild)?e.insertBefore(t,e.firstChild):e.appendChild(t)},e.createIcon=function(e,t,o){var i=this.createIconNoSpan(e,t,o);if(i.className.indexOf("ag-icon")>-1)return i;var n=document.createElement("span");return n.appendChild(i),n},e.createIconNoSpan=function(e,t,o,i){var n=null,r=o&&o.getColDef().icons;if(r&&(n=r[e]),t&&!n){var s=t.getIcons();s&&(n=s[e])}if(!n){var a=document.createElement("span"),l=this.iconNameClassMap[e];return l||(i?l=e:(console.warn("ag-Grid: Did not find icon "+e),l="")),a.setAttribute("class","ag-icon ag-icon-"+l),a.setAttribute("unselectable","on"),a}var p=void 0;if("function"==typeof n)p=n();else{if("string"!=typeof n)throw new Error("icon from grid options needs to be a string or a function");p=n}return"string"==typeof p?this.loadTemplate(p):this.isNodeOrElement(p)?p:void console.warn("ag-Grid: iconRenderer should return back a string or a dom object")},e.addStylesToElement=function(e,t){var o=this;t&&Object.keys(t).forEach((function(i){var n=o.hyphenToCamelCase(i);n&&(e.style[n]=t[i])}))},e.isHorizontalScrollShowing=function(e){return e.clientWidth<e.scrollWidth},e.isVerticalScrollShowing=function(e){return e.clientHeight<e.scrollHeight},e.getMaxDivHeight=function(){if(!document.body)return-1;var e=1e6,t=navigator.userAgent.toLowerCase().match(/firefox/)?6e6:1e9,o=this.loadTemplate("<div/>");for(document.body.appendChild(o);;){var i=2*e;if(o.style.height=i+"px",i>t||o.clientHeight!==i)break;e=i}return document.body.removeChild(o),e},e.getScrollbarWidth=function(){var e=document.body,t=document.createElement("div");t.style.width=t.style.height="100px",t.style.opacity="0",t.style.overflow="scroll",t.style.msOverflowStyle="scrollbar",t.style.position="absolute",e.appendChild(t);var o=t.offsetWidth-t.clientWidth;return t.parentNode&&t.parentNode.removeChild(t),o},e.hasOverflowScrolling=function(){var e=["webkit","moz","o","ms"],t=document.createElement("div"),o=!1;document.getElementsByTagName("body")[0].appendChild(t),t.setAttribute("style",e.map((function(e){return"-"+e+"-overflow-scrolling: touch"})).concat("overflow-scrolling: touch").join(";"));var i=window.getComputedStyle(t);if("touch"===i.overflowScrolling&&(o=!0),!o)for(var n=0,r=e;n<r.length;n++)if("touch"===i[r[n]+"OverflowScrolling"]){o=!0;break}return t.parentNode&&t.parentNode.removeChild(t),o},e.isKeyPressed=function(e,t){return(e.which||e.keyCode)===t},e.isCharacterKey=function(e){var t=e.which;return"number"==typeof t&&t?!e.ctrlKey&&!e.metaKey&&!e.altKey&&8!==e.which&&16!==e.which:void 0===t},e.setDisplayed=function(e,t){this.addOrRemoveCssClass(e,"ag-hidden",!t)},e.setVisible=function(e,t){this.addOrRemoveCssClass(e,"ag-invisible",!t)},e.setElementWidth=function(e,t){"flex"===t?(e.style.width=null,e.style.minWidth=null,e.style.maxWidth=null,e.style.flex="1 1 auto"):this.setFixedWidth(e,t)},e.setFixedWidth=function(e,t){t=this.formatSize(t),e.style.width=t,e.style.maxWidth=t,e.style.minWidth=t},e.setElementHeight=function(e,t){"flex"===t?(e.style.height=null,e.style.minHeight=null,e.style.maxHeight=null,e.style.flex="1 1 auto"):this.setFixedHeight(e,t)},e.setFixedHeight=function(e,t){t=this.formatSize(t),e.style.height=t,e.style.maxHeight=t,e.style.minHeight=t},e.isBrowserIE=function(){return void 0===this.isIE&&(this.isIE=/*@cc_on!@*/!!document.documentMode),this.isIE},e.isBrowserEdge=function(){return void 0===this.isEdge&&(this.isEdge=!this.isBrowserIE()&&!!window.StyleMedia),this.isEdge},e.isBrowserSafari=function(){if(void 0===this.isSafari){var e=window;this.isSafari=Object.prototype.toString.call(e.HTMLElement).indexOf("Constructor")>0||!!(t=!e.safari||e.safari.pushNotification)&&"[object SafariRemoteNotification]"===t.toString()}var t;return this.isSafari},e.isBrowserChrome=function(){if(void 0===this.isChrome){var e=window;this.isChrome=!!e.chrome&&(!!e.chrome.webstore||!!e.chrome.runtime)||/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}return this.isChrome},e.isBrowserFirefox=function(){if(void 0===this.isFirefox){var e=window;this.isFirefox=void 0!==e.InstallTrigger}return this.isFirefox},e.isIOSUserAgent=function(){return void 0===this.isIOS&&(this.isIOS=(/iPad|iPhone|iPod/.test(navigator.platform)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)&&!window.MSStream),this.isIOS},e.getTarget=function(e){var t=e;return t.target||t.srcElement},e.isElementChildOfClass=function(e,t,o){for(var i=0;e;){if(this.containsClass(e,t))return!0;if(e=e.parentElement,o&&++i>o)break}return!1},e.isElementInEventPath=function(e,t){return!(!t||!e)&&p.getEventPath(t).indexOf(e)>=0},e.isFunction=function(e){return!!(e&&e.constructor&&e.call&&e.apply)},e.createEventPath=function(e){for(var t=[],o=p.getTarget(e);o;)t.push(o),o=o.parentElement;return t},e.addAgGridEventPath=function(e){e.__agGridEventPath=this.getEventPath(e)},e.getEventPath=function(e){var t=e;return t.deepPath?t.deepPath():t.path?t.path:t.composedPath?t.composedPath():t.__agGridEventPath?t.__agGridEventPath:this.createEventPath(e)},e.forEachSnapshotFirst=function(e,t){e&&e.slice(0).forEach(t)},e.getBodyWidth=function(){return document.body?document.body.clientWidth:window.innerHeight?window.innerWidth:document.documentElement&&document.documentElement.clientWidth?document.documentElement.clientWidth:-1},e.getBodyHeight=function(){return document.body?document.body.clientHeight:window.innerHeight?window.innerHeight:document.documentElement&&document.documentElement.clientHeight?document.documentElement.clientHeight:-1},e.setCheckboxState=function(e,t){"boolean"==typeof t?(e.checked=t,e.indeterminate=!1):e.indeterminate=!0},e.traverseNodesWithKey=function(e,t){var o=[];!function e(i){i.forEach((function(i){if(i.group||i.hasChildren()){o.push(i.key);var n=o.join("|");t(i,n),e(i.childrenAfterGroup),o.pop()}}))}(e)},e.camelCaseToHyphen=function(e){return null==e?null:e.replace(/([A-Z])/g,(function(e){return"-"+e[0].toLowerCase()}))},e.hyphenToCamelCase=function(e){return null==e?null:e.replace(/-([a-z])/g,(function(e){return e[1].toUpperCase()}))},e.capitalise=function(e){return e[0].toUpperCase()+e.substr(1).toLowerCase()},e.cssStyleObjectToMarkup=function(e){var t=this;if(!e)return"";var o=[];return this.iterateObject(e,(function(e,i){var n=t.camelCaseToHyphen(e);o.push(n+": "+i+";")})),o.join(" ")},e.isNumeric=function(e){return""!==e&&(!isNaN(parseFloat(e))&&isFinite(e))},e.escape=function(e){return null!=e&&e.replace?e.replace(s,(function(e){return r[e]})):e},e.normalizeWheel=function(e){var t=0,o=0,i=0,n=0;return"detail"in e&&(o=e.detail),"wheelDelta"in e&&(o=-e.wheelDelta/120),"wheelDeltaY"in e&&(o=-e.wheelDeltaY/120),"wheelDeltaX"in e&&(t=-e.wheelDeltaX/120),"axis"in e&&e.axis===e.HORIZONTAL_AXIS&&(t=o,o=0),i=10*t,n=10*o,"deltaY"in e&&(n=e.deltaY),"deltaX"in e&&(i=e.deltaX),(i||n)&&e.deltaMode&&(1==e.deltaMode?(i*=40,n*=40):(i*=800,n*=800)),i&&!t&&(t=i<1?-1:1),n&&!o&&(o=n<1?-1:1),{spinX:t,spinY:o,pixelX:i,pixelY:n}},e.debounce=function(e,t,o){var i;return void 0===o&&(o=!1),function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var s=this,a=o&&!i;window.clearTimeout(i),i=window.setTimeout((function(){i=null,o||e.apply(s,n)}),t),a&&e.apply(s,n)}},e.stopPropagationForAgGrid=function(e){e.__ag_Grid_Stop_Propagation=!0},e.isStopPropagationForAgGrid=function(e){return!0===e.__ag_Grid_Stop_Propagation},e.executeInAWhile=function(e){this.executeAfter(e,400)},e.executeNextVMTurn=function(e){this.executeAfter(e,0)},e.executeAfter=function(e,t){e.length>0&&window.setTimeout((function(){e.forEach((function(e){return e()}))}),t)},e.referenceCompare=function(e,t){return null==e&&null==t||(null!=e||!t)&&((!e||null!=t)&&e===t)},e.get=function(e,t,o){if(null==e)return o;for(var i=t.split("."),n=e;i.length>1;)if(null==(n=n[i.shift()]))return o;var r=n[i[0]];return null!=r?r:o},e.set=function(e,t,o){if(null!=e){for(var i=t.split("."),n=e;i.length>1;)if(null==(n=n[i.shift()]))return;n[i[0]]=o}},e.addSafePassiveEventListener=function(t,o,i,n){var r=e.PASSIVE_EVENTS.indexOf(i)>=0?{passive:!0}:void 0;e.OUTSIDE_ANGULAR_EVENTS.indexOf(i)>=0?t.addEventListenerOutsideAngular(o,i,n,r):o.addEventListener(i,n,r)},e.camelCaseToHumanText=function(e){if(!e||null==e)return null;return e.replace(/([A-Z])([A-Z])([a-z])|([a-z])([A-Z])/g,"$1$4 $2$3$5").replace("."," ").split(" ").map((function(e){return e.substring(0,1).toUpperCase()+(e.length>1?e.substring(1,e.length):"")})).join(" ")},e.message=function(e){var t=document.createElement("div");t.innerHTML=e;var o=document.querySelector("#__ag__message");if(!o){o=this.loadTemplate('<div id="__ag__message" style="display: inline-block; position: absolute; top: 0px; left: 0px; color: white; background-color: black; z-index: 20; padding: 2px; border: 1px solid darkred; height: 200px; overflow-y: auto;"></div>'),document.body&&document.body.appendChild(o)}o.insertBefore(t,o.children[0])},e.sortRowNodesByOrder=function(e,t){if(e){for(var o=function(e,o){var i=t[e.id],n=t[o.id],r=void 0!==i,s=void 0!==n;return r&&s?i-n:!r&&!s?e.__objectId-o.__objectId:r?1:-1},i=!1,n=0;n<e.length-1;n++)if(o(e[n],e[n+1])>0){i=!0;break}i&&e.sort(o)}},e.fuzzyCheckStrings=function(e,t,o){var i=this,n={},r=e.filter((function(e){return!t.some((function(t){return t===e}))}));return r.length>0&&r.forEach((function(e){return n[e]=i.fuzzySuggestions(e,o)})),n},e.fuzzySuggestions=function(e,t,o,i){var n=i?p.string_weighted_distances:p.string_distances,r=t.map((function(t){return{value:t,relevance:n(e.toLowerCase(),t.toLocaleLowerCase())}}));return r.sort((function(e,t){return t.relevance-e.relevance})),o&&(r=r.filter((function(e){return 0!==e.relevance}))),r.map((function(e){return e.value}))},e.get_bigrams=function(e){var t,o,i,n=e.toLowerCase(),r=new Array(n.length-1);for(t=o=0,i=r.length;o<=i;t=o+=1)r[t]=n.slice(t,t+2);return r},e.string_distances=function(e,t){if(0===e.length&&0===t.length)return 0;var o,i,n=p.get_bigrams(e),r=p.get_bigrams(t),s=n.length+r.length,a=0;for(o=0,i=n.length;o<i;o++){var l,u=n[o],c=void 0;for(c=0,l=r.length;c<l;c++){u===r[c]&&a++}}return a>0?2*a/s:0},e.string_weighted_distances=function(e,t){for(var o=e.replace(/\s/g,""),i=t.replace(/\s/g,""),n=0,r=0,s=0;s<o.length;s++){var a=i.indexOf(o[s]);-1!==a&&(r=a,n+=100*(i.length-r)/i.length,n*=n)}return n},e.isNumpadDelWithNumlockOnForEdgeOrIe=function(t){return!(!e.isBrowserEdge()&&!e.isBrowserIE())&&(t.key===e.NUMPAD_DEL_NUMLOCK_ON_KEY&&t.charCode===e.NUMPAD_DEL_NUMLOCK_ON_CHARCODE)},e.bindCellRendererToHtmlElement=function(e,t){e.then((function(e){var o=e.getGui();null!=o&&("object"==typeof o?t.appendChild(o):t.innerHTML=o)}))},e.PASSIVE_EVENTS=["touchstart","touchend","touchmove","touchcancel"],e.OUTSIDE_ANGULAR_EVENTS=["mouseover","mouseout","mouseenter","mouseleave"],e.PRINTABLE_CHARACTERS="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!\"\xa3$%^&*()_+-=[];'#,./\\|<>?:@~{}",e.NUMPAD_DEL_NUMLOCK_ON_KEY="Del",e.NUMPAD_DEL_NUMLOCK_ON_CHARCODE=46,e.doOnceFlags={},e.supports={},e.isEventSupported=(t={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"},function(o){if("boolean"==typeof e.supports[o])return e.supports[o];var i=document.createElement(t[o]||"div"),n=(o="on"+o)in i;return n||(i.setAttribute(o,"return;"),n="function"==typeof i[o]),i=null,e.supports[o]=n}),e.areEqual=function(e,t){return e.length===t.length&&e.every((function(e,o){return t[o]===e}))},e.keys=function(e){var t=[];return e.forEach((function(e,o){return t.push(o)})),t},e.values=function(e){return Object.keys(e).map((function(t){return e[t]}))},e.includes=function(e,t){return e.indexOf(t)>-1},e.compose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(t){return e.reduce((function(e,t){return t(e)}),t)}},e.decToHex=function(e,t){for(var o="",i=0;i<t;i++)o+=String.fromCharCode(255&e),e>>>=8;return o},e.utf8_encode=function(e){var t=String.fromCharCode;function o(e,o){return t(e>>o&63|128)}function i(e){if(0==(4294967168&e))return t(e);var i="";return 0==(4294965248&e)?i=t(e>>6&31|192):0==(4294901760&e)?(!function(e){if(e>=55296&&e<=57343)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value")}(e),i=t(e>>12&15|224),i+=o(e,6)):0==(4292870144&e)&&(i=t(e>>18&7|240),i+=o(e,12),i+=o(e,6)),i+=t(63&e|128)}for(var n=function(e){for(var t,o,i=[],n=0,r=e.length;n<r;)(t=e.charCodeAt(n++))>=55296&&t<=56319&&n<r?56320==(64512&(o=e.charCodeAt(n++)))?i.push(((1023&t)<<10)+(1023&o)+65536):(i.push(t),n--):i.push(t);return i}(e),r=n.length,s=-1,a="";++s<r;)a+=i(n[s]);return a},e.deepCloneObject=function(e){return JSON.parse(JSON.stringify(e))},e.getProperty=function(e,t){return e[t]},e.setProperty=function(e,t,o){return e[t]=o},e.iconNameClassMap={columnGroupOpened:"expanded",columnGroupClosed:"contracted",columnSelectClosed:"tree-closed",columnSelectOpen:"tree-open",columnSelectIndeterminate:"tree-indeterminate",columnMovePin:"pin",columnMoveAdd:"plus",columnMoveHide:"eye-slash",columnMoveMove:"arrows",columnMoveLeft:"left",columnMoveRight:"right",columnMoveGroup:"group",columnMoveValue:"aggregation",columnMovePivot:"pivot",dropNotAllowed:"not-allowed",groupContracted:"contracted",groupExpanded:"expanded",chart:"chart",close:"cross",cancel:"cancel",check:"tick",checkboxChecked:"checkbox-checked",checkboxUnchecked:"checkbox-unchecked",checkboxIndeterminate:"checkbox-indeterminate",checkboxCheckedReadOnly:"checkbox-checked-readonly",checkboxUncheckedReadOnly:"checkbox-unchecked-readonly",checkboxIndeterminateReadOnly:"checkbox-indeterminate-readonly",first:"first",previous:"previous",next:"next",last:"last",linked:"linked",unlinked:"unlinked",colorPicker:"color-picker",radioButtonOn:"radio-button-on",radioButtonOff:"radio-button-off",groupLoading:"loading",data:"data",menu:"menu",filter:"filter",columns:"columns",maximize:"maximize",minimize:"minimize",menuPin:"pin",menuValue:"aggregation",menuAddRowGroup:"group",menuRemoveRowGroup:"group",clipboardCopy:"copy",clipboardCut:"cut",clipboardPaste:"paste",pivotPanel:"pivot",rowGroupPanel:"group",valuePanel:"aggregation",columnDrag:"grip",rowDrag:"grip",save:"save",smallLeft:"small-left",smallRight:"small-right",smallUp:"small-up",smallDown:"small-down",sortAscending:"asc",sortDescending:"desc",sortUnSort:"none"},e}(),l=function(){function e(e,t){void 0===e&&(e=0),void 0===t&&(t=1),this.nextValue=e,this.step=t}return e.prototype.next=function(){var e=this.nextValue;return this.nextValue+=this.step,e},e.prototype.peek=function(){return this.nextValue},e.prototype.skip=function(e){this.nextValue+=e},e}(),p=a; /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */!function(e){e[e.IN_PROGRESS=0]="IN_PROGRESS",e[e.RESOLVED=1]="RESOLVED"}(e||(e={}));var u=function(){function t(t){this.status=e.IN_PROGRESS,this.resolution=null,this.listOfWaiters=[],t(this.onDone.bind(this),this.onReject.bind(this))}return t.all=function(e){return new t((function(t){var o=[],i=e.length;e.forEach((function(e,n){e.then((function(e){i--,o[n]=e,0==i&&t(o)})),o.push(null)}))}))},t.resolve=function(e){return new t((function(t){return t(e)}))},t.external=function(){var e;return{promise:new t((function(t){e=t})),resolve:function(t){e(t)}}},t.prototype.then=function(t){this.status===e.IN_PROGRESS?this.listOfWaiters.push(t):t(this.resolution)},t.prototype.firstOneOnly=function(t){this.status===e.IN_PROGRESS?0===this.listOfWaiters.length&&this.listOfWaiters.push(t):t(this.resolution)},t.prototype.map=function(e){var o=this;return new t((function(t){o.then((function(o){t(e(o))}))}))},t.prototype.resolveNow=function(t,o){return this.status==e.IN_PROGRESS?t:o(this.resolution)},t.prototype.onDone=function(t){this.status=e.RESOLVED,this.resolution=t,this.listOfWaiters.forEach((function(e){return e(t)}))},t.prototype.onReject=function(e){console.warn("TBI")},t}(),c=function(){function e(){this.existingKeys={}}return e.prototype.addExistingKeys=function(e){for(var t=0;t<e.length;t++)this.existingKeys[e[t]]=!0},e.prototype.getUniqueKey=function(e,t){e=p.toStringOrNull(e);for(var o=0;;){var i=void 0;if(e?(i=e,0!==o&&(i+="_"+o)):t?(i=t,0!==o&&(i+="_"+o)):i=""+o,!this.existingKeys[i])return this.existingKeys[i]=!0,i;o++}},e}(),d=function(){function e(e,t){if(this.beanWrappers={},this.componentsMappedByName={},this.destroyed=!1,e&&e.beanClasses){this.contextParams=e,this.logger=t,this.logger.log(">> creating ag-Application Context"),this.setupComponents(),this.createBeans();var o=this.getBeanInstances();this.wireBeans(o),this.logger.log(">> ag-Application Context ready - component is alive")}}return e.prototype.getBeanInstances=function(){return p.values(this.beanWrappers).map((function(e){return e.beanInstance}))},e.prototype.setupComponents=function(){var e=this;this.contextParams.components&&this.contextParams.components.forEach((function(t){return e.addComponent(t)}))},e.prototype.addComponent=function(e){var t=e.componentName.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase().toUpperCase();this.componentsMappedByName[t]=e.componentClass},e.prototype.createComponentFromElement=function(e,t){var o=e.nodeName;return this.createComponent(o,t)},e.prototype.createComponent=function(e,t){if(this.componentsMappedByName&&this.componentsMappedByName[e]){var o=new this.componentsMappedByName[e];return this.wireBean(o,t),o}return null},e.prototype.wireBean=function(e,t){if(!e)throw Error("Can't wire to bean since it is null");this.wireBeans([e],t)},e.prototype.wireBeans=function(e,t){this.autoWireBeans(e),this.methodWireBeans(e),this.callLifeCycleMethods(e,"preConstructMethods"),p.exists(t)&&e.forEach(t),this.callLifeCycleMethods(e,"postConstructMethods")},e.prototype.createBeans=function(){var e=this;this.contextParams.beanClasses.forEach(this.createBeanWrapper.bind(this)),p.iterateObject(this.beanWrappers,(function(t,o){var i;o.bean.__agBeanMetaData&&o.bean.__agBeanMetaData.autowireMethods&&o.bean.__agBeanMetaData.autowireMethods.agConstructor&&(i=o.bean.__agBeanMetaData.autowireMethods.agConstructor);var n,r,s=e.getBeansForParameters(i,o.bean.name),a=(n=o.bean,r=[null].concat(s),new(n.bind.apply(n,r)));o.beanInstance=a}));var t=Object.keys(this.beanWrappers).join(", ");this.logger.log("created beans: "+t)},e.prototype.createBeanWrapper=function(e){var t=e.__agBeanMetaData;if(!t){var o=void 0;return o=e.prototype.constructor?e.prototype.constructor.name:""+e,void console.error("context item "+o+" is not a bean")}var i={bean:e,beanInstance:null,beanName:t.beanName};this.beanWrappers[t.beanName]=i},e.prototype.autoWireBeans=function(e){var t=this;e.forEach((function(e){t.forEachMetaDataInHierarchy(e,(function(o,i){var n=o.agClassAttributes;n&&n.forEach((function(o){var n=t.lookupBeanInstance(i,o.beanName,o.optional);e[o.attributeName]=n}))}))}))},e.prototype.methodWireBeans=function(e){var t=this;e.forEach((function(e){t.forEachMetaDataInHierarchy(e,(function(o,i){p.iterateObject(o.autowireMethods,(function(o,n){if("agConstructor"!==o){var r=t.getBeansForParameters(n,i);e[o].apply(e,r)}}))}))}))},e.prototype.forEachMetaDataInHierarchy=function(e,t){for(var o=Object.getPrototypeOf(e);null!=o;){var i=o.constructor;if(i.hasOwnProperty("__agBeanMetaData"))t(i.__agBeanMetaData,this.getBeanName(i));o=Object.getPrototypeOf(o)}},e.prototype.getBeanName=function(e){if(e.__agBeanMetaData&&e.__agBeanMetaData.beanName)return e.__agBeanMetaData.beanName;var t=e.toString();return t.substring(9,t.indexOf("("))},e.prototype.getBeansForParameters=function(e,t){var o=this,i=[];return e&&p.iterateObject(e,(function(e,n){var r=o.lookupBeanInstance(t,n);i[Number(e)]=r})),i},e.prototype.lookupBeanInstance=function(e,t,o){if(void 0===o&&(o=!1),"context"===t)return this;if(this.contextParams.providedBeanInstances&&this.contextParams.providedBeanInstances.hasOwnProperty(t))return this.contextParams.providedBeanInstances[t];var i=this.beanWrappers[t];return i?i.beanInstance:(o||console.error("ag-Grid: unable to find bean reference "+t+" while initialising "+e),null)},e.prototype.callLifeCycleMethods=function(e,t){var o=this;e.forEach((function(e){o.forEachMetaDataInHierarchy(e,(function(o){var i=o[t];i&&i.forEach((function(t){return e[t]()}))}))}))},e.prototype.getBean=function(e){return this.lookupBeanInstance("getBean",e,!0)},e.prototype.destroy=function(){if(!this.destroyed){this.logger.log(">> Shutting down ag-Application Context");var e=this.getBeanInstances();this.callLifeCycleMethods(e,"preDestroyMethods"),this.contextParams.providedBeanInstances=null,this.destroyed=!0,this.logger.log(">> ag-Application Context shut down - component is dead")}},e}(); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */function h(e,t,o){var i=w(e.constructor);i.postConstructMethods||(i.preConstructMethods=[]),i.preConstructMethods.push(t)}function g(e,t,o){var i=w(e.constructor);i.postConstructMethods||(i.postConstructMethods=[]),i.postConstructMethods.push(t)}function f(e,t,o){var i=w(e.constructor);i.preDestroyMethods||(i.preDestroyMethods=[]),i.preDestroyMethods.push(t)}function y(e){return function(t){w(t).beanName=e}}function m(e){return function(t,o,i){C(t,e,!1,t,o,null)}}function v(e){return function(t,o,i){C(t,e,!0,t,o,null)}}function C(e,t,o,i,n,r){if(null!==t)if("number"!=typeof r){var s=w(e.constructor);s.agClassAttributes||(s.agClassAttributes=[]),s.agClassAttributes.push({attributeName:n,beanName:t,optional:o})}else console.error("ag-Grid: Autowired should be on an attribute");else console.error("ag-Grid: Autowired name should not be null")}function E(e){return function(t,o,i){var n,r="function"==typeof t?t:t.constructor;if("number"==typeof i){var s=void 0;o?(n=w(r),s=o):(n=w(r),s="agConstructor"),n.autowireMethods||(n.autowireMethods={}),n.autowireMethods[s]||(n.autowireMethods[s]={}),n.autowireMethods[s][i]=e}}}function w(e){return e.hasOwnProperty("__agBeanMetaData")||(e.__agBeanMetaData={}),e.__agBeanMetaData} /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */var R,O=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},D=function(e,t){return function(o,i){t(o,i,e)}},b=function(){function e(){this.allSyncListeners={},this.allAsyncListeners={},this.globalSyncListeners=[],this.globalAsyncListeners=[],this.asyncFunctionsQueue=[],this.scheduled=!1,this.firedEvents={}}var t;return t=e,e.prototype.setBeans=function(e,t,o){if(void 0===o&&(o=null),this.logger=e.create("EventService"),o){var i=t.useAsyncEvents();this.addGlobalListener(o,i)}},e.prototype.getListenerList=function(e,t){var o=t?this.allAsyncListeners:this.allSyncListeners,i=o[e];return i||(i=[],o[e]=i),i},e.prototype.addEventListener=function(e,t,o){void 0===o&&(o=!1);var i=this.getListenerList(e,o);i.indexOf(t)<0&&i.push(t)},e.prototype.addModalPriorityEventListener=function(e,o,i){void 0===i&&(i=!1),this.addEventListener(e+t.PRIORITY,o,i)},e.prototype.addGlobalListener=function(e,t){void 0===t&&(t=!1),t?this.globalAsyncListeners.push(e):this.globalSyncListeners.push(e)},e.prototype.removeEventListener=function(e,t,o){void 0===o&&(o=!1);var i=this.getListenerList(e,o);p.removeFromArray(i,t)},e.prototype.removeGlobalListener=function(e,t){void 0===t&&(t=!1),t?p.removeFromArray(this.globalAsyncListeners,e):p.removeFromArray(this.globalSyncListeners,e)},e.prototype.dispatchEvent=function(e){this.dispatchToListeners(e,!0),this.dispatchToListeners(e,!1),this.firedEvents[e.type]=!0},e.prototype.dispatchEventOnce=function(e){this.firedEvents[e.type]||this.dispatchEvent(e)},e.prototype.dispatchToListeners=function(e,o){var i=this,n=o?this.globalAsyncListeners:this.globalSyncListeners,r=e.type,s=this.getListenerList(r+t.PRIORITY,o);p.forEachSnapshotFirst(s,(function(t){o?i.dispatchAsync((function(){return t(e)})):t(e)}));var a=this.getListenerList(r,o);p.forEachSnapshotFirst(a,(function(t){o?i.dispatchAsync((function(){return t(e)})):t(e)})),p.forEachSnapshotFirst(n,(function(t){o?i.dispatchAsync((function(){return t(r,e)})):t(r,e)}))},e.prototype.dispatchAsync=function(e){this.asyncFunctionsQueue.push(e),this.scheduled||(window.setTimeout(this.flushAsyncQueue.bind(this),0),this.scheduled=!0)},e.prototype.flushAsyncQueue=function(){this.scheduled=!1;var e=this.asyncFunctionsQueue.slice();this.asyncFunctionsQueue=[],e.forEach((function(e){return e()}))},e.PRIORITY="-P1",O([D(0,E("loggerFactory")),D(1,E("gridOptionsWrapper")),D(2,E("globalEventListener"))],e.prototype,"setBeans",null),e=t=O([y("eventService")],e)}();!function(e){e.CommunityCoreModule="@ag-grid-community/core",e.CommunityAllModules="@ag-grid-community/all",e.InfiniteRowModelModule="@ag-grid-community/infinite-row-model",e.ClientSideRowModelModule="@ag-grid-community/client-side-row-model",e.CsvExportModule="@ag-grid-community/csv-export",e.RowNodeCache="@ag-grid-community/row-node-cache",e.EnterpriseCoreModule="@ag-grid-enterprise/core",e.EnterpriseAllModules="@ag-grid-enterprise/all",e.RowGroupingModule="@ag-grid-enterprise/row-grouping",e.ColumnToolPanelModule="@ag-grid-enterprise/column-tool-panel",e.FiltersToolPanelModule="@ag-grid-enterprise/filters-tool-panel",e.MenuModule="@ag-grid-enterprise/menu",e.SetFilterModule="@ag-grid-enterprise/set-filter",e.StatusBarModule="@ag-grid-enterprise/status-bar",e.SideBarModule="@ag-grid-enterprise/side-bar",e.RangeSelectionModule="@ag-grid-enterprise/range-selection",e.MasterDetailModule="@ag-grid-enterprise/master-detail",e.RichSelectModule="@ag-grid-enterprise/rich-select",e.GridChartsModule="@ag-grid-enterprise/charts",e.ViewportRowModelModule="@ag-grid-enterprise/viewport-row-model",e.ServerSideRowModelModule="@ag-grid-enterprise/server-side-row-model",e.ExcelExportModule="@ag-grid-enterprise/excel-export",e.ClipboardModule="@ag-grid-enterprise/clipboard",e.AngularModule="@ag-grid-community/angular",e.ReactModule="@ag-grid-community/react",e.VueModule="@ag-grid-community/vue",e.PolymerModule="@ag-grid-community/polymer"}(R||(R={})); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */ var P=function(){function e(){}return e.register=function(e){this.modulesMap[e.moduleName]=e},e.assertRegistered=function(e,t){if(this.isRegistered(e))return!0;var o=t+e,i="ag-Grid: unable to use "+t+" as module "+e+' is not present. You need to load the module with: import "'+e+'"';return p.doOnce((function(){console.warn(i)}),o),!1},e.isRegistered=function(e){return!!this.modulesMap[e]},e.getRegisteredModules=function(){return p.values(this.modulesMap)},e.modulesMap={},e}(),S=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},T=function(){function e(e,t,o,i){this.moving=!1,this.menuVisible=!1,this.filterActive=!1,this.eventService=new b,this.rowGroupActive=!1,this.pivotActive=!1,this.aggregationActive=!1,this.colDef=e,this.userProvidedColDef=t,this.visible=!e.hide,this.sort=e.sort,this.sortedAt=e.sortedAt,this.colId=o,this.primary=i}return e.prototype.setColDef=function(e,t){this.colDef=e,this.userProvidedColDef=t},e.prototype.getUserProvidedColDef=function(){return this.userProvidedColDef},e.prototype.setParent=function(e){this.parent=e},e.prototype.getParent=function(){return this.parent},e.prototype.setOriginalParent=function(e){this.originalParent=e},e.prototype.getOriginalParent=function(){return this.originalParent},e.prototype.initialise=function(){this.setPinned(this.colDef.pinned);var e=this.gridOptionsWrapper.getMinColWidth(),t=this.gridOptionsWrapper.getMaxColWidth();this.colDef.minWidth?this.minWidth=this.colDef.minWidth:this.minWidth=e,this.colDef.maxWidth?this.maxWidth=this.colDef.maxWidth:this.maxWidth=t,this.actualWidth=this.columnUtils.calculateColInitialWidth(this.colDef);var o=this.gridOptionsWrapper.isSuppressFieldDotNotation();this.fieldContainsDots=p.exists(this.colDef.field)&&this.colDef.field.indexOf(".")>=0&&!o,this.tooltipFieldContainsDots=p.exists(this.colDef.tooltipField)&&this.colDef.tooltipField.indexOf(".")>=0&&!o,this.validate()},e.prototype.isEmptyGroup=function(){return!1},e.prototype.isRowGroupDisplayed=function(e){if(p.missing(this.colDef)||p.missing(this.colDef.showRowGroup))return!1;var t=!0===this.colDef.showRowGroup,o=this.colDef.showRowGroup===e;return t||o},e.prototype.getUniqueId=function(){return this.getId()},e.prototype.isPrimary=function(){return this.primary},e.prototype.isFilterAllowed=function(){var e=!!this.colDef.filter||!!this.colDef.filterFramework;return this.primary&&e},e.prototype.isFieldContainsDots=function(){return this.fieldContainsDots},e.prototype.isTooltipFieldContainsDots=function(){return this.tooltipFieldContainsDots},e.prototype.validate=function(){var e=this.colDef;function t(e,t,o){p.doOnce((function(){o?console.warn(e,o):p.doOnce((function(){return console.warn(e)}),t)}),t)}if(!P.isRegistered(R.RowGroupingModule)){["enableRowGroup","rowGroup","rowGroupIndex","enablePivot","enableValue","pivot","pivotIndex","aggFunc"].forEach((function(o){p.exists(e[o])&&t("ag-Grid: "+o+" is only valid with module Row Grouping, your column definition should not have "+o,"ColumnRowGroupingMissing"+o)}))}if(P.isRegistered(R.RichSelectModule)||"agRichSelect"!==this.colDef.cellEditor&&"agRichSelectCellEditor"!==this.colDef.cellEditor||t("ag-Grid: "+this.colDef.cellEditor+" can only be used with module "+R.RichSelectModule,"ColumnRichSelectMissing"),this.gridOptionsWrapper.isTreeData()){["rowGroup","rowGroupIndex","pivot","pivotIndex"].forEach((function(o){p.exists(e[o])&&t("ag-Grid: "+o+" is not possible when doing tree data, your column definition should not have "+o,"TreeDataCannotRowGroup")}))}p.exists(this.colDef.width)&&"number"!=typeof this.colDef.width&&t("ag-Grid: colDef.width should be a number, not "+typeof this.colDef.width,"ColumnCheck_asdfawef"),p.get(this,"colDef.cellRendererParams.restrictToOneGroup",null)&&t("ag-Grid: Since ag-grid 11.0.0 cellRendererParams.restrictToOneGroup is deprecated. You should use showRowGroup","ColumnCheck_sksldjf"),p.get(this,"colDef.cellRendererParams.keyMap",null)&&t("ag-Grid: Since ag-grid 11.0.0 cellRendererParams.keyMap is deprecated. You should use colDef.keyCreator","ColumnCheck_ieiruhgdf"),p.get(this,"colDef.cellRendererParams.keyMap",null)&&t("ag-Grid: Since ag-grid 11.0.0 cellRendererParams.keyMap is deprecated. You should use colDef.keyCreator","ColumnCheck_uitolghj"),e.floatingCellRenderer&&(t("ag-Grid: since v11, floatingCellRenderer is now pinnedRowCellRenderer","ColumnCheck_soihwewe"),this.colDef.pinnedRowCellRenderer=e.floatingCellRenderer),e.floatingRendererFramework&&(t("ag-Grid: since v11, floatingRendererFramework is now pinnedRowCellRendererFramework","ColumnCheck_zdkiouhwer"),this.colDef.pinnedRowCellRendererFramework=e.floatingRendererFramework),e.floatingRendererParams&&(console.warn("ag-Grid: since v11, floatingRendererParams is now pinnedRowCellRendererParams","ColumnCheck_retiuhjs"),this.colDef.pinnedRowCellRendererParams=e.floatingRendererParams),e.floatingValueFormatter&&(t("ag-Grid: since v11, floatingValueFormatter is now pinnedRowValueFormatter","ColumnCheck_qwroeihjdf"),this.colDef.pinnedRowValueFormatter=e.floatingValueFormatter),e.cellFormatter&&(t("ag-Grid: since v12, cellFormatter is now valueFormatter","ColumnCheck_eoireknml"),p.missing(this.colDef.valueFormatter)&&(this.colDef.valueFormatter=e.cellFormatter)),e.headerCellTemplate&&t("ag-Grid: since v15, headerCellTemplate is gone, use header component instead.","ColumnCheck_eroihxcm"),e.headerCellRenderer&&t("ag-Grid: since v15, headerCellRenderer is gone, use header component instead.","ColumnCheck_terteuh"),e.volatile&&t("ag-Grid: since v16, colDef.volatile is gone, please check refresh docs on how to refresh specific cells.","ColumnCheck_weoihjxcv"),e.suppressSorting&&(t("ag-Grid: since v20, colDef.suppressSorting is gone, instead use colDef.sortable=false.","ColumnCheck_43ljrer",this.colDef),this.colDef.sortable=!1),e.suppressFilter&&(t("ag-Grid: since v20, colDef.suppressFilter is gone, instead use colDef.filter=false.","ColumnCheck_erlkhfdm",this.colDef),this.colDef.filter=!1),e.suppressResize&&(t("ag-Grid: since v20, colDef.suppressResize is gone, instead use colDef.resizable=false.","ColumnCheck_weoihjxcv",this.colDef),this.colDef.resizable=!1),e.tooltip&&(t("ag-Grid: since v20.1, colDef.tooltip is gone, instead use colDef.tooltipValueGetter.","ColumnCheck_adslknjwef",this.colDef),this.colDef.tooltipValueGetter=e.tooltip),e.suppressToolPanel&&(t("ag-Grid: since v22, colDef.suppressToolPanel is gone, instead use suppressColumnsToolPanel / suppressFiltersToolPanel.","ColumnCheck_weihjlsjkdf",this.colDef),this.colDef.suppressColumnsToolPanel=!0)},e.prototype.addEventListener=function(e,t){this.eventService.addEventListener(e,t)},e.prototype.removeEventListener=function(e,t){this.eventService.removeEventListener(e,t)},e.prototype.createIsColumnFuncParams=function(e){return{node:e,data:e.data,column:this,colDef:this.colDef,context:this.gridOptionsWrapper.getContext(),api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi()}},e.prototype.isSuppressNavigable=function(e){if("boolean"==typeof this.colDef.suppressNavigable)return this.colDef.suppressNavigable;if("function"==typeof this.colDef.suppressNavigable){var t=this.createIsColumnFuncParams(e);return(0,this.colDef.suppressNavigable)(t)}return!1},e.prototype.isCellEditable=function(e){return!(e.group&&!this.gridOptionsWrapper.isEnableGroupEdit())&&this.isColumnFunc(e,this.colDef.editable)},e.prototype.isRowDrag=function(e){return this.isColumnFunc(e,this.colDef.rowDrag)},e.prototype.isDndSource=function(e){return this.isColumnFunc(e,this.colDef.dndSource)},e.prototype.isCellCheckboxSelection=function(e){return this.isColumnFunc(e,this.colDef.checkboxSelection)},e.prototype.isSuppressPaste=function(e){return this.isColumnFunc(e,this.colDef?this.colDef.suppressPaste:null)},e.prototype.isResizable=function(){return!0===this.colDef.resizable},e.prototype.isColumnFunc=function(e,t){return"boolean"==typeof t?t:"function"==typeof t&&t(this.createIsColumnFuncParams(e))},e.prototype.setMoving=function(t,o){void 0===o&&(o="api"),this.moving=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_MOVING_CHANGED,o))},e.prototype.createColumnEvent=function(e,t){return{api:this.gridApi,columnApi:this.columnApi,type:e,column:this,columns:[this],source:t}},e.prototype.isMoving=function(){return this.moving},e.prototype.getSort=function(){return this.sort},e.prototype.setSort=function(t,o){void 0===o&&(o="api"),this.sort!==t&&(this.sort=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_SORT_CHANGED,o)))},e.prototype.setMenuVisible=function(t,o){void 0===o&&(o="api"),this.menuVisible!==t&&(this.menuVisible=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_MENU_VISIBLE_CHANGED,o)))},e.prototype.isMenuVisible=function(){return this.menuVisible},e.prototype.isSortAscending=function(){return this.sort===o.SORT_ASC},e.prototype.isSortDescending=function(){return this.sort===o.SORT_DESC},e.prototype.isSortNone=function(){return p.missing(this.sort)},e.prototype.isSorting=function(){return p.exists(this.sort)},e.prototype.getSortedAt=function(){return this.sortedAt},e.prototype.setSortedAt=function(e){this.sortedAt=e},e.prototype.setAggFunc=function(e){this.aggFunc=e},e.prototype.getAggFunc=function(){return this.aggFunc},e.prototype.getLeft=function(){return this.left},e.prototype.getOldLeft=function(){return this.oldLeft},e.prototype.getRight=function(){return this.left+this.actualWidth},e.prototype.setLeft=function(t,o){void 0===o&&(o="api"),this.oldLeft=this.left,this.left!==t&&(this.left=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_LEFT_CHANGED,o)))},e.prototype.isFilterActive=function(){return this.filterActive},e.prototype.setFilterActive=function(t,o,i){void 0===o&&(o="api"),this.filterActive!==t&&(this.filterActive=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_FILTER_ACTIVE_CHANGED,o)));var n=this.createColumnEvent(e.EVENT_FILTER_CHANGED,o);i&&p.mergeDeep(n,i),this.eventService.dispatchEvent(n)},e.prototype.setPinned=function(e){!0===e||e===o.PINNED_LEFT?this.pinned=o.PINNED_LEFT:e===o.PINNED_RIGHT?this.pinned=o.PINNED_RIGHT:this.pinned=null},e.prototype.setFirstRightPinned=function(t,o){void 0===o&&(o="api"),this.firstRightPinned!==t&&(this.firstRightPinned=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_FIRST_RIGHT_PINNED_CHANGED,o)))},e.prototype.setLastLeftPinned=function(t,o){void 0===o&&(o="api"),this.lastLeftPinned!==t&&(this.lastLeftPinned=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_LAST_LEFT_PINNED_CHANGED,o)))},e.prototype.isFirstRightPinned=function(){return this.firstRightPinned},e.prototype.isLastLeftPinned=function(){return this.lastLeftPinned},e.prototype.isPinned=function(){return this.pinned===o.PINNED_LEFT||this.pinned===o.PINNED_RIGHT},e.prototype.isPinnedLeft=function(){return this.pinned===o.PINNED_LEFT},e.prototype.isPinnedRight=function(){return this.pinned===o.PINNED_RIGHT},e.prototype.getPinned=function(){return this.pinned},e.prototype.setVisible=function(t,o){void 0===o&&(o="api");var i=!0===t;this.visible!==i&&(this.visible=i,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_VISIBLE_CHANGED,o)))},e.prototype.isVisible=function(){return this.visible},e.prototype.getColDef=function(){return this.colDef},e.prototype.getColumnGroupShow=function(){return this.colDef.columnGroupShow},e.prototype.getColId=function(){return this.colId},e.prototype.getId=function(){return this.getColId()},e.prototype.getDefinition=function(){return this.colDef},e.prototype.getActualWidth=function(){return this.actualWidth},e.prototype.createBaseColDefParams=function(e){return{node:e,data:e.data,colDef:this.colDef,column:this,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext()}},e.prototype.getColSpan=function(e){if(p.missing(this.colDef.colSpan))return 1;var t=this.createBaseColDefParams(e),o=this.colDef.colSpan(t);return Math.max(o,1)},e.prototype.getRowSpan=function(e){if(p.missing(this.colDef.rowSpan))return 1;var t=this.createBaseColDefParams(e),o=this.colDef.rowSpan(t);return Math.max(o,1)},e.prototype.setActualWidth=function(t,o){void 0===o&&(o="api"),this.actualWidth!==t&&(this.actualWidth=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_WIDTH_CHANGED,o)))},e.prototype.isGreaterThanMax=function(e){return!!this.maxWidth&&e>this.maxWidth},e.prototype.getMinWidth=function(){return this.minWidth},e.prototype.getMaxWidth=function(){return this.maxWidth},e.prototype.setMinimum=function(e){void 0===e&&(e="api"),this.setActualWidth(this.minWidth,e)},e.prototype.setRowGroupActive=function(t,o){void 0===o&&(o="api"),this.rowGroupActive!==t&&(this.rowGroupActive=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_ROW_GROUP_CHANGED,o)))},e.prototype.isRowGroupActive=function(){return this.rowGroupActive},e.prototype.setPivotActive=function(t,o){void 0===o&&(o="api"),this.pivotActive!==t&&(this.pivotActive=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_PIVOT_CHANGED,o)))},e.prototype.isPivotActive=function(){return this.pivotActive},e.prototype.isAnyFunctionActive=function(){return this.isPivotActive()||this.isRowGroupActive()||this.isValueActive()},e.prototype.isAnyFunctionAllowed=function(){return this.isAllowPivot()||this.isAllowRowGroup()||this.isAllowValue()},e.prototype.setValueActive=function(t,o){void 0===o&&(o="api"),this.aggregationActive!==t&&(this.aggregationActive=t,this.eventService.dispatchEvent(this.createColumnEvent(e.EVENT_VALUE_CHANGED,o)))},e.prototype.isValueActive=function(){return this.aggregationActive},e.prototype.isAllowPivot=function(){return!0===this.colDef.enablePivot},e.prototype.isAllowValue=function(){return!0===this.colDef.enableValue},e.prototype.isAllowRowGroup=function(){return!0===this.colDef.enableRowGroup},e.prototype.getMenuTabs=function(e){var t=this.getColDef().menuTabs;return null==t&&(t=e),t},e.prototype.isLockPosition=function(){return console.warn("ag-Grid: since v21, col.isLockPosition() should not be used, please use col.getColDef().lockPosition instead."),!!this.colDef&&!!this.colDef.lockPosition},e.prototype.isLockVisible=function(){return console.warn("ag-Grid: since v21, col.isLockVisible() should not be used, please use col.getColDef().lockVisible instead."),!!this.colDef&&!!this.colDef.lockVisible},e.prototype.isLockPinned=function(){return console.warn("ag-Grid: since v21, col.isLockPinned() should not be used, please use col.getColDef().lockPinned instead."),!!this.colDef&&!!this.colDef.lockPinned},e.EVENT_MOVING_CHANGED="movingChanged",e.EVENT_LEFT_CHANGED="leftChanged",e.EVENT_WIDTH_CHANGED="widthChanged",e.EVENT_LAST_LEFT_PINNED_CHANGED="lastLeftPinnedChanged",e.EVENT_FIRST_RIGHT_PINNED_CHANGED="firstRightPinnedChanged",e.EVENT_VISIBLE_CHANGED="visibleChanged",e.EVENT_FILTER_CHANGED="filterChanged",e.EVENT_FILTER_ACTIVE_CHANGED="filterActiveChanged",e.EVENT_SORT_CHANGED="sortChanged",e.EVENT_MENU_VISIBLE_CHANGED="menuVisibleChanged",e.EVENT_ROW_GROUP_CHANGED="columnRowGroupChanged",e.EVENT_PIVOT_CHANGED="columnPivotChanged",e.EVENT_VALUE_CHANGED="columnValueChanged",S([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),S([m("columnUtils")],e.prototype,"columnUtils",void 0),S([m("columnApi")],e.prototype,"columnApi",void 0),S([m("gridApi")],e.prototype,"gridApi",void 0),S([m("context")],e.prototype,"context",void 0),S([g],e.prototype,"initialise",null),e}(),A=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},_=function(){function e(e,t,o,i){this.displayedChildren=[],this.localEventService=new b,this.groupId=t,this.instanceId=o,this.originalColumnGroup=e,this.pinned=i}return e.createUniqueId=function(e,t){return e+"_"+t},e.prototype.reset=function(){this.parent=null,this.children=null,this.displayedChildren=null},e.prototype.getParent=function(){return this.parent},e.prototype.setParent=function(e){this.parent=e},e.prototype.getUniqueId=function(){return e.createUniqueId(this.groupId,this.instanceId)},e.prototype.isEmptyGroup=function(){return 0===this.displayedChildren.length},e.prototype.isMoving=function(){var e=this.getOriginalColumnGroup().getLeafColumns();if(!e||0===e.length)return!1;var t=!0;return e.forEach((function(e){e.isMoving()||(t=!1)})),t},e.prototype.checkLeft=function(){if(this.displayedChildren.forEach((function(t){t instanceof e&&t.checkLeft()})),this.displayedChildren.length>0)if(this.gridOptionsWrapper.isEnableRtl()){var t=p.last(this.displayedChildren).getLeft();this.setLeft(t)}else{var o=this.displayedChildren[0].getLeft();this.setLeft(o)}else this.setLeft(null)},e.prototype.getLeft=function(){return this.left},e.prototype.getOldLeft=function(){return this.oldLeft},e.prototype.setLeft=function(t){this.oldLeft=t,this.left!==t&&(this.left=t,this.localEventService.dispatchEvent(this.createAgEvent(e.EVENT_LEFT_CHANGED)))},e.prototype.getPinned=function(){return this.pinned},e.prototype.createAgEvent=function(e){return{type:e}},e.prototype.addEventListener=function(e,t){this.localEventService.addEventListener(e,t)},e.prototype.removeEventListener=function(e,t){this.localEventService.removeEventListener(e,t)},e.prototype.getGroupId=function(){return this.groupId},e.prototype.getInstanceId=function(){return this.instanceId},e.prototype.isChildInThisGroupDeepSearch=function(t){var o=!1;return this.children.forEach((function(i){t===i&&(o=!0),i instanceof e&&i.isChildInThisGroupDeepSearch(t)&&(o=!0)})),o},e.prototype.getActualWidth=function(){var e=0;return this.displayedChildren&&this.displayedChildren.forEach((function(t){e+=t.getActualWidth()})),e},e.prototype.isResizable=function(){if(!this.displayedChildren)return!1;var e=!1;return this.displayedChildren.forEach((function(t){t.isResizable()&&(e=!0)})),e},e.prototype.getMinWidth=function(){var e=0;return this.displayedChildren.forEach((function(t){e+=t.getMinWidth()})),e},e.prototype.addChild=function(e){this.children||(this.children=[]),this.children.push(e)},e.prototype.getDisplayedChildren=function(){return this.displayedChildren},e.prototype.getLeafColumns=function(){var e=[];return this.addLeafColumns(e),e},e.prototype.getDisplayedLeafColumns=function(){var e=[];return this.addDisplayedLeafColumns(e),e},e.prototype.getDefinition=function(){return this.originalColumnGroup.getColGroupDef()},e.prototype.getColGroupDef=function(){return this.originalColumnGroup.getColGroupDef()},e.prototype.isPadding=function(){return this.originalColumnGroup.isPadding()},e.prototype.isExpandable=function(){return this.originalColumnGroup.isExpandable()},e.prototype.isExpanded=function(){return this.originalColumnGroup.isExpanded()},e.prototype.setExpanded=function(e){this.originalColumnGroup.setExpanded(e)},e.prototype.addDisplayedLeafColumns=function(t){this.displayedChildren.forEach((function(o){o instanceof T?t.push(o):o instanceof e&&o.addDisplayedLeafColumns(t)}))},e.prototype.addLeafColumns=function(t){this.children.forEach((function(o){o instanceof T?t.push(o):o instanceof e&&o.addLeafColumns(t)}))},e.prototype.getChildren=function(){return this.children},e.prototype.getColumnGroupShow=function(){return this.originalColumnGroup.getColumnGroupShow()},e.prototype.getOriginalColumnGroup=function(){return this.originalColumnGroup},e.prototype.calculateDisplayedColumns=function(){var t=this;this.displayedChildren=[];var o=this;if(this.isPadding())for(;o.getParent()&&o.isPadding();)o=o.getParent();o.originalColumnGroup.isExpandable()?this.children.forEach((function(i){switch(i.getColumnGroupShow()){case e.HEADER_GROUP_SHOW_OPEN:o.originalColumnGroup.isExpanded()&&t.displayedChildren.push(i);break;case e.HEADER_GROUP_SHOW_CLOSED:o.originalColumnGroup.isExpanded()||t.displayedChildren.push(i);break;default:t.displayedChildren.push(i)}})):this.displayedChildren=this.children,this.localEventService.dispatchEvent(this.createAgEvent(e.EVENT_DISPLAYED_CHILDREN_CHANGED))},e.HEADER_GROUP_SHOW_OPEN="open",e.HEADER_GROUP_SHOW_CLOSED="closed",e.HEADER_GROUP_PADDING="padding",e.EVENT_LEFT_CHANGED="leftChanged",e.EVENT_DISPLAYED_CHILDREN_CHANGED="displayedChildrenChanged",A([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),e}(),F=function(){function e(e,t,o,i){this.localEventService=new b,this.expandable=!1,this.colGroupDef=e,this.groupId=t,this.expanded=e&&!!e.openByDefault,this.padding=o,this.level=i}return e.prototype.setOriginalParent=function(e){this.originalParent=e},e.prototype.getOriginalParent=function(){return this.originalParent},e.prototype.getLevel=function(){return this.level},e.prototype.isVisible=function(){return!!this.children&&this.children.some((function(e){return e.isVisible()}))},e.prototype.isPadding=function(){return this.padding},e.prototype.setExpanded=function(t){this.expanded=void 0!==t&&t;var o={type:e.EVENT_EXPANDED_CHANGED};this.localEventService.dispatchEvent(o)},e.prototype.isExpandable=function(){return this.expandable},e.prototype.isExpanded=function(){return this.expanded},e.prototype.getGroupId=function(){return this.groupId},e.prototype.getId=function(){return this.getGroupId()},e.prototype.setChildren=function(e){this.children=e},e.prototype.getChildren=function(){return this.children},e.prototype.getColGroupDef=function(){return this.colGroupDef},e.prototype.getLeafColumns=function(){var e=[];return this.addLeafColumns(e),e},e.prototype.addLeafColumns=function(t){this.children&&this.children.forEach((function(o){o instanceof T?t.push(o):o instanceof e&&o.addLeafColumns(t)}))},e.prototype.getColumnGroupShow=function(){return this.padding?_.HEADER_GROUP_PADDING:this.colGroupDef.columnGroupShow},e.prototype.setupExpandable=function(){var e=this;this.setExpandable(),this.getLeafColumns().forEach((function(t){return t.addEventListener(T.EVENT_VISIBLE_CHANGED,e.onColumnVisibilityChanged.bind(e))}))},e.prototype.setExpandable=function(){if(!this.isPadding()){for(var t=!1,o=!1,i=!1,n=this.findChildren(),r=0,s=n.length;r<s;r++){var a=n[r];if(a.isVisible()){var l=a.getColumnGroupShow();if(l===_.HEADER_GROUP_SHOW_OPEN)t=!0,i=!0;else if(l===_.HEADER_GROUP_SHOW_CLOSED)o=!0,i=!0;else{if(t=!0,o=!0,l===_.HEADER_GROUP_PADDING)i=a.children.some((function(e){return void 0!==e.getColumnGroupShow()}))}}}var p=t&&o&&i;if(this.expandable!==p){this.expandable=p;var u={type:e.EVENT_EXPANDABLE_CHANGED};this.localEventService.dispatchEvent(u)}}},e.prototype.findChildren=function(){var t=this.children,o=t[0];if(o&&(!o.isPadding||!o.isPadding()))return t;for(;1===t.length&&t[0]instanceof e;)t=t[0].children;return t},e.prototype.onColumnVisibilityChanged=function(){this.setExpandable()},e.prototype.addEventListener=function(e,t){this.localEventService.addEventListener(e,t)},e.prototype.removeEventListener=function(e,t){this.localEventService.removeEventListener(e,t)},e.EVENT_EXPANDED_CHANGED="expandedChanged",e.EVENT_EXPANDABLE_CHANGED="expandableChanged",e}(),N={numericColumn:{headerClass:"ag-numeric-header",cellClass:"ag-numeric-cell"}},L=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},I=function(e,t){return function(o,i){t(o,i,e)}},G=function(){function e(){}return e.prototype.setBeans=function(e){this.logger=e.create("ColumnFactory")},e.prototype.createColumnTree=function(e,t,o){var i=new c;if(o){var n=o.map((function(e){return e.getId()}));i.addExistingKeys(n)}var r=o?o.slice():null,s=this.recursivelyCreateColumns(e,0,t,r,i,null),a=this.findMaxDept(s,0);this.logger.log("Number of levels for grouped columns is "+a);var l=this.balanceColumnTree(s,0,a,i);return this.columnUtils.depthFirstOriginalTreeSearch(null,l,(function(e,t){e instanceof F&&e.setupExpandable(),e.setOriginalParent(t)})),{columnTree:l,treeDept:a}},e.prototype.createForAutoGroups=function(e,t){var o=this,i=[];return e.forEach((function(e){var n=o.createAutoGroupTreeItem(t,e);i.push(n)})),i},e.prototype.createAutoGroupTreeItem=function(e,t){for(var o=t,i=this.findDepth(e)-1;i>=0;i--){var n=new F(null,"FAKE_PATH_"+t.getId()+"}_"+i,!0,i);this.context.wireBean(n),n.setChildren([o]),o.setOriginalParent(n),o=n}return o},e.prototype.findDepth=function(e){for(var t=0,o=e;o&&o[0]&&o[0]instanceof F;)t++,o=o[0].getChildren();return t},e.prototype.balanceColumnTree=function(e,t,o,i){for(var n=[],r=0;r<e.length;r++){var s=e[r];if(s instanceof F){var a=s,l=this.balanceColumnTree(a.getChildren(),t+1,o,i);a.setChildren(l),n.push(a)}else{for(var p=void 0,u=void 0,c=o-1;c>=t;c--){var d=i.getUniqueKey(null,null),h=this.createMergedColGroupDef(null),g=new F(h,d,!0,t);this.context.wireBean(g),u&&u.setChildren([g]),u=g,p||(p=u)}if(p){if(n.push(p),e.some((function(e){return e instanceof F}))){u.setChildren([s]);continue}u.setChildren(e);break}n.push(s)}}return n},e.prototype.findMaxDept=function(e,t){for(var o=t,i=0;i<e.length;i++){var n=e[i];if(n instanceof F){var r=n,s=this.findMaxDept(r.getChildren(),t+1);o<s&&(o=s)}}return o},e.prototype.recursivelyCreateColumns=function(e,t,o,i,n,r){var s=this,a=[];return e?(e.forEach((function(e){var l;l=s.isColumnGroup(e)?s.createColumnGroup(o,e,t,i,n,r):s.createColumn(o,e,i,n,r),a.push(l)})),a):a},e.prototype.createColumnGroup=function(e,t,o,i,n,r){var s=this.createMergedColGroupDef(t),a=n.getUniqueKey(s.groupId,null),l=new F(s,a,!1,o);this.context.wireBean(l);var p=this.recursivelyCreateColumns(s.children,o+1,e,i,n,l);return l.setChildren(p),l},e.prototype.createMergedColGroupDef=function(e){var t={};return p.assign(t,this.gridOptionsWrapper.getDefaultColGroupDef()),p.assign(t,e),this.checkForDeprecatedItems(t),t},e.prototype.createColumn=function(e,t,o,i,n){var r=this.mergeColDefs(t);this.checkForDeprecatedItems(r);var s=this.findExistingColumn(t,o);if(s)s.setColDef(r,t);else{var a=i.getUniqueKey(r.colId,r.field);s=new T(r,t,a,e),this.context.wireBean(s)}return s},e.prototype.findExistingColumn=function(e,t){var o=p.find(t,(function(t){var o=t.getUserProvidedColDef();return!!o&&(o===e||!!(null!==o.colId&&void 0!==o.colId)&&o.colId===e.colId)}));return o&&p.removeFromArray(t,o),o},e.prototype.mergeColDefs=function(e){var t={};return p.assign(t,this.gridOptionsWrapper.getDefaultColDef()),e.type&&this.assignColumnTypes(e,t),p.assign(t,e),t},e.prototype.assignColumnTypes=function(e,t){var o;if(e.type instanceof Array){e.type.some((function(e){return"string"!=typeof e}))?console.warn("ag-grid: if colDef.type is supplied an array it should be of type 'string[]'"):o=e.type}else{if("string"!=typeof e.type)return void console.warn("ag-grid: colDef.type should be of type 'string' | 'string[]'");o=e.type.split(",")}var i=p.assign({},this.gridOptionsWrapper.getColumnTypes(),N);o.forEach((function(e){var o=i[e.trim()];o?p.assign(t,o):console.warn("ag-grid: colDef.type '"+e+"' does not correspond to defined gridOptions.columnTypes")}))},e.prototype.checkForDeprecatedItems=function(e){if(e){var t=e;void 0!==t.group&&console.warn("ag-grid: colDef.group is invalid, please check documentation on how to do grouping as it changed in version 3"),void 0!==t.headerGroup&&console.warn("ag-grid: colDef.headerGroup is invalid, please check documentation on how to do grouping as it changed in version 3"),void 0!==t.headerGroupShow&&console.warn("ag-grid: colDef.headerGroupShow is invalid, should be columnGroupShow, please check documentation on how to do grouping as it changed in version 3"),void 0!==t.suppressRowGroup&&console.warn("ag-grid: colDef.suppressRowGroup is deprecated, please use colDef.type instead"),void 0!==t.suppressAggregation&&console.warn("ag-grid: colDef.suppressAggregation is deprecated, please use colDef.type instead"),(t.suppressRowGroup||t.suppressAggregation)&&console.warn("ag-grid: colDef.suppressAggregation and colDef.suppressRowGroup are deprecated, use allowRowGroup, allowPivot and allowValue instead"),t.displayName&&(console.warn("ag-grid: Found displayName "+t.displayName+", please use headerName instead, displayName is deprecated."),t.headerName=t.displayName)}},e.prototype.isColumnGroup=function(e){return void 0!==e.children},L([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),L([m("columnUtils")],e.prototype,"columnUtils",void 0),L([m("context")],e.prototype,"context",void 0),L([I(0,E("loggerFactory"))],e.prototype,"setBeans",null),e=L([y("columnFactory")],e)}(),M=function(){function e(){}return e.EVENT_COLUMN_EVERYTHING_CHANGED="columnEverythingChanged",e.EVENT_NEW_COLUMNS_LOADED="newColumnsLoaded",e.EVENT_COLUMN_PIVOT_MODE_CHANGED="columnPivotModeChanged",e.EVENT_COLUMN_ROW_GROUP_CHANGED="columnRowGroupChanged",e.EVENT_EXPAND_COLLAPSE_ALL="expandOrCollapseAll",e.EVENT_COLUMN_PIVOT_CHANGED="columnPivotChanged",e.EVENT_GRID_COLUMNS_CHANGED="gridColumnsChanged",e.EVENT_COLUMN_VALUE_CHANGED="columnValueChanged",e.EVENT_COLUMN_MOVED="columnMoved",e.EVENT_COLUMN_VISIBLE="columnVisible",e.EVENT_COLUMN_PINNED="columnPinned",e.EVENT_COLUMN_GROUP_OPENED="columnGroupOpened",e.EVENT_COLUMN_RESIZED="columnResized",e.EVENT_DISPLAYED_COLUMNS_CHANGED="displayedColumnsChanged",e.EVENT_VIRTUAL_COLUMNS_CHANGED="virtualColumnsChanged",e.EVENT_ROW_GROUP_OPENED="rowGroupOpened",e.EVENT_ROW_DATA_CHANGED="rowDataChanged",e.EVENT_ROW_DATA_UPDATED="rowDataUpdated",e.EVENT_PINNED_ROW_DATA_CHANGED="pinnedRowDataChanged",e.EVENT_RANGE_SELECTION_CHANGED="rangeSelectionChanged",e.EVENT_CHART_RANGE_SELECTION_CHANGED="chartRangeSelectionChanged",e.EVENT_CHART_OPTIONS_CHANGED="chartOptionsChanged",e.EVENT_TOOL_PANEL_VISIBLE_CHANGED="toolPanelVisibleChanged",e.EVENT_MODEL_UPDATED="modelUpdated",e.EVENT_PASTE_START="pasteStart",e.EVENT_PASTE_END="pasteEnd",e.EVENT_CELL_CLICKED="cellClicked",e.EVENT_CELL_DOUBLE_CLICKED="cellDoubleClicked",e.EVENT_CELL_MOUSE_DOWN="cellMouseDown",e.EVENT_CELL_CONTEXT_MENU="cellContextMenu",e.EVENT_CELL_VALUE_CHANGED="cellValueChanged",e.EVENT_ROW_VALUE_CHANGED="rowValueChanged",e.EVENT_CELL_FOCUSED="cellFocused",e.EVENT_ROW_SELECTED="rowSelected",e.EVENT_SELECTION_CHANGED="selectionChanged",e.EVENT_CELL_KEY_DOWN="cellKeyDown",e.EVENT_CELL_KEY_PRESS="cellKeyPress",e.EVENT_CELL_MOUSE_OVER="cellMouseOver",e.EVENT_CELL_MOUSE_OUT="cellMouseOut",e.EVENT_FILTER_CHANGED="filterChanged",e.EVENT_FILTER_MODIFIED="filterModified",e.EVENT_FILTER_OPENED="filterOpened",e.EVENT_SORT_CHANGED="sortChanged",e.EVENT_VIRTUAL_ROW_REMOVED="virtualRowRemoved",e.EVENT_ROW_CLICKED="rowClicked",e.EVENT_ROW_DOUBLE_CLICKED="rowDoubleClicked",e.EVENT_GRID_READY="gridReady",e.EVENT_GRID_SIZE_CHANGED="gridSizeChanged",e.EVENT_VIEWPORT_CHANGED="viewportChanged",e.EVENT_FIRST_DATA_RENDERED="firstDataRendered",e.EVENT_DRAG_STARTED="dragStarted",e.EVENT_DRAG_STOPPED="dragStopped",e.EVENT_ROW_EDITING_STARTED="rowEditingStarted",e.EVENT_ROW_EDITING_STOPPED="rowEditingStopped",e.EVENT_CELL_EDITING_STARTED="cellEditingStarted",e.EVENT_CELL_EDITING_STOPPED="cellEditingStopped",e.EVENT_BODY_SCROLL="bodyScroll",e.EVENT_ANIMATION_QUEUE_EMPTY="animationQueueEmpty",e.EVENT_HEIGHT_SCALE_CHANGED="heightScaleChanged",e.EVENT_PAGINATION_CHANGED="paginationChanged",e.EVENT_COMPONENT_STATE_CHANGED="componentStateChanged",e.EVENT_BODY_HEIGHT_CHANGED="bodyHeightChanged",e.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED="displayedColumnsWidthChanged",e.EVENT_SCROLL_VISIBILITY_CHANGED="scrollVisibilityChanged",e.EVENT_COLUMN_HOVER_CHANGED="columnHoverChanged",e.EVENT_FLASH_CELLS="flashCells",e.EVENT_ROW_DRAG_ENTER="rowDragEnter",e.EVENT_ROW_DRAG_MOVE="rowDragMove",e.EVENT_ROW_DRAG_LEAVE="rowDragLeave",e.EVENT_ROW_DRAG_END="rowDragEnd",e.EVENT_POPUP_TO_FRONT="popupToFront",e.EVENT_COLUMN_ROW_GROUP_CHANGE_REQUEST="columnRowGroupChangeRequest",e.EVENT_COLUMN_PIVOT_CHANGE_REQUEST="columnPivotChangeRequest",e.EVENT_COLUMN_VALUE_CHANGE_REQUEST="columnValueChangeRequest",e.EVENT_COLUMN_AGG_FUNC_CHANGE_REQUEST="columnAggFuncChangeRequest",e}(),x=function(){function e(){this.existingIds={}}return e.prototype.getInstanceIdForKey=function(e){var t,o=this.existingIds[e];return t="number"!=typeof o?0:o+1,this.existingIds[e]=t,t},e}(),V=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},W=function(e,t){return function(o,i){t(o,i,e)}},H=function(){function e(){this.primaryHeaderRowCount=0,this.secondaryHeaderRowCount=0,this.secondaryColumnsPresent=!1,this.gridHeaderRowCount=0,this.displayedLeftColumns=[],this.displayedRightColumns=[],this.displayedCenterColumns=[],this.allDisplayedColumns=[],this.allDisplayedVirtualColumns=[],this.allDisplayedCenterVirtualColumns=[],this.rowGroupColumns=[],this.valueColumns=[],this.pivotColumns=[],this.ready=!1,this.autoGroupsNeedBuilding=!1,this.pivotMode=!1,this.bodyWidth=0,this.leftWidth=0,this.rightWidth=0,this.bodyWidthDirty=!0}return e.prototype.init=function(){var e=this.gridOptionsWrapper.isPivotMode();this.suppressColumnVirtualisation=this.gridOptionsWrapper.isSuppressColumnVirtualisation(),this.isPivotSettingAllowed(e)&&(this.pivotMode=e),this.usingTreeData=this.gridOptionsWrapper.isTreeData()},e.prototype.setColumnDefs=function(e,t){void 0===t&&(t="api");var o=!!this.columnDefs;this.columnDefs=e,this.valueCache.expire(),this.autoGroupsNeedBuilding=!0;var i=this.primaryColumns,n=this.columnFactory.createColumnTree(e,!0,i);this.primaryColumnTree=n.columnTree,this.primaryHeaderRowCount=n.treeDept+1,this.primaryColumns=this.getColumnsFromTree(this.primaryColumnTree),this.extractRowGroupColumns(t,i),this.extractPivotColumns(t,i),this.createValueColumns(t,i),this.ready=!0,this.updateGridColumns(),this.updateDisplayedColumns(t),this.checkDisplayedVirtualColumns(),this.gridOptionsWrapper.isDeltaColumnMode()&&o&&this.resetColumnState(!0,t);var r={type:M.EVENT_COLUMN_EVERYTHING_CHANGED,api:this.gridApi,columnApi:this.columnApi,source:t};this.eventService.dispatchEvent(r);var s={type:M.EVENT_NEW_COLUMNS_LOADED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(s)},e.prototype.isAutoRowHeightActive=function(){return this.autoRowHeightColumns&&this.autoRowHeightColumns.length>0},e.prototype.getAllAutoRowHeightCols=function(){return this.autoRowHeightColumns},e.prototype.setVirtualViewportLeftAndRight=function(){this.gridOptionsWrapper.isEnableRtl()?(this.viewportLeft=this.bodyWidth-this.scrollPosition-this.scrollWidth,this.viewportRight=this.bodyWidth-this.scrollPosition):(this.viewportLeft=this.scrollPosition,this.viewportRight=this.scrollWidth+this.scrollPosition)},e.prototype.getDisplayedColumnsStartingAt=function(e){for(var t=e,o=[];t&&p.exists(t);)o.push(t),t=this.getDisplayedColAfter(t);return o},e.prototype.checkDisplayedVirtualColumns=function(){if(p.exists(this.displayedCenterColumns)){var e=this.allDisplayedVirtualColumns.map((function(e){return e.getId()})).join("#");if(this.updateVirtualSets(),e!==this.allDisplayedVirtualColumns.map((function(e){return e.getId()})).join("#")){var t={type:M.EVENT_VIRTUAL_COLUMNS_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)}}},e.prototype.setVirtualViewportPosition=function(e,t){(e!==this.scrollWidth||t!==this.scrollPosition||this.bodyWidthDirty)&&(this.scrollWidth=e,this.scrollPosition=t,this.bodyWidthDirty=!0,this.setVirtualViewportLeftAndRight(),this.ready&&this.checkDisplayedVirtualColumns())},e.prototype.isPivotMode=function(){return this.pivotMode},e.prototype.isPivotSettingAllowed=function(e){return!e||(!this.gridOptionsWrapper.isTreeData()||(console.warn("ag-Grid: Pivot mode not available in conjunction Tree Data i.e. 'gridOptions.treeData: true'"),!1))},e.prototype.setPivotMode=function(e,t){if(void 0===t&&(t="api"),e!==this.pivotMode&&this.isPivotSettingAllowed(this.pivotMode)){this.pivotMode=e,this.autoGroupsNeedBuilding=!0,this.updateGridColumns(),this.updateDisplayedColumns(t);var o={type:M.EVENT_COLUMN_PIVOT_MODE_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(o)}},e.prototype.getSecondaryPivotColumn=function(e,t){if(!this.secondaryColumnsPresent)return null;var o=this.getPrimaryColumn(t),i=null;return this.secondaryColumns&&this.secondaryColumns.forEach((function(t){var n=t.getColDef().pivotKeys,r=t.getColDef().pivotValueColumn;p.compareArrays(n,e)&&r===o&&(i=t)})),i},e.prototype.setBeans=function(e){this.logger=e.create("ColumnController")},e.prototype.setFirstRightAndLastLeftPinned=function(e){var t,o;this.gridOptionsWrapper.isEnableRtl()?(t=this.displayedLeftColumns?this.displayedLeftColumns[0]:null,o=this.displayedRightColumns?p.last(this.displayedRightColumns):null):(t=this.displayedLeftColumns?p.last(this.displayedLeftColumns):null,o=this.displayedRightColumns?this.displayedRightColumns[0]:null),this.gridColumns.forEach((function(i){i.setLastLeftPinned(i===t,e),i.setFirstRightPinned(i===o,e)}))},e.prototype.autoSizeColumns=function(e,t){var o=this;void 0===t&&(t="api");for(var i=[],n=-1;0!==n;)n=0,this.actionOnGridColumns(e,(function(e){if(i.indexOf(e)>=0)return!1;var r=o.autoWidthCalculator.getPreferredWidthForColumn(e);if(r>0){var s=o.normaliseColumnWidth(e,r);e.setActualWidth(s,t),i.push(e),n++}return!0}),t);if(i.length>0){var r={type:M.EVENT_COLUMN_RESIZED,columns:i,column:1===i.length?i[0]:null,finished:!0,api:this.gridApi,columnApi:this.columnApi,source:"autosizeColumns"};this.eventService.dispatchEvent(r)}},e.prototype.autoSizeColumn=function(e,t){void 0===t&&(t="api"),e&&this.autoSizeColumns([e],t)},e.prototype.autoSizeAllColumns=function(e){void 0===e&&(e="api");var t=this.getAllDisplayedColumns();this.autoSizeColumns(t,e)},e.prototype.getColumnsFromTree=function(e){var t=[];return function e(o){for(var i=0;i<o.length;i++){var n=o[i];n instanceof T?t.push(n):n instanceof F&&e(n.getChildren())}}(e),t},e.prototype.getAllDisplayedColumnGroups=function(){return this.displayedLeftColumnTree&&this.displayedRightColumnTree&&this.displayedCentreColumnTree?this.displayedLeftColumnTree.concat(this.displayedCentreColumnTree).concat(this.displayedRightColumnTree):null},e.prototype.getPrimaryColumnTree=function(){return this.primaryColumnTree},e.prototype.getHeaderRowCount=function(){return this.gridHeaderRowCount},e.prototype.getLeftDisplayedColumnGroups=function(){return this.displayedLeftColumnTree},e.prototype.getRightDisplayedColumnGroups=function(){return this.displayedRightColumnTree},e.prototype.getCenterDisplayedColumnGroups=function(){return this.displayedCentreColumnTree},e.prototype.getDisplayedColumnGroups=function(e){switch(e){case o.PINNED_LEFT:return this.getLeftDisplayedColumnGroups();case o.PINNED_RIGHT:return this.getRightDisplayedColumnGroups();default:return this.getCenterDisplayedColumnGroups()}},e.prototype.isColumnDisplayed=function(e){return this.getAllDisplayedColumns().indexOf(e)>=0},e.prototype.getAllDisplayedColumns=function(){return this.allDisplayedColumns},e.prototype.getAllDisplayedVirtualColumns=function(){return this.allDisplayedVirtualColumns},e.prototype.getDisplayedLeftColumnsForRow=function(e){return this.colSpanActive?this.getDisplayedColumnsForRow(e,this.displayedLeftColumns):this.displayedLeftColumns},e.prototype.getDisplayedRightColumnsForRow=function(e){return this.colSpanActive?this.getDisplayedColumnsForRow(e,this.displayedRightColumns):this.displayedRightColumns},e.prototype.getDisplayedColumnsForRow=function(e,t,o,i){for(var n,r=[],s=null,a=function(a){var l,p=t[a],u=t.length-a,c=Math.min(p.getColSpan(e),u),d=[p];if(c>1){for(var h=c-1,g=1;g<=h;g++)d.push(t[a+g]);a+=h}if(o?(l=!1,d.forEach((function(e){o(e)&&(l=!0)}))):l=!0,l){if(0===r.length&&s)!!i&&i(p)&&r.push(s);r.push(p)}s=p,n=a},l=0;l<t.length;l++)a(l),l=n;return r},e.prototype.getAllDisplayedCenterVirtualColumnsForRow=function(e){var t=this;if(!this.colSpanActive)return this.allDisplayedCenterVirtualColumns;var o=this.suppressColumnVirtualisation?null:this.isColumnInViewport.bind(this);return this.getDisplayedColumnsForRow(e,this.displayedCenterColumns,o,(function(e){return e.getLeft()>t.viewportLeft}))},e.prototype.isColumnInViewport=function(e){var t=e.getLeft(),o=e.getLeft()+e.getActualWidth(),i=this.viewportLeft-200,n=this.viewportRight+200;return!(t<i&&o<i)&&!(t>n&&o>n)},e.prototype.getPinnedLeftContainerWidth=function(){return this.getWidthOfColsInList(this.displayedLeftColumns)},e.prototype.getPinnedRightContainerWidth=function(){return this.getWidthOfColsInList(this.displayedRightColumns)},e.prototype.updatePrimaryColumnList=function(e,t,o,i,n,r){var s=this;if(void 0===r&&(r="api"),e&&!p.missingOrEmpty(e)){var a=!1;if(e.forEach((function(e){var n=s.getPrimaryColumn(e);if(n){if(o){if(t.indexOf(n)>=0)return;t.push(n)}else{if(t.indexOf(n)<0)return;p.removeFromArray(t,n)}i(n),a=!0}})),a){this.autoGroupsNeedBuilding&&this.updateGridColumns(),this.updateDisplayedColumns(r);var l={type:n,columns:t,column:1===t.length?t[0]:null,api:this.gridApi,columnApi:this.columnApi,source:r};this.eventService.dispatchEvent(l)}}},e.prototype.setRowGroupColumns=function(e,t){void 0===t&&(t="api"),this.autoGroupsNeedBuilding=!0,this.setPrimaryColumnList(e,this.rowGroupColumns,M.EVENT_COLUMN_ROW_GROUP_CHANGED,this.setRowGroupActive.bind(this),t)},e.prototype.setRowGroupActive=function(e,t,o){e!==t.isRowGroupActive()&&(t.setRowGroupActive(e,o),e||this.gridOptionsWrapper.isSuppressMakeColumnVisibleAfterUnGroup()||t.setVisible(!0,o))},e.prototype.addRowGroupColumn=function(e,t){void 0===t&&(t="api"),e&&this.addRowGroupColumns([e],t)},e.prototype.addRowGroupColumns=function(e,t){void 0===t&&(t="api"),this.autoGroupsNeedBuilding=!0,this.updatePrimaryColumnList(e,this.rowGroupColumns,!0,this.setRowGroupActive.bind(this,!0),M.EVENT_COLUMN_ROW_GROUP_CHANGED,t)},e.prototype.removeRowGroupColumns=function(e,t){void 0===t&&(t="api"),this.autoGroupsNeedBuilding=!0,this.updatePrimaryColumnList(e,this.rowGroupColumns,!1,this.setRowGroupActive.bind(this,!1),M.EVENT_COLUMN_ROW_GROUP_CHANGED,t)},e.prototype.removeRowGroupColumn=function(e,t){void 0===t&&(t="api"),e&&this.removeRowGroupColumns([e],t)},e.prototype.addPivotColumns=function(e,t){void 0===t&&(t="api"),this.updatePrimaryColumnList(e,this.pivotColumns,!0,(function(e){return e.setPivotActive(!0,t)}),M.EVENT_COLUMN_PIVOT_CHANGED,t)},e.prototype.setPivotColumns=function(e,t){void 0===t&&(t="api"),this.setPrimaryColumnList(e,this.pivotColumns,M.EVENT_COLUMN_PIVOT_CHANGED,(function(e,o){o.setPivotActive(e,t)}),t)},e.prototype.addPivotColumn=function(e,t){void 0===t&&(t="api"),this.addPivotColumns([e],t)},e.prototype.removePivotColumns=function(e,t){void 0===t&&(t="api"),this.updatePrimaryColumnList(e,this.pivotColumns,!1,(function(e){return e.setPivotActive(!1,t)}),M.EVENT_COLUMN_PIVOT_CHANGED,t)},e.prototype.removePivotColumn=function(e,t){void 0===t&&(t="api"),this.removePivotColumns([e],t)},e.prototype.setPrimaryColumnList=function(e,t,o,i,n){var r=this;t.length=0,p.exists(e)&&e.forEach((function(e){var o=r.getPrimaryColumn(e);o&&t.push(o)})),this.primaryColumns.forEach((function(e){var o=t.indexOf(e)>=0;i(o,e)})),this.autoGroupsNeedBuilding&&this.updateGridColumns(),this.updateDisplayedColumns(n);var s={type:o,columns:t,column:1===t.length?t[0]:null,api:this.gridApi,columnApi:this.columnApi,source:n};this.eventService.dispatchEvent(s)},e.prototype.setValueColumns=function(e,t){void 0===t&&(t="api"),this.setPrimaryColumnList(e,this.valueColumns,M.EVENT_COLUMN_VALUE_CHANGED,this.setValueActive.bind(this),t)},e.prototype.setValueActive=function(e,t,o){if(e!==t.isValueActive()&&(t.setValueActive(e,o),e&&!t.getAggFunc())){var i=this.aggFuncService.getDefaultAggFunc(t);t.setAggFunc(i)}},e.prototype.addValueColumns=function(e,t){void 0===t&&(t="api"),this.updatePrimaryColumnList(e,this.valueColumns,!0,this.setValueActive.bind(this,!0),M.EVENT_COLUMN_VALUE_CHANGED,t)},e.prototype.addValueColumn=function(e,t){void 0===t&&(t="api"),e&&this.addValueColumns([e],t)},e.prototype.removeValueColumn=function(e,t){void 0===t&&(t="api"),this.removeValueColumns([e],t)},e.prototype.removeValueColumns=function(e,t){void 0===t&&(t="api"),this.updatePrimaryColumnList(e,this.valueColumns,!1,this.setValueActive.bind(this,!1),M.EVENT_COLUMN_VALUE_CHANGED,t)},e.prototype.normaliseColumnWidth=function(e,t){return t<e.getMinWidth()&&(t=e.getMinWidth()),e.isGreaterThanMax(t)&&(t=e.getMaxWidth()),t},e.prototype.getPrimaryOrGridColumn=function(e){var t=this.getPrimaryColumn(e);return t||this.getGridColumn(e)},e.prototype.setColumnWidth=function(e,t,o,i,n){void 0===n&&(n="api");var r=this.getPrimaryOrGridColumn(e);if(r){var s=[];if(s.push({width:t,ratios:[1],columns:[r]}),"shift"===this.gridOptionsWrapper.getColResizeDefault()&&(o=!o),o){var a=this.getDisplayedColAfter(r);if(!a)return;var l=r.getActualWidth()-t,p=a.getActualWidth()+l;s.push({width:p,ratios:[1],columns:[a]})}this.resizeColumnSets(s,i,n)}},e.prototype.checkMinAndMaxWidthsForSet=function(e){var t=e.columns,o=e.width,i=0,n=0,r=!0;return t.forEach((function(e){i+=e.getMinWidth(),e.getMaxWidth()>0?n+=e.getMaxWidth():r=!1})),o>=i&&(!r||o<=n)},e.prototype.resizeColumnSets=function(e,t,o){if(p.every(e,this.checkMinAndMaxWidthsForSet.bind(this))){var i=[],n=[];e.forEach((function(e){var t=e.width,r=e.columns,s=e.ratios,a={},l={};r.forEach((function(e){return n.push(e)}));for(var p=!0,u=0,c=function(){if(++u>1e3)return console.error("ag-Grid: infinite loop in resizeColumnSets"),"break";p=!1;var e=[],o=0,i=t;r.forEach((function(t,n){if(l[t.getId()])i-=a[t.getId()];else{e.push(t);var r=s[n];o+=r}}));var n=1/o;e.forEach((function(o,r){var u;r===e.length-1?u=i:(u=Math.round(s[r]*t*n),i-=u),u<o.getMinWidth()?(u=o.getMinWidth(),l[o.getId()]=!0,p=!0):o.getMaxWidth()>0&&u>o.getMaxWidth()&&(u=o.getMaxWidth(),l[o.getId()]=!0,p=!0),a[o.getId()]=u}))};p;){if("break"===c())break}r.forEach((function(e){var t=a[e.getId()];e.getActualWidth()!==t&&(e.setActualWidth(t,o),i.push(e))}))}));var r=i.length>0;if(r&&(this.setLeftValues(o),this.updateBodyWidths(),this.checkDisplayedVirtualColumns()),r||t){var s={type:M.EVENT_COLUMN_RESIZED,columns:n,column:1===n.length?n[0]:null,finished:t,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(s)}}else if(t){var a=e&&e.length>0?e[0].columns:null,l={type:M.EVENT_COLUMN_RESIZED,columns:a,column:a&&1===a.length?a[0]:null,finished:t,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(l)}},e.prototype.setColumnAggFunc=function(e,t,o){if(void 0===o&&(o="api"),e){e.setAggFunc(t);var i={type:M.EVENT_COLUMN_VALUE_CHANGED,columns:[e],column:e,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(i)}},e.prototype.moveRowGroupColumn=function(e,t,o){void 0===o&&(o="api");var i=this.rowGroupColumns[e];this.rowGroupColumns.splice(e,1),this.rowGroupColumns.splice(t,0,i);var n={type:M.EVENT_COLUMN_ROW_GROUP_CHANGED,columns:this.rowGroupColumns,column:1===this.rowGroupColumns.length?this.rowGroupColumns[0]:null,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(n)},e.prototype.moveColumns=function(e,t,o){if(void 0===o&&(o="api"),this.columnAnimationService.start(),t>this.gridColumns.length-e.length)return console.warn("ag-Grid: tried to insert columns in invalid location, toIndex = "+t),void console.warn("ag-Grid: remember that you should not count the moving columns when calculating the new index");var i=this.getGridColumns(e);if(!!this.doesMovePassRules(i,t)){p.moveInArray(this.gridColumns,i,t),this.updateDisplayedColumns(o);var n={type:M.EVENT_COLUMN_MOVED,columns:i,column:1===i.length?i[0]:null,toIndex:t,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(n),this.columnAnimationService.finish()}},e.prototype.doesMovePassRules=function(e,t){var o=this.gridColumns.slice();return p.moveInArray(o,e,t),!!this.doesMovePassMarryChildren(o)&&!!this.doesMovePassLockedPositions(o)},e.prototype.doesMovePassLockedPositions=function(e){var t=!1,o=!0;return e.forEach((function(e){e.getColDef().lockPosition?t&&(o=!1):t=!0})),o},e.prototype.doesMovePassMarryChildren=function(e){var t=!0;return this.columnUtils.depthFirstOriginalTreeSearch(null,this.gridBalancedTree,(function(o){if(o instanceof F){var i=o;if(i.getColGroupDef()&&i.getColGroupDef().marryChildren){var n=[];i.getLeafColumns().forEach((function(t){var o=e.indexOf(t);n.push(o)})),Math.max.apply(Math,n)-Math.min.apply(Math,n)>i.getLeafColumns().length-1&&(t=!1)}}})),t},e.prototype.moveColumn=function(e,t,o){void 0===o&&(o="api"),this.moveColumns([e],t,o)},e.prototype.moveColumnByIndex=function(e,t,o){void 0===o&&(o="api");var i=this.gridColumns[e];this.moveColumn(i,t,o)},e.prototype.getBodyContainerWidth=function(){return this.bodyWidth},e.prototype.getContainerWidth=function(e){switch(e){case o.PINNED_LEFT:return this.leftWidth;case o.PINNED_RIGHT:return this.rightWidth;default:return this.bodyWidth}},e.prototype.updateBodyWidths=function(){var e=this.getWidthOfColsInList(this.displayedCenterColumns),t=this.getWidthOfColsInList(this.displayedLeftColumns),o=this.getWidthOfColsInList(this.displayedRightColumns);if(this.bodyWidthDirty=this.bodyWidth!==e,this.bodyWidth!==e||this.leftWidth!==t||this.rightWidth!==o){this.bodyWidth=e,this.leftWidth=t,this.rightWidth=o;var i={type:M.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(i)}},e.prototype.getValueColumns=function(){return this.valueColumns?this.valueColumns:[]},e.prototype.getPivotColumns=function(){return this.pivotColumns?this.pivotColumns:[]},e.prototype.isPivotActive=function(){return this.pivotColumns&&this.pivotColumns.length>0&&this.pivotMode},e.prototype.getRowGroupColumns=function(){return this.rowGroupColumns?this.rowGroupColumns:[]},e.prototype.getDisplayedCenterColumns=function(){return this.displayedCenterColumns},e.prototype.getDisplayedLeftColumns=function(){return this.displayedLeftColumns},e.prototype.getDisplayedRightColumns=function(){return this.displayedRightColumns},e.prototype.getDisplayedColumns=function(e){switch(e){case o.PINNED_LEFT:return this.getDisplayedLeftColumns();case o.PINNED_RIGHT:return this.getDisplayedRightColumns();default:return this.getDisplayedCenterColumns()}},e.prototype.getAllPrimaryColumns=function(){return this.primaryColumns?this.primaryColumns.slice():null},e.prototype.getSecondaryColumns=function(){return this.secondaryColumns?this.secondaryColumns.slice():null},e.prototype.getAllColumnsForQuickFilter=function(){return this.columnsForQuickFilter},e.prototype.getAllGridColumns=function(){return this.gridColumns},e.prototype.isEmpty=function(){return p.missingOrEmpty(this.gridColumns)},e.prototype.isRowGroupEmpty=function(){return p.missingOrEmpty(this.rowGroupColumns)},e.prototype.setColumnVisible=function(e,t,o){void 0===o&&(o="api"),this.setColumnsVisible([e],t,o)},e.prototype.setColumnsVisible=function(e,t,o){var i=this;void 0===o&&(o="api"),this.columnAnimationService.start(),this.actionOnGridColumns(e,(function(e){return e.isVisible()!==t&&(e.setVisible(t,o),!0)}),o,(function(){return{type:M.EVENT_COLUMN_VISIBLE,visible:t,column:null,columns:null,api:i.gridApi,columnApi:i.columnApi,source:o}})),this.columnAnimationService.finish()},e.prototype.setColumnPinned=function(e,t,o){void 0===o&&(o="api"),e&&this.setColumnsPinned([e],t,o)},e.prototype.setColumnsPinned=function(e,t,i){var n,r=this;(void 0===i&&(i="api"),"print"!==this.gridOptionsWrapper.getDomLayout())?(this.columnAnimationService.start(),n=!0===t||t===o.PINNED_LEFT?o.PINNED_LEFT:t===o.PINNED_RIGHT?o.PINNED_RIGHT:null,this.actionOnGridColumns(e,(function(e){return e.getPinned()!==n&&(e.setPinned(n),!0)}),i,(function(){return{type:M.EVENT_COLUMN_PINNED,pinned:n,column:null,columns:null,api:r.gridApi,columnApi:r.columnApi,source:i}})),this.columnAnimationService.finish()):console.warn("Changing the column pinning status is not allowed with domLayout='print'")},e.prototype.actionOnGridColumns=function(e,t,o,i){var n=this;if(!p.missingOrEmpty(e)){var r=[];if(e.forEach((function(e){var o=n.getGridColumn(e);o&&(!1!==t(o)&&r.push(o))})),0!==r.length&&(this.updateDisplayedColumns(o),p.exists(i)&&i)){var s=i();s.columns=r,s.column=1===r.length?r[0]:null,this.eventService.dispatchEvent(s)}}},e.prototype.getDisplayedColBefore=function(e){var t=this.getAllDisplayedColumns(),o=t.indexOf(e);return o>0?t[o-1]:null},e.prototype.getDisplayedColAfter=function(e){var t=this.getAllDisplayedColumns(),o=t.indexOf(e);return o<t.length-1?t[o+1]:null},e.prototype.getDisplayedGroupAfter=function(e){for(var t=e.getDisplayedLeafColumns()[0],o=e.getOriginalColumnGroup().getLevel();;){if(!(t=this.getDisplayedColAfter(t)))return null;for(var i=t.getParent();i.getOriginalColumnGroup().getLevel()!==o;)i=i.getParent();if(i!==e)return i}},e.prototype.isPinningLeft=function(){return this.displayedLeftColumns.length>0},e.prototype.isPinningRight=function(){return this.displayedRightColumns.length>0},e.prototype.getPrimaryAndSecondaryAndAutoColumns=function(){var e=this.primaryColumns?this.primaryColumns.slice(0):[];return this.groupAutoColumns&&p.exists(this.groupAutoColumns)&&this.groupAutoColumns.forEach((function(t){return e.push(t)})),this.secondaryColumnsPresent&&this.secondaryColumns&&this.secondaryColumns.forEach((function(t){return e.push(t)})),e},e.prototype.createStateItemFromColumn=function(e){var t=e.isRowGroupActive()?this.rowGroupColumns.indexOf(e):null,o=e.isPivotActive()?this.pivotColumns.indexOf(e):null,i=e.isValueActive()?e.getAggFunc():null;return{colId:e.getColId(),hide:!e.isVisible(),aggFunc:i,width:e.getActualWidth(),pivotIndex:o,pinned:e.getPinned(),rowGroupIndex:t}},e.prototype.getColumnState=function(){if(p.missing(this.primaryColumns))return[];var e=this.primaryColumns.map(this.createStateItemFromColumn.bind(this)),t=(this.groupAutoColumns?this.groupAutoColumns.map(this.createStateItemFromColumn.bind(this)):[]).concat(e);return this.pivotMode||this.orderColumnStateList(t),t},e.prototype.orderColumnStateList=function(e){var t=this.gridColumns.map((function(e){return e.getColId()}));e.sort((function(e,o){return t.indexOf(e.colId)-t.indexOf(o.colId)}))},e.prototype.resetColumnState=function(e,t){void 0===e&&(e=!1),void 0===t&&(t="api");var o=this.getColumnsFromTree(this.primaryColumnTree),i=[],n=1e3,r=1e3;o&&o.forEach((function(e){var t=e.getColDef().rowGroupIndex,o=e.getColDef().rowGroup,s=e.getColDef().pivotIndex,a=e.getColDef().pivot,l={colId:e.getColId(),aggFunc:e.getColDef().aggFunc,hide:e.getColDef().hide,pinned:e.getColDef().pinned,rowGroupIndex:t,pivotIndex:e.getColDef().pivotIndex,width:e.getColDef().width};p.missing(t)&&o&&(l.rowGroupIndex=n++),p.missing(s)&&a&&(l.pivotIndex=r++),i.push(l)})),this.setColumnState(i,e,t)},e.prototype.setColumnState=function(e,t,o){var i=this;if(void 0===t&&(t=!1),void 0===o&&(o="api"),p.missingOrEmpty(this.primaryColumns))return!1;var n=this.getColumnState();this.autoGroupsNeedBuilding=!0;var r=this.primaryColumns.slice();this.rowGroupColumns=[],this.valueColumns=[],this.pivotColumns=[];var s=!0,a={},l={},u=[];if(e&&e.forEach((function(e){if(p.exists(i.getAutoColumn(e.colId)))u.push(e);else{var t=i.getPrimaryColumn(e.colId);t?(i.syncColumnWithStateItem(t,e,a,l,o),p.removeFromArray(r,t)):(console.warn("ag-grid: column "+e.colId+" not found"),s=!1)}})),r.forEach(this.syncColumnWithNoState.bind(this)),this.rowGroupColumns.sort(this.sortColumnListUsingIndexes.bind(this,a)),this.pivotColumns.sort(this.sortColumnListUsingIndexes.bind(this,l)),this.updateGridColumns(),u.forEach((function(e){var t=i.getAutoColumn(e.colId);i.syncColumnWithStateItem(t,e,a,l,o)})),e){var c=e.map((function(e){return e.colId}));this.gridColumns.sort((function(e,t){return c.indexOf(e.getId())-c.indexOf(t.getId())}))}if(this.putFixedColumnsFirst(),this.updateDisplayedColumns(o),!t){var d={type:M.EVENT_COLUMN_EVERYTHING_CHANGED,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(d)}return this.raiseColumnEvents(n,o),s},e.prototype.raiseColumnEvents=function(e,t){var o=this;if(!this.gridOptionsWrapper.isSuppressSetColumnStateEvents()){var i=this.getColumnState(),n=function(n,r,s){if(!p.compareArrays(e.map(r).sort(),i.map(r).sort())){var a={type:n,columns:s,column:1===s.length?s[0]:null,api:o.gridApi,columnApi:o.columnApi,source:t};o.eventService.dispatchEvent(a)}},r=function(t){var i=[],n={};return e.forEach((function(e){n[e.colId]=e})),o.gridColumns.forEach((function(e){var o=n[e.getColId()];o&&!t(o,e)||i.push(e)})),i};n(M.EVENT_COLUMN_VALUE_CHANGED,(function(e){return e.colId+"-"+e.aggFunc}),this.valueColumns);n(M.EVENT_COLUMN_PIVOT_CHANGED,(function(e){return e.colId+"-"+e.pivotIndex}),this.pivotColumns);n(M.EVENT_COLUMN_ROW_GROUP_CHANGED,(function(e){return e.colId+"-"+e.rowGroupIndex}),this.rowGroupColumns);this.raiseColumnPinnedEvent(r((function(e,t){return e.pinned!==t.getPinned()})),t);var s=r((function(e,t){return e.hide===t.isVisible()}));this.raiseColumnVisibleEvent(s,t);this.raiseColumnResizeEvent(r((function(e,t){return e.width!==t.getActualWidth()})),t),this.raiseColumnMovedEvent(e,t)}},e.prototype.raiseColumnPinnedEvent=function(e,t){if(e.length>0){var o={type:M.EVENT_COLUMN_PINNED,pinned:null,columns:e,column:null,api:this.gridApi,columnApi:this.columnApi,source:t};this.eventService.dispatchEvent(o)}},e.prototype.raiseColumnVisibleEvent=function(e,t){if(e.length>0){var o={type:M.EVENT_COLUMN_VISIBLE,visible:void 0,columns:e,column:null,api:this.gridApi,columnApi:this.columnApi,source:t};this.eventService.dispatchEvent(o)}},e.prototype.raiseColumnResizeEvent=function(e,t){if(e.length>0){var o={type:M.EVENT_COLUMN_RESIZED,columns:e,column:null,finished:!0,api:this.gridApi,columnApi:this.columnApi,source:t};this.eventService.dispatchEvent(o)}},e.prototype.raiseColumnMovedEvent=function(e,t){for(var o=[],i=this.getColumnState(),n=function(t){var n=e[t],s=i[t];if(!n||s.hide)return"continue";if(n.colId!==s.colId){var a=p.find(r.allDisplayedColumns,(function(e){return e.getColId()===s.colId}));o.push(a)}},r=this,s=0;s<i.length;s++)n(s);if(o.length>0){var a={type:M.EVENT_COLUMN_MOVED,columns:o,column:null,toIndex:void 0,api:this.gridApi,columnApi:this.columnApi,source:t};this.eventService.dispatchEvent(a)}},e.prototype.sortColumnListUsingIndexes=function(e,t,o){return e[t.getId()]-e[o.getId()]},e.prototype.syncColumnWithNoState=function(e,t){e.setVisible(!1,t),e.setAggFunc(null),e.setPinned(null),e.setRowGroupActive(!1,t),e.setPivotActive(!1,t),e.setValueActive(!1,t)},e.prototype.syncColumnWithStateItem=function(e,t,o,i,n){if(e){e.setVisible(!t.hide,n),e.setPinned(t.pinned);var r=this.gridOptionsWrapper.getMinColWidth();t.width&&r&&t.width>=r&&e.setActualWidth(t.width,n),"string"==typeof t.aggFunc?(e.setAggFunc(t.aggFunc),e.setValueActive(!0,n),this.valueColumns.push(e)):(p.exists(t.aggFunc)&&console.warn("ag-Grid: stateItem.aggFunc must be a string. if using your own aggregation functions, register the functions first before using them in get/set state. This is because it isintended for the column state to be stored and retrieved as simple JSON."),e.setAggFunc(null),e.setValueActive(!1,n)),"number"==typeof t.rowGroupIndex?(this.rowGroupColumns.push(e),e.setRowGroupActive(!0,n),o[e.getId()]=t.rowGroupIndex):e.setRowGroupActive(!1,n),"number"==typeof t.pivotIndex?(this.pivotColumns.push(e),e.setPivotActive(!0,n),i[e.getId()]=t.pivotIndex):e.setPivotActive(!1,n)}},e.prototype.getGridColumns=function(e){return this.getColumns(e,this.getGridColumn.bind(this))},e.prototype.getColumns=function(e,t){var o=[];return e&&e.forEach((function(e){var i=t(e);i&&o.push(i)})),o},e.prototype.getColumnWithValidation=function(e){if(null==e)return null;var t=this.getGridColumn(e);return t||console.warn("ag-Grid: could not find column "+e),t},e.prototype.getPrimaryColumn=function(e){return this.getColumn(e,this.primaryColumns)},e.prototype.getGridColumn=function(e){return this.getColumn(e,this.gridColumns)},e.prototype.getColumn=function(e,t){if(!e)return null;for(var o=0;o<t.length;o++)if(this.columnsMatch(t[o],e))return t[o];return this.getAutoColumn(e)},e.prototype.getAutoColumn=function(e){var t=this;return this.groupAutoColumns&&p.exists(this.groupAutoColumns)&&!p.missing(this.groupAutoColumns)?p.find(this.groupAutoColumns,(function(o){return t.columnsMatch(o,e)})):null},e.prototype.columnsMatch=function(e,t){var o=e===t,i=e.getColDef()===t,n=e.getColId()==t;return o||i||n},e.prototype.getDisplayNameForColumn=function(e,t,o){if(void 0===o&&(o=!1),!e)return null;var i=this.getHeaderName(e.getColDef(),e,null,null,t);return o?this.wrapHeaderNameWithAggFunc(e,i):i},e.prototype.getDisplayNameForOriginalColumnGroup=function(e,t,o){var i=t?t.getColGroupDef():null;return i?this.getHeaderName(i,null,e,t,o):null},e.prototype.getDisplayNameForColumnGroup=function(e,t){return this.getDisplayNameForOriginalColumnGroup(e,e.getOriginalColumnGroup(),t)},e.prototype.getHeaderName=function(e,t,o,i,n){var r=e.headerValueGetter;if(r){var s={colDef:e,column:t,columnGroup:o,originalColumnGroup:i,location:n,api:this.gridOptionsWrapper.getApi(),context:this.gridOptionsWrapper.getContext()};return"function"==typeof r?r(s):"string"==typeof r?this.expressionService.evaluate(r,s):(console.warn("ag-grid: headerValueGetter must be a function or a string"),"")}return null!=e.headerName?e.headerName:e.field?p.camelCaseToHumanText(e.field):""},e.prototype.wrapHeaderNameWithAggFunc=function(e,t){if(this.gridOptionsWrapper.isSuppressAggFuncInHeader())return t;var o,i=e.getColDef().pivotValueColumn,n=null;if(p.exists(i))n=i?i.getAggFunc():null,o=!0;else{var r=e.isValueActive(),s=this.pivotMode||!this.isRowGroupEmpty();r&&s?(n=e.getAggFunc(),o=!0):o=!1}if(o){var a="string"==typeof n?n:"func";return this.gridOptionsWrapper.getLocaleTextFunc()(a,a)+"("+t+")"}return t},e.prototype.getColumnGroup=function(e,t){if(!e)return null;if(e instanceof _)return e;var o=this.getAllDisplayedColumnGroups(),i="number"==typeof t,n=null;return this.columnUtils.depthFirstAllColumnTreeSearch(o,(function(o){if(o instanceof _){var r=o;(i?e===r.getGroupId()&&t===r.getInstanceId():e===r.getGroupId())&&(n=r)}})),n},e.prototype.isReady=function(){return this.ready},e.prototype.createValueColumns=function(e,t){this.valueColumns=this.extractColumns(t,this.valueColumns,(function(t,o){return t.setValueActive(o,e)}),(function(){return null}),(function(e){return!!e.aggFunc})),this.valueColumns.forEach((function(e){e.getAggFunc()||e.setAggFunc(e.getColDef().aggFunc)}))},e.prototype.extractRowGroupColumns=function(e,t){this.rowGroupColumns=this.extractColumns(t,this.rowGroupColumns,(function(t,o){return t.setRowGroupActive(o,e)}),(function(e){return e.rowGroupIndex}),(function(e){return e.rowGroup}))},e.prototype.extractColumns=function(e,t,o,i,n){var r=this;t||(t=[]);var s=t.filter((function(e){return r.primaryColumns.indexOf(e)<0})),a=t.filter((function(e){return r.primaryColumns.indexOf(e)>=0})),l=this.primaryColumns.filter((function(t){return!e||e.indexOf(t)<0}));s.forEach((function(e){return o(e,!1)}));var p=[];return l.forEach((function(e){"number"==typeof i(e.getColDef())&&p.push(e)})),p.sort((function(e,t){var o=i(e.getColDef()),n=i(t.getColDef());return o===n?0:o<n?-1:1})),l.forEach((function(e){if(n(e.getColDef())){if(p.indexOf(e)>=0)return;p.push(e)}})),p.forEach((function(e){return o(e,!0)})),a.concat(p)},e.prototype.extractPivotColumns=function(e,t){this.pivotColumns=this.extractColumns(t,this.pivotColumns,(function(t,o){return t.setPivotActive(o,e)}),(function(e){return e.pivotIndex}),(function(e){return e.pivot}))},e.prototype.resetColumnGroupState=function(e){void 0===e&&(e="api");var t=[];this.columnUtils.depthFirstOriginalTreeSearch(null,this.primaryColumnTree,(function(e){if(e instanceof F){var o={groupId:e.getGroupId(),open:e.getColGroupDef().openByDefault};t.push(o)}})),this.setColumnGroupState(t,e)},e.prototype.getColumnGroupState=function(){var e=[];return this.columnUtils.depthFirstOriginalTreeSearch(null,this.gridBalancedTree,(function(t){if(t instanceof F){var o=t;e.push({groupId:o.getGroupId(),open:o.isExpanded()})}})),e},e.prototype.setColumnGroupState=function(e,t){var o=this;void 0===t&&(t="api"),this.columnAnimationService.start();var i=[];e.forEach((function(e){var t=e.groupId,n=e.open,r=o.getOriginalColumnGroup(t);r&&r.isExpanded()!==n&&(o.logger.log("columnGroupOpened("+r.getGroupId()+","+n+")"),r.setExpanded(n),i.push(r))})),this.updateGroupsAndDisplayedColumns(t),this.setFirstRightAndLastLeftPinned(t),i.forEach((function(e){var t={type:M.EVENT_COLUMN_GROUP_OPENED,columnGroup:e,api:o.gridApi,columnApi:o.columnApi};o.eventService.dispatchEvent(t)})),this.columnAnimationService.finish()},e.prototype.setColumnGroupOpened=function(e,t,o){var i;void 0===o&&(o="api"),i=e instanceof F?e.getId():e,this.setColumnGroupState([{groupId:i,open:t}],o)},e.prototype.getOriginalColumnGroup=function(e){if(e instanceof F)return e;"string"!=typeof e&&console.error("ag-Grid: group key must be a string");var t=null;return this.columnUtils.depthFirstOriginalTreeSearch(null,this.gridBalancedTree,(function(o){if(o instanceof F){var i=o;i.getId()===e&&(t=i)}})),t},e.prototype.calculateColumnsForDisplay=function(){var e=this;return this.pivotMode&&!this.secondaryColumnsPresent?this.gridColumns.filter((function(t){var o=e.groupAutoColumns&&p.includes(e.groupAutoColumns,t),i=e.valueColumns&&p.includes(e.valueColumns,t);return o||i})):this.gridColumns.filter((function(t){return e.groupAutoColumns&&p.includes(e.groupAutoColumns,t)||t.isVisible()}))},e.prototype.checkColSpanActiveInCols=function(e){var t=!1;return e.forEach((function(e){p.exists(e.getColDef().colSpan)&&(t=!0)})),t},e.prototype.calculateColumnsForGroupDisplay=function(){var e=this;this.groupDisplayColumns=[];var t=function(t){var o=t.getColDef();o&&p.exists(o.showRowGroup)&&e.groupDisplayColumns.push(t)};this.gridColumns.forEach(t),this.groupAutoColumns&&this.groupAutoColumns.forEach(t)},e.prototype.getGroupDisplayColumns=function(){return this.groupDisplayColumns},e.prototype.updateDisplayedColumns=function(e){var t=this.calculateColumnsForDisplay();this.buildDisplayedTrees(t),this.calculateColumnsForGroupDisplay(),this.updateGroupsAndDisplayedColumns(e),this.setFirstRightAndLastLeftPinned(e)},e.prototype.isSecondaryColumnsPresent=function(){return this.secondaryColumnsPresent},e.prototype.setSecondaryColumns=function(e,t){void 0===t&&(t="api");var o=e&&e.length>0;if(o||this.secondaryColumnsPresent){if(o){this.processSecondaryColumnDefinitions(e);var i=this.columnFactory.createColumnTree(e,!1);this.secondaryBalancedTree=i.columnTree,this.secondaryHeaderRowCount=i.treeDept+1,this.secondaryColumns=this.getColumnsFromTree(this.secondaryBalancedTree),this.secondaryColumnsPresent=!0}else this.secondaryBalancedTree=null,this.secondaryHeaderRowCount=-1,this.secondaryColumns=null,this.secondaryColumnsPresent=!1;this.updateGridColumns(),this.updateDisplayedColumns(t)}},e.prototype.processSecondaryColumnDefinitions=function(e){var t=this.gridOptionsWrapper.getProcessSecondaryColDefFunc(),o=this.gridOptionsWrapper.getProcessSecondaryColGroupDefFunc();(t||o)&&e&&function e(i){i.forEach((function(i){if(p.exists(i.children)){var n=i;o&&o(n),e(n.children)}else{t&&t(i)}}))}(e)},e.prototype.updateGridColumns=function(){this.gridColsArePrimary&&(this.lastPrimaryOrder=this.gridColumns),this.secondaryColumns&&this.secondaryBalancedTree?(this.gridBalancedTree=this.secondaryBalancedTree.slice(),this.gridHeaderRowCount=this.secondaryHeaderRowCount,this.gridColumns=this.secondaryColumns.slice(),this.gridColsArePrimary=!1):(this.gridBalancedTree=this.primaryColumnTree.slice(),this.gridHeaderRowCount=this.primaryHeaderRowCount,this.gridColumns=this.primaryColumns.slice(),this.gridColsArePrimary=!0,this.orderGridColsLikeLastPrimary()),this.addAutoGroupToGridColumns(),this.autoRowHeightColumns=this.gridColumns.filter((function(e){return e.getColDef().autoHeight})),this.putFixedColumnsFirst(),this.setupQuickFilterColumns(),this.clearDisplayedColumns(),this.colSpanActive=this.checkColSpanActiveInCols(this.gridColumns);var e={type:M.EVENT_GRID_COLUMNS_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)},e.prototype.orderGridColsLikeLastPrimary=function(){var e=this;if(!p.missing(this.lastPrimaryOrder)){var t=!0;if(this.gridColumns.forEach((function(o){e.lastPrimaryOrder.indexOf(o)>=0&&(t=!1)})),!t){var o=this.lastPrimaryOrder.filter((function(t){return e.gridColumns.indexOf(t)>=0})),i=this.gridColumns.filter((function(e){return o.indexOf(e)<0})),n=o.slice();i.forEach((function(e){var t=e.getOriginalParent();if(t){for(var o=[];!o.length&&t;){t.getLeafColumns().forEach((function(e){var t=n.indexOf(e)>=0,i=o.indexOf(e)<0;t&&i&&o.push(e)})),t=t.getOriginalParent()}if(o.length){var i=o.map((function(e){return n.indexOf(e)})),r=Math.max.apply(Math,i);p.insertIntoArray(n,e,r+1)}else n.push(e)}else n.push(e)})),this.gridColumns=n}}},e.prototype.isPrimaryColumnGroupsPresent=function(){return this.primaryHeaderRowCount>1},e.prototype.setupQuickFilterColumns=function(){this.groupAutoColumns?this.columnsForQuickFilter=this.primaryColumns.concat(this.groupAutoColumns):this.columnsForQuickFilter=this.primaryColumns},e.prototype.putFixedColumnsFirst=function(){var e=this.gridColumns.filter((function(e){return e.getColDef().lockPosition})),t=this.gridColumns.filter((function(e){return!e.getColDef().lockPosition}));this.gridColumns=e.concat(t)},e.prototype.addAutoGroupToGridColumns=function(){if(this.createGroupAutoColumnsIfNeeded(),!p.missing(this.groupAutoColumns)){this.gridColumns=this.groupAutoColumns?this.groupAutoColumns.concat(this.gridColumns):this.gridColumns;var e=this.columnFactory.createForAutoGroups(this.groupAutoColumns,this.gridBalancedTree);this.gridBalancedTree=e.concat(this.gridBalancedTree)}},e.prototype.clearDisplayedColumns=function(){this.displayedLeftColumnTree=[],this.displayedRightColumnTree=[],this.displayedCentreColumnTree=[],this.displayedLeftHeaderRows={},this.displayedRightHeaderRows={},this.displayedCentreHeaderRows={},this.displayedLeftColumns=[],this.displayedRightColumns=[],this.displayedCenterColumns=[],this.allDisplayedColumns=[],this.allDisplayedVirtualColumns=[]},e.prototype.updateGroupsAndDisplayedColumns=function(e){this.updateOpenClosedVisibilityInColumnGroups(),this.updateDisplayedColumnsFromTrees(e),this.updateVirtualSets(),this.updateBodyWidths();var t={type:M.EVENT_DISPLAYED_COLUMNS_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)},e.prototype.updateDisplayedColumnsFromTrees=function(e){this.addToDisplayedColumns(this.displayedLeftColumnTree,this.displayedLeftColumns),this.addToDisplayedColumns(this.displayedCentreColumnTree,this.displayedCenterColumns),this.addToDisplayedColumns(this.displayedRightColumnTree,this.displayedRightColumns),this.setupAllDisplayedColumns(),this.setLeftValues(e)},e.prototype.setupAllDisplayedColumns=function(){this.gridOptionsWrapper.isEnableRtl()?this.allDisplayedColumns=this.displayedRightColumns.concat(this.displayedCenterColumns).concat(this.displayedLeftColumns):this.allDisplayedColumns=this.displayedLeftColumns.concat(this.displayedCenterColumns).concat(this.displayedRightColumns)},e.prototype.setLeftValues=function(e){this.setLeftValuesOfColumns(e),this.setLeftValuesOfGroups()},e.prototype.setLeftValuesOfColumns=function(e){var t=this,o=this.primaryColumns.slice(0),i=this.gridOptionsWrapper.isEnableRtl();[this.displayedLeftColumns,this.displayedRightColumns,this.displayedCenterColumns].forEach((function(n){if(i){var r=t.getWidthOfColsInList(n);n.forEach((function(t){r-=t.getActualWidth(),t.setLeft(r,e)}))}else{var s=0;n.forEach((function(t){t.setLeft(s,e),s+=t.getActualWidth()}))}p.removeAllFromArray(o,n)})),o.forEach((function(t){t.setLeft(null,e)}))},e.prototype.setLeftValuesOfGroups=function(){[this.displayedLeftColumnTree,this.displayedRightColumnTree,this.displayedCentreColumnTree].forEach((function(e){e.forEach((function(e){e instanceof _&&e.checkLeft()}))}))},e.prototype.addToDisplayedColumns=function(e,t){t.length=0,this.columnUtils.depthFirstDisplayedColumnTreeSearch(e,(function(e){e instanceof T&&t.push(e)}))},e.prototype.updateDisplayedCenterVirtualColumns=function(){this.suppressColumnVirtualisation?this.allDisplayedCenterVirtualColumns=this.displayedCenterColumns:this.allDisplayedCenterVirtualColumns=this.filterOutColumnsWithinViewport(),this.allDisplayedVirtualColumns=this.allDisplayedCenterVirtualColumns.concat(this.displayedLeftColumns).concat(this.displayedRightColumns);var e={};return this.allDisplayedVirtualColumns.forEach((function(t){e[t.getId()]=!0})),e},e.prototype.getVirtualHeaderGroupRow=function(e,t){var i;switch(e){case o.PINNED_LEFT:i=this.displayedLeftHeaderRows[t];break;case o.PINNED_RIGHT:i=this.displayedRightHeaderRows[t];break;default:i=this.displayedCentreHeaderRows[t]}return p.missing(i)&&(i=[]),i},e.prototype.updateDisplayedVirtualGroups=function(e){function t(o,i,n){for(var r=!1,s=0;s<o.length;s++){var a=o[s],l=void 0;if(a instanceof T)l=!0===e[a.getId()];else l=t(a.getDisplayedChildren(),i,n+1);l&&(r=!0,i[n]||(i[n]=[]),i[n].push(a))}return r}this.displayedLeftHeaderRows={},this.displayedRightHeaderRows={},this.displayedCentreHeaderRows={},t(this.displayedLeftColumnTree,this.displayedLeftHeaderRows,0),t(this.displayedRightColumnTree,this.displayedRightHeaderRows,0),t(this.displayedCentreColumnTree,this.displayedCentreHeaderRows,0)},e.prototype.updateVirtualSets=function(){var e=this.updateDisplayedCenterVirtualColumns();this.updateDisplayedVirtualGroups(e)},e.prototype.filterOutColumnsWithinViewport=function(){return this.displayedCenterColumns.filter(this.isColumnInViewport.bind(this))},e.prototype.sizeColumnsToFit=function(e,t){var o=this;void 0===t&&(t="api");var i=this.getAllDisplayedColumns();if(!(e<=0||0===i.length)){var n=[],r=[];i.forEach((function(e){!0===e.getColDef().suppressSizeToFit?r.push(e):n.push(e)}));for(var s=n.slice(0),a=!1;!a;){a=!0;var l=e-this.getWidthOfColsInList(r);if(l<=0)n.forEach((function(e){e.setMinimum(t)}));else for(var u=l/this.getWidthOfColsInList(n),c=l,d=n.length-1;d>=0;d--){var h=n[d],g=Math.round(h.getActualWidth()*u);if(g<h.getMinWidth())h.setMinimum(t),f(h),a=!1;else if(h.isGreaterThanMax(g))h.setActualWidth(h.getMaxWidth(),t),f(h),a=!1;else{0===d?h.setActualWidth(c,t):h.setActualWidth(g,t)}c-=g}}this.setLeftValues(t),this.updateBodyWidths(),s.forEach((function(e){var t={type:M.EVENT_COLUMN_RESIZED,column:e,columns:[e],finished:!0,api:o.gridApi,columnApi:o.columnApi,source:"sizeColumnsToFit"};o.eventService.dispatchEvent(t)}))}function f(e){p.removeFromArray(n,e),r.push(e)}},e.prototype.buildDisplayedTrees=function(e){var t=[],i=[],n=[];e.forEach((function(e){switch(e.getPinned()){case"left":t.push(e);break;case"right":i.push(e);break;default:n.push(e)}}));var r=new x;this.displayedLeftColumnTree=this.displayedGroupCreator.createDisplayedGroups(t,this.gridBalancedTree,r,o.PINNED_LEFT,this.displayedLeftColumnTree),this.displayedRightColumnTree=this.displayedGroupCreator.createDisplayedGroups(i,this.gridBalancedTree,r,o.PINNED_RIGHT,this.displayedRightColumnTree),this.displayedCentreColumnTree=this.displayedGroupCreator.createDisplayedGroups(n,this.gridBalancedTree,r,null,this.displayedCentreColumnTree)},e.prototype.updateOpenClosedVisibilityInColumnGroups=function(){var e=this.getAllDisplayedColumnGroups();this.columnUtils.depthFirstAllColumnTreeSearch(e,(function(e){e instanceof _&&e.calculateDisplayedColumns()}))},e.prototype.getGroupAutoColumns=function(){return this.groupAutoColumns},e.prototype.createGroupAutoColumnsIfNeeded=function(){if(this.autoGroupsNeedBuilding){this.autoGroupsNeedBuilding=!1;var e=this.gridOptionsWrapper.isGroupUseEntireRow(this.pivotMode),t=this.gridOptionsWrapper.isGroupSuppressAutoColumn()&&!this.pivotMode,o=this.gridOptionsWrapper.isGroupSuppressRow();if((this.rowGroupColumns.length>0||this.usingTreeData)&&!t&&!e&&!o){var i=this.autoGroupColService.createAutoGroupColumns(this.rowGroupColumns);!this.autoColsEqual(i,this.groupAutoColumns)&&(this.groupAutoColumns=i)}else this.groupAutoColumns=null}},e.prototype.autoColsEqual=function(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;if(e.length!==t.length)return!1;for(var o=0;o<e.length;o++){var i=e[o],n=t[o];if(i.getColId()!==n.getColId())return!1}return!0},e.prototype.getWidthOfColsInList=function(e){for(var t=0,o=0;o<e.length;o++)t+=e[o].getActualWidth();return t},e.prototype.getGridBalancedTree=function(){return this.gridBalancedTree},V([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),V([m("expressionService")],e.prototype,"expressionService",void 0),V([m("columnFactory")],e.prototype,"columnFactory",void 0),V([m("displayedGroupCreator")],e.prototype,"displayedGroupCreator",void 0),V([m("autoWidthCalculator")],e.prototype,"autoWidthCalculator",void 0),V([m("eventService")],e.prototype,"eventService",void 0),V([m("columnUtils")],e.prototype,"columnUtils",void 0),V([m("context")],e.prototype,"context",void 0),V([m("columnAnimationService")],e.prototype,"columnAnimationService",void 0),V([m("autoGroupColService")],e.prototype,"autoGroupColService",void 0),V([v("aggFuncService")],e.prototype,"aggFuncService",void 0),V([v("valueCache")],e.prototype,"valueCache",void 0),V([m("columnApi")],e.prototype,"columnApi",void 0),V([m("gridApi")],e.prototype,"gridApi",void 0),V([g],e.prototype,"init",null),V([W(0,E("loggerFactory"))],e.prototype,"setBeans",null),e=V([y("columnController")],e)}(),k=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},B=function(){function e(){}return e.prototype.calculateColInitialWidth=function(e){return e.width?e.width<this.gridOptionsWrapper.getMinColWidth()?this.gridOptionsWrapper.getMinColWidth():e.width:this.gridOptionsWrapper.getColWidth()},e.prototype.getOriginalPathForColumn=function(e,t){var o=[],i=!1;return function t(n,r){for(var s=0;s<n.length;s++){if(i)return;var a=n[s];if(a instanceof F)t(a.getChildren(),r+1),o[r]=a;else a===e&&(i=!0)}}(t,0),i?o:null},e.prototype.depthFirstOriginalTreeSearch=function(e,t,o){var i=this;t&&t.forEach((function(t){t instanceof F&&i.depthFirstOriginalTreeSearch(t,t.getChildren(),o),o(t,e)}))},e.prototype.depthFirstAllColumnTreeSearch=function(e,t){var o=this;e&&e.forEach((function(e){e instanceof _&&o.depthFirstAllColumnTreeSearch(e.getChildren(),t),t(e)}))},e.prototype.depthFirstDisplayedColumnTreeSearch=function(e,t){var o=this;e&&e.forEach((function(e){e instanceof _&&o.depthFirstDisplayedColumnTreeSearch(e.getDisplayedChildren(),t),t(e)}))},k([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),e=k([y("columnUtils")],e)}(),U=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},j=function(){function e(){}return e.prototype.createDisplayedGroups=function(e,t,o,i,n){var r,s,a=this,l=[],u=this.mapOldGroupsById(n);return e.forEach((function(e){for(var n=a.getOriginalPathForColumn(t,e),c=[],d=!s,h=0;h<n.length;h++)if(d||n[h]!==s[h]){var g=a.createColumnGroup(n[h],o,u,i);c[h]=g,0==h?l.push(g):c[h-1].addChild(g)}else c[h]=r[h];0===c.length?l.push(e):p.last(c).addChild(e);r=c,s=n})),this.setupParentsIntoColumns(l,null),l},e.prototype.createColumnGroup=function(e,t,o,i){var n=e.getGroupId(),r=t.getInstanceIdForKey(n),s=o[_.createUniqueId(n,r)];return s&&s.getOriginalColumnGroup()!==e&&(s=null),p.exists(s)?s.reset():(s=new _(e,n,r,i),this.context.wireBean(s)),s},e.prototype.mapOldGroupsById=function(e){var t={},o=function(e){e.forEach((function(e){if(e instanceof _){var i=e;t[e.getUniqueId()]=i,o(i.getChildren())}}))};return e&&o(e),t},e.prototype.setupParentsIntoColumns=function(e,t){var o=this;e.forEach((function(e){if(e.setParent(t),e instanceof _){var i=e;o.setupParentsIntoColumns(i.getChildren(),i)}}))},e.prototype.getOriginalPathForColumn=function(e,t){var o=[],i=!1;return function e(n,r){for(var s=0;s<n.length;s++){if(i)return;var a=n[s];if(a instanceof F)e(a.getChildren(),r+1),o[r]=a;else a===t&&(i=!0)}}(e,0),i?o:(console.warn("could not get path"),null)},U([m("columnUtils")],e.prototype,"columnUtils",void 0),U([m("context")],e.prototype,"context",void 0),e=U([y("displayedGroupCreator")],e)}(),z=function(){for(var e=0,t=0,o=arguments.length;t<o;t++)e+=arguments[t].length;var i=Array(e),n=0;for(t=0;t<o;t++)for(var r=arguments[t],s=0,a=r.length;s<a;s++,n++)i[n]=r[s];return i},Y=function(){function e(){}return e.STRING_PROPERTIES=["sortingOrder","rowClass","rowSelection","overlayLoadingTemplate","overlayNoRowsTemplate","quickFilterText","rowModelType","editType","domLayout","clipboardDeliminator","rowGroupPanelShow","multiSortKey","pivotColumnGroupTotals","pivotRowTotals","pivotPanelShow"],e.OBJECT_PROPERTIES=["components","frameworkComponents","rowStyle","context","autoGroupColumnDef","groupColumnDef","localeText","icons","datasource","serverSideDatasource","viewportDatasource","groupRowRendererParams","aggFuncs","fullWidthCellRendererParams","defaultColGroupDef","defaultColDef","defaultExportParams","columnTypes","rowClassRules","detailGridOptions","detailCellRendererParams","loadingCellRendererParams","loadingOverlayComponentParams","noRowsOverlayComponentParams","popupParent","colResizeDefault","reduxStore","statusBar","sideBar"],e.ARRAY_PROPERTIES=["slaveGrids","alignedGrids","rowData","columnDefs","excelStyles","pinnedTopRowData","pinnedBottomRowData"],e.NUMBER_PROPERTIES=["rowHeight","detailRowHeight","rowBuffer","colWidth","headerHeight","groupHeaderHeight","floatingFiltersHeight","pivotHeaderHeight","pivotGroupHeaderHeight","groupDefaultExpanded","minColWidth","maxColWidth","viewportRowModelPageSize","viewportRowModelBufferSize","autoSizePadding","maxBlocksInCache","maxConcurrentDatasourceRequests","cacheOverflowSize","paginationPageSize","cacheBlockSize","infiniteInitialRowCount","scrollbarWidth","paginationStartPage","infiniteBlockSize","batchUpdateWaitMillis","blockLoadDebounceMillis","keepDetailRowsCount"],e.BOOLEAN_PROPERTIES=["toolPanelSuppressRowGroups","toolPanelSuppressValues","toolPanelSuppressPivots","toolPanelSuppressPivotMode","toolPanelSuppressSideButtons","toolPanelSuppressColumnFilter","toolPanelSuppressColumnSelectAll","toolPanelSuppressColumnExpandAll","suppressMakeColumnVisibleAfterUnGroup","suppressRowClickSelection","suppressCellSelection","suppressHorizontalScroll","alwaysShowVerticalScroll","debug","enableBrowserTooltips","enableColResize","enableCellExpressions","enableSorting","enableServerSideSorting","enableFilter","enableServerSideFilter","angularCompileRows","angularCompileFilters","angularCompileHeaders","groupSuppressAutoColumn","groupSelectsChildren","groupIncludeFooter","groupIncludeTotalFooter","groupUseEntireRow","groupSuppressRow","groupSuppressBlankHeader","forPrint","suppressMenuHide","rowDeselection","unSortIcon","suppressMultiSort","singleClickEdit","suppressLoadingOverlay","suppressNoRowsOverlay","suppressAutoSize","suppressParentsInRowNodes","showToolPanel","suppressColumnMoveAnimation","suppressMovableColumns","suppressFieldDotNotation","enableRangeSelection","enableRangeHandle","enableFillHandle","suppressClearOnFillReduction","deltaSort","suppressTouch","suppressAsyncEvents","allowContextMenuWithControlKey","suppressContextMenu","suppressMenuFilterPanel","suppressMenuMainPanel","suppressMenuColumnPanel","rememberGroupStateWhenNewData","enableCellChangeFlash","suppressDragLeaveHidesColumns","suppressMiddleClickScrolls","suppressPreventDefaultOnMouseWheel","suppressUseColIdForGroups","suppressCopyRowsToClipboard","copyHeadersToClipboard","pivotMode","suppressAggFuncInHeader","suppressColumnVirtualisation","suppressAggAtRootLevel","suppressFocusAfterRefresh","functionsPassive","functionsReadOnly","animateRows","groupSelectsFiltered","groupRemoveSingleChildren","groupRemoveLowestSingleChildren","enableRtl","suppressClickEdit","rowDragManaged","suppressRowDrag","enableGroupEdit","embedFullWidthRows","deprecatedEmbedFullWidthRows","suppressTabbing","suppressPaginationPanel","floatingFilter","groupHideOpenParents","groupMultiAutoColumn","pagination","stopEditingWhenGridLosesFocus","paginationAutoPageSize","suppressScrollOnNewData","purgeClosedRowNodes","cacheQuickFilter","deltaRowDataMode","ensureDomOrder","accentedSort","pivotTotals","suppressChangeDetection","valueCache","valueCacheNeverExpires","aggregateOnlyChangedColumns","suppressAnimationFrame","suppressExcelExport","suppressCsvExport","treeData","masterDetail","suppressMultiRangeSelection","enterMovesDownAfterEdit","enterMovesDown","suppressPropertyNamesCheck","rowMultiSelectWithClick","contractColumnSelection","suppressEnterpriseResetOnNewColumns","enableOldSetFilterModel","suppressRowHoverHighlight","gridAutoHeight","suppressRowTransform","suppressClipboardPaste","serverSideSortingAlwaysResets","reactNext","suppressSetColumnStateEvents","enableCharts","deltaColumnMode","suppressMaintainUnsortedOrder","enableCellTextSelection","suppressBrowserResizeObserver","suppressMaxRenderedRowRestriction","excludeChildrenWhenTreeDataFiltering","keepDetailRows","paginateChildRows","preventDefaultOnContextMenu"],e.FUNCTION_PROPERTIES=["localeTextFunc","groupRowInnerRenderer","groupRowInnerRendererFramework","dateComponent","dateComponentFramework","groupRowRenderer","groupRowRendererFramework","isExternalFilterPresent","getRowHeight","doesExternalFilterPass","getRowClass","getRowStyle","getRowClassRules","traverseNode","getContextMenuItems","getMainMenuItems","processRowPostCreate","processCellForClipboard","getNodeChildDetails","groupRowAggNodes","getRowNodeId","isFullWidthCell","fullWidthCellRenderer","fullWidthCellRendererFramework","doesDataFlower","processSecondaryColDef","processSecondaryColGroupDef","getBusinessKeyForNode","sendToClipboard","navigateToNextCell","tabToNextCell","getDetailRowData","processCellFromClipboard","getDocument","postProcessPopup","getChildCount","getDataPath","loadingCellRenderer","loadingCellRendererFramework","loadingOverlayComponent","loadingOverlayComponentFramework","noRowsOverlayComponent","noRowsOverlayComponentFramework","detailCellRenderer","detailCellRendererFramework","defaultGroupSortComparator","isRowMaster","isRowSelectable","postSort","processHeaderForClipboard","paginationNumberFormatter","processDataFromClipboard","getServerSideGroupKey","isServerSideGroup","suppressKeyboardEvent","createChartContainer","processChartOptions","getChartToolbarItems","fillOperation"],e.ALL_PROPERTIES=z(e.ARRAY_PROPERTIES,e.OBJECT_PROPERTIES,e.STRING_PROPERTIES,e.NUMBER_PROPERTIES,e.FUNCTION_PROPERTIES,e.BOOLEAN_PROPERTIES),e.FRAMEWORK_PROPERTIES=["__ob__","__metadata__","mappedColumnProperties","hasChildColumns","toColDef","createColDefFromGridColumn"],e}(),K=function(){function e(){}return e.STRING_PROPERTIES=["headerName","columnGroupShow","headerClass","toolPanelClass","headerValueGetter","pivotKeys","groupId","colId","sort","field","type","tooltipComponent","tooltipField","headerTooltip","cellClass","showRowGroup","template","templateUrl","filter","aggFunc","cellRenderer","cellEditor","pinned","chartDataType"],e.OBJECT_PROPERTIES=["headerGroupComponent","headerGroupComponentFramework","headerGroupComponentParams","cellStyle","cellRendererParams","cellEditorFramework","cellEditorParams","pinnedRowCellRendererFramework","pinnedRowCellRendererParams","filterFramework","filterParams","pivotValueColumn","headerComponent","headerComponentFramework","headerComponentParams","floatingFilterComponent","floatingFilterComponentParams","floatingFilterComponentFramework","tooltipComponent","tooltipComponentParams","tooltipComponentFramework","refData"],e.ARRAY_PROPERTIES=["children","sortingOrder","allowedAggFuncs","menuTabs","pivotTotalColumnIds","cellClassRules","icons"],e.NUMBER_PROPERTIES=["sortedAt","width","minWidth","maxWidth","rowGroupIndex","pivotIndex"],e.BOOLEAN_PROPERTIES=["suppressCellFlash","suppressColumnsToolPanel","suppressFiltersToolPanel","openByDefault","marryChildren","hide","rowGroup","pivot","checkboxSelection","headerCheckboxSelection","headerCheckboxSelectionFilteredOnly","suppressMenu","suppressSorting","suppressMovable","suppressFilter","lockPosition","lockVisible","lockPinned","unSortIcon","suppressSizeToFit","suppressResize","suppressAutoSize","enableRowGroup","enablePivot","enableValue","editable","suppressPaste","suppressNavigable","enableCellChangeFlash","rowDrag","dndSource","autoHeight","sortable","resizable","singleClickEdit"],e.FUNCTION_PROPERTIES=["dndSourceOnRowDrag","valueGetter","valueSetter","filterValueGetter","keyCreator","cellRenderer","cellRendererFramework","pinnedRowCellRenderer","valueFormatter","pinnedRowValueFormatter","valueParser","comparator","equals","pivotComparator","suppressKeyboardEvent","colSpan","rowSpan","getQuickFilterText","newValueHandler","onCellValueChanged","onCellClicked","onCellDoubleClicked","onCellContextMenu","tooltip","tooltipValueGetter","tooltipComponent","tooltipComponentFramework","cellRendererSelector","cellEditorSelector"],e.ALL_PROPERTIES=e.ARRAY_PROPERTIES.concat(e.OBJECT_PROPERTIES).concat(e.STRING_PROPERTIES).concat(e.NUMBER_PROPERTIES).concat(e.FUNCTION_PROPERTIES).concat(e.BOOLEAN_PROPERTIES),e.FRAMEWORK_PROPERTIES=["__ob__","__metadata__","mappedColumnProperties","hasChildColumns","toColDef","createColDefFromGridColumn"],e}(),q=function(){function
(){}return e.parse=function(t){if(!t)return null;if(!0===t)return{toolPanels:[e.DEFAULT_COLUMN_COMP,e.DEFAULT_FILTER_COMP],defaultToolPanel:"columns"};if("string"==typeof t)return e.parse([t]);if(Array.isArray(t)){var o=[];return t.forEach((function(t){var i=e.DEFAULT_BY_KEY[t];i?o.push(i):console.warn("ag-grid: the key "+t+" is not a valid key for specifying a tool panel, valid keys are: "+Object.keys(e.DEFAULT_BY_KEY).join(","))})),0===o.length?null:{toolPanels:o,defaultToolPanel:o[0].id}}return{toolPanels:e.parseComponents(t.toolPanels),defaultToolPanel:t.defaultToolPanel,hiddenByDefault:t.hiddenByDefault,position:t.position}},e.parseComponents=function(t){var o=[];return t.forEach((function(t){var i=null;if("string"==typeof t){var n=e.DEFAULT_BY_KEY[t];if(!n)return void console.warn("ag-grid: the key "+t+" is not a valid key for specifying a tool panel, valid keys are: "+Object.keys(e.DEFAULT_BY_KEY).join(","));i=n}else i=t;o.push(i)})),o},e.DEFAULT_COLUMN_COMP={id:"columns",labelDefault:"Columns",labelKey:"columns",iconKey:"columns",toolPanel:"agColumnsToolPanel"},e.DEFAULT_FILTER_COMP={id:"filters",labelDefault:"Filters",labelKey:"filters",iconKey:"filter",toolPanel:"agFiltersToolPanel"},e.DEFAULT_BY_KEY={columns:e.DEFAULT_COLUMN_COMP,filters:e.DEFAULT_FILTER_COMP},e}(),Q=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},X=function(e,t){return function(o,i){t(o,i,e)}},$=function(){for(var e=0,t=0,o=arguments.length;t<o;t++)e+=arguments[t].length;var i=Array(e),n=0;for(t=0;t<o;t++)for(var r=arguments[t],s=0,a=r.length;s<a;s++,n++)i[n]=r[s];return i}; /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */function J(e){return!0===e||"true"===e}var Z=function(){function e(){this.propertyEventService=new b,this.domDataKey="__AG_"+Math.random().toString(),this.layoutElements=[]}var t;return t=e,e.prototype.agWire=function(e,t){this.gridOptions.api=e,this.gridOptions.columnApi=t,this.checkForDeprecated(),this.checkForViolations()},e.prototype.destroy=function(){this.gridOptions.api=null,this.gridOptions.columnApi=null},e.prototype.init=function(){!0!==this.gridOptions.suppressPropertyNamesCheck&&(this.checkGridOptionsProperties(),this.checkColumnDefProperties());var e=this.useAsyncEvents();this.eventService.addGlobalListener(this.globalEventHandler.bind(this),e),this.isGroupSelectsChildren()&&this.isSuppressParentsInRowNodes()&&console.warn("ag-Grid: 'groupSelectsChildren' does not work with 'suppressParentsInRowNodes', this selection method needs the part in rowNode to work"),this.isGroupSelectsChildren()&&(this.isRowSelectionMulti()||console.warn("ag-Grid: rowSelection must be 'multiple' for groupSelectsChildren to make sense"),this.isRowModelServerSide()&&console.warn("ag-Grid: group selects children is NOT support for Server Side Row Model. This is because the rows are lazy loaded, so selecting a group is not possible asthe grid has no way of knowing what the children are.")),this.isGroupRemoveSingleChildren()&&this.isGroupHideOpenParents()&&console.warn("ag-Grid: groupRemoveSingleChildren and groupHideOpenParents do not work with each other, you need to pick one. And don't ask us how to us these together on our support forum either you will get the same answer!"),this.isEnableRangeSelection()&&P.assertRegistered(R.RangeSelectionModule,"enableRangeSelection"),this.isEnableRangeSelection()||!this.isEnableRangeHandle()&&!this.isEnableFillHandle()||console.warn("ag-Grid: 'enableRangeHandle' and 'enableFillHandle' will not work unless 'enableRangeSelection' is set to true"),this.addEventListener(t.PROP_DOM_LAYOUT,this.updateLayoutClasses.bind(this))},e.prototype.checkColumnDefProperties=function(){var e=this;null!=this.gridOptions.columnDefs&&this.gridOptions.columnDefs.forEach((function(t){var o=Object.getOwnPropertyNames(t),i=$(K.ALL_PROPERTIES,K.FRAMEWORK_PROPERTIES);e.checkProperties(o,i,i,"colDef","https://www.ag-grid.com/javascript-grid-column-properties/")}))},e.prototype.checkGridOptionsProperties=function(){var e=Object.getOwnPropertyNames(this.gridOptions),t=$(Y.ALL_PROPERTIES,Y.FRAMEWORK_PROPERTIES,p.values(M).map((function(e){return te.getCallbackForEvent(e)}))),o=$(t,["api","columnApi"]);this.checkProperties(e,o,t,"gridOptions","https://www.ag-grid.com/javascript-grid-properties/")},e.prototype.checkProperties=function(e,t,o,i,n){var r=p.fuzzyCheckStrings(e,t,o);p.iterateObject(r,(function(e,t){console.warn("ag-grid: invalid "+i+" property '"+e+"' did you mean any of these: "+t.slice(0,8).join(", "))})),Object.keys(r).length>0&&console.warn("ag-grid: to see all the valid "+i+" properties please check: "+n)},e.prototype.getDomData=function(e,t){var o=e[this.domDataKey];return o?o[t]:void 0},e.prototype.setDomData=function(e,t,o){var i=e[this.domDataKey];p.missing(i)&&(i={},e[this.domDataKey]=i),i[t]=o},e.prototype.isRowSelection=function(){return"single"===this.gridOptions.rowSelection||"multiple"===this.gridOptions.rowSelection},e.prototype.isRowDeselection=function(){return J(this.gridOptions.rowDeselection)},e.prototype.isRowSelectionMulti=function(){return"multiple"===this.gridOptions.rowSelection},e.prototype.isRowMultiSelectWithClick=function(){return J(this.gridOptions.rowMultiSelectWithClick)},e.prototype.getContext=function(){return this.gridOptions.context},e.prototype.isPivotMode=function(){return J(this.gridOptions.pivotMode)},e.prototype.isPivotTotals=function(){return J(this.gridOptions.pivotTotals)},e.prototype.getPivotColumnGroupTotals=function(){return this.gridOptions.pivotColumnGroupTotals},e.prototype.getPivotRowTotals=function(){return this.gridOptions.pivotRowTotals},e.prototype.isRowModelInfinite=function(){return this.gridOptions.rowModelType===o.ROW_MODEL_TYPE_INFINITE},e.prototype.isRowModelViewport=function(){return this.gridOptions.rowModelType===o.ROW_MODEL_TYPE_VIEWPORT},e.prototype.isRowModelServerSide=function(){return this.gridOptions.rowModelType===o.ROW_MODEL_TYPE_SERVER_SIDE},e.prototype.isRowModelDefault=function(){return p.missing(this.gridOptions.rowModelType)||this.gridOptions.rowModelType===o.ROW_MODEL_TYPE_CLIENT_SIDE||this.gridOptions.rowModelType===o.DEPRECATED_ROW_MODEL_TYPE_NORMAL},e.prototype.isFullRowEdit=function(){return"fullRow"===this.gridOptions.editType},e.prototype.isSuppressFocusAfterRefresh=function(){return J(this.gridOptions.suppressFocusAfterRefresh)},e.prototype.isSuppressBrowserResizeObserver=function(){return J(this.gridOptions.suppressBrowserResizeObserver)},e.prototype.isSuppressMaintainUnsortedOrder=function(){return J(this.gridOptions.suppressMaintainUnsortedOrder)},e.prototype.isSuppressClearOnFillReduction=function(){return J(this.gridOptions.suppressClearOnFillReduction)},e.prototype.isShowToolPanel=function(){return J(this.gridOptions.sideBar&&Array.isArray(this.getSideBar().toolPanels))},e.prototype.getSideBar=function(){return this.gridOptions.sideBar},e.prototype.isSuppressTouch=function(){return J(this.gridOptions.suppressTouch)},e.prototype.isSuppressRowTransform=function(){return J(this.gridOptions.suppressRowTransform)},e.prototype.isSuppressSetColumnStateEvents=function(){return J(this.gridOptions.suppressSetColumnStateEvents)},e.prototype.isAllowDragFromColumnsToolPanel=function(){return J(this.gridOptions.allowDragFromColumnsToolPanel)},e.prototype.useAsyncEvents=function(){return!J(this.gridOptions.suppressAsyncEvents)},e.prototype.isEnableCellChangeFlash=function(){return J(this.gridOptions.enableCellChangeFlash)},e.prototype.isGroupSelectsChildren=function(){var e=J(this.gridOptions.groupSelectsChildren);return e&&this.isTreeData()?(console.warn("ag-Grid: groupSelectsChildren does not work with tree data"),!1):e},e.prototype.isSuppressRowHoverHighlight=function(){return J(this.gridOptions.suppressRowHoverHighlight)},e.prototype.isGroupSelectsFiltered=function(){return J(this.gridOptions.groupSelectsFiltered)},e.prototype.isGroupHideOpenParents=function(){return J(this.gridOptions.groupHideOpenParents)},e.prototype.isGroupMultiAutoColumn=function(){return J(this.gridOptions.groupMultiAutoColumn)||J(this.gridOptions.groupHideOpenParents)},e.prototype.isGroupRemoveSingleChildren=function(){return J(this.gridOptions.groupRemoveSingleChildren)},e.prototype.isGroupRemoveLowestSingleChildren=function(){return J(this.gridOptions.groupRemoveLowestSingleChildren)},e.prototype.isGroupIncludeFooter=function(){return J(this.gridOptions.groupIncludeFooter)},e.prototype.isGroupIncludeTotalFooter=function(){return J(this.gridOptions.groupIncludeTotalFooter)},e.prototype.isGroupSuppressBlankHeader=function(){return J(this.gridOptions.groupSuppressBlankHeader)},e.prototype.isSuppressRowClickSelection=function(){return J(this.gridOptions.suppressRowClickSelection)},e.prototype.isSuppressCellSelection=function(){return J(this.gridOptions.suppressCellSelection)},e.prototype.isSuppressMultiSort=function(){return J(this.gridOptions.suppressMultiSort)},e.prototype.isMultiSortKeyCtrl=function(){return"ctrl"===this.gridOptions.multiSortKey},e.prototype.isGroupSuppressAutoColumn=function(){return J(this.gridOptions.groupSuppressAutoColumn)},e.prototype.isSuppressDragLeaveHidesColumns=function(){return J(this.gridOptions.suppressDragLeaveHidesColumns)},e.prototype.isSuppressScrollOnNewData=function(){return J(this.gridOptions.suppressScrollOnNewData)},e.prototype.isRowDragManaged=function(){return J(this.gridOptions.rowDragManaged)},e.prototype.isSuppressRowDrag=function(){return J(this.gridOptions.suppressRowDrag)},e.prototype.getDomLayout=function(){var e=this.gridOptions.domLayout||o.DOM_LAYOUT_NORMAL;return-1===[o.DOM_LAYOUT_PRINT,o.DOM_LAYOUT_AUTO_HEIGHT,o.DOM_LAYOUT_NORMAL].indexOf(e)?(p.doOnce((function(){return console.warn("ag-Grid: "+e+" is not valid for DOM Layout, valid values are "+o.DOM_LAYOUT_NORMAL+", "+o.DOM_LAYOUT_AUTO_HEIGHT+" and "+o.DOM_LAYOUT_PRINT)}),"warn about dom layout values"),o.DOM_LAYOUT_NORMAL):e},e.prototype.isSuppressHorizontalScroll=function(){return J(this.gridOptions.suppressHorizontalScroll)},e.prototype.isSuppressMaxRenderedRowRestriction=function(){return J(this.gridOptions.suppressMaxRenderedRowRestriction)},e.prototype.isExcludeChildrenWhenTreeDataFiltering=function(){return J(this.gridOptions.excludeChildrenWhenTreeDataFiltering)},e.prototype.isAlwaysShowVerticalScroll=function(){return J(this.gridOptions.alwaysShowVerticalScroll)},e.prototype.isSuppressLoadingOverlay=function(){return J(this.gridOptions.suppressLoadingOverlay)},e.prototype.isSuppressNoRowsOverlay=function(){return J(this.gridOptions.suppressNoRowsOverlay)},e.prototype.isSuppressFieldDotNotation=function(){return J(this.gridOptions.suppressFieldDotNotation)},e.prototype.getPinnedTopRowData=function(){return this.gridOptions.pinnedTopRowData},e.prototype.getPinnedBottomRowData=function(){return this.gridOptions.pinnedBottomRowData},e.prototype.isFunctionsPassive=function(){return J(this.gridOptions.functionsPassive)},e.prototype.isSuppressTabbing=function(){return J(this.gridOptions.suppressTabbing)},e.prototype.isSuppressChangeDetection=function(){return J(this.gridOptions.suppressChangeDetection)},e.prototype.isSuppressAnimationFrame=function(){return J(this.gridOptions.suppressAnimationFrame)},e.prototype.getQuickFilterText=function(){return this.gridOptions.quickFilterText},e.prototype.isCacheQuickFilter=function(){return J(this.gridOptions.cacheQuickFilter)},e.prototype.isUnSortIcon=function(){return J(this.gridOptions.unSortIcon)},e.prototype.isSuppressMenuHide=function(){return J(this.gridOptions.suppressMenuHide)},e.prototype.isEnterMovesDownAfterEdit=function(){return J(this.gridOptions.enterMovesDownAfterEdit)},e.prototype.isEnterMovesDown=function(){return J(this.gridOptions.enterMovesDown)},e.prototype.getRowStyle=function(){return this.gridOptions.rowStyle},e.prototype.getRowClass=function(){return this.gridOptions.rowClass},e.prototype.getRowStyleFunc=function(){return this.gridOptions.getRowStyle},e.prototype.getRowClassFunc=function(){return this.gridOptions.getRowClass},e.prototype.rowClassRules=function(){return this.gridOptions.rowClassRules},e.prototype.getCreateChartContainerFunc=function(){return this.gridOptions.createChartContainer},e.prototype.getPopupParent=function(){return this.gridOptions.popupParent},e.prototype.getBlockLoadDebounceMillis=function(){return this.gridOptions.blockLoadDebounceMillis},e.prototype.getPostProcessPopupFunc=function(){return this.gridOptions.postProcessPopup},e.prototype.getDoesDataFlowerFunc=function(){return this.gridOptions.doesDataFlower},e.prototype.getPaginationNumberFormatterFunc=function(){return this.gridOptions.paginationNumberFormatter},e.prototype.getChildCountFunc=function(){return this.gridOptions.getChildCount},e.prototype.getDefaultGroupSortComparator=function(){return this.gridOptions.defaultGroupSortComparator},e.prototype.getIsFullWidthCellFunc=function(){return this.gridOptions.isFullWidthCell},e.prototype.getFullWidthCellRendererParams=function(){return this.gridOptions.fullWidthCellRendererParams},e.prototype.isEmbedFullWidthRows=function(){return J(this.gridOptions.embedFullWidthRows)||J(this.gridOptions.deprecatedEmbedFullWidthRows)},e.prototype.getSuppressKeyboardEventFunc=function(){return this.gridOptions.suppressKeyboardEvent},e.prototype.getBusinessKeyForNodeFunc=function(){return this.gridOptions.getBusinessKeyForNode},e.prototype.getApi=function(){return this.gridOptions.api},e.prototype.getColumnApi=function(){return this.gridOptions.columnApi},e.prototype.isDeltaRowDataMode=function(){return J(this.gridOptions.deltaRowDataMode)},e.prototype.isDeltaColumnMode=function(){return J(this.gridOptions.deltaColumnMode)},e.prototype.isEnsureDomOrder=function(){return J(this.gridOptions.ensureDomOrder)},e.prototype.isEnableCharts=function(){return!!J(this.gridOptions.enableCharts)&&P.assertRegistered(R.GridChartsModule,"enableCharts")},e.prototype.getColResizeDefault=function(){return this.gridOptions.colResizeDefault},e.prototype.isSingleClickEdit=function(){return J(this.gridOptions.singleClickEdit)},e.prototype.isSuppressClickEdit=function(){return J(this.gridOptions.suppressClickEdit)},e.prototype.isStopEditingWhenGridLosesFocus=function(){return J(this.gridOptions.stopEditingWhenGridLosesFocus)},e.prototype.getGroupDefaultExpanded=function(){return this.gridOptions.groupDefaultExpanded},e.prototype.getMaxConcurrentDatasourceRequests=function(){return this.gridOptions.maxConcurrentDatasourceRequests},e.prototype.getMaxBlocksInCache=function(){return this.gridOptions.maxBlocksInCache},e.prototype.getCacheOverflowSize=function(){return this.gridOptions.cacheOverflowSize},e.prototype.getPaginationPageSize=function(){return this.gridOptions.paginationPageSize},e.prototype.isPaginateChildRows=function(){return!!(this.isGroupSuppressRow()||this.isGroupRemoveSingleChildren()||this.isGroupRemoveLowestSingleChildren())||J(this.gridOptions.paginateChildRows)},e.prototype.getCacheBlockSize=function(){return this.gridOptions.cacheBlockSize},e.prototype.getInfiniteInitialRowCount=function(){return this.gridOptions.infiniteInitialRowCount},e.prototype.isPurgeClosedRowNodes=function(){return J(this.gridOptions.purgeClosedRowNodes)},e.prototype.isSuppressPaginationPanel=function(){return J(this.gridOptions.suppressPaginationPanel)},e.prototype.getRowData=function(){return this.gridOptions.rowData},e.prototype.isGroupUseEntireRow=function(e){return!e&&J(this.gridOptions.groupUseEntireRow)},e.prototype.isEnableRtl=function(){return J(this.gridOptions.enableRtl)},e.prototype.getAutoGroupColumnDef=function(){return this.gridOptions.autoGroupColumnDef},e.prototype.isGroupSuppressRow=function(){return J(this.gridOptions.groupSuppressRow)},e.prototype.getRowGroupPanelShow=function(){return this.gridOptions.rowGroupPanelShow},e.prototype.getPivotPanelShow=function(){return this.gridOptions.pivotPanelShow},e.prototype.isAngularCompileRows=function(){return J(this.gridOptions.angularCompileRows)},e.prototype.isAngularCompileFilters=function(){return J(this.gridOptions.angularCompileFilters)},e.prototype.isAngularCompileHeaders=function(){return J(this.gridOptions.angularCompileHeaders)},e.prototype.isDebug=function(){return J(this.gridOptions.debug)},e.prototype.getColumnDefs=function(){return this.gridOptions.columnDefs},e.prototype.getColumnTypes=function(){return this.gridOptions.columnTypes},e.prototype.getDatasource=function(){return this.gridOptions.datasource},e.prototype.getViewportDatasource=function(){return this.gridOptions.viewportDatasource},e.prototype.getServerSideDatasource=function(){return this.gridOptions.serverSideDatasource},e.prototype.isAccentedSort=function(){return J(this.gridOptions.accentedSort)},e.prototype.isEnableBrowserTooltips=function(){return J(this.gridOptions.enableBrowserTooltips)},e.prototype.isEnableCellExpressions=function(){return J(this.gridOptions.enableCellExpressions)},e.prototype.isEnableGroupEdit=function(){return J(this.gridOptions.enableGroupEdit)},e.prototype.isSuppressMiddleClickScrolls=function(){return J(this.gridOptions.suppressMiddleClickScrolls)},e.prototype.isPreventDefaultOnContextMenu=function(){return J(this.gridOptions.preventDefaultOnContextMenu)},e.prototype.isSuppressPreventDefaultOnMouseWheel=function(){return J(this.gridOptions.suppressPreventDefaultOnMouseWheel)},e.prototype.isSuppressColumnVirtualisation=function(){return J(this.gridOptions.suppressColumnVirtualisation)},e.prototype.isSuppressContextMenu=function(){return J(this.gridOptions.suppressContextMenu)},e.prototype.isAllowContextMenuWithControlKey=function(){return J(this.gridOptions.allowContextMenuWithControlKey)},e.prototype.isSuppressCopyRowsToClipboard=function(){return J(this.gridOptions.suppressCopyRowsToClipboard)},e.prototype.isCopyHeadersToClipboard=function(){return J(this.gridOptions.copyHeadersToClipboard)},e.prototype.isSuppressClipboardPaste=function(){return J(this.gridOptions.suppressClipboardPaste)},e.prototype.isPagination=function(){return J(this.gridOptions.pagination)},e.prototype.isSuppressEnterpriseResetOnNewColumns=function(){return J(this.gridOptions.suppressEnterpriseResetOnNewColumns)},e.prototype.getProcessDataFromClipboardFunc=function(){return this.gridOptions.processDataFromClipboard},e.prototype.getBatchUpdateWaitMillis=function(){return p.exists(this.gridOptions.batchUpdateWaitMillis)?this.gridOptions.batchUpdateWaitMillis:o.BATCH_WAIT_MILLIS},e.prototype.isSuppressMovableColumns=function(){return J(this.gridOptions.suppressMovableColumns)},e.prototype.isAnimateRows=function(){return!this.isEnsureDomOrder()&&J(this.gridOptions.animateRows)},e.prototype.isSuppressColumnMoveAnimation=function(){return J(this.gridOptions.suppressColumnMoveAnimation)},e.prototype.isSuppressAggFuncInHeader=function(){return J(this.gridOptions.suppressAggFuncInHeader)},e.prototype.isSuppressAggAtRootLevel=function(){return J(this.gridOptions.suppressAggAtRootLevel)},e.prototype.isEnableRangeSelection=function(){return P.isRegistered(R.RangeSelectionModule)&&J(this.gridOptions.enableRangeSelection)},e.prototype.isEnableRangeHandle=function(){return J(this.gridOptions.enableRangeHandle)},e.prototype.isEnableFillHandle=function(){return J(this.gridOptions.enableFillHandle)},e.prototype.getFillOperation=function(){return this.gridOptions.fillOperation},e.prototype.isSuppressMultiRangeSelection=function(){return J(this.gridOptions.suppressMultiRangeSelection)},e.prototype.isPaginationAutoPageSize=function(){return J(this.gridOptions.paginationAutoPageSize)},e.prototype.isRememberGroupStateWhenNewData=function(){return J(this.gridOptions.rememberGroupStateWhenNewData)},e.prototype.getIcons=function(){return this.gridOptions.icons},e.prototype.getAggFuncs=function(){return this.gridOptions.aggFuncs},e.prototype.getSortingOrder=function(){return this.gridOptions.sortingOrder},e.prototype.getAlignedGrids=function(){return this.gridOptions.alignedGrids},e.prototype.isMasterDetail=function(){return!!J(this.gridOptions.masterDetail)&&P.assertRegistered(R.MasterDetailModule,"masterDetail")},e.prototype.isKeepDetailRows=function(){return J(this.gridOptions.keepDetailRows)},e.prototype.getKeepDetailRowsCount=function(){return this.gridOptions.keepDetailRowsCount>0?this.gridOptions.keepDetailRowsCount:10},e.prototype.getIsRowMasterFunc=function(){return this.gridOptions.isRowMaster},e.prototype.getIsRowSelectableFunc=function(){return this.gridOptions.isRowSelectable},e.prototype.getGroupRowRendererParams=function(){return this.gridOptions.groupRowRendererParams},e.prototype.getOverlayLoadingTemplate=function(){return this.gridOptions.overlayLoadingTemplate},e.prototype.getOverlayNoRowsTemplate=function(){return this.gridOptions.overlayNoRowsTemplate},e.prototype.isSuppressAutoSize=function(){return J(this.gridOptions.suppressAutoSize)},e.prototype.isEnableCellTextSelection=function(){return J(this.gridOptions.enableCellTextSelection)},e.prototype.isSuppressParentsInRowNodes=function(){return J(this.gridOptions.suppressParentsInRowNodes)},e.prototype.isFunctionsReadOnly=function(){return J(this.gridOptions.functionsReadOnly)},e.prototype.isFloatingFilter=function(){return this.gridOptions.floatingFilter},e.prototype.isEnableCellTextSelect=function(){return J(this.gridOptions.enableCellTextSelection)},e.prototype.isEnableOldSetFilterModel=function(){return J(this.gridOptions.enableOldSetFilterModel)},e.prototype.getDefaultColDef=function(){return this.gridOptions.defaultColDef},e.prototype.getDefaultColGroupDef=function(){return this.gridOptions.defaultColGroupDef},e.prototype.getDefaultExportParams=function(){return this.gridOptions.defaultExportParams},e.prototype.isSuppressCsvExport=function(){return J(this.gridOptions.suppressCsvExport)},e.prototype.isAllowShowChangeAfterFilter=function(){return J(this.gridOptions.allowShowChangeAfterFilter)},e.prototype.isSuppressExcelExport=function(){return J(this.gridOptions.suppressExcelExport)},e.prototype.isSuppressMakeColumnVisibleAfterUnGroup=function(){return J(this.gridOptions.suppressMakeColumnVisibleAfterUnGroup)},e.prototype.getNodeChildDetailsFunc=function(){return this.gridOptions.getNodeChildDetails},e.prototype.getDataPathFunc=function(){return this.gridOptions.getDataPath},e.prototype.getIsServerSideGroupFunc=function(){return this.gridOptions.isServerSideGroup},e.prototype.getServerSideGroupKeyFunc=function(){return this.gridOptions.getServerSideGroupKey},e.prototype.getGroupRowAggNodesFunc=function(){return this.gridOptions.groupRowAggNodes},e.prototype.getContextMenuItemsFunc=function(){return this.gridOptions.getContextMenuItems},e.prototype.getMainMenuItemsFunc=function(){return this.gridOptions.getMainMenuItems},e.prototype.getChartToolbarItemsFunc=function(){return this.gridOptions.getChartToolbarItems},e.prototype.getRowNodeIdFunc=function(){return this.gridOptions.getRowNodeId},e.prototype.getNavigateToNextCellFunc=function(){return this.gridOptions.navigateToNextCell},e.prototype.getTabToNextCellFunc=function(){return this.gridOptions.tabToNextCell},e.prototype.isTreeData=function(){return!!J(this.gridOptions.treeData)&&P.assertRegistered(R.RowGroupingModule,"Tree Data")},e.prototype.isValueCache=function(){return J(this.gridOptions.valueCache)},e.prototype.isValueCacheNeverExpires=function(){return J(this.gridOptions.valueCacheNeverExpires)},e.prototype.isDeltaSort=function(){return J(this.gridOptions.deltaSort)},e.prototype.isAggregateOnlyChangedColumns=function(){return J(this.gridOptions.aggregateOnlyChangedColumns)},e.prototype.getProcessSecondaryColDefFunc=function(){return this.gridOptions.processSecondaryColDef},e.prototype.getProcessSecondaryColGroupDefFunc=function(){return this.gridOptions.processSecondaryColGroupDef},e.prototype.getSendToClipboardFunc=function(){return this.gridOptions.sendToClipboard},e.prototype.getProcessRowPostCreateFunc=function(){return this.gridOptions.processRowPostCreate},e.prototype.getProcessCellForClipboardFunc=function(){return this.gridOptions.processCellForClipboard},e.prototype.getProcessHeaderForClipboardFunc=function(){return this.gridOptions.processHeaderForClipboard},e.prototype.getProcessCellFromClipboardFunc=function(){return this.gridOptions.processCellFromClipboard},e.prototype.getViewportRowModelPageSize=function(){return e=this.gridOptions.viewportRowModelPageSize,t=5,e>0?e:t;var e,t},e.prototype.getViewportRowModelBufferSize=function(){return e=this.gridOptions.viewportRowModelBufferSize,t=5,e>=0?e:t;var e,t},e.prototype.isServerSideSortingAlwaysResets=function(){return J(this.gridOptions.serverSideSortingAlwaysResets)},e.prototype.getPostSortFunc=function(){return this.gridOptions.postSort},e.prototype.getProcessChartOptionsFunc=function(){return this.gridOptions.processChartOptions},e.prototype.getClipboardDeliminator=function(){return p.exists(this.gridOptions.clipboardDeliminator)?this.gridOptions.clipboardDeliminator:"\t"},e.prototype.setProperty=function(e,t){var o=this.gridOptions,i=o[e];if(i!==t){o[e]=t;var n={type:e,currentValue:t,previousValue:i};this.propertyEventService.dispatchEvent(n)}},e.prototype.addLayoutElement=function(e){this.layoutElements.push(e),this.updateLayoutClasses()},e.prototype.updateLayoutClasses=function(){var e=this.getDomLayout(),t=e===o.DOM_LAYOUT_AUTO_HEIGHT,i=e===o.DOM_LAYOUT_PRINT,n=e===o.DOM_LAYOUT_NORMAL;this.layoutElements.forEach((function(e){p.addOrRemoveCssClass(e,"ag-layout-auto-height",t),p.addOrRemoveCssClass(e,"ag-layout-normal",n),p.addOrRemoveCssClass(e,"ag-layout-print",i)}))},e.prototype.addEventListener=function(e,o){t.checkEventDeprecation(e),this.propertyEventService.addEventListener(e,o)},e.checkEventDeprecation=function(e){"floatingRowDataChanged"===e&&console.warn("ag-Grid: floatingRowDataChanged is now called pinnedRowDataChanged")},e.prototype.removeEventListener=function(e,t){this.propertyEventService.removeEventListener(e,t)},e.prototype.getAutoSizePadding=function(){return this.gridOptions.autoSizePadding&&this.gridOptions.autoSizePadding>0?this.gridOptions.autoSizePadding:20},e.prototype.getHeaderHeight=function(){return"number"==typeof this.gridOptions.headerHeight?this.gridOptions.headerHeight:this.specialForNewMaterial(25,"headerHeight")},e.prototype.getFloatingFiltersHeight=function(){return"number"==typeof this.gridOptions.floatingFiltersHeight?this.gridOptions.floatingFiltersHeight:this.specialForNewMaterial(25,"headerHeight")},e.prototype.getGroupHeaderHeight=function(){return"number"==typeof this.gridOptions.groupHeaderHeight?this.gridOptions.groupHeaderHeight:this.getHeaderHeight()},e.prototype.getPivotHeaderHeight=function(){return"number"==typeof this.gridOptions.pivotHeaderHeight?this.gridOptions.pivotHeaderHeight:this.getHeaderHeight()},e.prototype.getPivotGroupHeaderHeight=function(){return"number"==typeof this.gridOptions.pivotGroupHeaderHeight?this.gridOptions.pivotGroupHeaderHeight:this.getGroupHeaderHeight()},e.prototype.isExternalFilterPresent=function(){return"function"==typeof this.gridOptions.isExternalFilterPresent&&this.gridOptions.isExternalFilterPresent()},e.prototype.doesExternalFilterPass=function(e){return"function"==typeof this.gridOptions.doesExternalFilterPass&&this.gridOptions.doesExternalFilterPass(e)},e.prototype.getDocument=function(){var e=null;return this.gridOptions.getDocument&&p.exists(this.gridOptions.getDocument)&&(e=this.gridOptions.getDocument()),e&&p.exists(e)?e:document},e.prototype.getMinColWidth=function(){return this.gridOptions.minColWidth&&this.gridOptions.minColWidth>t.MIN_COL_WIDTH?this.gridOptions.minColWidth:t.MIN_COL_WIDTH},e.prototype.getMaxColWidth=function(){return this.gridOptions.maxColWidth&&this.gridOptions.maxColWidth>t.MIN_COL_WIDTH?this.gridOptions.maxColWidth:null},e.prototype.getColWidth=function(){return"number"!=typeof this.gridOptions.colWidth||this.gridOptions.colWidth<t.MIN_COL_WIDTH?200:this.gridOptions.colWidth},e.prototype.getRowBuffer=function(){var e=this.gridOptions.rowBuffer;return"number"==typeof e?e<0&&(p.doOnce((function(){return console.warn("ag-Grid: rowBuffer should not be negative")}),"warn rowBuffer negative"),this.gridOptions.rowBuffer=e=0):e=o.ROW_BUFFER_SIZE,e},e.prototype.getRowBufferInPixels=function(){return this.getRowBuffer()*this.getRowHeightAsNumber()},e.prototype.getScrollbarWidth=function(){if(null==this.scrollWidth){var e="number"==typeof this.gridOptions.scrollbarWidth&&this.gridOptions.scrollbarWidth>=0;this.scrollWidth=e?this.gridOptions.scrollbarWidth:p.getScrollbarWidth()}return this.scrollWidth},e.prototype.checkForDeprecated=function(){var e=this,t=this.gridOptions;t.suppressUnSort&&console.warn("ag-grid: as of v1.12.4 suppressUnSort is not used. Please use sortingOrder instead."),t.suppressDescSort&&console.warn("ag-grid: as of v1.12.4 suppressDescSort is not used. Please use sortingOrder instead."),t.groupAggFields&&console.warn("ag-grid: as of v3 groupAggFields is not used. Please add appropriate agg fields to your columns."),t.groupHidePivotColumns&&console.warn("ag-grid: as of v3 groupHidePivotColumns is not used as pivot columns are now called rowGroup columns. Please refer to the documentation"),t.groupKeys&&console.warn("ag-grid: as of v3 groupKeys is not used. You need to set rowGroupIndex on the columns to group. Please refer to the documentation"),"boolean"==typeof t.groupDefaultExpanded&&console.warn("ag-grid: groupDefaultExpanded can no longer be boolean. for groupDefaultExpanded=true, use groupDefaultExpanded=9999 instead, to expand all the groups"),(t.onRowDeselected||t.rowDeselected)&&console.warn("ag-grid: since version 3.4 event rowDeselected no longer exists, please check the docs"),t.rowsAlreadyGrouped&&console.warn("ag-grid: since version 3.4 rowsAlreadyGrouped no longer exists, please use getNodeChildDetails() instead"),t.groupAggFunction&&console.warn("ag-grid: since version 4.3.x groupAggFunction is now called groupRowAggNodes"),t.checkboxSelection&&console.warn("ag-grid: since version 8.0.x checkboxSelection is not supported as a grid option. If you want this on all columns, use defaultColDef instead and set it there"),t.paginationInitialRowCount&&console.warn("ag-grid: since version 9.0.x paginationInitialRowCount is now called infiniteInitialRowCount"),t.infinitePageSize&&console.warn("ag-grid: since version 9.0.x infinitePageSize is now called cacheBlockSize"),t.infiniteBlockSize&&console.warn("ag-grid: since version 10.0.x infiniteBlockSize is now called cacheBlockSize"),t.maxPagesInCache&&console.warn("ag-grid: since version 10.0.x maxPagesInCache is now called maxBlocksInCache"),t.paginationOverflowSize&&console.warn("ag-grid: since version 10.0.x paginationOverflowSize is now called cacheOverflowSize"),t.suppressMenuFilterPanel&&console.warn("ag-grid: since version 11.0.x, use property colDef.menuTabs=['generalMenuTab','columnsMenuTab'] instead of suppressMenuFilterPanel=true"),t.suppressMenuMainPanel&&console.warn("ag-grid: since version 11.0.x, use property colDef.menuTabs=['filterMenuTab','columnsMenuTab'] instead of suppressMenuMainPanel=true"),t.suppressMenuColumnPanel&&console.warn("ag-grid: since version 11.0.x, use property colDef.menuTabs=['generalMenuTab','filterMenuTab'] instead of suppressMenuColumnPanel=true"),t.suppressUseColIdForGroups&&console.warn("ag-grid: since version 11.0.x, this is not in use anymore. You should be able to remove it from your definition"),t.groupSuppressRow&&console.warn("ag-grid: since version 18.2.x, 'groupSuppressRow' should not be used anymore. Instead remove row groups and perform custom sorting."),t.groupColumnDef&&console.warn("ag-grid: since version 11.0.x, groupColumnDef has been renamed, this property is now called autoGroupColumnDef. Please change your configuration accordingly"),t.slaveGrids&&console.warn("ag-grid: since version 12.x, slaveGrids has been renamed, this property is now called alignedGrids. Please change your configuration accordingly"),t.floatingTopRowData&&console.warn("ag-grid: since version 12.x, floatingTopRowData is now called pinnedTopRowData"),t.floatingBottomRowData&&console.warn("ag-grid: since version 12.x, floatingBottomRowData is now called pinnedBottomRowData"),t.paginationStartPage&&console.warn("ag-grid: since version 12.x, paginationStartPage is gone, please call api.paginationGoToPage("+t.paginationStartPage+") instead."),t.getHeaderCellTemplate&&console.warn("ag-grid: since version 15.x, getHeaderCellTemplate is gone, please check the header documentation on how to set header templates."),t.headerCellTemplate&&console.warn("ag-grid: since version 15.x, headerCellTemplate is gone, please check the header documentation on how to set header templates."),t.headerCellRenderer&&console.warn("ag-grid: since version 15.x, headerCellRenderer is gone, please check the header documentation on how to set header templates."),t.angularCompileHeaders&&console.warn("ag-grid: since version 15.x, angularCompileHeaders is gone, please see the getting started for Angular 1 docs to see how to do headers in Angular 1.x."),t.pivotTotals&&(console.warn("ag-grid: since version 18.x, pivotTotals has been removed, instead if using pivotTotals, set pivotColumnGroupTotals='before'|'after'."),t.pivotColumnGroupTotals="before"),"inMemory"===t.rowModelType&&(console.warn("ag-grid: since version 18.x, The In Memory Row Model has been renamed to the Client Side Row Model, set rowModelType='clientSide' instead."),t.rowModelType="clientSide"),"enterprise"===t.rowModelType&&(console.warn("ag-grid: since version 18.x, The Enterprise Row Model has been renamed to the Server Side Row Model, set rowModelType='serverSide' instead."),t.rowModelType="serverSide"),t.layoutInterval&&console.warn("ag-grid: since version 18.x, layoutInterval is no longer a property. This is because the grid now uses CSS Flex for layout."),t.gridAutoHeight&&(console.warn("ag-grid: since version 19.x, gridAutoHeight is gone, please use domLayout=autoHeight instead"),t.domLayout="autoHeight"),!0===t.showToolPanel&&(console.warn("ag-grid: since version 19.x, showToolPanel is gone, please specify toolPanel components. See https://www.ag-grid.com/javascript-grid-tool-panel/"),t.showToolPanel=void 0,t.sideBar=t.sideBar||!0),!1===t.showToolPanel&&(console.warn("ag-grid: since version 19.x, showToolPanel is gone, please specify toolPanel components. See https://www.ag-grid.com/javascript-grid-tool-panel/"),t.showToolPanel=void 0,t.sideBar=t.sideBar||!1);var o={toolPanelSuppressRowGroups:"suppressRowGroups",toolPanelSuppressValues:"suppressValues",toolPanelSuppressPivots:"suppressPivots",toolPanelSuppressPivotMode:"suppressPivotMode",toolPanelSuppressColumnFilter:"suppressColumnFilter",toolPanelSuppressColumnSelectAll:"suppressColumnSelectAll",toolPanelSuppressSideButtons:"suppressSideButtons",toolPanelSuppressColumnExpandAll:"suppressColumnExpandAll",contractColumnSelection:"contractColumnSelection"},i={};Object.keys(o).forEach((function(t){var n=o[t],r=e.gridOptions[t];if(void 0!==r){if("toolPanelSuppressSideButtons"===t)return void console.warn("ag-grid: since v19.0 toolPanelSuppressSideButtons has been completely removed. See https://www.ag-grid.com/javascript-grid-tool-panel/");console.warn("ag-grid: since v19.0 gridOptions."+t+" is deprecated, please use gridOptions.sideBar.toolPanel[columnsIndex].componentParams."+n),i[n]=r}})),Object.keys(i).length>0&&!p.exists(t.sideBar)&&(console.warn("ag-grid: since version 19.x, sideBar is mandatory if using toolPanel related properties. See https://www.ag-grid.com/javascript-grid-tool-panel/"),t.sideBar=!0),null!=t.sideBar&&(t.sideBar=q.parse(t.sideBar));var n=this.gridOptions.sideBar;if(Object.keys(i).length>0&&n&&n.toolPanels){var r=n.toolPanels.filter((function(e){return"columns"===e.id}));1===r.length&&p.mergeDeep(r[0],{componentParams:i})}t.enableStatusBar&&(console.warn("ag-grid: since version 19.x, enableStatusBar is gone, please specify statusBar components"),t.statusBar=t.statusBar||{components:[{component:"agAggregationComponent"}]}),t.alwaysShowStatusBar&&console.warn("ag-grid: since version 19.x, alwaysShowStatusBar is gone. Please specify a min-height on the ag-status-bar css class, eg .ag-status-bar {min-height: 35px; }"),(t.enableServerSideSorting||t.enableSorting)&&(console.warn("ag-Grid: since v20, grid options enableSorting and enableServerSideSorting are gone. Instead set sortable=true on the column definition for the columns sorting are allowed on. To migrate from gridOption.enableSorting=true, set gridOptions.defaultColDef.sortable=true"),t.defaultColDef||(t.defaultColDef={}),t.defaultColDef.sortable||(t.defaultColDef.sortable=!0)),(t.enableFilter||t.enableServerSideFilter)&&(console.warn("ag-Grid: since v20, grid options enableFilter and enableServerSideFilter are gone. Instead set filter=true (if not already specifying a specific filter) on the column definition for the columns filtering is allowed on. To migrate from gridOptions.enableFilter=true, set gridOptions.defaultColDef.filter=true. If you are explicitly setting specific filters for each column (ie colDef.filter is already set) the you don't need to do anything."),t.defaultColDef||(t.defaultColDef={}),t.defaultColDef.filter||(t.defaultColDef.filter=!0)),t.enableColResize&&(console.warn("ag-Grid: since v20, grid options enableColResize is gone. Instead set resizable=true on the column definition for the columns resizing are allowed on. To migrate from gridOption.enableColResize=true, set gridOptions.defaultColDef.resizable=true"),t.defaultColDef||(t.defaultColDef={}),t.defaultColDef.resizable||(t.defaultColDef.resizable=!0)),t.deprecatedEmbedFullWidthRows&&console.warn("ag-Grid: since v21.2, deprecatedEmbedFullWidthRows has been replaced with embedFullWidthRows."),t.suppressTabbing&&console.warn("ag-Grid: since v20.1, suppressTabbing is replaced with the more powerful grid callback suppressKeyboardEvent(params) which can suppress any keyboard event including tabbing."),t.doesDataFlower&&console.warn("ag-Grid: since v21.1, doesDataFlower is deprecated. Master/Detail is the new way for showing child data for a row and was introduced over a year ago. Please migrate your code to use master/detail instead."),t.enableOldSetFilterModel&&console.warn("ag-Grid: since v22.x, enableOldSetFilterModel is deprecated. Please move to the new Set Filter Model as the old one may not be supported in v23 onwards.")},e.prototype.checkForViolations=function(){this.isTreeData()&&this.treeDataViolations()},e.prototype.treeDataViolations=function(){this.isRowModelDefault()&&p.missing(this.getDataPathFunc())&&console.warn("ag-Grid: property usingTreeData=true with rowModel=clientSide, but you did not provide getDataPath function, please provide getDataPath function if using tree data."),this.isRowModelServerSide()&&(p.missing(this.getIsServerSideGroupFunc())&&console.warn("ag-Grid: property usingTreeData=true with rowModel=serverSide, but you did not provide isServerSideGroup function, please provide isServerSideGroup function if using tree data."),p.missing(this.getServerSideGroupKeyFunc())&&console.warn("ag-Grid: property usingTreeData=true with rowModel=serverSide, but you did not provide getServerSideGroupKey function, please provide getServerSideGroupKey function if using tree data."))},e.prototype.getLocaleTextFunc=function(){if(this.gridOptions.localeTextFunc)return this.gridOptions.localeTextFunc;var e=this;return function(t,o){var i=e.gridOptions.localeText;return i&&i[t]?i[t]:o}},e.prototype.globalEventHandler=function(e,t){var o=te.getCallbackForEvent(e);"function"==typeof this.gridOptions[o]&&this.gridOptions[o](t)},e.prototype.getRowHeightAsNumber=function(){return!this.gridOptions.rowHeight||p.missing(this.gridOptions.rowHeight)?this.getDefaultRowHeight():this.gridOptions.rowHeight&&this.isNumeric(this.gridOptions.rowHeight)?this.gridOptions.rowHeight:(console.warn("ag-Grid row height must be a number if not using standard row model"),this.getDefaultRowHeight())},e.prototype.getRowHeightForNode=function(e,t){if(void 0===t&&(t=!1),"function"==typeof this.gridOptions.getRowHeight){if(t)return{height:this.getDefaultRowHeight(),estimated:!0};var o={node:e,data:e.data,api:this.gridOptions.api,context:this.gridOptions.context};return{height:this.gridOptions.getRowHeight(o),estimated:!1}}if(e.detail&&this.isMasterDetail())return this.isNumeric(this.gridOptions.detailRowHeight)?{height:this.gridOptions.detailRowHeight,estimated:!1}:{height:300,estimated:!1};var i=this.getDefaultRowHeight(),n=this.gridOptions.rowHeight&&this.isNumeric(this.gridOptions.rowHeight)?this.gridOptions.rowHeight:i,r=Math.min(i,n);if(this.columnController.isAutoRowHeightActive()){if(t)return{height:n,estimated:!0};var s=this.autoHeightCalculator.getPreferredHeightForRow(e);return{height:Math.max(s,r),estimated:!1}}return{height:n,estimated:!1}},e.prototype.isDynamicRowHeight=function(){return"function"==typeof this.gridOptions.getRowHeight},e.prototype.getVirtualItemHeight=function(){return this.specialForNewMaterial(20,"virtualItemHeight")},e.prototype.isNumeric=function(e){return!isNaN(e)&&"number"==typeof e},e.prototype.specialForNewMaterial=function(e,t){var o=this.environment.getTheme().theme;return o&&0===o.indexOf("ag-theme")?this.environment.getSassVariable(o,t):e},e.prototype.getDefaultRowHeight=function(){return this.specialForNewMaterial(25,"rowHeight")},e.MIN_COL_WIDTH=10,e.PROP_HEADER_HEIGHT="headerHeight",e.PROP_GROUP_REMOVE_SINGLE_CHILDREN="groupRemoveSingleChildren",e.PROP_GROUP_REMOVE_LOWEST_SINGLE_CHILDREN="groupRemoveLowestSingleChildren",e.PROP_PIVOT_HEADER_HEIGHT="pivotHeaderHeight",e.PROP_SUPPRESS_CLIPBOARD_PASTE="suppressClipboardPaste",e.PROP_GROUP_HEADER_HEIGHT="groupHeaderHeight",e.PROP_PIVOT_GROUP_HEADER_HEIGHT="pivotGroupHeaderHeight",e.PROP_FLOATING_FILTERS_HEIGHT="floatingFiltersHeight",e.PROP_SUPPRESS_ROW_DRAG="suppressRowDrag",e.PROP_POPUP_PARENT="popupParent",e.PROP_DOM_LAYOUT="domLayout",Q([m("gridOptions")],e.prototype,"gridOptions",void 0),Q([m("columnController")],e.prototype,"columnController",void 0),Q([m("eventService")],e.prototype,"eventService",void 0),Q([m("gridApi")],e.prototype,"gridApi",void 0),Q([m("columnApi")],e.prototype,"columnApi",void 0),Q([m("environment")],e.prototype,"environment",void 0),Q([m("autoHeightCalculator")],e.prototype,"autoHeightCalculator",void 0),Q([m("context")],e.prototype,"context",void 0),Q([X(0,E("gridApi")),X(1,E("columnApi"))],e.prototype,"agWire",null),Q([f],e.prototype,"destroy",null),Q([g],e.prototype,"init",null),e=t=Q([y("gridOptionsWrapper")],e)}(),ee=function(){for(var e=0,t=0,o=arguments.length;t<o;t++)e+=arguments[t].length;var i=Array(e),n=0;for(t=0;t<o;t++)for(var r=arguments[t],s=0,a=r.length;s<a;s++,n++)i[n]=r[s];return i},te=function(){function e(){}return e.getEventCallbacks=function(){return e.EVENT_CALLBACKS||(e.EVENT_CALLBACKS=e.EVENTS.map((function(t){return e.getCallbackForEvent(t)}))),e.EVENT_CALLBACKS},e.copyAttributesToGridOptions=function(t,o,i){void 0===i&&(i=!1),oe(o),"object"!=typeof t&&(t={});var n=t,r=function(e){return void 0!==o[e]};return ee(e.ARRAY_PROPERTIES,e.STRING_PROPERTIES,e.OBJECT_PROPERTIES,e.FUNCTION_PROPERTIES,e.getEventCallbacks()).filter(r).forEach((function(e){return n[e]=o[e]})),e.BOOLEAN_PROPERTIES.filter(r).forEach((function(t){return n[t]=e.toBoolean(o[t])})),e.NUMBER_PROPERTIES.filter(r).forEach((function(t){return n[t]=e.toNumber(o[t])})),i||e.EVENTS.filter((function(t){return r(t)||r(e.getCallbackForEvent(t))})).forEach((function(e){return Z.checkEventDeprecation(e)})),t},e.getCallbackForEvent=function(e){return!e||e.length<2?e:"on"+e[0].toUpperCase()+e.substr(1)},e.processOnChange=function(t,o,i,n){if(t){oe(t);var r=o,s=function(e){return t[e]};ee(e.ARRAY_PROPERTIES,e.OBJECT_PROPERTIES,e.STRING_PROPERTIES,e.getEventCallbacks()).filter(s).forEach((function(e){return r[e]=t[e].currentValue})),e.BOOLEAN_PROPERTIES.filter(s).forEach((function(o){return r[o]=e.toBoolean(t[o].currentValue)})),e.NUMBER_PROPERTIES.filter(s).forEach((function(o){return r[o]=e.toNumber(t[o].currentValue)})),t.enableCellTextSelection&&i.setEnableCellTextSelection(e.toBoolean(t.enableCellTextSelection.currentValue)),t.showToolPanel&&i.showToolPanel(e.toBoolean(t.showToolPanel.currentValue)),t.quickFilterText&&i.setQuickFilter(t.quickFilterText.currentValue),t.rowData&&i.setRowData(t.rowData.currentValue),t.pinnedTopRowData&&i.setPinnedTopRowData(t.pinnedTopRowData.currentValue),t.pinnedBottomRowData&&i.setPinnedBottomRowData(t.pinnedBottomRowData.currentValue),t.columnDefs&&i.setColumnDefs(t.columnDefs.currentValue,"gridOptionsChanged"),t.datasource&&i.setDatasource(t.datasource.currentValue),t.headerHeight&&i.setHeaderHeight(e.toNumber(t.headerHeight.currentValue)),t.paginationPageSize&&i.paginationSetPageSize(e.toNumber(t.paginationPageSize.currentValue)),t.pivotMode&&n.setPivotMode(e.toBoolean(t.pivotMode.currentValue)),t.groupRemoveSingleChildren&&i.setGroupRemoveSingleChildren(e.toBoolean(t.groupRemoveSingleChildren.currentValue)),t.suppressRowDrag&&i.setSuppressRowDrag(e.toBoolean(t.suppressRowDrag.currentValue)),t.gridAutoHeight&&i.setGridAutoHeight(e.toBoolean(t.gridAutoHeight.currentValue)),t.suppressClipboardPaste&&i.setSuppressClipboardPaste(e.toBoolean(t.suppressClipboardPaste.currentValue)),t.sideBar&&i.setSideBar(t.sideBar.currentValue);var a={type:M.EVENT_COMPONENT_STATE_CHANGED,api:o.api,columnApi:o.columnApi};p.iterateObject(t,(function(e,t){a[e]=t})),i.dispatchEvent(a)}},e.toBoolean=function(e){return"boolean"==typeof e?e:"string"==typeof e&&("TRUE"===e.toUpperCase()||""==e)},e.toNumber=function(e){return"number"==typeof e?e:"string"==typeof e?Number(e):void 0},e.EVENTS=[],e.STRING_PROPERTIES=Y.STRING_PROPERTIES,e.OBJECT_PROPERTIES=Y.OBJECT_PROPERTIES,e.ARRAY_PROPERTIES=Y.ARRAY_PROPERTIES,e.NUMBER_PROPERTIES=Y.NUMBER_PROPERTIES,e.BOOLEAN_PROPERTIES=Y.BOOLEAN_PROPERTIES,e.FUNCTION_PROPERTIES=Y.FUNCTION_PROPERTIES,e.ALL_PROPERTIES=Y.ALL_PROPERTIES,e}(); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */function oe(e){(e.rowDeselected||e.onRowDeselected)&&console.warn("ag-grid: as of v3.4 rowDeselected no longer exists. Please check the docs.")} /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */te.EVENTS=p.values(M);var ie,ne=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},re=function(){function e(){var e=this;this.destroyFunctions=[],this.destroyed=!1,this.getContext=function(){return e.context},this.isAlive=function(){return!e.destroyed}}return e.prototype.getFrameworkOverrides=function(){return this.frameworkOverrides},e.prototype.destroy=function(){this.destroyFunctions.forEach((function(e){return e()})),this.destroyFunctions.length=0,this.destroyed=!0,this.dispatchEvent({type:e.EVENT_DESTROYED})},e.prototype.addEventListener=function(e,t){this.localEventService||(this.localEventService=new b),this.localEventService.addEventListener(e,t)},e.prototype.removeEventListener=function(e,t){this.localEventService&&this.localEventService.removeEventListener(e,t)},e.prototype.dispatchEventAsync=function(e){var t=this;window.setTimeout((function(){return t.dispatchEvent(e)}),0)},e.prototype.dispatchEvent=function(e){this.localEventService&&this.localEventService.dispatchEvent(e)},e.prototype.addDestroyableEventListener=function(e,t,o){var i=this;if(!this.destroyed){e instanceof HTMLElement?p.addSafePassiveEventListener(this.getFrameworkOverrides(),e,t,o):(Window,e.addEventListener(t,o));var n=function(){e instanceof HTMLElement?e.removeEventListener(t,o):(Window,e.removeEventListener(t,o)),i.destroyFunctions=i.destroyFunctions.filter((function(e){return e!==n}))};return this.destroyFunctions.push(n),n}},e.prototype.addDestroyFunc=function(e){this.isAlive()?this.destroyFunctions.push(e):e()},e.prototype.wireDependentBean=function(e,t){return e.destroy&&this.addDestroyFunc(e.destroy.bind(e)),this.wireBean(e,t)},e.prototype.wireBean=function(e,t){return(t||this.getContext()).wireBean(e),e},e.EVENT_DESTROYED="destroyed",ne([m("context")],e.prototype,"context",void 0),ne([m("frameworkOverrides")],e.prototype,"frameworkOverrides",void 0),ne([f],e.prototype,"destroy",null),e}(),se=(ie=function(e,t){return(ie=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(e,t)},function(e,t){function o(){this.constructor=e}ie(e,t),e.prototype=null===t?Object.create(t):(o.prototype=t.prototype,new o)}),ae=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},le=new l,pe=function(e){function t(t){var o=e.call(this)||this;return o.childComponents=[],o.annotatedEventListeners=[],o.displayed=!0,o.visible=!0,o.compId=le.next(),t&&o.setTemplate(t),o}return se(t,e),t.prototype.getCompId=function(){return this.compId},t.prototype.createChildComponentsFromTags=function(e){var t=this;p.copyNodeList(e.childNodes).forEach((function(o){var i=t.getContext().createComponentFromElement(o,(function(e){t.copyAttributesFromNode(o,e.getGui())}));if(i){if(i.addItems&&o.children.length){t.createChildComponentsFromTags(o);var n=Array.prototype.slice.call(o.children);i.addItems(n)}t.swapComponentForNode(i,e,o)}else o.childNodes&&t.createChildComponentsFromTags(o)}))},t.prototype.copyAttributesFromNode=function(e,t){p.iterateNamedNodeMap(e.attributes,(function(e,o){t.setAttribute(e,o)}))},t.prototype.swapComponentForNode=function(e,t,o){var i=e.getGui();t.replaceChild(i,o),t.insertBefore(document.createComment(o.nodeName),i),this.childComponents.push(e),this.swapInComponentForQuerySelectors(e,o)},t.prototype.swapInComponentForQuerySelectors=function(e,t){for(var o=Object.getPrototypeOf(this),i=this;null!=o;){var n=o.__agComponentMetaData,r=o.constructor.name;n&&n[r]&&n[r].querySelectors&&n[r].querySelectors.forEach((function(o){i[o.attributeName]===t&&(i[o.attributeName]=e)})),o=Object.getPrototypeOf(o)}},t.prototype.setTemplate=function(e){var t=p.loadTemplate(e);this.setTemplateFromElement(t)},t.prototype.setTemplateFromElement=function(e){this.eGui=e,this.eGui.__agComponent=this,this.addAnnotatedEventListeners(),this.wireQuerySelectors(),!!this.getContext()&&this.createChildComponentsFromTags(this.getGui())},t.prototype.createChildComponentsPreConstruct=function(){!!this.getGui()&&this.createChildComponentsFromTags(this.getGui())},t.prototype.wireQuerySelectors=function(){var e=this;if(this.eGui)for(var t=Object.getPrototypeOf(this),o=function(){var o=t.__agComponentMetaData,n=t.constructor.name;if(o&&o[n]&&o[n].querySelectors){var r=i;o[n].querySelectors.forEach((function(t){var o=e.eGui.querySelector(t.querySelector);if(o){var i=o.__agComponent;r[t.attributeName]=i||o}}))}t=Object.getPrototypeOf(t)},i=this;null!=t;)o()},t.prototype.addAnnotatedEventListeners=function(){var e=this;if(this.removeAnnotatedEventListeners(),this.eGui){var t=this.getAgComponentMetaData("listenerMethods");p.missingOrEmpty(t)||(this.annotatedEventListeners||(this.annotatedEventListeners=[]),t.forEach((function(t){var o=e[t.methodName].bind(e);e.eGui.addEventListener(t.eventName,o),e.annotatedEventListeners.push({eventName:t.eventName,listener:o})})))}},t.prototype.getAgComponentMetaData=function(e){for(var t=[],o=Object.getPrototypeOf(this);null!=o;){var i=o.__agComponentMetaData,n=o.constructor.name;if(void 0===n){var r=/function\s([^(]{1,})\(/.exec(o.constructor.toString());r&&r.length>1&&(n=r[1].trim())}i&&i[n]&&i[n][e]&&(t=t.concat(i[n][e])),o=Object.getPrototypeOf(o)}return t},t.prototype.removeAnnotatedEventListeners=function(){var e=this;this.annotatedEventListeners&&this.eGui&&(this.annotatedEventListeners.forEach((function(t){e.eGui.removeEventListener(t.eventName,t.listener)})),this.annotatedEventListeners=[])},t.prototype.getGui=function(){return this.eGui},t.prototype.setParentComponent=function(e){this.parentComponent=e},t.prototype.getParentComponent=function(){return this.parentComponent},t.prototype.setGui=function(e){this.eGui=e},t.prototype.queryForHtmlElement=function(e){return this.eGui.querySelector(e)},t.prototype.queryForHtmlInputElement=function(e){return this.eGui.querySelector(e)},t.prototype.appendChild=function(e){if(p.isNodeOrElement(e))this.eGui.appendChild(e);else{var t=e;this.eGui.appendChild(t.getGui()),this.childComponents.push(t)}},t.prototype.addFeature=function(e,t){this.wireDependentBean(e,t)},t.prototype.isDisplayed=function(){return this.displayed},t.prototype.setVisible=function(e){e!==this.visible&&(this.visible=e,p.setVisible(this.eGui,e))},t.prototype.setDisplayed=function(e){if(e!==this.displayed){this.displayed=e,p.setDisplayed(this.eGui,e);var o={type:t.EVENT_DISPLAYED_CHANGED,visible:this.displayed};this.dispatchEvent(o)}},t.prototype.addOrRemoveCssClass=function(e,t){p.addOrRemoveCssClass(this.eGui,e,t)},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.childComponents.forEach((function(e){e&&e.destroy&&e.destroy()})),this.childComponents.length=0,this.removeAnnotatedEventListeners()},t.prototype.addGuiEventListener=function(e,t){var o=this;this.getGui().addEventListener(e,t),this.addDestroyFunc((function(){return o.getGui().removeEventListener(e,t)}))},t.prototype.addCssClass=function(e){p.addCssClass(this.getGui(),e)},t.prototype.removeCssClass=function(e){p.removeCssClass(this.getGui(),e)},t.prototype.getAttribute=function(e){var t=this.getGui();return t?t.getAttribute(e):null},t.prototype.getRefElement=function(e){return this.queryForHtmlElement('[ref="'+e+'"]')},t.EVENT_DISPLAYED_CHANGED="displayedChanged",ae([h],t.prototype,"createChildComponentsPreConstruct",null),t}(re),ue=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ce=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ue(t,e),t.prototype.isPopup=function(){return!0},t.prototype.setParentComponent=function(t){p.addCssClass(t.getGui(),"ag-has-popup"),e.prototype.setParentComponent.call(this,t)},t.prototype.destroy=function(){var t=this.parentComponent;t&&t.isAlive()&&p.removeCssClass(t.getGui(),"ag-has-popup"),e.prototype.destroy.call(this)},t}(pe),de=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),he=function(e){function t(){var o=e.call(this,t.TEMPLATE)||this;return o.eInput=o.getGui().querySelector("input"),o}return de(t,e),t.prototype.init=function(e){this.params=e;var t,i=this.eInput;e.cellStartedEdit?(this.focusAfterAttached=!0,e.keyPress===o.KEY_BACKSPACE||e.keyPress===o.KEY_DELETE?t="":e.charPress?t=e.charPress:(t=this.getStartValue(e),e.keyPress!==o.KEY_F2&&(this.highlightAllOnFocus=!0))):(this.focusAfterAttached=!1,t=this.getStartValue(e));p.exists(t)&&(i.value=t),this.addDestroyableEventListener(i,"keydown",(function(e){var t=e.keyCode===o.KEY_PAGE_UP,i=e.keyCode===o.KEY_PAGE_DOWN;(t||i)&&e.preventDefault()}))},t.prototype.afterGuiAttached=function(){if(this.focusAfterAttached){var e=this.eInput;if(p.isBrowserSafari()||e.focus(),this.highlightAllOnFocus)e.select();else{var t=e.value?e.value.length:0;t>0&&e.setSelectionRange(t,t)}}},t.prototype.focusIn=function(){var e=this.eInput;e.focus(),e.select()},t.prototype.getValue=function(){var e=this.eInput;return this.params.parseValue(e.value)},t.prototype.getStartValue=function(e){return e.useFormatter||e.column.getColDef().refData?e.formatValue(e.value):e.value},t.prototype.isPopup=function(){return!1},t.TEMPLATE='<div class="ag-input-wrapper" role="presentation"><input class="ag-cell-edit-input" type="text"/></div>',t}(ce); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */ function ge(e){return ye.bind(this,e)}function fe(e){return ye.bind(this,"[ref="+e+"]")}function ye(e,t,o,i){null!==e?"number"!=typeof i?Ce(t,"querySelectors",{attributeName:o,querySelector:e}):console.error("ag-Grid: QuerySelector should be on an attribute"):console.error("ag-Grid: QuerySelector selector should not be null")}function me(e){return ve.bind(this,e)}function ve(e,t,o){null!==e?Ce(t,"listenerMethods",{methodName:o,eventName:e}):console.error("ag-Grid: EventListener eventName should not be null")}function Ce(e,t,o){var i=function(e,t){e.__agComponentMetaData||(e.__agComponentMetaData={});e.__agComponentMetaData[t]||(e.__agComponentMetaData[t]={});return e.__agComponentMetaData[t]} /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */(e,e.constructor.name);i[t]||(i[t]=[]),i[t].push(o)}var Ee,we=function(){function e(e,t,o){var i=this;this.alive=!0,e.newDateComponent(t).then((function(e){i.alive?(i.dateComp=e,o.appendChild(e.getGui()),e.afterGuiAttached&&e.afterGuiAttached(),i.tempValue&&e.setDate(i.tempValue)):e.destroy&&e.destroy()}))}return e.prototype.destroy=function(){this.alive=!1,this.dateComp&&this.dateComp.destroy&&this.dateComp.destroy()},e.prototype.getDate=function(){return this.dateComp?this.dateComp.getDate():this.tempValue},e.prototype.setDate=function(e){this.dateComp?this.dateComp.setDate(e):this.tempValue=e},e}(),Re=function(){function e(){this.customFilterOptions={}}return e.prototype.init=function(e,t){this.filterOptions=e.filterOptions?e.filterOptions:t,this.mapCustomOptions(),this.selectDefaultItem(e)},e.prototype.getFilterOptions=function(){return this.filterOptions},e.prototype.mapCustomOptions=function(){var e=this;this.filterOptions&&this.filterOptions.forEach((function(t){"string"!=typeof t&&(t.displayKey?t.displayName?t.test?e.customFilterOptions[t.displayKey]=t:console.warn("ag-Grid: ignoring FilterOptionDef as it doesn't contain a 'test'"):console.warn("ag-Grid: ignoring FilterOptionDef as it doesn't contain a 'displayName'"):console.warn("ag-Grid: ignoring FilterOptionDef as it doesn't contain a 'displayKey'"))}))},e.prototype.selectDefaultItem=function(e){if(e.defaultOption)this.defaultOption=e.defaultOption;else if(this.filterOptions.length>=1){var t=this.filterOptions[0];"string"==typeof t?this.defaultOption=t:t.displayKey?this.defaultOption=t.displayKey:console.warn("ag-Grid: invalid FilterOptionDef supplied as it doesn't contain a 'displayKey'")}else console.warn("ag-Grid: no filter options for filter")},e.prototype.getDefaultOption=function(){return this.defaultOption},e.prototype.getCustomOption=function(e){return this.customFilterOptions[e]},e}(),Oe=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),De=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},be=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Oe(t,e),t.prototype.onFilterChanged=function(){console.warn("ag-Grid: you should not call onFilterChanged() directly on the filter, please call\n gridApi.onFilterChanged() instead. onFilterChanged is not part of the exposed filter interface (it was\n a method that existed on an old version of the filters that was not intended for public use."),this.providedFilterParams.filterChangedCallback()},t.prototype.isFilterActive=function(){return!!this.appliedModel},t.prototype.postConstruct=function(){var e=this.createTemplate();this.setTemplate(e)},t.prototype.init=function(e){this.setParams(e),this.resetUiToDefaults(),this.updateUiVisibility(),this.setupOnBtApplyDebounce()},t.prototype.setParams=function(e){var i=this;if(this.providedFilterParams=e,this.clearActive=!0===e.clearButton,this.applyActive=t.isUseApplyButton(e),e.newRowsAction===t.NEW_ROWS_ACTION_KEEP)this.newRowsActionKeep=!0;else if(e.newRowsAction===t.NEW_ROWS_ACTION_CLEAR)this.newRowsActionKeep=!1;else{var n=this.rowModel.getType(),r=[o.ROW_MODEL_TYPE_SERVER_SIDE,o.ROW_MODEL_TYPE_INFINITE];this.newRowsActionKeep=r.indexOf(n)>=0}p.setDisplayed(this.eApplyButton,this.applyActive),this.addDestroyableEventListener(this.eApplyButton,"click",(function(){return i.onBtApply()})),p.setDisplayed(this.eClearButton,this.clearActive),this.addDestroyableEventListener(this.eClearButton,"click",this.onBtClear.bind(this));var s=this.applyActive||this.clearActive;p.setDisplayed(this.eButtonsPanel,s)},t.prototype.getDefaultDebounceMs=function(){return 0},t.prototype.setupOnBtApplyDebounce=function(){var e=t.getDebounceMs(this.providedFilterParams,this.getDefaultDebounceMs());this.onBtApplyDebounce=p.debounce(this.onBtApply.bind(this),e)},t.prototype.getModel=function(){return this.appliedModel},t.prototype.setModel=function(e){e?this.setModelIntoUi(e):this.resetUiToDefaults(),this.updateUiVisibility(),this.applyModel()},t.prototype.onBtClear=function(){this.resetUiToDefaults(),this.updateUiVisibility(),this.onUiChanged()},t.prototype.applyModel=function(){var e=this.appliedModel;return this.appliedModel=this.getModelFromUi(),!this.areModelsEqual(this.appliedModel,e)},t.prototype.onBtApply=function(e){void 0===e&&(e=!1),this.applyModel()&&this.providedFilterParams.filterChangedCallback({afterFloatingFilter:e})},t.prototype.onNewRowsLoaded=function(){this.newRowsActionKeep||(this.resetUiToDefaults(),this.appliedModel=null)},t.prototype.isNewRowsActionKeep=function(){return this.newRowsActionKeep},t.prototype.onUiChanged=function(e){void 0===e&&(e=!1),this.updateUiVisibility(),this.providedFilterParams.filterModifiedCallback(),e?this.onBtApply(!0):this.applyActive||this.onBtApplyDebounce()},t.prototype.createTemplate=function(){var e=this.createBodyTemplate(),t=this.gridOptionsWrapper.getLocaleTextFunc();return"<div>\n <div class='ag-filter-body-wrapper' ref=\"eFilterBodyWrapper\">"+e+'</div>\n <div class="ag-filter-apply-panel" ref="eButtonsPanel">\n <button type="button" ref="eClearButton">'+t("clearFilter","Clear Filter")+'</button>\n <button type="button" ref="eApplyButton">'+t("applyFilter","Apply Filter")+"</button>\n </div>\n </div>"},t.getDebounceMs=function(e,o){return t.isUseApplyButton(e)?(null!=e.debounceMs&&console.warn("ag-Grid: debounceMs is ignored when applyButton = true"),0):null!=e.debounceMs?e.debounceMs:o},t.isUseApplyButton=function(e){return e.apply&&!e.applyButton&&(console.warn("ag-Grid: as of ag-Grid v21, filterParams.apply is now filterParams.applyButton, please change to applyButton"),e.applyButton=!0),!0===e.applyButton},t.NEW_ROWS_ACTION_KEEP="keep",t.NEW_ROWS_ACTION_CLEAR="clear",De([fe("eButtonsPanel")],t.prototype,"eButtonsPanel",void 0),De([fe("eFilterBodyWrapper")],t.prototype,"eFilterBodyWrapper",void 0),De([fe("eApplyButton")],t.prototype,"eApplyButton",void 0),De([fe("eClearButton")],t.prototype,"eClearButton",void 0),De([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),De([m("rowModel")],t.prototype,"rowModel",void 0),De([g],t.prototype,"postConstruct",null),t}(pe),Pe=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Se=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s}; /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */!function(e){e[e.One=0]="One",e[e.Two=1]="Two"}(Ee||(Ee={}));var Te,Ae={loadingOoo:"Loading...",empty:"Choose One",equals:"Equals",notEqual:"Not equal",lessThan:"Less than",greaterThan:"Greater than",inRange:"In range",lessThanOrEqual:"Less than or equals",greaterThanOrEqual:"Greater than or equals",filterOoo:"Filter...",contains:"Contains",notContains:"Not contains",startsWith:"Starts with",endsWith:"Ends with",searchOoo:"Search...",selectAll:"Select All",applyFilter:"Apply Filter",clearFilter:"Clear Filter",andCondition:"AND",orCondition:"OR"},_e=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Pe(t,e),t.prototype.showValueFrom=function(e){return!this.doesFilterHaveHiddenInput(e)&&e!==t.EMPTY},t.prototype.showValueTo=function(e){return e===t.IN_RANGE},t.prototype.onFloatingFilterChanged=function(e,t){this.setValueFromFloatingFilter(t),this.setTypeFromFloatingFilter(e),this.onUiChanged(!0)},t.prototype.setTypeFromFloatingFilter=function(e){this.eType1.value=e,this.eType2.value=null,this.eJoinOperatorAnd.checked=!0},t.prototype.getModelFromUi=function(){return this.isConditionUiComplete(Ee.One)?this.isAllowTwoConditions()&&this.isConditionUiComplete(Ee.Two)?{filterType:this.getFilterType(),operator:this.getJoinOperator(),condition1:this.createCondition(Ee.One),condition2:this.createCondition(Ee.Two)}:this.createCondition(Ee.One):null},t.prototype.getCondition1Type=function(){return this.eType1.value},t.prototype.getCondition2Type=function(){return this.eType2.value},t.prototype.getJoinOperator=function(){return this.eJoinOperatorOr.checked?"OR":"AND"},t.prototype.areModelsEqual=function(e,t){if(!e&&!t)return!0;if(!e&&t||e&&!t)return!1;var o,i=!e.operator,n=!t.operator;if(!i&&n||i&&!n)return!1;if(i){var r=e,s=t;o=this.areSimpleModelsEqual(r,s)}else{var a=e,l=t;o=a.operator===l.operator&&this.areSimpleModelsEqual(a.condition1,l.condition1)&&this.areSimpleModelsEqual(a.condition2,l.condition2)}return o},t.prototype.setModelIntoUi=function(e){if(e.operator){var t=e,o="OR"===t.operator;this.eJoinOperatorAnd.checked=!o,this.eJoinOperatorOr.checked=o,this.eType1.value=t.condition1.type,this.eType2.value=t.condition2.type,this.setConditionIntoUi(t.condition1,Ee.One),this.setConditionIntoUi(t.condition2,Ee.Two)}else{var i=e;this.eJoinOperatorAnd.checked=!0,this.eJoinOperatorOr.checked=!1,this.eType1.value=i.type,this.eType2.value=this.optionsFactory.getDefaultOption(),this.setConditionIntoUi(i,Ee.One),this.setConditionIntoUi(null,Ee.Two)}},t.prototype.doesFilterPass=function(e){var t=this.getModel();if(t.operator){var o=t,i=this.individualConditionPasses(e,o.condition1),n=this.individualConditionPasses(e,o.condition2);return"AND"===o.operator?i&&n:i||n}var r=t;return this.individualConditionPasses(e,r)},t.prototype.setParams=function(t){e.prototype.setParams.call(this,t),this.simpleFilterParams=t,this.optionsFactory=new Re,this.optionsFactory.init(t,this.getDefaultFilterOptions()),this.allowTwoConditions=!t.suppressAndOrCondition,this.putOptionsIntoDropdown(),this.addChangedListeners()},t.prototype.putOptionsIntoDropdown=function(){var e=this,t=this.optionsFactory.getFilterOptions();t.forEach((function(t){var o=function(){var o="string"==typeof t?t:t.displayKey,i=e.translate(o),n=document.createElement("option");return n.text=i,n.value=o,n};e.eType1.add(o()),e.eType2.add(o())}));var o=t.length<=1;this.eType1.disabled=o,this.eType2.disabled=o},t.prototype.isAllowTwoConditions=function(){return this.allowTwoConditions},t.prototype.createBodyTemplate=function(){var e=this.createValueTemplate(Ee.One),t=this.createValueTemplate(Ee.Two),o="ag-simple-filter-and-or-"+this.getCompId(),i=this.gridOptionsWrapper.getLocaleTextFunc();return'<select class="ag-filter-select" ref="eOptions1"></select>\n '+e+"\n "+('<div class="ag-filter-condition" ref="eJoinOperatorPanel">\n <label>\n <input ref="eJoinOperatorAnd" type="radio" class="and" name="'+o+'" value="AND")} checked="checked" />\n '+i("andCondition","AND")+'\n </label>\n <label>\n <input ref="eJoinOperatorOr" type="radio" class="or" name="'+o+'" value="OR" />\n '+i("orCondition","OR")+"\n </label>\n </div>")+'\n <select class="ag-filter-select" ref="eOptions2"></select>\n '+t},t.prototype.updateUiVisibility=function(){var e=this.isConditionUiComplete(Ee.One),t=this.allowTwoConditions&&e;p.setDisplayed(this.eCondition2Body,t),p.setDisplayed(this.eType2,t),p.setDisplayed(this.eJoinOperatorPanel,t)},t.prototype.resetUiToDefaults=function(){this.eJoinOperatorAnd.checked=!0;var e=this.optionsFactory.getDefaultOption();this.eType1.value=e,this.eType2.value=e},t.prototype.translate=function(e){var t=this.gridOptionsWrapper.getLocaleTextFunc(),o=Ae[e];return!o&&this.optionsFactory.getCustomOption(e)&&(o=this.optionsFactory.getCustomOption(e).displayName),t(e,o)},t.prototype.addChangedListeners=function(){var e=this,t=function(){return e.onUiChanged()};this.addDestroyableEventListener(this.eType1,"change",t),this.addDestroyableEventListener(this.eType2,"change",t),this.addDestroyableEventListener(this.eJoinOperatorOr,"change",t),this.addDestroyableEventListener(this.eJoinOperatorAnd,"change",t)},t.prototype.doesFilterHaveHiddenInput=function(e){var t=this.optionsFactory.getCustomOption(e);return t&&t.hideFilterInput},t.EMPTY="empty",t.EQUALS="equals",t.NOT_EQUAL="notEqual",t.LESS_THAN="lessThan",t.LESS_THAN_OR_EQUAL="lessThanOrEqual",t.GREATER_THAN="greaterThan",t.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",t.IN_RANGE="inRange",t.CONTAINS="contains",t.NOT_CONTAINS="notContains",t.STARTS_WITH="startsWith",t.ENDS_WITH="endsWith",Se([fe("eOptions1")],t.prototype,"eType1",void 0),Se([fe("eOptions2")],t.prototype,"eType2",void 0),Se([fe("eJoinOperatorAnd")],t.prototype,"eJoinOperatorAnd",void 0),Se([fe("eJoinOperatorOr")],t.prototype,"eJoinOperatorOr",void 0),Se([fe("eCondition2Body")],t.prototype,"eCondition2Body",void 0),Se([fe("eJoinOperatorPanel")],t.prototype,"eJoinOperatorPanel",void 0),t}(be),Fe=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ne=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Fe(t,e),t.prototype.setParams=function(t){e.prototype.setParams.call(this,t),this.scalarFilterParams=t,this.checkDeprecatedParams()},t.prototype.checkDeprecatedParams=function(){this.scalarFilterParams.nullComparator&&(console.warn("ag-Grid: Since v21.0, the property filterParams.nullComparator is deprecated. Please use filterParams.includeBlanksInEquals, filterParams.includeBlanksInLessThan and filterParams.includeBlanksInGreaterThan instead."),this.scalarFilterParams.includeBlanksInEquals=this.scalarFilterParams.nullComparator.equals,this.scalarFilterParams.includeBlanksInLessThan=this.scalarFilterParams.nullComparator.lessThan,this.scalarFilterParams.includeBlanksInGreaterThan=this.scalarFilterParams.nullComparator.greaterThan)},t.prototype.nullComparator=function(e,o,i){if(null==i){var n=this.canNullsPassFilter(e);if(e===t.EMPTY)return 0;if(e===t.EQUALS)return n?0:1;if(e===t.GREATER_THAN)return n?1:-1;if(e===t.GREATER_THAN_OR_EQUAL)return n?1:-1;if(e===t.LESS_THAN_OR_EQUAL)return n?-1:1;if(e===t.LESS_THAN)return n?-1:1;if(e===t.NOT_EQUAL)return n?1:0}return this.comparator()(o,i)},t.prototype.canNullsPassFilter=function(e){switch(e){case _e.GREATER_THAN:case _e.GREATER_THAN_OR_EQUAL:return this.scalarFilterParams.includeBlanksInGreaterThan;case _e.LESS_THAN:case _e.LESS_THAN_OR_EQUAL:return this.scalarFilterParams.includeBlanksInLessThan;case _e.EQUALS:return this.scalarFilterParams.includeBlanksInEquals}},t.prototype.individualConditionPasses=function(e,o){var i=this.scalarFilterParams.valueGetter(e.node),n=this.mapRangeFromModel(o),r=n.from,s=n.to,a=o.type,l=this.optionsFactory.getCustomOption(a);if(l&&(null!=r||l.hideFilterInput))return l.test(r,i);var p=this.nullComparator(a,r,i);if(a===t.EQUALS)return 0===p;if(a===t.GREATER_THAN)return p>0;if(a===t.GREATER_THAN_OR_EQUAL)return p>=0;if(a===t.LESS_THAN_OR_EQUAL)return p<=0;if(a===t.LESS_THAN)return p<0;if(a===t.NOT_EQUAL)return 0!=p;var u=this.nullComparator(a,s,i);if(a===t.IN_RANGE)return this.scalarFilterParams.inRangeInclusive?p>=0&&u<=0:p>0&&u<0;throw new Error("Unexpected type of filter: "+a)},t.DEFAULT_NULL_COMPARATOR={equals:!1,lessThan:!1,greaterThan:!1},t}(_e),Le=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ie=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ge=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Le(t,e),t.prototype.mapRangeFromModel=function(e){return{from:p.parseYyyyMmDdToDate(e.dateFrom,"-"),to:p.parseYyyyMmDdToDate(e.dateTo,"-")}},t.prototype.setValueFromFloatingFilter=function(e){if(null!=e){var t=p.parseYyyyMmDdToDate(e,"-");this.dateCompFrom1.setDate(t)}else this.dateCompFrom1.setDate(null);this.dateCompTo1.setDate(null),this.dateCompFrom2.setDate(null),this.dateCompTo2.setDate(null)},t.prototype.setConditionIntoUi=function(e,t){var o=t===Ee.One,i=e?e.dateFrom:null,n=e?e.dateTo:null,r=p.parseYyyyMmDdToDate(i,"-"),s=p.parseYyyyMmDdToDate(n,"-"),a=o?this.dateCompFrom1:this.dateCompFrom2,l=o?this.dateCompTo1:this.dateCompTo2;a.setDate(r),l.setDate(s)},t.prototype.resetUiToDefaults=function(){e.prototype.resetUiToDefaults.call(this),this.dateCompTo1.setDate(null),this.dateCompTo2.setDate(null),this.dateCompFrom1.setDate(null),this.dateCompFrom2.setDate(null)},t.prototype.comparator=function(){return this.dateFilterParams.comparator?this.dateFilterParams.comparator:this.defaultComparator.bind(this)},t.prototype.defaultComparator=function(e,t){return t<e?-1:t>e?1:null!=t?0:-1},t.prototype.setParams=function(t){e.prototype.setParams.call(this,t),this.dateFilterParams=t,this.createDateComponents()},t.prototype.createDateComponents=function(){var e=this,t={onDateChanged:function(){return e.onUiChanged()},filterParams:this.dateFilterParams};this.dateCompFrom1=new we(this.userComponentFactory,t,this.ePanelFrom1),this.dateCompFrom2=new we(this.userComponentFactory,t,this.ePanelFrom2),this.dateCompTo1=new we(this.userComponentFactory,t,this.ePanelTo1),this.dateCompTo2=new we(this.userComponentFactory,t,this.ePanelTo2),this.addDestroyFunc((function(){e.dateCompFrom1.destroy(),e.dateCompFrom2.destroy(),e.dateCompTo1.destroy(),e.dateCompTo2.destroy()}))},t.prototype.getDefaultFilterOptions=function(){return t.DEFAULT_FILTER_OPTIONS},t.prototype.createValueTemplate=function(e){var t=e===Ee.One?"1":"2";return'<div class="ag-filter-body" ref="eCondition'+t+'Body">\n <div class="ag-filter-date-from" ref="ePanelFrom'+t+'">\n </div>\n <div class="ag-filter-date-to" ref="ePanelTo'+t+'"">\n </div>\n </div>'},t.prototype.isConditionUiComplete=function(e){var t=e===Ee.One,o=t?this.getCondition1Type():this.getCondition2Type(),i=t?this.dateCompFrom1:this.dateCompFrom2,n=t?this.dateCompTo1:this.dateCompTo2,r=i.getDate(),s=n.getDate();return o!==_e.EMPTY&&(!!this.doesFilterHaveHiddenInput(o)||(o===_e.IN_RANGE?null!=r&&null!=s:null!=r))},t.prototype.areSimpleModelsEqual=function(e,t){return e.dateFrom===t.dateFrom&&e.dateTo===t.dateTo&&e.type===t.type},t.prototype.getFilterType=function(){return t.FILTER_TYPE},t.prototype.createCondition=function(e){var o=e===Ee.One,i=o?this.getCondition1Type():this.getCondition2Type(),n=o?this.dateCompTo1:this.dateCompTo2,r=o?this.dateCompFrom1:this.dateCompFrom2;return{dateTo:p.serializeDateToYyyyMmDd(n.getDate(),"-"),dateFrom:p.serializeDateToYyyyMmDd(r.getDate(),"-"),type:i,filterType:t.FILTER_TYPE}},t.prototype.updateUiVisibility=function(){e.prototype.updateUiVisibility.call(this);var t=this.showValueFrom(this.getCondition1Type());p.setDisplayed(this.ePanelFrom1,t);var o=this.showValueTo(this.getCondition1Type());p.setDisplayed(this.ePanelTo1,o);var i=this.showValueFrom(this.getCondition2Type());p.setDisplayed(this.ePanelFrom2,i);var n=this.showValueTo(this.getCondition2Type());p.setDisplayed(this.ePanelTo2,n)},t.FILTER_TYPE="date",t.DEFAULT_FILTER_OPTIONS=[Ne.EQUALS,Ne.GREATER_THAN,Ne.LESS_THAN,Ne.NOT_EQUAL,Ne.IN_RANGE],Ie([fe("ePanelFrom1")],t.prototype,"ePanelFrom1",void 0),Ie([fe("ePanelFrom2")],t.prototype,"ePanelFrom2",void 0),Ie([fe("ePanelTo1")],t.prototype,"ePanelTo1",void 0),Ie([fe("ePanelTo2")],t.prototype,"ePanelTo2",void 0),Ie([m("userComponentFactory")],t.prototype,"userComponentFactory",void 0),t}(Ne),Me=function(){function e(e,t){var o=this;void 0===t&&(t=!1),this.destroyFuncs=[],this.touching=!1,this.eventService=new b,this.eElement=e,this.preventMouseClick=t;var i=this.onTouchStart.bind(this),n=this.onTouchMove.bind(this),r=this.onTouchEnd.bind(this);this.eElement.addEventListener("touchstart",i,{passive:!0}),this.eElement.addEventListener("touchmove",n,{passive:!0}),this.eElement.addEventListener("touchend",r,{passive:!1}),this.destroyFuncs.push((function(){o.eElement.removeEventListener("touchstart",i,{passive:!0}),o.eElement.removeEventListener("touchmove",n,{passive:!0}),o.eElement.removeEventListener("touchend",r,{passive:!1})}))}return e.prototype.getActiveTouch=function(e){for(var t=0;t<e.length;t++){if(e[t].identifier===this.touchStart.identifier)return e[t]}return null},e.prototype.addEventListener=function(e,t){this.eventService.addEventListener(e,t)},e.prototype.removeEventListener=function(e,t){this.eventService.removeEventListener(e,t)},e.prototype.onTouchStart=function(t){var o=this;if(!this.touching){this.touchStart=t.touches[0],this.touching=!0,this.moved=!1;var i=this.touchStart;window.setTimeout((function(){var n=o.touchStart===i;if(o.touching&&n&&!o.moved){o.moved=!0;var r={type:e.EVENT_LONG_TAP,touchStart:o.touchStart,touchEvent:t};o.eventService.dispatchEvent(r)}}),500)}},e.prototype.onTouchMove=function(e){if(this.touching){var t=this.getActiveTouch(e.touches);if(t)!p.areEventsNear(t,this.touchStart,4)&&(this.moved=!0)}},e.prototype.onTouchEnd=function(t){if(this.touching){if(!this.moved){var o={type:e.EVENT_TAP,touchStart:this.touchStart};this.eventService.dispatchEvent(o),this.checkForDoubleTap()}this.preventMouseClick&&t.preventDefault(),this.touching=!1}},e.prototype.checkForDoubleTap=function(){var t=(new Date).getTime();if(this.lastTapTime&&this.lastTapTime>0)if(t-this.lastTapTime>e.DOUBLE_TAP_MILLIS){var o={type:e.EVENT_DOUBLE_TAP,touchStart:this.touchStart};this.eventService.dispatchEvent(o),this.lastTapTime=null}else this.lastTapTime=t;else this.lastTapTime=t},e.prototype.destroy=function(){this.destroyFuncs.forEach((function(e){return e()}))},e.EVENT_TAP="tap",e.EVENT_DOUBLE_TAP="doubleTap",e.EVENT_LONG_TAP="longTap",e.DOUBLE_TAP_MILLIS=500,e}(),xe=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ve=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},We=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.lastMovingChanged=0,t}return xe(t,e),t.prototype.init=function(e){var o=p.firstExistingValue(e.template,t.TEMPLATE);o=o&&o.trim?o.trim():o,this.setTemplate(o),this.params=e,this.setupTap(),this.setupIcons(e.column),this.setupMenu(),this.setupSort(),this.setupFilterIcon(),this.setupText(e.displayName)},t.prototype.setupText=function(e){var t=p.escape(e);this.eText&&(this.eText.innerHTML=t)},t.prototype.setupIcons=function(e){this.addInIcon("sortAscending",this.eSortAsc,e),this.addInIcon("sortDescending",this.eSortDesc,e),this.addInIcon("sortUnSort",this.eSortNone,e),this.addInIcon("menu",this.eMenu,e),this.addInIcon("filter",this.eFilter,e)},t.prototype.addInIcon=function(e,t,o){if(null!=t){var i=p.createIconNoSpan(e,this.gridOptionsWrapper,o);t.appendChild(i)}},t.prototype.setupTap=function(){var e=this,t=this.gridOptionsWrapper;if(!t.isSuppressTouch()){var o=new Me(this.getGui(),!0),i=t.isSuppressMenuHide(),n=i&&p.exists(this.eMenu),r=n?new Me(this.eMenu,!0):o;if(this.params.enableMenu){var s=n?"EVENT_TAP":"EVENT_LONG_TAP";this.addDestroyableEventListener(r,Me[s],(function(o){t.getApi().showColumnMenuAfterMouseClick(e.params.column,o.touchStart)}))}if(this.params.enableSorting){this.addDestroyableEventListener(o,Me.EVENT_TAP,(function(t){var o=t.touchStart.target;i&&e.eMenu.contains(o)||e.sortController.progressSort(e.params.column,!1,"uiColumnSorted")}))}this.addDestroyFunc((function(){return o.destroy()})),n&&this.addDestroyFunc((function(){return r.destroy()}))}},t.prototype.setupMenu=function(){var e=this;if(this.eMenu){var t=this.gridOptionsWrapper.isSuppressMenuHide();if(!this.params.enableMenu||p.isIOSUserAgent()&&!t)p.removeFromParent(this.eMenu);else{this.addDestroyableEventListener(this.eMenu,"click",(function(){return e.showMenu(e.eMenu)})),t||(this.eMenu.style.opacity="0",this.addGuiEventListener("mouseover",(function(){e.eMenu.style.opacity="1"})),this.addGuiEventListener("mouseout",(function(){e.eMenu.style.opacity="0"})));var o=this.eMenu.style;o.transition="opacity 0.2s, border 0.2s",o["-webkit-transition"]="opacity 0.2s, border 0.2s"}}},t.prototype.showMenu=function(e){this.menuFactory.showMenuAfterButtonClick(this.params.column,e)},t.prototype.removeSortIcons=function(){p.removeFromParent(this.eSortAsc),p.removeFromParent(this.eSortDesc),p.removeFromParent(this.eSortNone),p.removeFromParent(this.eSortOrder)},t.prototype.setupSort=function(){var e=this;if(this.params.enableSorting){var t=this.gridOptionsWrapper.isMultiSortKeyCtrl();this.addDestroyableEventListener(this.params.column,T.EVENT_MOVING_CHANGED,(function(){e.lastMovingChanged=(new Date).getTime()})),this.eLabel&&this.addDestroyableEventListener(this.eLabel,"click",(function(o){var i=e.params.column.isMoving(),n=(new Date).getTime()-e.lastMovingChanged<50;if(!(i||n)){var r=t?o.ctrlKey||o.metaKey:o.shiftKey;e.params.progressSort(r)}})),this.addDestroyableEventListener(this.params.column,T.EVENT_SORT_CHANGED,this.onSortChanged.bind(this)),this.onSortChanged(),this.addDestroyableEventListener(this.eventService,M.EVENT_SORT_CHANGED,this.setMultiSortOrder.bind(this)),this.setMultiSortOrder()}else this.removeSortIcons()},t.prototype.onSortChanged=function(){if(p.addOrRemoveCssClass(this.getGui(),"ag-header-cell-sorted-asc",this.params.column.isSortAscending()),p.addOrRemoveCssClass(this.getGui(),"ag-header-cell-sorted-desc",this.params.column.isSortDescending()),p.addOrRemoveCssClass(this.getGui(),"ag-header-cell-sorted-none",this.params.column.isSortNone()),this.eSortAsc&&p.addOrRemoveCssClass(this.eSortAsc,"ag-hidden",!this.params.column.isSortAscending()),this.eSortDesc&&p.addOrRemoveCssClass(this.eSortDesc,"ag-hidden",!this.params.column.isSortDescending()),this.eSortNone){var e=!this.params.column.getColDef().unSortIcon&&!this.gridOptionsWrapper.isUnSortIcon();p.addOrRemoveCssClass(this.eSortNone,"ag-hidden",e||!this.params.column.isSortNone())}},t.prototype.setMultiSortOrder=function(){if(this.eSortOrder){var e=this.params.column,t=this.sortController.getColumnsWithSortingOrdered(),o=t.indexOf(e),i=t.length>1,n=e.isSorting()&&i;p.setDisplayed(this.eSortOrder,n),o>=0?this.eSortOrder.innerHTML=(o+1).toString():p.clearElement(this.eSortOrder)}},t.prototype.setupFilterIcon=function(){this.eFilter&&(this.addDestroyableEventListener(this.params.column,T.EVENT_FILTER_CHANGED,this.onFilterChanged.bind(this)),this.onFilterChanged())},t.prototype.onFilterChanged=function(){var e=this.params.column.isFilterActive();p.addOrRemoveCssClass(this.eFilter,"ag-hidden",!e)},t.TEMPLATE='<div class="ag-cell-label-container" role="presentation"> <span ref="eMenu" class="ag-header-icon ag-header-cell-menu-button" aria-hidden="true"></span> <div ref="eLabel" class="ag-header-cell-label" role="presentation" unselectable="on"> <span ref="eText" class="ag-header-cell-text" role="columnheader" unselectable="on"></span> <span ref="eFilter" class="ag-header-icon ag-filter-icon" aria-hidden="true"></span> <span ref="eSortOrder" class="ag-header-icon ag-sort-order" aria-hidden="true"></span> <span ref="eSortAsc" class="ag-header-icon ag-sort-ascending-icon" aria-hidden="true"></span> <span ref="eSortDesc" class="ag-header-icon ag-sort-descending-icon" aria-hidden="true"></span> <span ref="eSortNone" class="ag-header-icon ag-sort-none-icon" aria-hidden="true"></span> </div></div>',Ve([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Ve([m("sortController")],t.prototype,"sortController",void 0),Ve([m("menuFactory")],t.prototype,"menuFactory",void 0),Ve([m("eventService")],t.prototype,"eventService",void 0),Ve([fe("eFilter")],t.prototype,"eFilter",void 0),Ve([fe("eSortAsc")],t.prototype,"eSortAsc",void 0),Ve([fe("eSortDesc")],t.prototype,"eSortDesc",void 0),Ve([fe("eSortNone")],t.prototype,"eSortNone",void 0),Ve([fe("eSortOrder")],t.prototype,"eSortOrder",void 0),Ve([fe("eMenu")],t.prototype,"eMenu",void 0),Ve([fe("eLabel")],t.prototype,"eLabel",void 0),Ve([fe("eText")],t.prototype,"eText",void 0),t}(pe),He=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ke=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Be=function(e){function t(){return e.call(this,t.TEMPLATE)||this}return He(t,e),t.prototype.init=function(e){this.params=e,this.setupLabel(),this.addGroupExpandIcon(),this.setupExpandIcons()},t.prototype.setupExpandIcons=function(){var e=this;this.addInIcon("columnGroupOpened","agOpened"),this.addInIcon("columnGroupClosed","agClosed");var t=function(t){if(!p.isStopPropagationForAgGrid(t)){var o=!e.params.columnGroup.isExpanded();e.columnController.setColumnGroupOpened(e.params.columnGroup.getOriginalColumnGroup(),o,"uiColumnExpanded")}};this.addTouchAndClickListeners(this.eCloseIcon,t),this.addTouchAndClickListeners(this.eOpenIcon,t);var o=function(e){p.stopPropagationForAgGrid(e)};this.addDestroyableEventListener(this.eCloseIcon,"dblclick",o),this.addDestroyableEventListener(this.eOpenIcon,"dblclick",o),this.addDestroyableEventListener(this.getGui(),"dblclick",t),this.updateIconVisibility();var i=this.params.columnGroup.getOriginalColumnGroup();this.addDestroyableEventListener(i,F.EVENT_EXPANDED_CHANGED,this.updateIconVisibility.bind(this)),this.addDestroyableEventListener(i,F.EVENT_EXPANDABLE_CHANGED,this.updateIconVisibility.bind(this))},t.prototype.addTouchAndClickListeners=function(e,t){var o=new Me(e);this.addDestroyableEventListener(o,Me.EVENT_TAP,t),this.addDestroyFunc((function(){return o.destroy()})),this.addDestroyableEventListener(e,"click",t)},t.prototype.updateIconVisibility=function(){if(this.params.columnGroup.isExpandable()){var e=this.params.columnGroup.isExpanded();p.setDisplayed(this.eOpenIcon,e),p.setDisplayed(this.eCloseIcon,!e)}else p.setDisplayed(this.eOpenIcon,!1),p.setDisplayed(this.eCloseIcon,!1)},t.prototype.addInIcon=function(e,t){var o=p.createIconNoSpan(e,this.gridOptionsWrapper,null);this.getRefElement(t).appendChild(o)},t.prototype.addGroupExpandIcon=function(){if(!this.params.columnGroup.isExpandable())return p.setDisplayed(this.eOpenIcon,!1),void p.setDisplayed(this.eCloseIcon,!1)},t.prototype.setupLabel=function(){this.params.displayName&&""!==this.params.displayName&&(this.getRefElement("agLabel").innerHTML=this.params.displayName)},t.TEMPLATE='<div class="ag-header-group-cell-label" ref="agContainer" role="presentation"><span ref="agLabel" class="ag-header-group-text" role="columnheader"></span><span ref="agOpened" class="ag-header-icon ag-header-expand-icon ag-header-expand-icon-expanded"></span><span ref="agClosed" class="ag-header-icon ag-header-expand-icon ag-header-expand-icon-collapsed"></span></div>',ke([m("columnController")],t.prototype,"columnController",void 0),ke([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),ke([fe("agOpened")],t.prototype,"eOpenIcon",void 0),ke([fe("agClosed")],t.prototype,"eCloseIcon",void 0),t}(pe),Ue=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},je=function(){function e(){this.childrenMapped={},this.selectable=!0,this.__objectId=e.OBJECT_ID_SEQUENCE++,this.alreadyRendered=!1,this.selected=!1}return e.prototype.setData=function(e){var t=this.data;this.data=e,this.valueCache.onDataChanged(),this.updateDataOnDetailNode(),this.checkRowSelectable();var o=this.createDataChangedEvent(e,t,!1);this.dispatchLocalEvent(o)},e.prototype.updateDataOnDetailNode=function(){this.detailNode&&(this.detailNode.data=this.data)},e.prototype.createDataChangedEvent=function(t,o,i){return{type:e.EVENT_DATA_CHANGED,node:this,oldData:o,newData:t,update:i}},e.prototype.createLocalRowEvent=function(e){return{type:e,node:this}},e.prototype.updateData=function(e){var t=this.data;this.data=e,this.updateDataOnDetailNode(),this.checkRowSelectable(),this.updateDataOnDetailNode();var o=this.createDataChangedEvent(e,t,!0);this.dispatchLocalEvent(o)},e.prototype.getRowIndexString=function(){return this.rowPinned===o.PINNED_TOP?"t-"+this.rowIndex:this.rowPinned===o.PINNED_BOTTOM?"b-"+this.rowIndex:this.rowIndex.toString()},e.prototype.createDaemonNode=function(){var t=new e;return this.context.wireBean(t),t.id=this.id,t.data=this.data,t.daemon=!0,t.selected=this.selected,t.level=this.level,t},e.prototype.setDataAndId=function(e,t){var o=p.exists(this.id)?this.createDaemonNode():null,i=this.data;this.data=e,this.updateDataOnDetailNode(),this.setId(t),this.selectionController.syncInRowNode(this,o),this.checkRowSelectable();var n=this.createDataChangedEvent(e,i,!1);this.dispatchLocalEvent(n)},e.prototype.checkRowSelectable=function(){var e=this.gridOptionsWrapper.getIsRowSelectableFunc(),t=e&&p.exists(this);this.setRowSelectable(!t||e(this))},e.prototype.setRowSelectable=function(t){this.selectable!==t&&(this.selectable=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_SELECTABLE_CHANGED)))},e.prototype.setId=function(e){var t=this.gridOptionsWrapper.getRowNodeIdFunc();t?this.data?this.id=t(this.data):this.id=void 0:this.id=e},e.prototype.isPixelInRange=function(e){return e>=this.rowTop&&e<this.rowTop+this.rowHeight},e.prototype.clearRowTop=function(){this.oldRowTop=this.rowTop,this.setRowTop(null)},e.prototype.setFirstChild=function(t){this.firstChild!==t&&(this.firstChild=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_FIRST_CHILD_CHANGED)))},e.prototype.setLastChild=function(t){this.lastChild!==t&&(this.lastChild=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_LAST_CHILD_CHANGED)))},e.prototype.setChildIndex=function(t){this.childIndex!==t&&(this.childIndex=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_CHILD_INDEX_CHANGED)))},e.prototype.setRowTop=function(t){this.rowTop!==t&&(this.rowTop=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_TOP_CHANGED)))},e.prototype.setDragging=function(t){this.dragging!==t&&(this.dragging=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_DRAGGING_CHANGED)))},e.prototype.setAllChildrenCount=function(t){this.allChildrenCount!==t&&(this.allChildrenCount=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_ALL_CHILDREN_COUNT_CHANGED)))},e.prototype.setRowHeight=function(t,o){void 0===o&&(o=!1),this.rowHeight=t,this.rowHeightEstimated=o,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_HEIGHT_CHANGED))},e.prototype.setRowIndex=function(t){this.rowIndex=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_ROW_INDEX_CHANGED))},e.prototype.setUiLevel=function(t){this.uiLevel!==t&&(this.uiLevel=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_UI_LEVEL_CHANGED)))},e.prototype.setExpanded=function(t){if(this.expanded!==t){this.expanded=t,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(e.EVENT_EXPANDED_CHANGED));var o=this.createGlobalRowEvent(M.EVENT_ROW_GROUP_OPENED);this.mainEventService.dispatchEvent(o),this.gridOptionsWrapper.isGroupIncludeFooter()&&this.gridApi.redrawRows({rowNodes:[this]})}},e.prototype.createGlobalRowEvent=function(e){return{type:e,node:this,data:this.data,rowIndex:this.rowIndex,rowPinned:this.rowPinned,context:this.gridOptionsWrapper.getContext(),api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi()}},e.prototype.dispatchLocalEvent=function(e){this.eventService&&this.eventService.dispatchEvent(e)},e.prototype.setDataValue=function(e,t){var o=this.columnController.getPrimaryColumn(e);this.valueService.setValue(this,o,t),this.dispatchCellChangedEvent(o,t)},e.prototype.setGroupValue=function(e,t){var o=this.columnController.getGridColumn(e);p.missing(this.groupData)&&(this.groupData={}),this.groupData[o.getColId()]=t,this.dispatchCellChangedEvent(o,t)},e.prototype.setAggData=function(e){var t=this,o=p.getAllKeysInObjects([this.aggData,e]);this.aggData=e,this.eventService&&o.forEach((function(e){var o=t.columnController.getGridColumn(e),i=t.aggData?t.aggData[e]:void 0;t.dispatchCellChangedEvent(o,i)}))},e.prototype.hasChildren=function(){return this.group||this.childrenAfterGroup&&this.childrenAfterGroup.length>0},e.prototype.isEmptyRowGroupNode=function(){return this.group&&p.missingOrEmpty(this.childrenAfterGroup)},e.prototype.dispatchCellChangedEvent=function(t,o){var i={type:e.EVENT_CELL_CHANGED,node:this,column:t,newValue:o};this.dispatchLocalEvent(i)},e.prototype.resetQuickFilterAggregateText=function(){this.quickFilterAggregateText=null},e.prototype.isExpandable=function(){return this.hasChildren()||this.master},e.prototype.isSelected=function(){return this.footer?this.sibling.isSelected():this.selected},e.prototype.depthFirstSearch=function(e){this.childrenAfterGroup&&this.childrenAfterGroup.forEach((function(t){return t.depthFirstSearch(e)})),e(this)},e.prototype.calculateSelectedFromChildren=function(){var e,t=!1,o=!1,i=!1;if(this.childrenAfterGroup)for(var n=0;n<this.childrenAfterGroup.length;n++){var r=this.childrenAfterGroup[n];if(r.selectable)switch(r.isSelected()){case!0:t=!0;break;case!1:o=!0;break;default:i=!0}}e=i?void 0:!(!t||o)||!(!t&&o)&&void 0,this.selectThisNode(e)},e.prototype.setSelectedInitialValue=function(e){this.selected=e},e.prototype.setSelected=function(e,t,o){void 0===t&&(t=!1),void 0===o&&(o=!1),this.setSelectedParams({newValue:e,clearSelection:t,suppressFinishActions:o,rangeSelect:!1})},e.prototype.isRowPinned=function(){return this.rowPinned===o.PINNED_TOP||this.rowPinned===o.PINNED_BOTTOM},e.prototype.setSelectedParams=function(e){var t=this.gridOptionsWrapper.isGroupSelectsChildren(),o=!0===e.newValue,i=!0===e.clearSelection,n=!0===e.suppressFinishActions,r=!0===e.rangeSelect,s=t&&!0===e.groupSelectsFiltered;if(void 0===this.id)return console.warn("ag-Grid: cannot select node until id for node is known"),0;if(this.rowPinned)return console.warn("ag-Grid: cannot select pinned rows"),0;if(this.footer)return this.sibling.setSelectedParams(e);if(r){var a=this.selectionController.getLastSelectedNode()!==this,l=this.gridOptionsWrapper.isRowSelectionMulti();if(a&&l)return this.doRowRangeSelection()}var p=0;s&&this.group||this.selectThisNode(o)&&p++;if(t&&this.group&&(p+=this.selectChildNodes(o,s)),!n){if(o&&(i||!this.gridOptionsWrapper.isRowSelectionMulti())&&(p+=this.selectionController.clearOtherNodes(this)),p>0){this.selectionController.updateGroupsFromChildrenSelections();var u={type:M.EVENT_SELECTION_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.mainEventService.dispatchEvent(u)}o&&this.selectionController.setLastSelectedNode(this)}return p},e.prototype.doRowRangeSelection=function(){var e=0,t=this.gridOptionsWrapper.isGroupSelectsChildren(),o=this.selectionController.getLastSelectedNode();this.rowModel.getNodesInRangeForSelection(this,o).forEach((function(o){o.group&&t||o.selectThisNode(!0)&&e++})),this.selectionController.updateGroupsFromChildrenSelections();var i={type:M.EVENT_SELECTION_CHANGED,api:this.gridApi,columnApi:this.columnApi};return this.mainEventService.dispatchEvent(i),e},e.prototype.isParentOfNode=function(e){for(var t=this.parent;t;){if(t===e)return!0;t=t.parent}return!1},e.prototype.selectThisNode=function(t){if(!this.selectable||this.selected===t)return!1;this.selected=t,this.eventService&&this.dispatchLocalEvent(this.createLocalRowEvent(e.EVENT_ROW_SELECTED));var o=this.createGlobalRowEvent(M.EVENT_ROW_SELECTED);return this.mainEventService.dispatchEvent(o),!0},e.prototype.selectChildNodes=function(e,t){var o=t?this.childrenAfterFilter:this.childrenAfterGroup,i=0;if(!p.missing(o)){for(var n=0;n<o.length;n++)i+=o[n].setSelectedParams({newValue:e,clearSelection:!1,suppressFinishActions:!0,groupSelectsFiltered:t});return i}},e.prototype.addEventListener=function(e,t){this.eventService||(this.eventService=new b),this.eventService.addEventListener(e,t)},e.prototype.removeEventListener=function(e,t){this.eventService.removeEventListener(e,t)},e.prototype.onMouseEnter=function(){this.dispatchLocalEvent(this.createLocalRowEvent(e.EVENT_MOUSE_ENTER))},e.prototype.onMouseLeave=function(){this.dispatchLocalEvent(this.createLocalRowEvent(e.EVENT_MOUSE_LEAVE))},e.prototype.getFirstChildOfFirstChild=function(e){for(var t,o=this,i=!0,n=!1;i&&!n;){var r=o.parent;p.exists(r)&&o.firstChild?r.rowGroupColumn===e&&(n=!0,t=r):i=!1,o=r}return n?t:null},e.prototype.isFullWidthCell=function(){var e=this.gridOptionsWrapper.getIsFullWidthCellFunc();return!!e&&e(this)},e.OBJECT_ID_SEQUENCE=0,e.EVENT_ROW_SELECTED="rowSelected",e.EVENT_DATA_CHANGED="dataChanged",e.EVENT_CELL_CHANGED="cellChanged",e.EVENT_ALL_CHILDREN_COUNT_CHANGED="allChildrenCountChanged",e.EVENT_MOUSE_ENTER="mouseEnter",e.EVENT_MOUSE_LEAVE="mouseLeave",e.EVENT_HEIGHT_CHANGED="heightChanged",e.EVENT_TOP_CHANGED="topChanged",e.EVENT_FIRST_CHILD_CHANGED="firstChildChanged",e.EVENT_LAST_CHILD_CHANGED="lastChildChanged",e.EVENT_CHILD_INDEX_CHANGED="childIndexChanged",e.EVENT_ROW_INDEX_CHANGED="rowIndexChanged",e.EVENT_EXPANDED_CHANGED="expandedChanged",e.EVENT_SELECTABLE_CHANGED="selectableChanged",e.EVENT_UI_LEVEL_CHANGED="uiLevelChanged",e.EVENT_DRAGGING_CHANGED="draggingChanged",Ue([m("eventService")],e.prototype,"mainEventService",void 0),Ue([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Ue([m("selectionController")],e.prototype,"selectionController",void 0),Ue([m("columnController")],e.prototype,"columnController",void 0),Ue([m("valueService")],e.prototype,"valueService",void 0),Ue([m("rowModel")],e.prototype,"rowModel",void 0),Ue([m("context")],e.prototype,"context",void 0),Ue([m("valueCache")],e.prototype,"valueCache",void 0),Ue([m("columnApi")],e.prototype,"columnApi",void 0),Ue([m("gridApi")],e.prototype,"gridApi",void 0),e}(),ze=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ye=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ke=function(e){function t(){return e.call(this,'<span class="ag-selection-checkbox"/>')||this}return ze(t,e),t.prototype.createAndAddIcons=function(){this.eCheckedIcon=p.createIconNoSpan("checkboxChecked",this.gridOptionsWrapper,this.column),this.eUncheckedIcon=p.createIconNoSpan("checkboxUnchecked",this.gridOptionsWrapper,this.column),this.eIndeterminateIcon=p.createIconNoSpan("checkboxIndeterminate",this.gridOptionsWrapper,this.column);var e=this.getGui();e.appendChild(this.eCheckedIcon),e.appendChild(this.eUncheckedIcon),e.appendChild(this.eIndeterminateIcon)},t.prototype.onDataChanged=function(){this.onSelectionChanged()},t.prototype.onSelectableChanged=function(){this.showOrHideSelect()},t.prototype.onSelectionChanged=function(){var e=this.rowNode.isSelected();p.setDisplayed(this.eCheckedIcon,!0===e),p.setDisplayed(this.eUncheckedIcon,!1===e),p.setDisplayed(this.eIndeterminateIcon,"boolean"!=typeof e)},t.prototype.onCheckedClicked=function(){var e=this.gridOptionsWrapper.isGroupSelectsFiltered();return this.rowNode.setSelectedParams({newValue:!1,groupSelectsFiltered:e})},t.prototype.onUncheckedClicked=function(e){var t=this.gridOptionsWrapper.isGroupSelectsFiltered();return this.rowNode.setSelectedParams({newValue:!0,rangeSelect:e.shiftKey,groupSelectsFiltered:t})},t.prototype.onIndeterminateClicked=function(e){0===this.onUncheckedClicked(e)&&this.onCheckedClicked()},t.prototype.init=function(e){this.rowNode=e.rowNode,this.column=e.column,this.createAndAddIcons(),this.onSelectionChanged(),this.addGuiEventListener("click",(function(e){return p.stopPropagationForAgGrid(e)})),this.addGuiEventListener("dblclick",(function(e){return p.stopPropagationForAgGrid(e)})),this.addDestroyableEventListener(this.eCheckedIcon,"click",this.onCheckedClicked.bind(this)),this.addDestroyableEventListener(this.eUncheckedIcon,"click",this.onUncheckedClicked.bind(this)),this.addDestroyableEventListener(this.eIndeterminateIcon,"click",this.onIndeterminateClicked.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_ROW_SELECTED,this.onSelectionChanged.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_DATA_CHANGED,this.onDataChanged.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_SELECTABLE_CHANGED,this.onSelectableChanged.bind(this)),this.isRowSelectableFunc=this.gridOptionsWrapper.getIsRowSelectableFunc(),(this.isRowSelectableFunc||this.checkboxCallbackExists())&&(this.addDestroyableEventListener(this.eventService,M.EVENT_DISPLAYED_COLUMNS_CHANGED,this.showOrHideSelect.bind(this)),this.showOrHideSelect())},t.prototype.showOrHideSelect=function(){var e=this.rowNode.selectable;e&&this.checkboxCallbackExists()&&(e=this.column.isCellCheckboxSelection(this.rowNode)),this.setDisplayed(e)},t.prototype.checkboxCallbackExists=function(){var e=this.column?this.column.getColDef():null;return e&&"function"==typeof e.checkboxSelection},Ye([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Ye([m("eventService")],t.prototype,"eventService",void 0),Ye([m("gridApi")],t.prototype,"gridApi",void 0),Ye([m("columnApi")],t.prototype,"columnApi",void 0),t}(pe),qe=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s};!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.REGISTERED_BY_NAME=1]="REGISTERED_BY_NAME",e[e.HARDCODED=2]="HARDCODED"}(Te||(Te={}));var Qe,Xe=function(){function e(){}return e.prototype.newDateComponent=function(e){return this.createAndInitUserComponent(this.gridOptions,e,"dateComponent","agDateInput")},e.prototype.newHeaderComponent=function(e){return this.createAndInitUserComponent(e.column.getColDef(),e,"headerComponent","agColumnHeader")},e.prototype.newHeaderGroupComponent=function(e){return this.createAndInitUserComponent(e.columnGroup.getColGroupDef(),e,"headerGroupComponent","agColumnGroupHeader")},e.prototype.newFullWidthGroupRowInnerCellRenderer=function(e){return this.createAndInitUserComponent(this.gridOptions,e,"groupRowInnerRenderer",null,!0)},e.prototype.newFullWidthCellRenderer=function(e,t,o){return this.createAndInitUserComponent(null,e,t,o)},e.prototype.newCellRenderer=function(e,t){return this.createAndInitUserComponent(e,t,"cellRenderer",null,!0)},e.prototype.newPinnedRowCellRenderer=function(e,t){return this.createAndInitUserComponent(e,t,"pinnedRowCellRenderer",null,!0)},e.prototype.newCellEditor=function(e,t){return this.createAndInitUserComponent(e,t,"cellEditor","agCellEditor")},e.prototype.newInnerCellRenderer=function(e,t){return this.createAndInitUserComponent(e,t,"innerRenderer",null)},e.prototype.newLoadingOverlayComponent=function(e){return this.createAndInitUserComponent(this.gridOptions,e,"loadingOverlayComponent","agLoadingOverlay")},e.prototype.newNoRowsOverlayComponent=function(e){return this.createAndInitUserComponent(this.gridOptions,e,"noRowsOverlayComponent","agNoRowsOverlay")},e.prototype.newTooltipComponent=function(e){var t=e.colDef;return this.createAndInitUserComponent(t,e,"tooltipComponent","agTooltipComponent")},e.prototype.newFilterComponent=function(e,t,o,i){return this.createAndInitUserComponent(e,t,"filter",o,!1,i)},e.prototype.newFloatingFilterComponent=function(e,t,o){return this.createAndInitUserComponent(e,t,"floatingFilterComponent",o,!0)},e.prototype.newToolPanelComponent=function(e,t){return this.createAndInitUserComponent(e,t,"toolPanel")},e.prototype.newStatusPanelComponent=function(e,t){return this.createAndInitUserComponent(e,t,"statusPanel")},e.prototype.createAndInitUserComponent=function(e,t,o,i,n,r){void 0===n&&(n=!1),e||(e=this.gridOptions);var s=this.createComponentInstance(e,o,t,i,n);if(!s)return null;var a=s.componentInstance,l=this.createFinalParams(e,o,t,s.paramsFromSelector);this.addReactHacks(l);var p=r?r(l,a):l,c=this.initComponent(a,p);return null==c?u.resolve(a):c.map((function(e){return a}))},e.prototype.addReactHacks=function(e){var t=this.context.getBean("agGridReact");t&&(e.agGridReact=p.cloneObject(t));var o=this.context.getBean("frameworkComponentWrapper");o&&(e.frameworkComponentWrapper=o)},e.prototype.createUserComponentFromConcreteClass=function(e,t){var o=new e;return this.initComponent(o,t),o},e.prototype.lookupComponentClassDef=function(e,t,o,i){void 0===o&&(o=null);var n,r=null,s=null,a=null,l=null;if(null!=e){var p=e[t];null==p||!0===p||("string"==typeof p?r=p:"boolean"==typeof p||(this.agComponentUtils.doesImplementIComponent(p)?s=p:a=p)),l=e[t+"Framework"],n=e[t+"Selector"]}if(s&&l||r&&l||a&&l)throw Error("ag-grid: you are trying to specify: "+t+" twice as a component.");if(l&&!this.frameworkComponentWrapper)throw Error("ag-grid: you are specifying a framework component but you are not using a framework version of ag-grid for : "+t);if(n&&(r||s||a||l))throw Error("ag-grid: you can't specify both, the selector and the component of ag-grid for : "+t);if(l)return{componentFromFramework:!0,component:l,source:Te.HARDCODED,paramsFromSelector:null};if(s)return{componentFromFramework:!1,component:s,source:Te.HARDCODED,paramsFromSelector:null};if(a)return this.agComponentUtils.adaptFunction(t,a,!1,Te.HARDCODED);var u,c=n?n(o):null;if(!(u=c&&c.component?c.component:r||i))return null;var d=this.lookupFromRegisteredComponents(t,u);return d?{componentFromFramework:d.componentFromFramework,component:d.component,source:d.source,paramsFromSelector:c?c.params:null}:null},e.prototype.lookupFromRegisteredComponents=function(e,t){var o=null!=t?t:e,i=this.userComponentRegistry.retrieve(o);return null==i?null:i.componentFromFramework?{component:i.component,componentFromFramework:!0,source:Te.REGISTERED_BY_NAME,paramsFromSelector:null}:this.agComponentUtils.doesImplementIComponent(i.component)?{component:i.component,componentFromFramework:!1,source:i.source==Qe.REGISTERED?Te.REGISTERED_BY_NAME:Te.DEFAULT,paramsFromSelector:null}:this.agComponentUtils.adaptFunction(e,i.component,i.componentFromFramework,i.source==Qe.REGISTERED?Te.REGISTERED_BY_NAME:Te.DEFAULT)},e.prototype.createFinalParams=function(e,t,o,i){void 0===i&&(i=null);var n={};p.mergeDeep(n,o);var r=e?e[t+"Params"]:null;return null!=r&&("function"==typeof r?p.mergeDeep(n,r(o)):"object"==typeof r&&p.mergeDeep(n,r)),p.mergeDeep(n,i),n},e.prototype.createComponentInstance=function(e,t,o,i,n){var r,s=this.lookupComponentClassDef(e,t,o,i);if(!s||!s.component){var a=e?e[t]:i,l=a||i;return n||console.error("Could not find component "+l+", did you forget to configure this component?"),null}if(s.componentFromFramework){var p=s.component,u=this.componentMetadataProvider.retrieve(t);r=this.frameworkComponentWrapper.wrap(p,u.mandatoryMethodList,u.optionalMethodList,i)}else r=new s.component;return{componentInstance:r,paramsFromSelector:s.paramsFromSelector}},e.prototype.initComponent=function(e,t){return this.context.wireBean(e),null==e.init?void 0:e.init(t)},qe([m("gridOptions")],e.prototype,"gridOptions",void 0),qe([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),qe([m("context")],e.prototype,"context",void 0),qe([m("agComponentUtils")],e.prototype,"agComponentUtils",void 0),qe([m("componentMetadataProvider")],e.prototype,"componentMetadataProvider",void 0),qe([m("userComponentRegistry")],e.prototype,"userComponentRegistry",void 0),qe([v("frameworkComponentWrapper")],e.prototype,"frameworkComponentWrapper",void 0),e=qe([y("userComponentFactory")],e)}(),$e=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Je=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ze=function(e){function t(){return e.call(this,t.TEMPLATE)||this}return $e(t,e),t.prototype.init=function(e){this.params=e,this.gridOptionsWrapper.isGroupIncludeTotalFooter()&&this.assignBlankValueToGroupFooterCell(e);var t=this.isEmbeddedRowMismatch(),o=null==e.value;this.cellIsBlank=t||o,this.cellIsBlank||(this.setupDragOpenParents(),this.addExpandAndContract(),this.addCheckboxIfNeeded(),this.addValueElement(),this.setupIndent())},t.prototype.assignBlankValueToGroupFooterCell=function(e){e.value||-1!=e.node.level||(e.value="")},t.prototype.isEmbeddedRowMismatch=function(){if(this.params.fullWidth&&this.gridOptionsWrapper.isEmbedFullWidthRows()){var e=this.params.pinned===o.PINNED_LEFT,t=this.params.pinned===o.PINNED_RIGHT,i=!e&&!t;return this.gridOptionsWrapper.isEnableRtl()?this.columnController.isPinningLeft()?!t:!i:this.columnController.isPinningLeft()?!e:!i}return!1},t.prototype.setIndent=function(){if(!this.gridOptionsWrapper.isGroupHideOpenParents()){var e=this.params,t=e.node.uiLevel;e.padding>=0?this.setPaddingDeprecatedWay(t,e.padding):(this.indentClass&&this.removeCssClass(this.indentClass),this.indentClass="ag-row-group-indent-"+t,this.addCssClass(this.indentClass))}},t.prototype.setPaddingDeprecatedWay=function(e,t){p.doOnce((function(){return console.warn("ag-Grid: since v14.2, configuring padding for groupCellRenderer should be done with Sass variables and themes. Please see the ag-Grid documentation page for Themes, in particular the property $row-group-indent-size.")}),"groupCellRenderer->doDeprecatedWay");var o=e*t;this.gridOptionsWrapper.isEnableRtl()?this.getGui().style.paddingRight=o+"px":this.getGui().style.paddingLeft=o+"px"},t.prototype.setupIndent=function(){var e=this.params.node;this.params.suppressPadding||(this.addDestroyableEventListener(e,je.EVENT_UI_LEVEL_CHANGED,this.setIndent.bind(this)),this.setIndent())},t.prototype.addValueElement=function(){var e=this.params,t=this.displayedGroup;t.footer?this.createFooterCell():t.hasChildren()||p.get(e.colDef,"cellRendererParams.innerRenderer",null)||p.get(e.colDef,"cellRendererParams.innerRendererFramework",null)?(this.createGroupCell(),t.hasChildren()&&this.addChildCount()):this.createLeafCell()},t.prototype.createFooterCell=function(){var e,t=this.params.footerValueGetter;if(t){var o=p.cloneObject(this.params);o.value=this.params.value,"function"==typeof t?e=t(o):"string"==typeof t?e=this.expressionService.evaluate(t,o):console.warn("ag-Grid: footerValueGetter should be either a function or a string (expression)")}else e="Total "+this.params.value;this.eValue.innerHTML=e},t.prototype.createGroupCell=function(){var e,t=this,o=this.params,i=this.displayedGroup.rowGroupColumn,n=i||o.column,r=this.params.value,s=n?this.valueFormatterService.formatValue(n,o.node,o.scope,r):null;o.valueFormatted=s,(e=1==o.fullWidth?this.useFullWidth(o):this.useInnerRenderer(this.params.colDef.cellRendererParams,n.getColDef(),o))&&e.then((function(e){t.innerCellRenderer=e}))},t.prototype.useInnerRenderer=function(e,t,o){var i=this,n=null,r=this.userComponentFactory.lookupComponentClassDef(e,"innerRenderer");if(r&&null!=r.component&&r.source!=Te.DEFAULT)n=this.userComponentFactory.newInnerCellRenderer(e,o);else{var s=this.userComponentFactory.lookupComponentClassDef(t,"cellRenderer");n=s&&s.source!=Te.DEFAULT?this.userComponentFactory.newCellRenderer(t,o):s&&s.source==Te.DEFAULT&&p.get(t,"cellRendererParams.innerRenderer",null)?this.userComponentFactory.newInnerCellRenderer(t.cellRendererParams,o):this.userComponentFactory.newCellRenderer({},o)}return null!=n?n.then((function(e){null!=e?p.bindCellRendererToHtmlElement(n,i.eValue):i.eValue.innerText=null!=o.valueFormatted?o.valueFormatted:o.value})):this.eValue.innerText=null!=o.valueFormatted?o.valueFormatted:o.value,n},t.prototype.useFullWidth=function(e){var t=this.userComponentFactory.newFullWidthGroupRowInnerCellRenderer(e);return null!=t?p.bindCellRendererToHtmlElement(t,this.eValue):this.eValue.innerText=null!=e.valueFormatted?e.valueFormatted:e.value,t},t.prototype.addChildCount=function(){this.params.suppressCount||(this.addDestroyableEventListener(this.displayedGroup,je.EVENT_ALL_CHILDREN_COUNT_CHANGED,this.updateChildCount.bind(this)),this.updateChildCount())},t.prototype.updateChildCount=function(){var e=this.displayedGroup.allChildrenCount;this.eChildCount.innerHTML=e>=0?"("+e+")":""},t.prototype.createLeafCell=function(){p.exists(this.params.value)&&(this.eValue.innerText=this.params.valueFormatted?this.params.valueFormatted:this.params.value)},t.prototype.isUserWantsSelected=function(){var e=this.params.checkbox;return"function"==typeof e?e(this.params):!0===e},t.prototype.addCheckboxIfNeeded=function(){var e=this.displayedGroup,t=this.isUserWantsSelected()&&!e.footer&&!e.rowPinned&&!e.detail;if(t){var o=new Ke;this.getContext().wireBean(o),o.init({rowNode:e,column:this.params.column}),this.eCheckbox.appendChild(o.getGui()),this.addDestroyFunc((function(){return o.destroy()}))}p.addOrRemoveCssClass(this.eCheckbox,"ag-invisible",!t)},t.prototype.addExpandAndContract=function(){var e=this.params,t=e.eGridCell,o=p.createIconNoSpan("groupExpanded",this.gridOptionsWrapper,null),i=p.createIconNoSpan("groupContracted",this.gridOptionsWrapper,null);this.eExpanded.appendChild(o),this.eContracted.appendChild(i),this.addDestroyableEventListener(this.eExpanded,"click",this.onExpandClicked.bind(this)),this.addDestroyableEventListener(this.eContracted,"click",this.onExpandClicked.bind(this)),this.addDestroyableEventListener(t,"keydown",this.onKeyDown.bind(this)),this.addDestroyableEventListener(e.node,je.EVENT_EXPANDED_CHANGED,this.showExpandAndContractIcons.bind(this)),this.showExpandAndContractIcons(),this.addDestroyableEventListener(this.displayedGroup,je.EVENT_ALL_CHILDREN_COUNT_CHANGED,this.onAllChildrenCountChanged.bind(this)),this.gridOptionsWrapper.isEnableGroupEdit()||!this.isExpandable()||e.suppressDoubleClickExpand||this.addDestroyableEventListener(t,"dblclick",this.onCellDblClicked.bind(this))},t.prototype.onAllChildrenCountChanged=function(){this.showExpandAndContractIcons(),this.setIndent()},t.prototype.onKeyDown=function(e){if(p.isKeyPressed(e,o.KEY_ENTER)){if(this.params.suppressEnterExpand)return;if(this.params.column&&this.params.column.isCellEditable(this.params.node))return;e.preventDefault(),this.onExpandOrContract()}},t.prototype.setupDragOpenParents=function(){var e=this.params.column,t=this.params.node;if(this.gridOptionsWrapper.isGroupHideOpenParents())if(t.hasChildren()){var o=t.rowGroupColumn;this.draggedFromHideOpenParents=!!o&&!e.isRowGroupDisplayed(o.getId())}else this.draggedFromHideOpenParents=!0;else this.draggedFromHideOpenParents=!1;if(this.draggedFromHideOpenParents)for(var i=t.parent;!p.missing(i);){if(i.rowGroupColumn&&e.isRowGroupDisplayed(i.rowGroupColumn.getId())){this.displayedGroup=i;break}i=i.parent}p.missing(this.displayedGroup)&&(this.displayedGroup=t)},t.prototype.onExpandClicked=function(e){p.isStopPropagationForAgGrid(e)||(p.stopPropagationForAgGrid(e),this.onExpandOrContract())},t.prototype.onCellDblClicked=function(e){p.isStopPropagationForAgGrid(e)||(p.isElementInEventPath(this.eExpanded,e)||p.isElementInEventPath(this.eContracted,e)||this.onExpandOrContract())},t.prototype.onExpandOrContract=function(){var e=this.displayedGroup;e.setExpanded(!e.expanded)},t.prototype.isExpandable=function(){var e=this.params.node,t=this.columnController.isPivotMode()&&e.leafGroup;return this.draggedFromHideOpenParents||e.isExpandable()&&!e.footer&&!t},t.prototype.showExpandAndContractIcons=function(){var e=this.params.node;if(this.isExpandable()){var t=!!this.draggedFromHideOpenParents||e.expanded;p.setDisplayed(this.eContracted,!t),p.setDisplayed(this.eExpanded,t)}else p.setDisplayed(this.eExpanded,!1),p.setDisplayed(this.eContracted,!1);var o=this.displayedGroup,i=this.columnController.isPivotMode()&&o.leafGroup,n=!o.isExpandable(),r=o.footer||n||i;this.addOrRemoveCssClass("ag-row-group",!r),this.addOrRemoveCssClass("ag-row-group-leaf-indent",r)},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.innerCellRenderer&&this.innerCellRenderer.destroy&&this.innerCellRenderer.destroy()},t.prototype.refresh=function(){return!1},t.TEMPLATE='<span class="ag-cell-wrapper"><span class="ag-group-expanded" ref="eExpanded"></span><span class="ag-group-contracted" ref="eContracted"></span><span class="ag-group-checkbox ag-invisible" ref="eCheckbox"></span><span class="ag-group-value" ref="eValue"></span><span class="ag-group-child-count" ref="eChildCount"></span></span>',Je([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Je([m("expressionService")],t.prototype,"expressionService",void 0),Je([m("eventService")],t.prototype,"eventService",void 0),Je([m("valueFormatterService")],t.prototype,"valueFormatterService",void 0),Je([m("columnController")],t.prototype,"columnController",void 0),Je([m("mouseEventService")],t.prototype,"mouseEventService",void 0),Je([m("userComponentFactory")],t.prototype,"userComponentFactory",void 0),Je([fe("eExpanded")],t.prototype,"eExpanded",void 0),Je([fe("eContracted")],t.prototype,"eContracted",void 0),Je([fe("eCheckbox")],t.prototype,"eCheckbox",void 0),Je([fe("eValue")],t.prototype,"eValue",void 0),Je([fe("eChildCount")],t.prototype,"eChildCount",void 0),t}(pe),et=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),tt=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},ot=function(e){function t(){var o=e.call(this,t.TEMPLATE)||this;return o.refreshCount=0,o}return et(t,e),t.prototype.init=function(e){this.eValue=this.queryForHtmlElement(".ag-value-change-value"),this.eDelta=this.queryForHtmlElement(".ag-value-change-delta"),this.refresh(e)},t.prototype.showDelta=function(e,t){var o=Math.abs(t),i=e.formatValue(o),n=p.exists(i)?i:o,r=t>=0;this.eDelta.innerHTML=r?"\u2191"+n:"\u2193"+n,p.addOrRemoveCssClass(this.eDelta,"ag-value-change-delta-up",r),p.addOrRemoveCssClass(this.eDelta,"ag-value-change-delta-down",!r)},t.prototype.setTimerToRemoveDelta=function(){var e=this;this.refreshCount++;var t=this.refreshCount;window.setTimeout((function(){t===e.refreshCount&&e.hideDeltaValue()}),2e3)},t.prototype.hideDeltaValue=function(){p.removeCssClass(this.eValue,"ag-value-change-value-highlight"),p.clearElement(this.eDelta)},t.prototype.refresh=function(e){var t=e.value;if(t!==this.lastValue&&(p.exists(e.valueFormatted)?this.eValue.innerHTML=e.valueFormatted:p.exists(e.value)?this.eValue.innerHTML=t:p.clearElement(this.eValue),!this.filterManager.isSuppressFlashingCellsBecauseFiltering())){if("number"==typeof t&&"number"==typeof this.lastValue){var o=t-this.lastValue;this.showDelta(e,o)}return this.lastValue&&p.addCssClass(this.eValue,"ag-value-change-value-highlight"),this.setTimerToRemoveDelta(),this.lastValue=t,!0}},t.TEMPLATE='<span><span class="ag-value-change-delta"></span><span class="ag-value-change-value"></span></span>',tt([m("filterManager")],t.prototype,"filterManager",void 0),t}(pe),it=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),nt=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},rt=function(e){function t(){var o=e.call(this,t.TEMPLATE)||this;return o.refreshCount=0,o.eCurrent=o.queryForHtmlElement(".ag-value-slide-current"),o}return it(t,e),t.prototype.init=function(e){this.params=e,this.refresh(e)},t.prototype.addSlideAnimation=function(){var e=this;this.refreshCount++;var t=this.refreshCount;this.ePrevious&&this.getGui().removeChild(this.ePrevious),this.ePrevious=p.loadTemplate('<span class="ag-value-slide-previous ag-value-slide-out"></span>'),this.ePrevious.innerHTML=this.eCurrent.innerHTML,this.getGui().insertBefore(this.ePrevious,this.eCurrent),window.setTimeout((function(){t===e.refreshCount&&p.addCssClass(e.ePrevious,"ag-value-slide-out-end")}),50),window.setTimeout((function(){t===e.refreshCount&&(e.getGui().removeChild(e.ePrevious),e.ePrevious=null)}),3e3)},t.prototype.refresh=function(e){var t=e.value;if(p.missing(t)&&(t=""),t!==this.lastValue&&!this.filterManager.isSuppressFlashingCellsBecauseFiltering())return this.addSlideAnimation(),this.lastValue=t,p.exists(e.valueFormatted)?this.eCurrent.innerHTML=e.valueFormatted:p.exists(e.value)?this.eCurrent.innerHTML=t:p.clearElement(this.eCurrent),!0},t.TEMPLATE='<span><span class="ag-value-slide-current"></span></span>',nt([m("filterManager")],t.prototype,"filterManager",void 0),t}(pe),st=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),at=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},lt=function(e){function t(){return e.call(this,t.TEMPLATE)||this}return st(t,e),t.prototype.init=function(e){var t=p.createIconNoSpan("groupLoading",this.gridOptionsWrapper,null);this.eLoadingIcon.appendChild(t);var o=this.gridOptionsWrapper.getLocaleTextFunc();this.eLoadingText.innerText=o("loadingOoo","Loading")},t.prototype.refresh=function(e){return!1},t.TEMPLATE='<div class="ag-stub-cell">\n <span class="ag-loading-icon" ref="eLoadingIcon"></span>\n <span class="ag-loading-text" ref="eLoadingText"></span>\n </div>',at([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),at([fe("eLoadingIcon")],t.prototype,"eLoadingIcon",void 0),at([fe("eLoadingText")],t.prototype,"eLoadingText",void 0),t}(pe),pt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ut=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},ct=function(e){function t(){var t=e.call(this,'<div class="ag-cell-edit-input"><select class="ag-cell-edit-input"/></div>')||this;return t.eSelect=t.getGui().querySelector("select"),t}return pt(t,e),t.prototype.init=function(e){var t=this;this.focusAfterAttached=e.cellStartedEdit,p.missing(e.values)?console.warn("ag-Grid: no values found for select cellEditor"):(e.values.forEach((function(o){var i=document.createElement("option");i.value=o;var n=t.valueFormatterService.formatValue(e.column,null,null,o),r=null!=n;i.text=r?n:o,e.value===o&&(i.selected=!0),t.eSelect.appendChild(i)})),this.gridOptionsWrapper.isFullRowEdit()||this.addDestroyableEventListener(this.eSelect,"change",(function(){return e.stopEditing()})),this.addDestroyableEventListener(this.eSelect,"keydown",(function(e){(e.keyCode===o.KEY_UP||e.keyCode===o.KEY_DOWN)&&e.stopPropagation()})),this.addDestroyableEventListener(this.eSelect,"mousedown",(function(e){e.stopPropagation()})))},t.prototype.afterGuiAttached=function(){this.focusAfterAttached&&this.eSelect.focus()},t.prototype.focusIn=function(){this.eSelect.focus()},t.prototype.getValue=function(){return this.eSelect.value},t.prototype.isPopup=function(){return!1},ut([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),ut([m("valueFormatterService")],t.prototype,"valueFormatterService",void 0),t}(ce),dt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ht=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return dt(t,e),t.prototype.isPopup=function(){return!0},t}(he),gt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ft=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return gt(t,e),t.prototype.isPopup=function(){return!0},t}(ct),yt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),mt=function(e){function t(){return e.call(this,t.TEMPLATE)||this}return yt(t,e),t.prototype.init=function(e){this.params=e,this.focusAfterAttached=e.cellStartedEdit,this.textarea=document.createElement("textarea"),this.textarea.maxLength=e.maxLength?e.maxLength:"200",this.textarea.cols=e.cols?e.cols:"60",this.textarea.rows=e.rows?e.rows:"10",p.exists(e.value)&&(this.textarea.value=e.value.toString()),this.getGui().querySelector(".ag-large-textarea").appendChild(this.textarea),this.addGuiEventListener("keydown",this.onKeyDown.bind(this))},t.prototype.onKeyDown=function(e){var t=e.which||e.keyCode;(t==o.KEY_LEFT||t==o.KEY_UP||t==o.KEY_RIGHT||t==o.KEY_DOWN||e.shiftKey&&t==o.KEY_ENTER)&&e.stopPropagation()},t.prototype.afterGuiAttached=function(){this.focusAfterAttached&&this.textarea.focus()},t.prototype.getValue=function(){return this.params.parseValue(this.textarea.value)},t.TEMPLATE='<div class="ag-large-text" tabindex="0"><div class="ag-large-textarea"></div></div>',t}(ce),vt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ct=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Et=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return vt(t,e),t.prototype.mapRangeFromModel=function(e){return{from:e.filter,to:e.filterTo}},t.prototype.getDefaultDebounceMs=function(){return 500},t.prototype.resetUiToDefaults=function(){e.prototype.resetUiToDefaults.call(this),this.eValueFrom1.value=null,this.eValueFrom2.value=null,this.eValueTo1.value=null,this.eValueTo2.value=null},t.prototype.setConditionIntoUi=function(e,t){var o=t===Ee.One,i=o?this.eValueFrom1:this.eValueFrom2,n=o?this.eValueTo1:this.eValueTo2;i.value=e?""+e.filter:null,n.value=e?""+e.filterTo:null},t.prototype.setValueFromFloatingFilter=function(e){this.eValueFrom1.value=e,this.eValueFrom2.value=null,this.eValueTo1.value=null,this.eValueTo2.value=null},t.prototype.comparator=function(){return function(e,t){return e===t?0:e<t?1:e>t?-1:void 0}},t.prototype.setParams=function(t){e.prototype.setParams.call(this,t),this.addValueChangedListeners()},t.prototype.addValueChangedListeners=function(){var e=this,t=function(){return e.onUiChanged()};this.addDestroyableEventListener(this.eValueFrom1,"input",t),this.addDestroyableEventListener(this.eValueFrom2,"input",t),this.addDestroyableEventListener(this.eValueTo1,"input",t),this.addDestroyableEventListener(this.eValueTo2,"input",t)},t.prototype.afterGuiAttached=function(){this.eValueFrom1.focus()},t.prototype.getDefaultFilterOptions=function(){return t.DEFAULT_FILTER_OPTIONS},t.prototype.createValueTemplate=function(e){var t=e===Ee.One?"1":"2",o=this.translate.bind(this);return'<div class="ag-filter-body" ref="eCondition'+t+'Body" role="presentation">\n <div class="ag-input-wrapper" role="presentation">\n <input class="ag-filter-filter" ref="eValueFrom'+t+'" type="text" placeholder="'+o("filterOoo")+'"/>\n </div>\n <div class="ag-input-wrapper ag-filter-number-to" ref="ePanel'+t+'" role="presentation">\n <input class="ag-filter-filter" ref="eValueTo'+t+'" type="text" placeholder="'+o("filterOoo")+'"/>\n </div>\n </div>'},t.prototype.isConditionUiComplete=function(e){var t=e===Ee.One,o=t?this.getCondition1Type():this.getCondition2Type(),i=t?this.eValueFrom1:this.eValueFrom2,n=t?this.eValueTo1:this.eValueTo2,r=this.stringToFloat(i.value),s=this.stringToFloat(n.value);return o!==_e.EMPTY&&(!!this.doesFilterHaveHiddenInput(o)||(o===_e.IN_RANGE?null!=r&&null!=s:null!=r))},t.prototype.areSimpleModelsEqual=function(e,t){return e.filter===t.filter&&e.filterTo===t.filterTo&&e.type===t.type},t.prototype.getFilterType=function(){return t.FILTER_TYPE},t.prototype.stringToFloat=function(e){var t=p.makeNull(e);return t&&""===t.trim()&&(t=null),null!=t?parseFloat(t):null},t.prototype.createCondition=function(e){var o=e===Ee.One,i=o?this.getCondition1Type():this.getCondition2Type(),n=o?this.eValueFrom1:this.eValueFrom2,r=this.stringToFloat(n.value),s=o?this.eValueTo1:this.eValueTo2,a=this.stringToFloat(s.value),l={filterType:t.FILTER_TYPE,type:i};return this.doesFilterHaveHiddenInput(i)||(l.filter=r,l.filterTo=a),l},t.prototype.updateUiVisibility=function(){e.prototype.updateUiVisibility.call(this);var t=this.showValueFrom(this.getCondition1Type());p.setDisplayed(this.eValueFrom1,t);var o=this.showValueTo(this.getCondition1Type());p.setDisplayed(this.eValueTo1,o);var i=this.showValueFrom(this.getCondition2Type());p.setDisplayed(this.eValueFrom2,i);var n=this.showValueTo(this.getCondition2Type());p.setDisplayed(this.eValueTo2,n)},t.FILTER_TYPE="number",t.DEFAULT_FILTER_OPTIONS=[Ne.EQUALS,Ne.NOT_EQUAL,Ne.LESS_THAN,Ne.LESS_THAN_OR_EQUAL,Ne.GREATER_THAN,Ne.GREATER_THAN_OR_EQUAL,Ne.IN_RANGE],Ct([fe("eValueFrom1")],t.prototype,"eValueFrom1",void 0),Ct([fe("eValueFrom2")],t.prototype,"eValueFrom2",void 0),Ct([fe("eValueTo1")],t.prototype,"eValueTo1",void 0),Ct([fe("eValueTo2")],t.prototype,"eValueTo2",void 0),t}(Ne),wt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Rt=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ot=function(e){function t(){return e.call(this)||this}return wt(t,e),t.prototype.init=function(e){var o=this.gridOptionsWrapper.getOverlayLoadingTemplate()?this.gridOptionsWrapper.getOverlayLoadingTemplate():t.DEFAULT_LOADING_OVERLAY_TEMPLATE,i=this.gridOptionsWrapper.getLocaleTextFunc(),n=o.replace("[LOADING...]",i("loadingOoo","Loading..."));this.setTemplate(n)},t.DEFAULT_LOADING_OVERLAY_TEMPLATE='<span class="ag-overlay-loading-center">[LOADING...]</span>',Rt([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),t}(pe),Dt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),bt=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Pt=function(e){function t(){return e.call(this)||this}return Dt(t,e),t.prototype.init=function(e){var o=this.gridOptionsWrapper.getOverlayNoRowsTemplate()?this.gridOptionsWrapper.getOverlayNoRowsTemplate():t.DEFAULT_NO_ROWS_TEMPLATE,i=this.gridOptionsWrapper.getLocaleTextFunc(),n=o.replace("[NO_ROWS_TO_SHOW]",i("noRowsToShow","No Rows To Show"));this.setTemplate(n)},t.DEFAULT_NO_ROWS_TEMPLATE='<span class="ag-overlay-no-rows-center">[NO_ROWS_TO_SHOW]</span>',bt([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),t}(pe),St=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Tt=function(e){function t(){return e.call(this,'<div class="ag-tooltip"></div>')||this}return St(t,e),t.prototype.init=function(e){var t=e.value;this.getGui().innerHTML=t},t}(ce),At=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),_t=function(e){function t(){return e.call(this,'<div class="ag-input-wrapper" role="presentation"><input class="ag-filter-filter" type="text" placeholder="yyyy-mm-dd"></div>')||this}return At(t,e),t.prototype.init=function(e){this.eDateInput=this.getGui().querySelector("input"),(p.isBrowserChrome()||e.filterParams.browserDatePicker)&&(p.isBrowserIE()?console.warn("ag-grid: browserDatePicker is specified to true, but it is not supported in IE 11, reverting to plain text date picker"):this.eDateInput.type="date"),this.listener=e.onDateChanged,this.addGuiEventListener("input",this.listener)},t.prototype.getDate=function(){return p.parseYyyyMmDdToDate(this.eDateInput.value,"-")},t.prototype.setDate=function(e){this.eDateInput.value=p.serializeDateToYyyyMmDd(e,"-")},t}(pe),Ft=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Nt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Ft(t,e),t.prototype.getDefaultDebounceMs=function(){return 0},t.prototype.getTextFromModel=function(e){if(!e)return null;if(e.operator){var t=e,o=this.conditionToString(t.condition1),i=this.conditionToString(t.condition2);return o+" "+t.operator+" "+i}var n=e;return this.conditionToString(n)},t.prototype.isEventFromFloatingFilter=function(e){return e&&e.afterFloatingFilter},t.prototype.getLastType=function(){return this.lastType},t.prototype.setLastTypeFromModel=function(e){if(e){var t;if(e.operator)t=e.condition1;else t=e;this.lastType=t.type}},t.prototype.canWeEditAfterModelFromParentFilter=function(e){if(!e)return this.isTypeEditable(this.lastType);if(e.operator)return!1;var t=e;return this.isTypeEditable(t.type)},t.prototype.init=function(e){this.optionsFactory=new Re,this.optionsFactory.init(e.filterParams,this.getDefaultFilterOptions()),this.lastType=this.optionsFactory.getDefaultOption();var t=this.isTypeEditable(this.lastType);this.setEditable(t)},t.prototype.doesFilterHaveHiddenInput=function(e){var t=this.optionsFactory.getCustomOption(e);return t&&t.hideFilterInput},t.prototype.isTypeEditable=function(e){return!this.doesFilterHaveHiddenInput(e)&&(e&&e!=_e.IN_RANGE&&e!=_e.EMPTY)},t}(pe),Lt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),It=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Gt=function(e){function t(){return e.call(this,'<div class="ag-input-wrapper" role="presentation">\n <input ref="eReadOnlyText" disabled="true" class="ag-floating-filter-input">\n <div ref="eDateWrapper" style="display: flex; flex: 1 1 auto; overflow: hidden;"></div>\n </div>')||this}return Lt(t,e),t.prototype.getDefaultFilterOptions=function(){return Ge.DEFAULT_FILTER_OPTIONS},t.prototype.conditionToString=function(e){return e.type==_e.IN_RANGE?e.dateFrom+"-"+e.dateTo:null!=e.dateFrom?""+e.dateFrom:""+e.type},t.prototype.init=function(t){e.prototype.init.call(this,t),this.params=t,this.createDateComponent()},t.prototype.setEditable=function(e){p.setDisplayed(this.eDateWrapper,e),p.setDisplayed(this.eReadOnlyText,!e)},t.prototype.onParentModelChanged=function(t,o){if(!this.isEventFromFloatingFilter(o)){e.prototype.setLastTypeFromModel.call(this,t);var i=this.canWeEditAfterModelFromParentFilter(t);if(this.setEditable(i),i){if(t){var n=t;this.dateComp.setDate(p.parseYyyyMmDdToDate(n.dateFrom,"-"))}else this.dateComp.setDate(null);this.eReadOnlyText.value=""}else this.eReadOnlyText.value=this.getTextFromModel(t),this.dateComp.setDate(null)}},t.prototype.onDateChanged=function(){var e=this,t=this.dateComp.getDate(),o=p.serializeDateToYyyyMmDd(t,"-");this.params.parentFilterInstance((function(t){t&&t.onFloatingFilterChanged(e.getLastType(),o)}))},t.prototype.createDateComponent=function(){var e=this,t=be.getDebounceMs(this.params.filterParams,this.getDefaultDebounceMs()),o={onDateChanged:p.debounce(this.onDateChanged.bind(this),t),filterParams:this.params.column.getColDef().filterParams};this.dateComp=new we(this.userComponentFactory,o,this.eDateWrapper),this.addDestroyFunc((function(){e.dateComp.destroy()}))},It([m("userComponentFactory")],t.prototype,"userComponentFactory",void 0),It([fe("eReadOnlyText")],t.prototype,"eReadOnlyText",void 0),It([fe("eDateWrapper")],t.prototype,"eDateWrapper",void 0),t}(Nt),Mt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),xt=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Vt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Mt(t,e),t.prototype.getDefaultDebounceMs=function(){return 500},t.prototype.getValue=function(e){var t=e.value;return(t=p.makeNull(t))&&""===t.trim()&&(t=null),t},t.prototype.addValueChangedListeners=function(){var e=this,t=function(){return e.onUiChanged()};this.addDestroyableEventListener(this.eValue1,"input",t),this.addDestroyableEventListener(this.eValue2,"input",t)},t.prototype.setParams=function(o){e.prototype.setParams.call(this,o),this.textFilterParams=o,this.comparator=this.textFilterParams.textCustomComparator?this.textFilterParams.textCustomComparator:t.DEFAULT_COMPARATOR,this.formatter=this.textFilterParams.textFormatter?this.textFilterParams.textFormatter:1==this.textFilterParams.caseSensitive?t.DEFAULT_FORMATTER:t.DEFAULT_LOWERCASE_FORMATTER,this.addValueChangedListeners()},t.prototype.setConditionIntoUi=function(e,t){(t===Ee.One?this.eValue1:this.eValue2).value=e?e.filter:null},t.prototype.createCondition=function(e){var o=e===Ee.One,i=o?this.getCondition1Type():this.getCondition2Type(),n=o?this.eValue1:this.eValue2,r=this.getValue(n),s={filterType:t.FILTER_TYPE,type:i};return this.doesFilterHaveHiddenInput(i)||(s.filter=r),s},t.prototype.getFilterType=function(){return t.FILTER_TYPE},t.prototype.areSimpleModelsEqual=function(e,t){return e.filter===t.filter&&e.type===t.type},t.prototype.resetUiToDefaults=function(){e.prototype.resetUiToDefaults.call(this),this.eValue1.value=null,this.eValue2.value=null},t.prototype.setValueFromFloatingFilter=function(e){this.eValue1.value=e,this.eValue2.value=null},t.prototype.getDefaultFilterOptions=function(){return t.DEFAULT_FILTER_OPTIONS},t.prototype.createValueTemplate=function(e){var t=e===Ee.One?"1":"2";return'<div class="ag-filter-body" ref="eCondition'+t+'Body" role="presentation">\n <div class="ag-input-wrapper" ref="eInputWrapper'+t+'" role="presentation">\n <input class="ag-filter-filter" ref="eValue'+t+'" type="text" placeholder="'+this.gridOptionsWrapper.getLocaleTextFunc()("filterOoo","Filter...")+'"/>\n </div>\n </div>'},t.prototype.updateUiVisibility=function(){e.prototype.updateUiVisibility.call(this);var t=this.showValueFrom(this.getCondition1Type());p.setDisplayed(this.eInputWrapper1,t);var o=this.showValueFrom(this.getCondition2Type());p.setDisplayed(this.eInputWrapper2,o)},t.prototype.afterGuiAttached=function(){this.eValue1.focus()},t.prototype.isConditionUiComplete=function(e){var t=e===Ee.One,o=t?this.getCondition1Type():this.getCondition2Type(),i=t?this.eValue1:this.eValue2;if(o===_e.EMPTY)return!1;var n=this.getValue(i);return!!this.doesFilterHaveHiddenInput(o)||null!=n},t.prototype.individualConditionPasses=function(e,t){var o=t.filter,i=t.type,n=this.textFilterParams.valueGetter(e.node),r=this.formatter(n),s=this.optionsFactory.getCustomOption(i);if(s&&(null!=o||s.hideFilterInput))return s.test(o,r);if(null==n)return i===_e.NOT_EQUAL||i===_e.NOT_CONTAINS;var a=this.formatter(o);return this.comparator(i,r,a)},t.FILTER_TYPE="text",t.DEFAULT_FILTER_OPTIONS=[_e.CONTAINS,_e.NOT_CONTAINS,_e.EQUALS,_e.NOT_EQUAL,_e.STARTS_WITH,_e.ENDS_WITH],t.DEFAULT_FORMATTER=function(e){return e},t.DEFAULT_LOWERCASE_FORMATTER=function(e){return null==e?null:e.toString().toLowerCase()},t.DEFAULT_COMPARATOR=function(e,o,i){switch(e){case t.CONTAINS:return o.indexOf(i)>=0;case t.NOT_CONTAINS:return-1===o.indexOf(i);case t.EQUALS:return o===i;case t.NOT_EQUAL:return o!=i;case t.STARTS_WITH:return 0===o.indexOf(i);case t.ENDS_WITH:var n=o.lastIndexOf(i);return n>=0&&n===o.length-i.length;default:return console.warn("invalid filter type "+e),!1}},xt([fe("eValue1")],t.prototype,"eValue1",void 0),xt([fe("eValue2")],t.prototype,"eValue2",void 0),xt([fe("eInputWrapper1")],t.prototype,"eInputWrapper1",void 0),xt([fe("eInputWrapper2")],t.prototype,"eInputWrapper2",void 0),t}(_e),Wt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ht=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},kt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Wt(t,e),t.prototype.postConstruct=function(){this.setTemplate('<div class="ag-input-wrapper" role="presentation">\n <input ref="eFloatingFilterText" class="ag-floating-filter-input">\n </div>')},t.prototype.getDefaultDebounceMs=function(){return 500},t.prototype.onParentModelChanged=function(e,t){if(!this.isEventFromFloatingFilter(t)){this.setLastTypeFromModel(e);var o=this.getTextFromModel(e);this.eFloatingFilterText.value=o;var i=this.canWeEditAfterModelFromParentFilter(e);this.setEditable(i)}},t.prototype.init=function(t){e.prototype.init.call(this,t),this.params=t,this.applyActive=be.isUseApplyButton(this.params.filterParams);var o=be.getDebounceMs(this.params.filterParams,this.getDefaultDebounceMs()),i=p.debounce(this.syncUpWithParentFilter.bind(this),o);this.addDestroyableEventListener(this.eFloatingFilterText,"input",i),this.addDestroyableEventListener(this.eFloatingFilterText,"keypress",i),this.addDestroyableEventListener(this.eFloatingFilterText,"keydown",i);var n=t.column.getDefinition();n.filterParams&&n.filterParams.filterOptions&&1===n.filterParams.filterOptions.length&&"inRange"===n.filterParams.filterOptions[0]&&(this.eFloatingFilterText.disabled=!0)},t.prototype.syncUpWithParentFilter=function(e){var t=this,i=this.eFloatingFilterText.value,n=p.isKeyPressed(e,o.KEY_ENTER);this.applyActive&&!n||this.params.parentFilterInstance((function(e){e&&e.onFloatingFilterChanged(t.getLastType(),i)}))},t.prototype.setEditable=function(e){this.eFloatingFilterText.disabled=!e},Ht([fe("eFloatingFilterText")],t.prototype,"eFloatingFilterText",void 0),Ht([g],t.prototype,"postConstruct",null),t}(Nt),Bt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ut=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Bt(t,e),t.prototype.getDefaultFilterOptions=function(){return Et.DEFAULT_FILTER_OPTIONS},t.prototype.conditionToString=function(e){return e.type==_e.IN_RANGE?e.filter+"-"+e.filterTo:null!=e.filter?""+e.filter:""+e.type},t}(kt),jt=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),zt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return jt(t,e),t.prototype.conditionToString=function(e){return null!=e.filter?""+e.filter:""+e.type},t.prototype.getDefaultFilterOptions=function(){return Vt.DEFAULT_FILTER_OPTIONS},t}(kt),Yt=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s}; /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.REGISTERED=1]="REGISTERED"}(Qe||(Qe={}));var Kt,qt=function(){function e(){this.agGridDefaults={agDateInput:_t,agColumnHeader:We,agColumnGroupHeader:Be,agTextColumnFloatingFilter:zt,agNumberColumnFloatingFilter:Ut,agDateColumnFloatingFilter:Gt,agAnimateShowChangeCellRenderer:ot,agAnimateSlideCellRenderer:rt,agGroupCellRenderer:Ze,agGroupRowRenderer:Ze,agLoadingCellRenderer:lt,agCellEditor:he,agTextCellEditor:he,agSelectCellEditor:ct,agPopupTextCellEditor:ht,agPopupSelectCellEditor:ft,agLargeTextCellEditor:mt,agTextColumnFilter:Vt,agNumberColumnFilter:Et,agDateColumnFilter:Ge,agLoadingOverlay:Ot,agNoRowsOverlay:Pt,agTooltipComponent:Tt},this.agDeprecatedNames={set:{newComponentName:"agSetColumnFilter",propertyHolder:"filter"},text:{newComponentName:"agTextColumnFilter",propertyHolder:"filter"},number:{newComponentName:"agNumberColumnFilter",propertyHolder:"filter"},date:{newComponentName:"agDateColumnFilter",propertyHolder:"filter"},group:{newComponentName:"agGroupCellRenderer",propertyHolder:"cellRenderer"},animateShowChange:{newComponentName:"agAnimateShowChangeCellRenderer",propertyHolder:"cellRenderer"},animateSlide:{newComponentName:"agAnimateSlideCellRenderer",propertyHolder:"cellRenderer"},select:{newComponentName:"agSelectCellEditor",propertyHolder:"cellEditor"},largeText:{newComponentName:"agLargeTextCellEditor",propertyHolder:"cellEditor"},popupSelect:{newComponentName:"agPopupSelectCellEditor",propertyHolder:"cellEditor"},popupText:{newComponentName:"agPopupTextCellEditor",propertyHolder:"cellEditor"},richSelect:{newComponentName:"agRichSelectCellEditor",propertyHolder:"cellEditor"},headerComponent:{newComponentName:"agColumnHeader",propertyHolder:"headerComponent"}},this.jsComponents={},this.frameworkComponents={}}return e.prototype.init=function(){var e=this;null!=this.gridOptions.components&&Object.keys(this.gridOptions.components).forEach((function(t){e.registerComponent(t,e.gridOptions.components[t])})),null!=this.gridOptions.frameworkComponents&&Object.keys(this.gridOptions.frameworkComponents).forEach((function(t){e.registerFwComponent(t,e.gridOptions.frameworkComponents[t])}))},e.prototype.registerDefaultComponent=function(e,t){var o=this.translateIfDeprecated(e);this.agGridDefaults[o]?console.error("Trying to overwrite a default component. You should call registerComponent"):this.agGridDefaults[o]=t},e.prototype.registerComponent=function(e,t){var o=this.translateIfDeprecated(e);this.frameworkComponents[o]?console.error("Trying to register a component that you have already registered for frameworks: "+o):this.jsComponents[o]=t},e.prototype.registerFwComponent=function(e,t){var o=this.translateIfDeprecated(e);this.jsComponents[o]?console.error("Trying to register a component that you have already registered for plain javascript: "+o):this.frameworkComponents[o]=t},e.prototype.retrieve=function(e){var t=this.translateIfDeprecated(e);return this.frameworkComponents[t]?{componentFromFramework:!0,component:this.frameworkComponents[t],source:Qe.REGISTERED}:this.jsComponents[t]?{componentFromFramework:!1,component:this.jsComponents[t],source:Qe.REGISTERED}:this.agGridDefaults[t]?this.agGridDefaults[t]?{componentFromFramework:!1,component:this.agGridDefaults[t],source:Qe.DEFAULT}:null:(Object.keys(this.agGridDefaults).indexOf(t)<0&&console.warn("ag-Grid: Looking for component ["+t+"] but it wasn't found."),null)},e.prototype.translateIfDeprecated=function(e){var t=this.agDeprecatedNames[e];return null!=t?(p.doOnce((function(){console.warn("ag-grid. Since v15.0 component names have been renamed to be namespaced. You should rename "+t.propertyHolder+":"+e+" to "+t.propertyHolder+":"+t.newComponentName)}),"DEPRECATE_COMPONENT_"+e),t.newComponentName):e},Yt([m("gridOptions")],e.prototype,"gridOptions",void 0),Yt([m("context")],e.prototype,"context",void 0),Yt([g],e.prototype,"init",null),e=Yt([y("userComponentRegistry")],e)}(),Qt=function(){function e(e,t){this.active=!0,this.nodeIdsToColumns={},this.mapToItems={},this.keepingColumns=e,this.pathRoot={rowNode:t,children:null},this.mapToItems[t.id]=this.pathRoot}return e.prototype.setInactive=function(){this.active=!1},e.prototype.isActive=function(){return this.active},e.prototype.depthFirstSearchChangedPath=function(e,t){if(e.children)for(var o=0;o<e.children.length;o++)this.depthFirstSearchChangedPath(e.children[o],t);t(e.rowNode)},e.prototype.depthFirstSearchEverything=function(e,t,o){if(e.childrenAfterGroup)for(var i=0;i<e.childrenAfterGroup.length;i++){var n=e.childrenAfterGroup[i];n.childrenAfterGroup?this.depthFirstSearchEverything(e.childrenAfterGroup[i],t,o):o&&t(n)}t(e)},e.prototype.forEachChangedNodeDepthFirst=function(e,t){void 0===t&&(t=!1),this.active?this.depthFirstSearchChangedPath(this.pathRoot,e):this.depthFirstSearchEverything(this.pathRoot.rowNode,e,t)},e.prototype.executeFromRootNode=function(e){e(this.pathRoot.rowNode)},e.prototype.createPathItems=function(e){for(var t=e,o=0;!this.mapToItems[t.id];){var i={rowNode:t,children:null};this.mapToItems[t.id]=i,o++,t=t.parent}return o},e.prototype.populateColumnsMap=function(e,t){var o=this;if(this.keepingColumns&&t)for(var i=e;i;)this.nodeIdsToColumns[i.id]||(this.nodeIdsToColumns[i.id]={}),t.forEach((function(e){return o.nodeIdsToColumns[i.id][e.getId()]=!0})),i=i.parent},e.prototype.linkPathItems=function(e,t){for(var o=e,i=0;i<t;i++){var n=this.mapToItems[o.id],r=this.mapToItems[o.parent.id];r.children||(r.children=[]),r.children.push(n),o=o.parent}},e.prototype.addParentNode=function(e,t){if(e&&!e.isRowPinned()){var o=this.createPathItems(e);this.linkPathItems(e,o),this.populateColumnsMap(e,t)}},e.prototype.canSkip=function(e){return this.active&&!this.mapToItems[e.id]},e.prototype.getValueColumnsForNode=function(e,t){if(!this.keepingColumns)return t;var o=this.nodeIdsToColumns[e.id];return t.filter((function(e){return o[e.getId()]}))},e.prototype.getNotValueColumnsForNode=function(e,t){if(!this.keepingColumns)return null;var o=this.nodeIdsToColumns[e.id];return t.filter((function(e){return!o[e.getId()]}))},e}(),Xt=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},$t=function(e,t){return function(o,i){t(o,i,e)}},Jt=function(){function e(){}return e.prototype.setBeans=function(e){this.logger=e.create("SelectionController"),this.reset(),this.gridOptionsWrapper.isRowModelDefault()?this.eventService.addEventListener(M.EVENT_ROW_DATA_CHANGED,this.reset.bind(this)):this.logger.log("dont know what to do here")},e.prototype.init=function(){this.groupSelectsChildren=this.gridOptionsWrapper.isGroupSelectsChildren(),this.eventService.addEventListener(M.EVENT_ROW_SELECTED,this.onRowSelected.bind(this))},e.prototype.setLastSelectedNode=function(e){this.lastSelectedNode=e},e.prototype.getLastSelectedNode=function(){return this.lastSelectedNode},e.prototype.getSelectedNodes=function(){var e=[];return p.iterateObject(this.selectedNodes,(function(t,o){o&&e.push(o)})),e},e.prototype.getSelectedRows=function(){var e=[];return p.iterateObject(this.selectedNodes,(function(t,o){o&&o.data&&e.push(o.data)})),e},e.prototype.removeGroupsFromSelection=function(){var e=this;p.iterateObject(this.selectedNodes,(function(t,o){o&&o.group&&(e.selectedNodes[o.id]=void 0)}))},e.prototype.updateGroupsFromChildrenSelections=function(e){if(this.gridOptionsWrapper.isGroupSelectsChildren()&&this.rowModel.getType()===o.ROW_MODEL_TYPE_CLIENT_SIDE){var t=this.rowModel.getRootNode();e||(e=new Qt(!0,t)).setInactive(),e.forEachChangedNodeDepthFirst((function(e){e!==t&&e.calculateSelectedFromChildren()}))}},e.prototype.getNodeForIdIfSelected=function(e){return this.selectedNodes[e]},e.prototype.clearOtherNodes=function(e){var t=this,o={},i=0;return p.iterateObject(this.selectedNodes,(function(n,r){if(r&&r.id!==e.id){var s=t.selectedNodes[r.id];i+=s.setSelectedParams({newValue:!1,clearSelection:!1,suppressFinishActions:!0}),t.groupSelectsChildren&&r.parent&&(o[r.parent.id]=r.parent)}})),p.iterateObject(o,(function(e,t){t.calculateSelectedFromChildren()})),i},e.prototype.onRowSelected=function(e){var t=e.node;this.groupSelectsChildren&&t.group||(t.isSelected()?this.selectedNodes[t.id]=t:this.selectedNodes[t.id]=void 0)},e.prototype.syncInRowNode=function(e,t){this.syncInOldRowNode(e,t),this.syncInNewRowNode(e)},e.prototype.syncInOldRowNode=function(e,t){p.exists(t)&&e.id!==t.id&&(p.exists(this.selectedNodes[t.id])&&(this.selectedNodes[t.id]=t))},e.prototype.syncInNewRowNode=function(e){p.exists(this.selectedNodes[e.id])?(e.setSelectedInitialValue(!0),this.selectedNodes[e.id]=e):e.setSelectedInitialValue(!1)},e.prototype.reset=function(){this.logger.log("reset"),this.selectedNodes={},this.lastSelectedNode=null},e.prototype.getBestCostNodeSelection=function(){if(this.rowModel.getType()===o.ROW_MODEL_TYPE_CLIENT_SIDE){var e=this.rowModel.getTopLevelNodes();if(null!==e){var t=[];return function e(o){for(var i=0,n=o.length;i<n;i++){var r=o[i];r.isSelected()?t.push(r):r.group&&r.children&&e(r.children)}}(e),t}console.warn("selectAll not available doing rowModel=virtual")}else console.warn("getBestCostNodeSelection is only available when using normal row model")},e.prototype.setRowModel=function(e){this.rowModel=e},e.prototype.isEmpty=function(){var e=0;return p.iterateObject(this.selectedNodes,(function(t,o){o&&e++})),0===e},e.prototype.deselectAllRowNodes=function(e){void 0===e&&(e=!1);var t=function(e){return e.selectThisNode(!1)},i=this.rowModel.getType()===o.ROW_MODEL_TYPE_CLIENT_SIDE;if(e){if(!i)return void console.error("ag-Grid: selecting just filtered only works with In Memory Row Model");this.rowModel.forEachNodeAfterFilter(t)}else p.iterateObject(this.selectedNodes,(function(e,o){o&&t(o)})),this.reset();i&&this.groupSelectsChildren&&this.updateGroupsFromChildrenSelections();var n={type:M.EVENT_SELECTION_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(n)},e.prototype.selectAllRowNodes=function(e){if(void 0===e&&(e=!1),this.rowModel.getType()!==o.ROW_MODEL_TYPE_CLIENT_SIDE)throw new Error("selectAll only available with normal row model, ie not "+this.rowModel.getType());var t=this.rowModel,i=function(e){return e.selectThisNode(!0)};e?t.forEachNodeAfterFilter(i):t.forEachNode(i),this.rowModel.getType()===o.ROW_MODEL_TYPE_CLIENT_SIDE&&this.groupSelectsChildren&&this.updateGroupsFromChildrenSelections();var n={type:M.EVENT_SELECTION_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(n)},e.prototype.selectNode=function(e,t){e&&e.setSelectedParams({newValue:!0,clearSelection:!t})},e.prototype.deselectIndex=function(e){var t=this.rowModel.getRow(e);this.deselectNode(t)},e.prototype.deselectNode=function(e){e&&e.setSelectedParams({newValue:!1,clearSelection:!1})},e.prototype.selectIndex=function(e,t){var o=this.rowModel.getRow(e);this.selectNode(o,t)},Xt([m("eventService")],e.prototype,"eventService",void 0),Xt([m("rowModel")],e.prototype,"rowModel",void 0),Xt([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Xt([m("columnApi")],e.prototype,"columnApi",void 0),Xt([m("gridApi")],e.prototype,"gridApi",void 0),Xt([$t(0,E("loggerFactory"))],e.prototype,"setBeans",null),Xt([g],e.prototype,"init",null),e=Xt([y("selectionController")],e)}(),Zt=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},eo=function(){function e(){}return e.prototype.sizeColumnsToFit=function(e){void 0===e&&console.error("ag-Grid: missing parameter to columnApi.sizeColumnsToFit(gridWidth)"),this.columnController.sizeColumnsToFit(e,"api")},e.prototype.setColumnGroupOpened=function(e,t){this.columnController.setColumnGroupOpened(e,t,"api")},e.prototype.getColumnGroup=function(e,t){return this.columnController.getColumnGroup(e,t)},e.prototype.getOriginalColumnGroup=function(e){return this.columnController.getOriginalColumnGroup(e)},e.prototype.getDisplayNameForColumn=function(e,t){return this.columnController.getDisplayNameForColumn(e,t)},e.prototype.getDisplayNameForColumnGroup=function(e,t){return this.columnController.getDisplayNameForColumnGroup(e,t)},e.prototype.getColumn=function(e){return this.columnController.getPrimaryColumn(e)},e.prototype.setColumnState=function(e){return this.columnController.setColumnState(e,!1,"api")},e.prototype.getColumnState=function(){return this.columnController.getColumnState()},e.prototype.resetColumnState=function(){this.columnController.resetColumnState(!1,"api")},e.prototype.getColumnGroupState=function(){return this.columnController.getColumnGroupState()},e.prototype.setColumnGroupState=function(e){this.columnController.setColumnGroupState(e,"api")},e.prototype.resetColumnGroupState=function(){this.columnController.resetColumnGroupState("api")},e.prototype.isPinning=function(){return this.columnController.isPinningLeft()||this.columnController.isPinningRight()},e.prototype.isPinningLeft=function(){return this.columnController.isPinningLeft()},e.prototype.isPinningRight=function(){return this.columnController.isPinningRight()},e.prototype.getDisplayedColAfter=function(e){return this.columnController.getDisplayedColAfter(e)},e.prototype.getDisplayedColBefore=function(e){return this.columnController.getDisplayedColBefore(e)},e.prototype.setColumnVisible=function(e,t){this.columnController.setColumnVisible(e,t,"api")},e.prototype.setColumnsVisible=function(e,t){this.columnController.setColumnsVisible(e,t,"api")},e.prototype.setColumnPinned=function(e,t){this.columnController.setColumnPinned(e,t,"api")},e.prototype.setColumnsPinned=function(e,t){this.columnController.setColumnsPinned(e,t,"api")},e.prototype.getAllColumns=function(){return this.columnController.getAllPrimaryColumns()},e.prototype.getAllGridColumns=function(){return this.columnController.getAllGridColumns()},e.prototype.getDisplayedLeftColumns=function(){return this.columnController.getDisplayedLeftColumns()},e.prototype.getDisplayedCenterColumns=function(){return this.columnController.getDisplayedCenterColumns()},e.prototype.getDisplayedRightColumns=function(){return this.columnController.getDisplayedRightColumns()},e.prototype.getAllDisplayedColumns=function(){return this.columnController.getAllDisplayedColumns()},e.prototype.getAllDisplayedVirtualColumns=function(){return this.columnController.getAllDisplayedVirtualColumns()},e.prototype.moveColumn=function(e,t){"number"==typeof e?(console.warn("ag-Grid: you are using moveColumn(fromIndex, toIndex) - moveColumn takes a column key and a destination index, not two indexes, to move with indexes use moveColumnByIndex(from,to) instead"),this.columnController.moveColumnByIndex(e,t,"api")):this.columnController.moveColumn(e,t,"api")},e.prototype.moveColumnByIndex=function(e,t){this.columnController.moveColumnByIndex(e,t,"api")},e.prototype.moveColumns=function(e,t){this.columnController.moveColumns(e,t,"api")},e.prototype.moveRowGroupColumn=function(e,t){this.columnController.moveRowGroupColumn(e,t)},e.prototype.setColumnAggFunc=function(e,t){this.columnController.setColumnAggFunc(e,t)},e.prototype.setColumnWidth=function(e,t,o){void 0===o&&(o=!0),this.columnController.setColumnWidth(e,t,!1,o)},e.prototype.setPivotMode=function(e){this.columnController.setPivotMode(e)},e.prototype.isPivotMode=function(){return this.columnController.isPivotMode()},e.prototype.getSecondaryPivotColumn=function(e,t){return this.columnController.getSecondaryPivotColumn(e,t)},e.prototype.setValueColumns=function(e){this.columnController.setValueColumns(e,"api")},e.prototype.getValueColumns=function(){return this.columnController.getValueColumns()},e.prototype.removeValueColumn=function(e){this.columnController.removeValueColumn(e,"api")},e.prototype.removeValueColumns=function(e){this.columnController.removeValueColumns(e,"api")},e.prototype.addValueColumn=function(e){this.columnController.addValueColumn(e,"api")},e.prototype.addValueColumns=function(e){this.columnController.addValueColumns(e,"api")},e.prototype.setRowGroupColumns=function(e){this.columnController.setRowGroupColumns(e,"api")},e.prototype.removeRowGroupColumn=function(e){this.columnController.removeRowGroupColumn(e,"api")},e.prototype.removeRowGroupColumns=function(e){this.columnController.removeRowGroupColumns(e,"api")},e.prototype.addRowGroupColumn=function(e){this.columnController.addRowGroupColumn(e,"api")},e.prototype.addRowGroupColumns=function(e){this.columnController.addRowGroupColumns(e,"api")},e.prototype.getRowGroupColumns=function(){return this.columnController.getRowGroupColumns()},e.prototype.setPivotColumns=function(e){this.columnController.setPivotColumns(e,"api")},e.prototype.removePivotColumn=function(e){this.columnController.removePivotColumn(e,"api")},e.prototype.removePivotColumns=function(e){this.columnController.removePivotColumns(e,"api")},e.prototype.addPivotColumn=function(e){this.columnController.addPivotColumn(e,"api")},e.prototype.addPivotColumns=function(e){this.columnController.addPivotColumns(e,"api")},e.prototype.getPivotColumns=function(){return this.columnController.getPivotColumns()},e.prototype.getLeftDisplayedColumnGroups=function(){return this.columnController.getLeftDisplayedColumnGroups()},e.prototype.getCenterDisplayedColumnGroups=function(){return this.columnController.getCenterDisplayedColumnGroups()},e.prototype.getRightDisplayedColumnGroups=function(){return this.columnController.getRightDisplayedColumnGroups()},e.prototype.getAllDisplayedColumnGroups=function(){return this.columnController.getAllDisplayedColumnGroups()},e.prototype.autoSizeColumn=function(e){return this.columnController.autoSizeColumn(e,"api")},e.prototype.autoSizeColumns=function(e){return this.columnController.autoSizeColumns(e,"api")},e.prototype.autoSizeAllColumns=function(){this.columnController.autoSizeAllColumns("api")},e.prototype.setSecondaryColumns=function(e){this.columnController.setSecondaryColumns(e,"api")},e.prototype.getSecondaryColumns=function(){return this.columnController.getSecondaryColumns()},e.prototype.getPrimaryColumns=function(){return this.columnController.getAllPrimaryColumns()},e.prototype.columnGroupOpened=function(e,t){console.error("ag-Grid: columnGroupOpened no longer exists, use setColumnGroupOpened"),this.setColumnGroupOpened(e,t)},e.prototype.hideColumns=function(e,t){console.error("ag-Grid: hideColumns is deprecated, use setColumnsVisible"),this.columnController.setColumnsVisible(e,!t,"api")},e.prototype.hideColumn=function(e,t){console.error("ag-Grid: hideColumn is deprecated, use setColumnVisible"),this.columnController.setColumnVisible(e,!t,"api")},e.prototype.setState=function(e){return console.error("ag-Grid: setState is deprecated, use setColumnState"),this.setColumnState(e)},e.prototype.getState=function(){return console.error("ag-Grid: getState is deprecated, use getColumnState"),this.getColumnState()},e.prototype.resetState=function(){console.error("ag-Grid: resetState is deprecated, use resetColumnState"),this.resetColumnState()},e.prototype.getAggregationColumns=function(){return console.error("ag-Grid: getAggregationColumns is deprecated, use getValueColumns"),this.columnController.getValueColumns()},e.prototype.removeAggregationColumn=function(e){console.error("ag-Grid: removeAggregationColumn is deprecated, use removeValueColumn"),this.columnController.removeValueColumn(e,"api")},e.prototype.removeAggregationColumns=function(e){console.error("ag-Grid: removeAggregationColumns is deprecated, use removeValueColumns"),this.columnController.removeValueColumns(e,"api")},e.prototype.addAggregationColumn=function(e){console.error("ag-Grid: addAggregationColumn is deprecated, use addValueColumn"),this.columnController.addValueColumn(e,"api")},e.prototype.addAggregationColumns=function(e){console.error("ag-Grid: addAggregationColumns is deprecated, use addValueColumns"),this.columnController.addValueColumns(e,"api")},e.prototype.setColumnAggFunction=function(e,t){console.error("ag-Grid: setColumnAggFunction is deprecated, use setColumnAggFunc"),this.columnController.setColumnAggFunc(e,t,"api")},e.prototype.getDisplayNameForCol=function(e){return console.error("ag-Grid: getDisplayNameForCol is deprecated, use getDisplayNameForColumn"),this.getDisplayNameForColumn(e,null)},Zt([m("columnController")],e.prototype,"columnController",void 0),e=Zt([y("columnApi")],e)}(); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */!function(e){e[e.VALUE=0]="VALUE",e[e.DIMENSION=1]="DIMENSION"}(Kt||(Kt={})); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */ var to,oo,io,no=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},ro=function(e,t){return function(o,i){t(o,i,e)}};!function(e){e[e.ToolPanel=0]="ToolPanel",e[e.HeaderCell=1]="HeaderCell",e[e.RowDrag=2]="RowDrag"}(to||(to={})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(oo||(oo={})),function(e){e[e.Left=0]="Left",e[e.Right=1]="Right"}(io||(io={}));var so,ao=function(){function e(){this.dragSourceAndParamsList=[],this.dropTargets=[]}var t;return t=e,e.prototype.init=function(){this.ePinnedIcon=p.createIcon("columnMovePin",this.gridOptionsWrapper,null),this.ePlusIcon=p.createIcon("columnMoveAdd",this.gridOptionsWrapper,null),this.eHiddenIcon=p.createIcon("columnMoveHide",this.gridOptionsWrapper,null),this.eMoveIcon=p.createIcon("columnMoveMove",this.gridOptionsWrapper,null),this.eLeftIcon=p.createIcon("columnMoveLeft",this.gridOptionsWrapper,null),this.eRightIcon=p.createIcon("columnMoveRight",this.gridOptionsWrapper,null),this.eGroupIcon=p.createIcon("columnMoveGroup",this.gridOptionsWrapper,null),this.eAggregateIcon=p.createIcon("columnMoveValue",this.gridOptionsWrapper,null),this.ePivotIcon=p.createIcon("columnMovePivot",this.gridOptionsWrapper,null),this.eDropNotAllowedIcon=p.createIcon("dropNotAllowed",this.gridOptionsWrapper,null)},e.prototype.setBeans=function(e){this.logger=e.create("OldToolPanelDragAndDropService")},e.prototype.addDragSource=function(e,t){void 0===t&&(t=!1);var o={eElement:e.eElement,dragStartPixels:e.dragStartPixels,onDragStart:this.onDragStart.bind(this,e),onDragStop:this.onDragStop.bind(this),onDragging:this.onDragging.bind(this)};this.dragSourceAndParamsList.push({params:o,dragSource:e}),this.dragService.addDragSource(o,t)},e.prototype.removeDragSource=function(e){var t=p.find(this.dragSourceAndParamsList,(function(t){return t.dragSource===e}));t&&(this.dragService.removeDragSource(t.params),p.removeFromArray(this.dragSourceAndParamsList,t))},e.prototype.destroy=function(){var e=this;this.dragSourceAndParamsList.forEach((function(t){e.dragService.removeDragSource(t.params)})),this.dragSourceAndParamsList.length=0},e.prototype.nudge=function(){this.dragging&&this.onDragging(this.eventLastTime,!0)},e.prototype.onDragStart=function(e,t){this.dragging=!0,this.dragSource=e,this.eventLastTime=t,this.dragItem=this.dragSource.dragItemCallback(),this.lastDropTarget=this.dragSource.dragSourceDropTarget,this.dragSource.dragStarted&&this.dragSource.dragStarted(),this.createGhost()},e.prototype.onDragStop=function(e){if(this.eventLastTime=null,this.dragging=!1,this.dragSource.dragStopped&&this.dragSource.dragStopped(),this.lastDropTarget&&this.lastDropTarget.onDragStop){var t=this.createDropTargetEvent(this.lastDropTarget,e,null,null,!1);this.lastDropTarget.onDragStop(t)}this.lastDropTarget=null,this.dragItem=null,this.removeGhost()},e.prototype.onDragging=function(e,t){var o=this.workOutHDirection(e),i=this.workOutVDirection(e);this.eventLastTime=e,this.positionGhost(e);var n=p.find(this.dropTargets,this.isMouseOnDropTarget.bind(this,e));if(n!==this.lastDropTarget)this.leaveLastTargetIfExists(e,o,i,t),this.enterDragTargetIfExists(n,e,o,i,t),this.lastDropTarget=n;else if(n){var r=this.createDropTargetEvent(n,e,o,i,t);n.onDragging(r)}},e.prototype.enterDragTargetIfExists=function(e,t,o,i,n){if(e){var r=this.createDropTargetEvent(e,t,o,i,n);e.onDragEnter(r),this.setGhostIcon(e.getIconName?e.getIconName():null)}},e.prototype.leaveLastTargetIfExists=function(e,t,o,i){if(this.lastDropTarget){var n=this.createDropTargetEvent(this.lastDropTarget,e,t,o,i);this.lastDropTarget.onDragLeave(n),this.setGhostIcon(null)}},e.prototype.getAllContainersFromDropTarget=function(e){var t=[e.getContainer()],o=e.getSecondaryContainers?e.getSecondaryContainers():null;return o&&(t=t.concat(o)),t},e.prototype.isMouseOnDropTarget=function(e,t){var o=this.getAllContainersFromDropTarget(t),i=!1;return o.forEach((function(t){if(t){var o=t.getBoundingClientRect();if(0!==o.width&&0!==o.height){var n=e.clientX>=o.left&&e.clientX<=o.right,r=e.clientY>=o.top&&e.clientY<=o.bottom;n&&r&&(i=!0)}}})),!!i&&t.isInterestedIn(this.dragSource.type)},e.prototype.addDropTarget=function(e){this.dropTargets.push(e)},e.prototype.workOutHDirection=function(e){return this.eventLastTime.clientX>e.clientX?io.Left:this.eventLastTime.clientX<e.clientX?io.Right:null},e.prototype.workOutVDirection=function(e){return this.eventLastTime.clientY>e.clientY?oo.Up:this.eventLastTime.clientY<e.clientY?oo.Down:null},e.prototype.createDropTargetEvent=function(e,t,o,i,n){var r=e.getContainer().getBoundingClientRect();return{event:t,x:t.clientX-r.left,y:t.clientY-r.top,vDirection:i,hDirection:o,dragSource:this.dragSource,fromNudge:n,dragItem:this.dragItem}},e.prototype.positionGhost=function(e){var t=this.eGhost.getBoundingClientRect().height,o=p.getBodyWidth()-2,i=p.getBodyHeight()-2,n=e.pageY-t/2,r=e.pageX-30,s=this.gridOptionsWrapper.getDocument(),a=window.pageYOffset||s.documentElement.scrollTop,l=window.pageXOffset||s.documentElement.scrollLeft;o>0&&r+this.eGhost.clientWidth>o+l&&(r=o+l-this.eGhost.clientWidth),r<0&&(r=0),i>0&&n+this.eGhost.clientHeight>i+a&&(n=i+a-this.eGhost.clientHeight),n<0&&(n=0),this.eGhost.style.left=r+"px",this.eGhost.style.top=n+"px"},e.prototype.removeGhost=function(){this.eGhost&&this.eGhostParent&&this.eGhostParent.removeChild(this.eGhost),this.eGhost=null},e.prototype.createGhost=function(){this.eGhost=p.loadTemplate(t.GHOST_TEMPLATE);var e=this.environment.getTheme().theme;e&&p.addCssClass(this.eGhost,e),this.eGhostIcon=this.eGhost.querySelector(".ag-dnd-ghost-icon"),this.setGhostIcon(null),this.eGhost.querySelector(".ag-dnd-ghost-label").innerHTML=p.escape(this.dragSource.dragItemName),this.eGhost.style.height="25px",this.eGhost.style.top="20px",this.eGhost.style.left="20px";var o=this.gridOptionsWrapper.getDocument();this.eGhostParent=o.querySelector("body"),this.eGhostParent?this.eGhostParent.appendChild(this.eGhost):console.warn("ag-Grid: could not find document body, it is needed for dragging columns")},e.prototype.setGhostIcon=function(e,o){var i;switch(void 0===o&&(o=!1),p.clearElement(this.eGhostIcon),e){case t.ICON_ADD:i=this.ePlusIcon;break;case t.ICON_PINNED:i=this.ePinnedIcon;break;case t.ICON_MOVE:i=this.eMoveIcon;break;case t.ICON_LEFT:i=this.eLeftIcon;break;case t.ICON_RIGHT:i=this.eRightIcon;break;case t.ICON_GROUP:i=this.eGroupIcon;break;case t.ICON_AGGREGATE:i=this.eAggregateIcon;break;case t.ICON_PIVOT:i=this.ePivotIcon;break;case t.ICON_NOT_ALLOWED:i=this.eDropNotAllowedIcon;break;default:i=this.eHiddenIcon}this.eGhostIcon.appendChild(i),p.addOrRemoveCssClass(this.eGhostIcon,"ag-shake-left-to-right",o)},e.ICON_PINNED="pinned",e.ICON_ADD="add",e.ICON_MOVE="move",e.ICON_LEFT="left",e.ICON_RIGHT="right",e.ICON_GROUP="group",e.ICON_AGGREGATE="aggregate",e.ICON_PIVOT="pivot",e.ICON_NOT_ALLOWED="notAllowed",e.GHOST_TEMPLATE='<div class="ag-dnd-ghost"> <span class="ag-dnd-ghost-icon ag-shake-left-to-right"></span> <div class="ag-dnd-ghost-label"> </div></div>',no([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),no([m("dragService")],e.prototype,"dragService",void 0),no([m("environment")],e.prototype,"environment",void 0),no([m("columnController")],e.prototype,"columnController",void 0),no([g],e.prototype,"init",null),no([ro(0,E("loggerFactory"))],e.prototype,"setBeans",null),no([f],e.prototype,"destroy",null),e=t=no([y("dragAndDropService")],e)}(),lo=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),po=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},uo=function(e){function t(t,o,i,n){var r=e.call(this,'<div class="ag-row-drag"></div>')||this;return r.rowNode=t,r.column=o,r.cellValue=i,r.beans=n,r}return lo(t,e),t.prototype.postConstruct=function(){this.getGui().appendChild(p.createIconNoSpan("rowDrag",this.beans.gridOptionsWrapper,null)),this.addDragSource(),this.checkCompatibility(),this.beans.gridOptionsWrapper.isRowDragManaged()?this.addFeature(new go(this,this.beans,this.rowNode,this.column),this.beans.context):this.addFeature(new ho(this,this.beans,this.rowNode,this.column),this.beans.context)},t.prototype.checkCompatibility=function(){var e=this.beans.gridOptionsWrapper.isRowDragManaged();this.beans.gridOptionsWrapper.isTreeData()&&e&&p.doOnce((function(){return console.warn("ag-Grid: If using row drag with tree data, you cannot have rowDragManaged=true")}),"RowDragComp.managedAndTreeData")},t.prototype.addDragSource=function(){var e=this,t={rowNode:this.rowNode},o={type:to.RowDrag,eElement:this.getGui(),dragItemName:this.cellValue,dragItemCallback:function(){return t},dragStartPixels:0};this.beans.dragAndDropService.addDragSource(o,!0),this.addDestroyFunc((function(){return e.beans.dragAndDropService.removeDragSource(o)}))},po([g],t.prototype,"postConstruct",null),t}(pe),co=function(e){function t(t,o,i){var n=e.call(this)||this;return n.parent=t,n.column=i,n.rowNode=o,n}return lo(t,e),t.prototype.setDisplayedOrVisible=function(e){if(e)this.parent.setDisplayed(!1);else{var t=this.column.isRowDrag(this.rowNode);p.isFunction(this.column.getColDef().rowDrag)?this.parent.setVisible(t):this.parent.setDisplayed(t)}},t}(re),ho=function(e){function t(t,o,i,n){var r=e.call(this,t,i,n)||this;return r.beans=o,r}return lo(t,e),t.prototype.postConstruct=function(){this.addDestroyableEventListener(this.beans.gridOptionsWrapper,"suppressRowDrag",this.onSuppressRowDrag.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_DATA_CHANGED,this.workOutVisibility.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_CELL_CHANGED,this.workOutVisibility.bind(this)),this.workOutVisibility()},t.prototype.onSuppressRowDrag=function(){this.workOutVisibility()},t.prototype.workOutVisibility=function(){var e=this.beans.gridOptionsWrapper.isSuppressRowDrag();this.setDisplayedOrVisible(e)},po([g],t.prototype,"postConstruct",null),t}(co),go=function(e){function t(t,o,i,n){var r=e.call(this,t,i,n)||this;return r.beans=o,r}return lo(t,e),t.prototype.postConstruct=function(){this.addDestroyableEventListener(this.beans.eventService,M.EVENT_SORT_CHANGED,this.onSortChanged.bind(this)),this.addDestroyableEventListener(this.beans.eventService,M.EVENT_FILTER_CHANGED,this.onFilterChanged.bind(this)),this.addDestroyableEventListener(this.beans.eventService,M.EVENT_COLUMN_ROW_GROUP_CHANGED,this.onRowGroupChanged.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_DATA_CHANGED,this.workOutVisibility.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_CELL_CHANGED,this.workOutVisibility.bind(this)),this.addDestroyableEventListener(this.beans.gridOptionsWrapper,"suppressRowDrag",this.onSuppressRowDrag.bind(this)),this.updateSortActive(),this.updateFilterActive(),this.updateRowGroupActive(),this.workOutVisibility()},t.prototype.updateRowGroupActive=function(){var e=this.beans.columnController.getRowGroupColumns();this.rowGroupActive=!p.missingOrEmpty(e)},t.prototype.onRowGroupChanged=function(){this.updateRowGroupActive(),this.workOutVisibility()},t.prototype.updateSortActive=function(){var e=this.beans.sortController.getSortModel();this.sortActive=!p.missingOrEmpty(e)},t.prototype.onSortChanged=function(){this.updateSortActive(),this.workOutVisibility()},t.prototype.updateFilterActive=function(){this.filterActive=this.beans.filterManager.isAnyFilterPresent()},t.prototype.onFilterChanged=function(){this.updateFilterActive(),this.workOutVisibility()},t.prototype.onSuppressRowDrag=function(){this.workOutVisibility()},t.prototype.workOutVisibility=function(){var e=this.sortActive||this.filterActive||this.rowGroupActive,t=this.beans.gridOptionsWrapper.isSuppressRowDrag(),o=e||t;this.setDisplayedOrVisible(o)},po([g],t.prototype,"postConstruct",null),t}(co),fo=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),yo=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},mo=function(e){function t(t){var o=e.call(this,'<div class="ag-popup-editor" tabindex="-1"/>')||this;return o.getGuiCalledOnChild=!1,o.cellEditor=t,o}return fo(t,e),t.prototype.onKeyDown=function(e){p.isUserSuppressingKeyboardEvent(this.gridOptionsWrapper,e,this.params.node,this.params.column,!0)||this.params.onKeyDown(e)},t.prototype.getGui=function(){return this.getGuiCalledOnChild||(this.appendChild(this.cellEditor.getGui()),this.getGuiCalledOnChild=!0),e.prototype.getGui.call(this)},t.prototype.init=function(o){var i=this;this.params=o,this.gridOptionsWrapper.setDomData(this.getGui(),t.DOM_KEY_POPUP_EDITOR_WRAPPER,!0),this.addDestroyFunc((function(){i.cellEditor.destroy&&i.cellEditor.destroy()})),this.addDestroyableEventListener(e.prototype.getGui.call(this),"keydown",this.onKeyDown.bind(this))},t.prototype.afterGuiAttached=function(){this.cellEditor.afterGuiAttached&&this.cellEditor.afterGuiAttached()},t.prototype.getValue=function(){return this.cellEditor.getValue()},t.prototype.isCancelBeforeStart=function(){if(this.cellEditor.isCancelBeforeStart)return this.cellEditor.isCancelBeforeStart()},t.prototype.isCancelAfterEnd=function(){if(this.cellEditor.isCancelAfterEnd)return this.cellEditor.isCancelAfterEnd()},t.prototype.focusIn=function(){this.cellEditor.focusIn&&this.cellEditor.focusIn()},t.prototype.focusOut=function(){this.cellEditor.focusOut&&this.cellEditor.focusOut()},t.DOM_KEY_POPUP_EDITOR_WRAPPER="popupEditorWrapper",yo([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),t}(ce),vo=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Co=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Eo=function(e){function t(t,o,i,n,r){var s=e.call(this,'<div class="ag-row-drag" draggable="true"></div>')||this;return s.rowNode=t,s.column=o,s.cellValue=i,s.beans=n,s.eCell=r,s}return vo(t,e),t.prototype.postConstruct=function(){this.getGui().appendChild(p.createIconNoSpan("rowDrag",this.beans.gridOptionsWrapper,null)),this.addDragSource(),this.checkVisibility()},t.prototype.addDragSource=function(){this.addGuiEventListener("dragstart",this.onDragStart.bind(this))},t.prototype.onDragStart=function(e){var t=this,o=this.column.getColDef().dndSourceOnRowDrag,i=p.isBrowserIE();i||e.dataTransfer.setDragImage(this.eCell,0,0);o?o({rowNode:this.rowNode,dragEvent:e}):function(){try{var o=JSON.stringify(t.rowNode.data);i?e.dataTransfer.setData("text",o):(e.dataTransfer.setData("application/json",o),e.dataTransfer.setData("text/plain",o))}catch(e){}}()},t.prototype.checkVisibility=function(){var e=this.column.isDndSource(this.rowNode);this.setDisplayed(e)},Co([g],t.prototype,"postConstruct",null),t}(pe),wo=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ro=function(){return(Ro=Object.assign||function(e){for(var t,o=1,i=arguments.length;o<i;o++)for(var n in t=arguments[o])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},Oo=function(e){function t(t,o,i,n,r,s,a){var l=e.call(this)||this;if(l.editingCell=!1,l.suppressRefreshCell=!1,l.scope=null,l.cellEditorVersion=0,l.cellRendererVersion=0,l.scope=t,l.beans=o,l.column=i,l.rowNode=n,l.rowComp=r,l.autoHeightCell=s,l.printLayout=a,l.createGridCellVo(),l.rangeSelectionEnabled=l.beans.rangeController&&o.gridOptionsWrapper.isEnableRangeSelection(),l.cellFocused=l.beans.focusedCellController.isCellFocused(l.cellPosition),l.firstRightPinned=l.column.isFirstRightPinned(),l.lastLeftPinned=l.column.isLastLeftPinned(),l.rangeSelectionEnabled&&l.beans.rangeController){var u=l.beans.rangeController;l.rangeCount=u.getCellRangeCount(l.cellPosition),l.rangeCount&&(l.hasChartRange=u.getCellRanges().every((function(e){return p.exists(e.type)})))}return l.getValueAndFormat(),l.setUsingWrapper(),l.chooseCellRenderer(),l.setupColSpan(),l.rowSpan=l.column.getRowSpan(l.rowNode),l}return wo(t,e),t.prototype.getCreateTemplate=function(){var e=this.beans.gridOptionsWrapper.isEnableCellTextSelection()?"":'unselectable="on"',t=[],o=this.column,i=this.getCellWidth(),n=this.modifyLeftForPrintLayout(this.getCellLeft()),r=this.getInitialValueToRender(),s=p.get(this.column,"colDef.template",null)?r:p.escape(r);this.tooltip=this.getToolTip();var a=p.escape(this.tooltip),l=p.escape(o.getId()),u="",c="",d=this.preProcessStylesFromColDef(),h=this.getInitialCssClasses(),g=this.getStylesForRowSpanning();return this.usingWrapper&&(u='<div ref="eCellWrapper" class="ag-cell-wrapper"><span ref="eCellValue" class="ag-cell-value" '+e+">",c="</span></div>"),t.push("<div"),t.push(' tabindex="-1"'),t.push(" "+e),t.push(' role="gridcell"'),t.push(' comp-id="'+this.getCompId()+'" '),t.push(' col-id="'+l+'"'),t.push(' class="'+h.join(" ")+'"'),this.beans.gridOptionsWrapper.isEnableBrowserTooltips()&&p.exists(a)&&t.push('title="'+a+'"'),t.push(' style="width: '+i+"px; left: "+n+"px; "+d+" "+g+'" >'),t.push(u),p.exists(s,!0)&&t.push(s),t.push(c),t.push("</div>"),t.join("")},t.prototype.getStylesForRowSpanning=function(){return 1===this.rowSpan?"":"height: "+this.beans.gridOptionsWrapper.getRowHeightAsNumber()*this.rowSpan+"px; z-index: 1;"},t.prototype.afterAttached=function(){var e='[comp-id="'+this.getCompId()+'"]',t=this.eParentRow.querySelector(e);this.setGui(t),this.addDomData(),this.populateTemplate(),this.createCellRendererInstance(!0),this.angular1Compile(),this.rangeSelectionEnabled&&this.shouldHaveSelectionHandle()&&this.addSelectionHandle(),p.exists(this.tooltip)&&!this.beans.gridOptionsWrapper.isEnableBrowserTooltips()&&this.beans.tooltipManager.registerTooltip(this)},t.prototype.onColumnHover=function(){var e=this.beans.columnHoverService.isHovered(this.column);p.addOrRemoveCssClass(this.getGui(),"ag-column-hover",e)},t.prototype.onCellChanged=function(e){e.column===this.column&&this.refreshCell({})},t.prototype.getCellLeft=function(){return(this.beans.gridOptionsWrapper.isEnableRtl()&&this.colsSpanning?p.last(this.colsSpanning):this.column).getLeft()},t.prototype.getCellWidth=function(){if(!this.colsSpanning)return this.column.getActualWidth();var e=0;return this.colsSpanning.forEach((function(t){return e+=t.getActualWidth()})),e},t.prototype.onFlashCells=function(e){var t=this.beans.cellPositionUtils.createId(this.cellPosition);e.cells[t]&&this.animateCell("highlight")},t.prototype.setupColSpan=function(){p.missing(this.getComponentHolder().colSpan)||(this.addDestroyableEventListener(this.beans.eventService,M.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayColumnsChanged.bind(this)),this.addDestroyableEventListener(this.beans.eventService,M.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,this.onWidthChanged.bind(this)),this.colsSpanning=this.getColSpanningList())},t.prototype.getColSpanningList=function(){var e=this.column.getColSpan(this.rowNode),t=[];if(1===e)t.push(this.column);else for(var o=this.column,i=this.column.getPinned(),n=0;o&&n<e&&(t.push(o),(o=this.beans.columnController.getDisplayedColAfter(o))&&!p.missing(o))&&i===o.getPinned();n++);return t},t.prototype.onDisplayColumnsChanged=function(){var e=this.getColSpanningList();p.compareArrays(this.colsSpanning,e)||(this.colsSpanning=e,this.onWidthChanged(),this.onLeftChanged())},t.prototype.getInitialCssClasses=function(){var e=["ag-cell","ag-cell-not-inline-editing"];return this.autoHeightCell||e.push("ag-cell-with-height"),!this.beans.gridOptionsWrapper.isSuppressCellSelection()&&this.cellFocused&&e.push("ag-cell-focus"),this.firstRightPinned&&e.push("ag-cell-first-right-pinned"),this.lastLeftPinned&&e.push("ag-cell-last-left-pinned"),this.beans.columnHoverService.isHovered(this.column)&&e.push("ag-column-hover"),p.pushAll(e,this.preProcessClassesFromColDef()),p.pushAll(e,this.preProcessCellClassRules()),p.pushAll(e,this.getInitialRangeClasses()),this.usingWrapper||e.push("ag-cell-value"),e},t.prototype.getInitialValueToRender=function(){if(this.usingCellRenderer)return"string"==typeof this.cellRendererGui?this.cellRendererGui:"";var e=this.getComponentHolder();return e.template?e.template:e.templateUrl?this.beans.templateService.getTemplate(e.templateUrl,this.refreshCell.bind(this,!0))||"":this.getValueToUse()},t.prototype.getRenderedRow=function(){return this.rowComp},t.prototype.isSuppressNavigable=function(){return this.column.isSuppressNavigable(this.rowNode)},t.prototype.getCellRenderer=function(){return this.cellRenderer},t.prototype.getCellEditor=function(){return this.cellEditor},t.prototype.refreshCell=function(e){if(!this.suppressRefreshCell&&!this.editingCell){var t=this.getComponentHolder(),o=e&&e.newData,i=e&&e.suppressFlash||t.suppressCellFlash,n=e&&e.forceRefresh,r=this.value;this.getValueAndFormat();var s=!this.valuesAreEqual(r,this.value);if(n||s){!o&&this.attemptCellRendererRefresh()||this.replaceContentsAfterRefresh();var a=this.beans.filterManager.isSuppressFlashingCellsBecauseFiltering();!i&&!a&&(this.beans.gridOptionsWrapper.isEnableCellChangeFlash()||t.enableCellChangeFlash)&&this.flashCell(),this.postProcessStylesFromColDef(),this.postProcessClassesFromColDef()}this.updateAngular1ScopeAndCompile(),this.refreshToolTip(),this.postProcessCellClassRules()}},t.prototype.flashCell=function(){this.animateCell("data-changed")},t.prototype.animateCell=function(e){var t="ag-cell-"+e,o="ag-cell-"+e+"-animation",i=this.getGui();p.addCssClass(i,t),p.removeCssClass(i,o),window.setTimeout((function(){p.removeCssClass(i,t),p.addCssClass(i,o),window.setTimeout((function(){p.removeCssClass(i,o)}),1e3)}),500)},t.prototype.replaceContentsAfterRefresh=function(){p.clearElement(this.eParentOfValue),this.cellRenderer&&this.cellRenderer.destroy&&this.cellRenderer.destroy(),this.cellRenderer=null,this.cellRendererGui=null,this.putDataIntoCellAfterRefresh(),this.updateAngular1ScopeAndCompile()},t.prototype.updateAngular1ScopeAndCompile=function(){this.beans.gridOptionsWrapper.isAngularCompileRows()&&this.scope&&(this.scope.data=Ro({},this.rowNode.data),this.angular1Compile())},t.prototype.angular1Compile=function(){if(this.beans.gridOptionsWrapper.isAngularCompileRows()){var e=this.getGui();if(!e.classList.contains("ng-scope")||0===e.childElementCount){var t=this.beans.$compile(e)(this.scope);this.addDestroyFunc((function(){t.remove()}))}}},t.prototype.postProcessStylesFromColDef=function(){var e=this.processStylesFromColDef();e&&p.addStylesToElement(this.getGui(),e)},t.prototype.preProcessStylesFromColDef=function(){var e=this.processStylesFromColDef();return p.cssStyleObjectToMarkup(e)},t.prototype.processStylesFromColDef=function(){var e=this.getComponentHolder();if(e.cellStyle){var t=void 0;if("function"==typeof e.cellStyle){var o={value:this.value,data:this.rowNode.data,node:this.rowNode,colDef:e,column:this.column,$scope:this.scope,context:this.beans.gridOptionsWrapper.getContext(),api:this.beans.gridOptionsWrapper.getApi()};t=(0,e.cellStyle)(o)}else t=e.cellStyle;return t}},t.prototype.postProcessClassesFromColDef=function(){var e=this;this.processClassesFromColDef((function(t){return p.addCssClass(e.getGui(),t)}))},t.prototype.preProcessClassesFromColDef=function(){var e=[];return this.processClassesFromColDef((function(t){return e.push(t)})),e},t.prototype.processClassesFromColDef=function(e){var t=this.getComponentHolder();this.beans.stylingService.processStaticCellClasses(t,{value:this.value,data:this.rowNode.data,node:this.rowNode,colDef:t,rowIndex:this.rowNode.rowIndex,$scope:this.scope,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext()},e)},t.prototype.putDataIntoCellAfterRefresh=function(){var e=this.getComponentHolder();if(e.template)this.eParentOfValue.innerHTML=e.template;else if(e.templateUrl){var t=this.beans.templateService.getTemplate(e.templateUrl,this.refreshCell.bind(this,!0));t&&(this.eParentOfValue.innerHTML=t)}else if(this.chooseCellRenderer(),this.usingCellRenderer)this.createCellRendererInstance();else{var o=this.getValueToUse();null!=o&&(this.eParentOfValue.innerHTML=p.escape(o))}},t.prototype.attemptCellRendererRefresh=function(){if(p.missing(this.cellRenderer)||!this.cellRenderer||p.missing(this.cellRenderer.refresh))return!1;var e=this.createCellRendererParams(),t=this.beans.userComponentFactory.createFinalParams(this.getComponentHolder(),this.cellRendererType,e),o=this.cellRenderer.refresh(t);return!0===o||void 0===o},t.prototype.refreshToolTip=function(){var e=this.getToolTip();if(this.tooltip!==e){var t=p.exists(e),o=p.exists(this.tooltip);if(!t||this.tooltip!==e.toString())if(this.tooltip=e,this.beans.gridOptionsWrapper.isEnableBrowserTooltips())if(t){var i=p.escape(this.tooltip);this.eParentOfValue.setAttribute("title",i)}else this.eParentOfValue.removeAttribute("title");else o?t||this.beans.tooltipManager.unregisterTooltip(this):t&&this.beans.tooltipManager.registerTooltip(this)}},t.prototype.valuesAreEqual=function(e,t){var o=this.getComponentHolder(),i=o?o.equals:null;return i?i(e,t):e===t},t.prototype.getToolTip=function(){var e=this.getComponentHolder(),t=this.rowNode.data;if(e.tooltipField&&p.exists(t))return p.getValueUsingField(t,e.tooltipField,this.column.isTooltipFieldContainsDots());var o=e.tooltipValueGetter||e.tooltip;return o?o({api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),colDef:e,column:this.getColumn(),context:this.beans.gridOptionsWrapper.getContext(),value:this.value,valueFormatted:this.valueFormatted,rowIndex:this.cellPosition.rowIndex,node:this.rowNode,data:this.rowNode.data,$scope:this.scope}):null},t.prototype.getTooltipText=function(e){return void 0===e&&(e=!0),e?p.escape(this.tooltip):this.tooltip},t.prototype.processCellClassRules=function(e,t){var o=this.getComponentHolder();this.beans.stylingService.processClassRules(o.cellClassRules,{value:this.value,data:this.rowNode.data,node:this.rowNode,colDef:o,rowIndex:this.cellPosition.rowIndex,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),$scope:this.scope,context:this.beans.gridOptionsWrapper.getContext()},e,t)},t.prototype.postProcessCellClassRules=function(){var e=this;this.processCellClassRules((function(t){p.addCssClass(e.getGui(),t)}),(function(t){p.removeCssClass(e.getGui(),t)}))},t.prototype.preProcessCellClassRules=function(){var e=[];return this.processCellClassRules((function(t){e.push(t)}),(function(e){})),e},t.prototype.setUsingWrapper=function(){var e=this.getComponentHolder();if(this.rowNode.rowPinned)return this.usingWrapper=!1,this.includeSelectionComponent=!1,this.includeRowDraggingComponent=!1,void(this.includeDndSourceComponent=!1);var t="function"==typeof e.checkboxSelection,o="function"==typeof e.rowDrag,i="function"==typeof e.dndSource;this.includeSelectionComponent=t||!0===e.checkboxSelection,this.includeRowDraggingComponent=o||!0===e.rowDrag,this.includeDndSourceComponent=i||!0===e.dndSource,this.usingWrapper=this.includeRowDraggingComponent||this.includeSelectionComponent||this.includeDndSourceComponent},t.prototype.chooseCellRenderer=function(){var e=this.getComponentHolder();if(e.template||e.templateUrl)this.usingCellRenderer=!1;else{var o=this.createCellRendererParams(),i=this.beans.userComponentFactory.lookupComponentClassDef(e,"cellRenderer",o);this.beans.userComponentFactory.lookupComponentClassDef(e,"pinnedRowCellRenderer",o)&&this.rowNode.rowPinned?(this.cellRendererType=t.CELL_RENDERER_TYPE_PINNED,this.usingCellRenderer=!0):i?(this.cellRendererType=t.CELL_RENDERER_TYPE_NORMAL,this.usingCellRenderer=!0):this.usingCellRenderer=!1}},t.prototype.createCellRendererInstance=function(e){var o=this;if(void 0===e&&(e=!1),this.usingCellRenderer){var i=this.beans.gridOptionsWrapper.isAngularCompileRows(),n=this.beans.gridOptionsWrapper.isSuppressAnimationFrame();(i||n||this.autoHeightCell)&&(e=!1);var r=this.createCellRendererParams();this.cellRendererVersion++;var s=this.afterCellRendererCreated.bind(this,this.cellRendererVersion),a=this.cellRendererType===t.CELL_RENDERER_TYPE_NORMAL,l=function(){var e;(e=a?o.beans.userComponentFactory.newCellRenderer(o.getComponentHolder(),r):o.beans.userComponentFactory.newPinnedRowCellRenderer(o.getComponentHolder(),r))&&e.then(s)};e?this.beans.taskQueue.createTask(l,this.rowNode.rowIndex,"createTasksP2"):l()}},t.prototype.afterCellRendererCreated=function(e,t){this.isAlive()&&e===this.cellRendererVersion?(this.cellRenderer=t,this.cellRendererGui=this.cellRenderer.getGui(),p.missing(this.cellRendererGui)||this.editingCell||this.eParentOfValue.appendChild(this.cellRendererGui)):t.destroy&&t.destroy()},t.prototype.createCellRendererParams=function(){var e=this;return{value:this.value,valueFormatted:this.valueFormatted,getValue:this.getValue.bind(this),setValue:function(t){e.beans.valueService.setValue(e.rowNode,e.column,t)},formatValue:this.formatValue.bind(this),data:this.rowNode.data,node:this.rowNode,colDef:this.getComponentHolder(),column:this.column,$scope:this.scope,rowIndex:this.cellPosition.rowIndex,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext(),refreshCell:this.refreshCell.bind(this),eGridCell:this.getGui(),eParentOfValue:this.eParentOfValue,addRowCompListener:this.rowComp?this.rowComp.addEventListener.bind(this.rowComp):null,addRenderedRowListener:function(t,o){console.warn("ag-Grid: since ag-Grid .v11, params.addRenderedRowListener() is now params.addRowCompListener()"),e.rowComp&&e.rowComp.addEventListener(t,o)}}},t.prototype.formatValue=function(e){var t=this.beans.valueFormatterService.formatValue(this.column,this.rowNode,this.scope,e);return null!=t?t:e},t.prototype.getValueToUse=function(){return null!==this.valueFormatted&&void 0!==this.valueFormatted?this.valueFormatted:this.value},t.prototype.getValueAndFormat=function(){this.value=this.getValue(),this.valueFormatted=this.beans.valueFormatterService.formatValue(this.column,this.rowNode,this.scope,this.value)},t.prototype.getValue=function(){var e=this.rowNode.leafGroup&&this.beans.columnController.isPivotMode(),t=this.rowNode.group&&this.rowNode.expanded&&!this.rowNode.footer&&!e,o=this.beans.gridOptionsWrapper.isGroupIncludeFooter(),i=this.beans.gridOptionsWrapper.isGroupSuppressBlankHeader(),n=t&&o&&!i;return this.beans.valueService.getValue(this.column,this.rowNode,!1,n)},t.prototype.onMouseEvent=function(e,t){if(!p.isStopPropagationForAgGrid(t))switch(e){case"click":this.onCellClicked(t);break;case"mousedown":this.onMouseDown(t);break;case"dblclick":this.onCellDoubleClicked(t);break;case"mouseout":this.onMouseOut(t);break;case"mouseover":this.onMouseOver(t)}},t.prototype.dispatchCellContextMenuEvent=function(e){var t=this.getComponentHolder(),o=this.createEvent(e,M.EVENT_CELL_CONTEXT_MENU);this.beans.eventService.dispatchEvent(o),t.onCellContextMenu&&window.setTimeout((function(){return t.onCellContextMenu(o)}),0)},t.prototype.createEvent=function(e,t){var o={node:this.rowNode,data:this.rowNode.data,value:this.value,column:this.column,colDef:this.getComponentHolder(),context:this.beans.gridOptionsWrapper.getContext(),api:this.beans.gridApi,columnApi:this.beans.columnApi,rowPinned:this.rowNode.rowPinned,event:e,type:t,rowIndex:this.rowNode.rowIndex};return this.scope&&(o.$scope=this.scope),o},t.prototype.onMouseOut=function(e){var t=this.createEvent(e,M.EVENT_CELL_MOUSE_OUT);this.beans.eventService.dispatchEvent(t),this.beans.columnHoverService.clearMouseOver()},t.prototype.onMouseOver=function(e){var t=this.createEvent(e,M.EVENT_CELL_MOUSE_OVER);this.beans.eventService.dispatchEvent(t),this.beans.columnHoverService.setMouseOver([this.column])},t.prototype.onCellDoubleClicked=function(e){var t=this.getComponentHolder(),o=this.createEvent(e,M.EVENT_CELL_DOUBLE_CLICKED);this.beans.eventService.dispatchEvent(o),"function"==typeof t.onCellDoubleClicked&&window.setTimeout((function(){return t.onCellDoubleClicked(o)}),0),!this.beans.gridOptionsWrapper.isSingleClickEdit()&&!this.beans.gridOptionsWrapper.isSuppressClickEdit()&&this.startRowOrCellEdit()},t.prototype.startRowOrCellEdit=function(e,t){this.beans.gridOptionsWrapper.isFullRowEdit()?this.rowComp.startRowEditing(e,t,this):this.startEditingIfEnabled(e,t,!0)},t.prototype.isCellEditable=function(){return this.column.isCellEditable(this.rowNode)},t.prototype.startEditingIfEnabled=function(e,t,o){if(void 0===e&&(e=null),void 0===t&&(t=null),void 0===o&&(o=!1),this.isCellEditable()&&!this.editingCell){this.editingCell=!0,this.cellEditorVersion++;var i=this.afterCellEditorCreated.bind(this,this.cellEditorVersion),n=this.createCellEditorParams(e,t,o);this.createCellEditor(n).then(i),p.missing(this.cellEditor)&&o&&this.focusCell(!0)}},t.prototype.createCellEditor=function(e){var t=this;return this.beans.userComponentFactory.newCellEditor(this.column.getColDef(),e).map((function(o){if(!(o.isPopup&&o.isPopup()))return o;t.beans.gridOptionsWrapper.isFullRowEdit()&&console.warn("ag-Grid: popup cellEditor does not work with fullRowEdit - you cannot use them both - either turn off fullRowEdit, or stop using popup editors.");var i=new mo(o);return t.beans.context.wireBean(i),i.init(e),i}))},t.prototype.afterCellEditorCreated=function(e,t){if(!(e!==this.cellEditorVersion)&&this.editingCell){if(t.isCancelBeforeStart&&t.isCancelBeforeStart())return t.destroy&&t.destroy(),void(this.editingCell=!1);if(!t.getGui)return console.warn("ag-Grid: cellEditor for column "+this.column.getId()+" is missing getGui() method"),t.render&&console.warn("ag-Grid: we found 'render' on the component, are you trying to set a React renderer but added it as colDef.cellEditor instead of colDef.cellEditorFmk?"),t.destroy&&t.destroy(),void(this.editingCell=!1);this.cellEditor=t,this.cellEditorInPopup=void 0!==t.isPopup&&t.isPopup(),this.setInlineEditingClass(),this.cellEditorInPopup?this.addPopupCellEditor():this.addInCellEditor(),t.afterGuiAttached&&t.afterGuiAttached();var o=this.createEvent(null,M.EVENT_CELL_EDITING_STARTED);this.beans.eventService.dispatchEvent(o)}else t.destroy&&t.destroy()},t.prototype.addInCellEditor=function(){p.clearElement(this.getGui()),this.cellEditor&&this.getGui().appendChild(this.cellEditor.getGui()),this.angular1Compile()},t.prototype.addPopupCellEditor=function(){var e=this,t=this.cellEditor?this.cellEditor.getGui():null,o=this.beans.gridOptionsWrapper.isStopEditingWhenGridLosesFocus();this.hideEditorPopup=this.beans.popupService.addPopup(o,t,!0,(function(){e.onPopupEditorClosed()})),this.beans.popupService.positionPopupOverComponent({column:this.column,rowNode:this.rowNode,type:"popupCellEditor",eventSource:this.getGui(),ePopup:t,keepWithinBounds:!0}),this.angular1Compile()},t.prototype.onPopupEditorClosed=function(){this.editingCell&&(this.stopRowOrCellEdit(),this.beans.focusedCellController.isCellFocused(this.cellPosition)&&this.focusCell(!0))},t.prototype.setInlineEditingClass=function(){if(this.isAlive()){var e=this.editingCell&&!this.cellEditorInPopup,t=this.editingCell&&this.cellEditorInPopup;p.addOrRemoveCssClass(this.getGui(),"ag-cell-inline-editing",e),p.addOrRemoveCssClass(this.getGui(),"ag-cell-not-inline-editing",!e),p.addOrRemoveCssClass(this.getGui(),"ag-cell-popup-editing",t),p.addOrRemoveCssClass(this.getGui().parentNode,"ag-row-inline-editing",e),p.addOrRemoveCssClass(this.getGui().parentNode,"ag-row-not-inline-editing",!e)}},t.prototype.createCellEditorParams=function(e,t,o){return{value:this.getValue(),keyPress:e,charPress:t,column:this.column,colDef:this.column.getColDef(),rowIndex:this.cellPosition.rowIndex,node:this.rowNode,data:this.rowNode.data,api:this.beans.gridOptionsWrapper.getApi(),cellStartedEdit:o,columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext(),$scope:this.scope,onKeyDown:this.onKeyDown.bind(this),stopEditing:this.stopEditingAndFocus.bind(this),eGridCell:this.getGui(),parseValue:this.parseValue.bind(this),formatValue:this.formatValue.bind(this)}},t.prototype.stopEditingAndFocus=function(e){void 0===e&&(e=!1),this.stopRowOrCellEdit(),this.focusCell(!0),e||this.navigateAfterEdit()},t.prototype.parseValue=function(e){var t=this.getComponentHolder(),o={node:this.rowNode,data:this.rowNode.data,oldValue:this.value,newValue:e,colDef:t,column:this.column,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext()},i=t.valueParser;return p.exists(i)?this.beans.expressionService.evaluate(i,o):e},t.prototype.focusCell=function(e){void 0===e&&(e=!1),this.beans.focusedCellController.setFocusedCell(this.cellPosition.rowIndex,this.column,this.rowNode.rowPinned,e),this.refreshHandle()},t.prototype.setFocusInOnEditor=function(){this.editingCell&&(this.cellEditor&&this.cellEditor.focusIn?this.cellEditor.focusIn():this.focusCell(!0))},t.prototype.isEditing=function(){return this.editingCell},t.prototype.onKeyDown=function(e){var t=e.which||e.keyCode;switch(t){case o.KEY_ENTER:this.onEnterKeyDown();break;case o.KEY_F2:this.onF2KeyDown();break;case o.KEY_ESCAPE:this.onEscapeKeyDown();break;case o.KEY_TAB:this.onTabKeyDown(e);break;case o.KEY_BACKSPACE:case o.KEY_DELETE:this.onBackspaceOrDeleteKeyPressed(t);break;case o.KEY_DOWN:case o.KEY_UP:case o.KEY_RIGHT:case o.KEY_LEFT:this.onNavigationKeyPressed(e,t)}},t.prototype.setFocusOutOnEditor=function(){this.editingCell&&this.cellEditor&&this.cellEditor.focusOut&&this.cellEditor.focusOut()},t.prototype.onNavigationKeyPressed=function(e,t){this.editingCell||(e.shiftKey&&this.rangeSelectionEnabled?this.onShiftRangeSelect(t):this.beans.rowRenderer.navigateToNextCell(e,t,this.cellPosition,!0),e.preventDefault())},t.prototype.onShiftRangeSelect=function(e){if(this.beans.rangeController){var t=this.beans.rangeController.extendLatestRangeInDirection(e);t&&this.beans.rowRenderer.ensureCellVisible(t)}},t.prototype.onTabKeyDown=function(e){this.beans.rowRenderer.onTabKeyDown(this,e)},t.prototype.onBackspaceOrDeleteKeyPressed=function(e){this.editingCell||this.startRowOrCellEdit(e)},t.prototype.onEnterKeyDown=function(){this.editingCell||this.rowComp.isEditing()?this.stopEditingAndFocus():this.beans.gridOptionsWrapper.isEnterMovesDown()?this.beans.rowRenderer.navigateToNextCell(null,o.KEY_DOWN,this.cellPosition,!1):this.startRowOrCellEdit(o.KEY_ENTER)},t.prototype.navigateAfterEdit=function(){this.beans.gridOptionsWrapper.isFullRowEdit()||this.beans.gridOptionsWrapper.isEnterMovesDownAfterEdit()&&this.beans.rowRenderer.navigateToNextCell(null,o.KEY_DOWN,this.cellPosition,!1)},t.prototype.onF2KeyDown=function(){this.editingCell||this.startRowOrCellEdit(o.KEY_F2)},t.prototype.onEscapeKeyDown=function(){this.editingCell&&(this.stopRowOrCellEdit(!0),this.focusCell(!0))},t.prototype.onKeyPress=function(e){if(!(p.getTarget(e)!==this.getGui())&&!this.editingCell){var t=String.fromCharCode(e.charCode);" "===t?this.onSpaceKeyPressed(e):p.isEventFromPrintableCharacter(e)&&(this.startRowOrCellEdit(null,t),e.preventDefault())}},t.prototype.onSpaceKeyPressed=function(e){if(!this.editingCell&&this.beans.gridOptionsWrapper.isRowSelection()){var t=this.rowNode.isSelected();this.rowNode.setSelected(!t)}e.preventDefault()},t.prototype.onMouseDown=function(e){var t=!1,o=e.button,i=e.ctrlKey,n=e.metaKey,r=e.shiftKey,s=e.target,a=this.beans,l=a.eventService,u=a.rangeController;if(u&&(u.isCellInAnyRange(this.getCellPosition())&&2===o))return;if((p.isBrowserIE()||p.isBrowserEdge())&&this.getGui().contains(s)&&(t=!0),!r||u&&!u.getCellRanges().length?this.focusCell(t):e.preventDefault(),!p.isElementChildOfClass(s,"ag-selection-checkbox",3)){if(p.isLeftClick(e)&&u){var c=this.cellPosition;if(r)u.extendLatestRangeToCell(c);else{var d=i||n;u.setRangeToCell(c,d)}}var h=this.createEvent(e,M.EVENT_CELL_MOUSE_DOWN);l.dispatchEvent(h)}},t.prototype.isDoubleClickOnIPad=function(){if(p.isIOSUserAgent()&&!p.isEventSupported("dblclick"))return!1;var e=(new Date).getTime(),t=e-this.lastIPadMouseClickEvent<200;return this.lastIPadMouseClickEvent=e,t},t.prototype.onCellClicked=function(e){if(this.isDoubleClickOnIPad())return this.onCellDoubleClicked(e),void e.preventDefault();var t=this.createEvent(e,M.EVENT_CELL_CLICKED);this.beans.eventService.dispatchEvent(t);var o=this.getComponentHolder();o.onCellClicked&&window.setTimeout((function(){return o.onCellClicked(t)}),0),(this.beans.gridOptionsWrapper.isSingleClickEdit()||o.singleClickEdit)&&!this.beans.gridOptionsWrapper.isSuppressClickEdit()&&this.startRowOrCellEdit()},t.prototype.createGridCellVo=function(){this.cellPosition={rowIndex:this.rowNode.rowIndex,rowPinned:this.rowNode.rowPinned,column:this.column}},t.prototype.getCellPosition=function(){return this.cellPosition},t.prototype.getParentRow=function(){return this.eParentRow},t.prototype.setParentRow=function(e){this.eParentRow=e},t.prototype.getColumn=function(){return this.column},t.prototype.getComponentHolder=function(){return this.column.getColDef()},t.prototype.detach=function(){this.eParentRow.removeChild(this.getGui())},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.stopEditing(),this.cellRenderer&&this.cellRenderer.destroy&&(this.cellRenderer.destroy(),this.cellRenderer=null),this.selectionHandle&&this.selectionHandle.destroy()},t.prototype.onLeftChanged=function(){var e=this.modifyLeftForPrintLayout(this.getCellLeft());this.getGui().style.left=e+"px"},t.prototype.modifyLeftForPrintLayout=function(e){return this.printLayout?this.column.getPinned()===o.PINNED_LEFT?e:this.column.getPinned()===o.PINNED_RIGHT?this.beans.columnController.getPinnedLeftContainerWidth()+this.beans.columnController.getBodyContainerWidth()+e:this.beans.columnController.getPinnedLeftContainerWidth()+e:e},t.prototype.onWidthChanged=function(){var e=this.getCellWidth();this.getGui().style.width=e+"px"},t.prototype.getRangeBorders=function(){var e,t,o=this,i=this.beans.gridOptionsWrapper.isEnableRtl(),n=!1,r=!1,s=!1,a=!1,l=this.cellPosition.column,p=this.beans.rangeController;i?(e=this.beans.columnController.getDisplayedColAfter(l),t=this.beans.columnController.getDisplayedColBefore(l)):(e=this.beans.columnController.getDisplayedColBefore(l),t=this.beans.columnController.getDisplayedColAfter(l));var u=p.getCellRanges().filter((function(e){return p.isCellInSpecificRange(o.cellPosition,e)}));e||(a=!0),t||(r=!0);for(var c=0;c<u.length&&!(n&&r&&s&&a);c++){var d=u[c],h=p.getRangeStartRow(d),g=p.getRangeEndRow(d);!n&&this.beans.rowPositionUtils.sameRow(h,this.cellPosition)&&(n=!0),!s&&this.beans.rowPositionUtils.sameRow(g,this.cellPosition)&&(s=!0),!a&&d.columns.indexOf(e)<0&&(a=!0),!r&&d.columns.indexOf(t)<0&&(r=!0)}return{top:n,right:r,bottom:s,left:a}},t.prototype.getInitialRangeClasses=function(){var e=[];if(!this.rangeSelectionEnabled||!this.rangeCount)return e;var t=this.beans.rangeController;e.push("ag-cell-range-selected"),this.hasChartRange&&e.push("ag-cell-range-chart");var o=Math.min(this.rangeCount,4);if(e.push("ag-cell-range-selected-"+o),1!==this.rangeCount||t.isMoreThanOneCell()||e.push("ag-cell-range-single-cell"),this.rangeCount>0){var i=this.getRangeBorders();i.top&&e.push("ag-cell-range-top"),i.right&&e.push("ag-cell-range-right"),i.bottom&&e.push("ag-cell-range-bottom"),i.left&&e.push("ag-cell-range-left")}return this.selectionHandle&&e.push("ag-cell-range-handle"),e},t.prototype.onRowIndexChanged=function(){this.createGridCellVo(),this.onCellFocused(),this.onRangeSelectionChanged()},t.prototype.onRangeSelectionChanged=function(){if(this.beans.rangeController){var e=this.beans,t=this.cellPosition,o=this.rangeCount,i=e.rangeController,n=i.getCellRangeCount(t),r=this.getGui();o!==n&&(p.addOrRemoveCssClass(r,"ag-cell-range-selected",0!==n),p.addOrRemoveCssClass(r,"ag-cell-range-selected-1",1===n),p.addOrRemoveCssClass(r,"ag-cell-range-selected-2",2===n),p.addOrRemoveCssClass(r,"ag-cell-range-selected-3",3===n),p.addOrRemoveCssClass(r,"ag-cell-range-selected-4",n>=4),this.rangeCount=n);var s=this.rangeCount&&i.getCellRanges().every((function(e){return p.exists(e.type)}));this.hasChartRange!==s&&(p.addOrRemoveCssClass(r,"ag-cell-range-chart",s),this.hasChartRange=s),this.updateRangeBorders();var a=1===this.rangeCount&&!i.isMoreThanOneCell();p.addOrRemoveCssClass(r,"ag-cell-range-single-cell",a),this.refreshHandle(),p.addOrRemoveCssClass(r,"ag-cell-range-handle",!!this.selectionHandle)}},t.prototype.shouldHaveSelectionHandle=function(){var e=this.beans,t=e.gridOptionsWrapper,o=e.rangeController,i=this.getGui(),n=o.getCellRanges(),r=n.length;if(!r)return!1;var s=p.last(n),a=n[0].type===Kt.DIMENSION,l=(t.isEnableFillHandle()||t.isEnableRangeHandle()||this.hasChartRange&&!a)&&1===r&&!this.editingCell;if(!l&&this.hasChartRange){var u=this.getCellPosition();l=a&&2===r&&o.isCellInSpecificRange(this.getCellPosition(),s);var c=a&&o.isCellInSpecificRange(u,n[0]);p.addOrRemoveCssClass(i,"ag-cell-range-chart-category",c)}return this.rangeCount&&l&&null!=s.endRow&&this.beans.rangeController.isContiguousRange(s)&&(p.containsClass(i,"ag-cell-range-single-cell")||p.containsClass(i,"ag-cell-range-bottom")&&p.containsClass(i,"ag-cell-range-right"))},t.prototype.addSelectionHandle=function(){var e=this.beans,t=e.gridOptionsWrapper,o=e.context,i=e.rangeController,n=p.last(i.getCellRanges()).type,r=t.isEnableFillHandle()&&p.missing(n)?"fill":"range";this.selectionHandle&&this.selectionHandle.getType()!==r&&(this.selectionHandle.destroy(),this.selectionHandle=void 0),this.selectionHandle||(this.selectionHandle=o.createComponentFromElement(document.createElement("ag-"+r+"-handle"))),this.selectionHandle.refresh(this)},t.prototype.updateRangeBordersIfRangeCount=function(){this.rangeCount>0&&(this.updateRangeBorders(),this.refreshHandle())},t.prototype.refreshHandle=function(){if(this.beans.rangeController){var e=this.shouldHaveSelectionHandle();this.selectionHandle&&!e&&(this.selectionHandle.destroy(),this.selectionHandle=null),e&&this.addSelectionHandle()}},t.prototype.updateRangeBorders=function(){var e=this.getRangeBorders(),t=1===this.rangeCount&&!this.beans.rangeController.isMoreThanOneCell(),o=!t&&e.top,i=!t&&e.right,n=!t&&e.bottom,r=!t&&e.left,s=this.getGui();p.addOrRemoveCssClass(s,"ag-cell-range-top",o),p.addOrRemoveCssClass(s,"ag-cell-range-right",i),p.addOrRemoveCssClass(s,"ag-cell-range-bottom",n),p.addOrRemoveCssClass(s,"ag-cell-range-left",r)},t.prototype.onFirstRightPinnedChanged=function(){var e=this.column.isFirstRightPinned();this.firstRightPinned!==e&&(this.firstRightPinned=e,p.addOrRemoveCssClass(this.getGui(),"ag-cell-first-right-pinned",e))},t.prototype.onLastLeftPinnedChanged=function(){var e=this.column.isLastLeftPinned();this.lastLeftPinned!==e&&(this.lastLeftPinned=e,p.addOrRemoveCssClass(this.getGui(),"ag-cell-last-left-pinned",e))},t.prototype.populateTemplate=function(){this.usingWrapper?(this.eParentOfValue=this.getRefElement("eCellValue"),this.eCellWrapper=this.getRefElement("eCellWrapper"),this.includeRowDraggingComponent&&this.addRowDragging(),this.includeDndSourceComponent&&this.addDndSource(),this.includeSelectionComponent&&this.addSelectionCheckbox()):this.eParentOfValue=this.getGui()},t.prototype.getFrameworkOverrides=function(){return this.beans.frameworkOverrides},t.prototype.addRowDragging=function(){var e=this.beans.gridOptionsWrapper.isPagination(),t=this.beans.gridOptionsWrapper.isRowDragManaged(),o=this.beans.gridOptionsWrapper.isRowModelDefault();if(t){if(!o)return void p.doOnce((function(){return console.warn("ag-Grid: managed row dragging is only allowed in the Client Side Row Model")}),"CellComp.addRowDragging");if(e)return void p.doOnce((function(){return console.warn("ag-Grid: managed row dragging is not possible when doing pagination")}),"CellComp.addRowDragging")}var i=new uo(this.rowNode,this.column,this.getValueToUse(),this.beans);this.addFeature(i,this.beans.context),this.eCellWrapper.insertBefore(i.getGui(),this.eParentOfValue)},t.prototype.addDndSource=function(){var e=new Eo(this.rowNode,this.column,this.getValueToUse(),this.beans,this.getGui());this.addFeature(e,this.beans.context),this.eCellWrapper.insertBefore(e.getGui(),this.eParentOfValue)},t.prototype.addSelectionCheckbox=function(){var e=new Ke;this.beans.context.wireBean(e);var t=this.getComponentHolder().checkboxSelection;t="function"==typeof t?t:null,e.init({rowNode:this.rowNode,column:this.column,visibleFunc:t}),this.addDestroyFunc((function(){return e.destroy()})),this.eCellWrapper.insertBefore(e.getGui(),this.eParentOfValue)},t.prototype.addDomData=function(){var e=this,o=this.getGui();this.beans.gridOptionsWrapper.setDomData(o,t.DOM_DATA_KEY_CELL_COMP,this),this.addDestroyFunc((function(){return e.beans.gridOptionsWrapper.setDomData(o,t.DOM_DATA_KEY_CELL_COMP,null)}))},t.prototype.onCellFocused=function(e){var t=this.beans.focusedCellController.isCellFocused(this.cellPosition);t!==this.cellFocused&&(!this.beans.gridOptionsWrapper.isSuppressCellSelection()&&p.addOrRemoveCssClass(this.getGui(),"ag-cell-focus",t),this.cellFocused=t);t&&e&&e.forceBrowserFocus&&(this.getGui().focus(),document.activeElement&&document.activeElement!==document.body||this.getGui().focus());var o=this.beans.gridOptionsWrapper.isFullRowEdit();t||o||!this.editingCell||this.stopRowOrCellEdit()},t.prototype.stopRowOrCellEdit=function(e){void 0===e&&(e=!1),this.beans.gridOptionsWrapper.isFullRowEdit()?this.rowComp.stopRowEditing(e):this.stopEditing(e)},t.prototype.stopEditing=function(e){if(void 0===e&&(e=!1),this.editingCell)if(this.cellEditor){var t,o=!1;if(!e)this.cellEditor.isCancelAfterEnd&&this.cellEditor.isCancelAfterEnd()||(t=this.cellEditor.getValue(),o=!0);if(this.editingCell=!1,this.cellEditor.destroy&&this.cellEditor.destroy(),this.cellEditor=null,this.cellEditorInPopup&&this.hideEditorPopup)this.hideEditorPopup(),this.hideEditorPopup=null;else if(p.clearElement(this.getGui()),this.usingWrapper)this.getGui().appendChild(this.eCellWrapper);else if(this.cellRenderer){var i=this.cellRendererGui;i&&this.getGui().appendChild(i)}this.setInlineEditingClass(),o&&(this.suppressRefreshCell=!0,this.rowNode.setDataValue(this.column,t),this.suppressRefreshCell=!1),this.refreshCell({forceRefresh:!0,suppressFlash:!0});var n=this.createEvent(null,M.EVENT_CELL_EDITING_STOPPED);this.beans.eventService.dispatchEvent(n)}else this.editingCell=!1},t.DOM_DATA_KEY_CELL_COMP="cellComp",t.CELL_RENDERER_TYPE_NORMAL="cellRenderer",t.CELL_RENDERER_TYPE_PINNED="pinnedRowCellRenderer",t}(pe),Do=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),bo=function(){return(bo=Object.assign||function(e){for(var t,o=1,i=arguments.length;o<i;o++)for(var n in t=arguments[o])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},Po=function(e){function t(t,o,i,n,r,s,a,l,p,u,c){var d=e.call(this)||this;return d.eAllRowContainers=[],d.active=!0,d.rowContainerReadyCount=0,d.refreshNeeded=!1,d.columnRefreshPending=!1,d.cellComps={},d.createSecondPassFuncs=[],d.removeFirstPassFuncs=[],d.removeSecondPassFuncs=[],d.initialised=!1,d.elementOrderChanged=!1,d.parentScope=t,d.beans=a,d.bodyContainerComp=o,d.pinnedLeftContainerComp=i,d.pinnedRightContainerComp=n,d.fullWidthContainerComp=r,d.rowNode=s,d.rowIsEven=d.rowNode.rowIndex%2==0,d.paginationPage=d.beans.paginationProxy.getCurrentPage(),d.useAnimationFrameForCreate=p,d.printLayout=u,d.embedFullWidth=c,d.setAnimateFlags(l),d}return Do(t,e),t.prototype.init=function(){var e=this;this.rowFocused=this.beans.focusedCellController.isRowFocused(this.rowNode.rowIndex,this.rowNode.rowPinned),this.scope=this.createChildScopeOrNull(this.rowNode.data),this.setupRowContainers(),this.addListeners(),this.slideRowIn&&this.createSecondPassFuncs.push((function(){e.onTopChanged()})),this.fadeRowIn&&this.createSecondPassFuncs.push((function(){e.eAllRowContainers.forEach((function(e){return p.removeCssClass(e,"ag-opacity-zero")}))}))},t.prototype.createTemplate=function(e,t){void 0===t&&(t=null);var o=[],i=this.rowNode.rowHeight,n=this.getInitialRowClasses(t).join(" "),r=p.escape(this.rowNode.id),s=this.preProcessStylesFromGridOptions(),a=this.getRowBusinessKey(),l=p.escape(a),u=this.getInitialRowTopStyle(),c=this.rowNode.getRowIndexString(),d=this.beans.gridPanel.headerRootComp.getHeaderRowCount();return o.push("<div"),o.push(' role="row"'),o.push(' row-index="'+c+'" aria-rowindex="'+(d+this.rowNode.rowIndex+1)+'"'),o.push(r?' row-id="'+r+'"':""),o.push(a?' row-business-key="'+l+'"':""),o.push(' comp-id="'+this.getCompId()+'"'),o.push(' class="'+n+'"'),o.push(' style="height: '+i+"px; "+u+" "+s+'">'),o.push(e),o.push("</div>"),o.join("")},t.prototype.getCellForCol=function(e){var t=this.cellComps[e.getColId()];return t?t.getGui():null},t.prototype.afterFlush=function(){this.initialised||(this.initialised=!0,this.executeProcessRowPostCreateFunc())},t.prototype.executeProcessRowPostCreateFunc=function(){var e=this.beans.gridOptionsWrapper.getProcessRowPostCreateFunc();e&&e({eRow:this.eBodyRow,ePinnedLeftRow:this.ePinnedLeftRow,ePinnedRightRow:this.ePinnedRightRow,node:this.rowNode,api:this.beans.gridOptionsWrapper.getApi(),rowIndex:this.rowNode.rowIndex,addRenderedRowListener:this.addEventListener.bind(this),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext()})},t.prototype.getInitialRowTopStyle=function(){if(this.printLayout)return"";var e=this.slideRowIn?this.roundRowTopToBounds(this.rowNode.oldRowTop):this.rowNode.rowTop,t=this.applyPaginationOffset(e),o=this.beans.maxDivHeightScaler.getRealPixelPosition(t);return this.beans.gridOptionsWrapper.isSuppressRowTransform()?"top: "+o+"px; ":"transform: translateY("+o+"px);"},t.prototype.getRowBusinessKey=function(){var e=this.beans.gridOptionsWrapper.getBusinessKeyForNodeFunc();if("function"==typeof e)return e(this.rowNode)},t.prototype.areAllContainersReady=function(){return 3===this.rowContainerReadyCount},t.prototype.lazyCreateCells=function(e,t){if(this.active){var o=this.createCells(e);t.innerHTML=o.template,this.callAfterRowAttachedOnCells(o.cellComps,t),this.rowContainerReadyCount++,this.areAllContainersReady()&&this.refreshNeeded&&this.refreshCells()}},t.prototype.createRowContainer=function(e,t,o){var i=this,n=this.useAnimationFrameForCreate,r=n?{cellComps:[],template:""}:this.createCells(t),s=this.createTemplate(r.template);e.appendRowTemplate(s,(function(){var s=e.getRowElement(i.getCompId());i.afterRowAttached(e,s),o(s),n?i.beans.taskQueue.createTask(i.lazyCreateCells.bind(i,t,s),i.rowNode.rowIndex,"createTasksP1"):(i.callAfterRowAttachedOnCells(r.cellComps,s),i.rowContainerReadyCount=3)}))},t.prototype.createChildScopeOrNull=function(e){if(!this.beans.gridOptionsWrapper.isAngularCompileRows())return null;var t=this.parentScope.$new();return t.data=bo({},e),t.rowNode=this.rowNode,t.context=this.beans.gridOptionsWrapper.getContext(),this.addDestroyFunc((function(){t.$destroy(),t.data=null,t.rowNode=null,t.context=null})),t},t.prototype.setupRowContainers=function(){var e=this.rowNode.isFullWidthCell(),o=this.beans.doingMasterDetail&&this.rowNode.detail,i=this.beans.columnController.isPivotMode(),n=this.rowNode.group&&!this.rowNode.footer&&this.beans.gridOptionsWrapper.isGroupUseEntireRow(i);this.rowNode.stub?this.createFullWidthRows(t.LOADING_CELL_RENDERER,t.LOADING_CELL_RENDERER_COMP_NAME):o?this.createFullWidthRows(t.DETAIL_CELL_RENDERER,t.DETAIL_CELL_RENDERER_COMP_NAME):e?this.createFullWidthRows(t.FULL_WIDTH_CELL_RENDERER,null):n?this.createFullWidthRows(t.GROUP_ROW_RENDERER,t.GROUP_ROW_RENDERER_COMP_NAME):this.setupNormalRowContainers()},t.prototype.setupNormalRowContainers=function(){var e,t,o,i=this;this.printLayout?(e=this.beans.columnController.getAllDisplayedColumns(),t=[],o=[]):(e=this.beans.columnController.getAllDisplayedCenterVirtualColumnsForRow(this.rowNode),t=this.beans.columnController.getDisplayedLeftColumnsForRow(this.rowNode),o=this.beans.columnController.getDisplayedRightColumnsForRow(this.rowNode)),this.createRowContainer(this.bodyContainerComp,e,(function(e){return i.eBodyRow=e})),this.createRowContainer(this.pinnedRightContainerComp,o,(function(e){return i.ePinnedRightRow=e})),this.createRowContainer(this.pinnedLeftContainerComp,t,(function(e){return i.ePinnedLeftRow=e}))},t.prototype.createFullWidthRows=function(e,t){var i=this;this.fullWidthRow=!0,this.embedFullWidth?(this.createFullWidthRowContainer(this.bodyContainerComp,null,null,e,t,(function(e){i.eFullWidthRowBody=e}),(function(e){i.fullWidthRowComponentBody=e})),this.printLayout||(this.createFullWidthRowContainer(this.pinnedLeftContainerComp,o.PINNED_LEFT,"ag-cell-last-left-pinned",e,t,(function(e){i.eFullWidthRowLeft=e}),(function(e){i.fullWidthRowComponentLeft=e})),this.createFullWidthRowContainer(this.pinnedRightContainerComp,o.PINNED_RIGHT,"ag-cell-first-right-pinned",e,t,(function(e){i.eFullWidthRowRight=e}),(function(e){i.fullWidthRowComponentRight=e})))):this.createFullWidthRowContainer(this.fullWidthContainerComp,null,null,e,t,(function(e){i.eFullWidthRow=e}),(function(e){i.fullWidthRowComponent=e}))},t.prototype.setAnimateFlags=function(e){if(e){var t=p.exists(this.rowNode.oldRowTop);this.slideRowIn=t,this.fadeRowIn=!t}else this.slideRowIn=!1,this.fadeRowIn=!1},t.prototype.isEditing=function(){return this.editingRow},t.prototype.stopRowEditing=function(e){this.stopEditing(e)},t.prototype.isFullWidth=function(){return this.fullWidthRow},t.prototype.refreshFullWidth=function(){var e=this,t=function(t,o,i){if(!t||!o)return!0;if(!o.refresh)return!1;var n=e.createFullWidthParams(t,i);return o.refresh(n)},i=t(this.eFullWidthRow,this.fullWidthRowComponent,null),n=t(this.eFullWidthRowBody,this.fullWidthRowComponentBody,null),r=t(this.eFullWidthRowLeft,this.fullWidthRowComponentLeft,o.PINNED_LEFT),s=t(this.eFullWidthRowRight,this.fullWidthRowComponentRight,o.PINNED_RIGHT);return i&&n&&r&&s},t.prototype.addListeners=function(){this.addDestroyableEventListener(this.rowNode,je.EVENT_HEIGHT_CHANGED,this.onRowHeightChanged.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_ROW_SELECTED,this.onRowSelected.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_ROW_INDEX_CHANGED,this.onRowIndexChanged.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_TOP_CHANGED,this.onTopChanged.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_EXPANDED_CHANGED,this.onExpandedChanged.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_DATA_CHANGED,this.onRowNodeDataChanged.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_CELL_CHANGED,this.onRowNodeCellChanged.bind(this)),this.addDestroyableEventListener(this.rowNode,je.EVENT_DRAGGING_CHANGED,this.onRowNodeDraggingChanged.bind(this));var e=this.beans.eventService;this.addDestroyableEventListener(e,M.EVENT_HEIGHT_SCALE_CHANGED,this.onTopChanged.bind(this)),this.addDestroyableEventListener(e,M.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this)),this.addDestroyableEventListener(e,M.EVENT_VIRTUAL_COLUMNS_CHANGED,this.onVirtualColumnsChanged.bind(this)),this.addDestroyableEventListener(e,M.EVENT_COLUMN_RESIZED,this.onColumnResized.bind(this)),this.addDestroyableEventListener(e,M.EVENT_CELL_FOCUSED,this.onCellFocusChanged.bind(this)),this.addDestroyableEventListener(e,M.EVENT_PAGINATION_CHANGED,this.onPaginationChanged.bind(this)),this.addDestroyableEventListener(e,M.EVENT_GRID_COLUMNS_CHANGED,this.onGridColumnsChanged.bind(this)),this.addDestroyableEventListener(e,M.EVENT_MODEL_UPDATED,this.onModelUpdated.bind(this)),this.addDestroyableEventListener(e,M.EVENT_COLUMN_MOVED,this.onColumnMoved.bind(this)),this.addListenersForCellComps()},t.prototype.addListenersForCellComps=function(){var e=this;this.addDestroyableEventListener(this.rowNode,je.EVENT_ROW_INDEX_CHANGED,(function(){e.forEachCellComp((function(e){return e.onRowIndexChanged()}))})),this.addDestroyableEventListener(this.rowNode,je.EVENT_CELL_CHANGED,(function(t){e.forEachCellComp((function(e){return e.onCellChanged(t)}))}))},t.prototype.onGridColumnsChanged=function(){this.removeRenderedCells(Object.keys(this.cellComps))},t.prototype.onRowNodeDataChanged=function(e){this.forEachCellComp((function(t){return t.refreshCell({suppressFlash:!e.update,newData:!e.update})})),this.onRowSelected(),this.postProcessCss()},t.prototype.onRowNodeCellChanged=function(e){this.postProcessCss()},t.prototype.postProcessCss=function(){this.postProcessStylesFromGridOptions(),this.postProcessClassesFromGridOptions(),this.postProcessRowClassRules(),this.postProcessRowDragging()},t.prototype.onRowNodeDraggingChanged=function(){this.postProcessRowDragging()},t.prototype.postProcessRowDragging=function(){var e=this.rowNode.dragging;this.eAllRowContainers.forEach((function(t){return p.addOrRemoveCssClass(t,"ag-row-dragging",e)}))},t.prototype.onExpandedChanged=function(){var e=this.rowNode;this.eAllRowContainers.forEach((function(t){return p.addOrRemoveCssClass(t,"ag-row-group-expanded",e.expanded)})),this.eAllRowContainers.forEach((function(t){return p.addOrRemoveCssClass(t,"ag-row-group-contracted",!e.expanded)}))},t.prototype.onDisplayedColumnsChanged=function(){this.fullWidthRow||this.refreshCells()},t.prototype.destroyFullWidthComponents=function(){this.fullWidthRowComponent&&(this.beans.detailRowCompCache.addOrDestroy(this.rowNode,null,this.fullWidthRowComponent),this.fullWidthRowComponent=null),this.fullWidthRowComponentBody&&(this.beans.detailRowCompCache.addOrDestroy(this.rowNode,null,this.fullWidthRowComponentBody),this.fullWidthRowComponent=null),this.fullWidthRowComponentLeft&&(this.beans.detailRowCompCache.addOrDestroy(this.rowNode,o.PINNED_LEFT,this.fullWidthRowComponentLeft),this.fullWidthRowComponentLeft=null),this.fullWidthRowComponentRight&&(this.beans.detailRowCompCache.addOrDestroy(this.rowNode,o.PINNED_RIGHT,this.fullWidthRowComponentRight),this.fullWidthRowComponent=null)},t.prototype.getContainerForCell=function(e){switch(e){case o.PINNED_LEFT:return this.ePinnedLeftRow;case o.PINNED_RIGHT:return this.ePinnedRightRow;default:return this.eBodyRow}},t.prototype.onVirtualColumnsChanged=function(){this.fullWidthRow||this.refreshCells()},t.prototype.onColumnResized=function(){this.fullWidthRow||this.refreshCells()},t.prototype.refreshCells=function(){if(this.areAllContainersReady())if(this.beans.gridOptionsWrapper.isSuppressAnimationFrame()||this.printLayout)this.refreshCellsInAnimationFrame();else{if(this.columnRefreshPending)return;this.beans.taskQueue.createTask(this.refreshCellsInAnimationFrame.bind(this),this.rowNode.rowIndex,"createTasksP1")}else this.refreshNeeded=!0},t.prototype.refreshCellsInAnimationFrame=function(){if(this.active){var e,t,o;this.columnRefreshPending=!1,this.printLayout?(e=this.beans.columnController.getAllDisplayedColumns(),t=[],o=[]):(e=this.beans.columnController.getAllDisplayedCenterVirtualColumnsForRow(this.rowNode),t=this.beans.columnController.getDisplayedLeftColumnsForRow(this.rowNode),o=this.beans.columnController.getDisplayedRightColumnsForRow(this.rowNode)),this.insertCellsIntoContainer(this.eBodyRow,e),this.insertCellsIntoContainer(this.ePinnedLeftRow,t),this.insertCellsIntoContainer(this.ePinnedRightRow,o),this.elementOrderChanged=!1;var i=Object.keys(this.cellComps);e.forEach((function(e){return p.removeFromArray(i,e.getId())})),t.forEach((function(e){return p.removeFromArray(i,e.getId())})),o.forEach((function(e){return p.removeFromArray(i,e.getId())}));var n=i.filter(this.isCellEligibleToBeRemoved.bind(this));this.removeRenderedCells(n)}},t.prototype.onColumnMoved=function(){this.elementOrderChanged=!0},t.prototype.removeRenderedCells=function(e){var t=this;e.forEach((function(e){var o=t.cellComps[e];p.missing(o)||(o.detach(),o.destroy(),t.cellComps[e]=null)}))},t.prototype.isCellEligibleToBeRemoved=function(e){var t=this.beans.columnController.getAllDisplayedColumns(),o=this.cellComps[e];if(!o)return!0;if(this.isCellInWrongRow(o))return!0;var i=o.isEditing(),n=this.beans.focusedCellController.isCellFocused(o.getCellPosition());if(i||n){var r=o.getColumn();return!(t.indexOf(r)>=0)}return!0},t.prototype.ensureCellInCorrectContainer=function(e){if(!this.printLayout){var t=e.getGui(),o=e.getColumn().getPinned(),i=this.getContainerForCell(o),n=e.getParentRow();n!==i&&(n&&n.removeChild(t),i.appendChild(t),e.setParentRow(i),this.elementOrderChanged=!0)}},t.prototype.isCellInWrongRow=function(e){var t=e.getColumn(),o=this.getContainerForCell(t.getPinned());return e.getParentRow()!==o},t.prototype.insertCellsIntoContainer=function(e,t){var o=this;if(e){var i=[],n=[];if(t.forEach((function(t){var r=t.getId(),s=o.cellComps[r];s?o.ensureCellInCorrectContainer(s):o.createNewCell(t,e,i,n)})),i.length>0&&(p.appendHtml(e,i.join("")),this.callAfterRowAttachedOnCells(n,e)),this.elementOrderChanged&&this.beans.gridOptionsWrapper.isEnsureDomOrder()){var r=t.map((function(e){return o.getCellForCol(e)}));p.setDomChildOrder(e,r)}}},t.prototype.addDomData=function(e){var o=this.beans.gridOptionsWrapper;o.setDomData(e,t.DOM_DATA_KEY_RENDERED_ROW,this),this.addDestroyFunc((function(){o.setDomData(e,t.DOM_DATA_KEY_RENDERED_ROW,null)}))},t.prototype.createNewCell=function(e,t,o,i){var n=new Oo(this.scope,this.beans,e,this.rowNode,this,!1,this.printLayout),r=n.getCreateTemplate();o.push(r),i.push(n),this.cellComps[e.getId()]=n,n.setParentRow(t),this.elementOrderChanged=!0},t.prototype.onMouseEvent=function(e,t){switch(e){case"dblclick":this.onRowDblClick(t);break;case"click":this.onRowClick(t)}},t.prototype.createRowEvent=function(e,t){return{type:e,node:this.rowNode,data:this.rowNode.data,rowIndex:this.rowNode.rowIndex,rowPinned:this.rowNode.rowPinned,context:this.beans.gridOptionsWrapper.getContext(),api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),event:t}},t.prototype.createRowEventWithSource=function(e,t){var o=this.createRowEvent(e,t);return o.source=this,o},t.prototype.onRowDblClick=function(e){if(!p.isStopPropagationForAgGrid(e)){var t=this.createRowEventWithSource(M.EVENT_ROW_DOUBLE_CLICKED,e);this.beans.eventService.dispatchEvent(t)}},t.prototype.onRowClick=function(e){if(!p.isStopPropagationForAgGrid(e)){var t=this.createRowEventWithSource(M.EVENT_ROW_CLICKED,e);this.beans.eventService.dispatchEvent(t);var o=e.ctrlKey||e.metaKey,i=e.shiftKey;if(!this.rowNode.group&&this.rowNode.selectable&&!this.rowNode.rowPinned&&this.beans.gridOptionsWrapper.isRowSelection()&&!this.beans.gridOptionsWrapper.isSuppressRowClickSelection()){var n=this.beans.gridOptionsWrapper.isRowMultiSelectWithClick(),r=this.beans.gridOptionsWrapper.isRowDeselection();if(this.rowNode.isSelected())n?this.rowNode.setSelectedParams({newValue:!1}):o?r&&this.rowNode.setSelectedParams({newValue:!1}):this.rowNode.setSelectedParams({newValue:!0,clearSelection:!0});else{var s=!n&&!o;this.rowNode.setSelectedParams({newValue:!0,clearSelection:s,rangeSelect:i})}}}},t.prototype.createFullWidthRowContainer=function(e,t,o,i,n,r,s){var a=this,l=this.createTemplate("",o);e.appendRowTemplate(l,(function(){var o=e.getRowElement(a.getCompId()),l=a.createFullWidthParams(o,t),p=function(e){if(a.isAlive()){var t=e.getGui();o.appendChild(t),s(e)}else e.destroy&&e.destroy()},u=a.beans.detailRowCompCache.get(a.rowNode,t);if(u)p(u);else{var c=a.beans.userComponentFactory.newFullWidthCellRenderer(l,i,n);if(!c){var d=P.isRegistered(R.MasterDetailModule);return void("agDetailCellRenderer"!==n||d?console.error("ag-Grid: fullWidthCellRenderer "+n+" not found"):console.warn("ag-Grid: cell renderer agDetailCellRenderer (for master detail) not found. Did you forget to include the master detail module?"))}c.then(p)}a.afterRowAttached(e,o),r(o),a.angular1Compile(o)}))},t.prototype.angular1Compile=function(e){this.scope&&this.beans.$compile(e)(this.scope)},t.prototype.createFullWidthParams=function(e,t){return{fullWidth:!0,data:this.rowNode.data,node:this.rowNode,value:this.rowNode.key,$scope:this.scope?this.scope:this.parentScope,$compile:this.beans.$compile,rowIndex:this.rowNode.rowIndex,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext(),eGridCell:e,eParentOfValue:e,pinned:t,addRenderedRowListener:this.addEventListener.bind(this)}},t.prototype.getInitialRowClasses=function(e){var t=[],o=this.beans.gridOptionsWrapper.isTreeData(),i=this.rowNode;return p.exists(e)&&t.push(e),t.push("ag-row"),t.push(this.rowFocused?"ag-row-focus":"ag-row-no-focus"),this.fadeRowIn&&t.push("ag-opacity-zero"),t.push(this.rowIsEven?"ag-row-even":"ag-row-odd"),i.isSelected()&&t.push("ag-row-selected"),i.group?(t.push("ag-row-group"),t.push("ag-row-level-"+i.level),i.footer&&t.push("ag-row-footer")):t.push("ag-row-level-"+(i.parent?i.parent.level+1:"0")),i.stub&&t.push("ag-row-stub"),this.fullWidthRow&&t.push("ag-full-width-row"),(o?i.allChildrenCount:i.group&&!i.footer)&&t.push(i.expanded?"ag-row-group-expanded":"ag-row-group-contracted"),i.dragging&&t.push("ag-row-dragging"),p.pushAll(t,this.processClassesFromGridOptions()),p.pushAll(t,this.preProcessRowClassRules()),t.push(this.printLayout?"ag-row-position-relative":"ag-row-position-absolute"),this.firstRowOnPage=this.isFirstRowOnPage(),this.lastRowOnPage=this.isLastRowOnPage(),this.firstRowOnPage&&t.push("ag-row-first"),this.lastRowOnPage&&t.push("ag-row-last"),t},t.prototype.isFirstRowOnPage=function(){return this.rowNode.rowIndex===this.beans.paginationProxy.getPageFirstRow()},t.prototype.isLastRowOnPage=function(){return this.rowNode.rowIndex===this.beans.paginationProxy.getPageLastRow()},t.prototype.onModelUpdated=function(){var e=this.isFirstRowOnPage(),t=this.isLastRowOnPage();this.firstRowOnPage!==e&&(this.firstRowOnPage=e,this.eAllRowContainers.forEach((function(t){return p.addOrRemoveCssClass(t,"ag-row-first",e)}))),this.lastRowOnPage!==t&&(this.lastRowOnPage=t,this.eAllRowContainers.forEach((function(e){return p.addOrRemoveCssClass(e,"ag-row-last",t)})))},t.prototype.preProcessRowClassRules=function(){var e=[];return this.processRowClassRules((function(t){e.push(t)}),(function(e){})),e},t.prototype.processRowClassRules=function(e,t){this.beans.stylingService.processClassRules(this.beans.gridOptionsWrapper.rowClassRules(),{value:void 0,colDef:void 0,data:this.rowNode.data,node:this.rowNode,rowIndex:this.rowNode.rowIndex,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),$scope:this.scope,context:this.beans.gridOptionsWrapper.getContext()},e,t)},t.prototype.stopEditing=function(e){if(void 0===e&&(e=!1),this.forEachCellComp((function(t){t.stopEditing(e)})),this.editingRow){if(!e){var t=this.createRowEvent(M.EVENT_ROW_VALUE_CHANGED);this.beans.eventService.dispatchEvent(t)}this.setEditingRow(!1)}},t.prototype.setEditingRow=function(e){this.editingRow=e,this.eAllRowContainers.forEach((function(t){return p.addOrRemoveCssClass(t,"ag-row-editing",e)}));var t=e?this.createRowEvent(M.EVENT_ROW_EDITING_STARTED):this.createRowEvent(M.EVENT_ROW_EDITING_STOPPED);this.beans.eventService.dispatchEvent(t)},t.prototype.startRowEditing=function(e,t,o){void 0===e&&(e=null),void 0===t&&(t=null),void 0===o&&(o=null),this.editingRow||(this.forEachCellComp((function(i){var n=i===o;n?i.startEditingIfEnabled(e,t,n):i.startEditingIfEnabled(null,null,n)})),this.setEditingRow(!0))},t.prototype.forEachCellComp=function(e){p.iterateObject(this.cellComps,(function(t,o){o&&e(o)}))},t.prototype.postProcessClassesFromGridOptions=function(){var e=this,t=this.processClassesFromGridOptions();t&&t.length&&t.forEach((function(t){e.eAllRowContainers.forEach((function(e){return p.addCssClass(e,t)}))}))},t.prototype.postProcessRowClassRules=function(){var e=this;this.processRowClassRules((function(t){e.eAllRowContainers.forEach((function(e){return p.addCssClass(e,t)}))}),(function(t){e.eAllRowContainers.forEach((function(e){return p.removeCssClass(e,t)}))}))},t.prototype.processClassesFromGridOptions=function(){var e=[],t=function(t){"string"==typeof t?e.push(t):Array.isArray(t)&&t.forEach((function(t){return e.push(t)}))},o=this.beans.gridOptionsWrapper.getRowClass();if(o){if("function"==typeof o)return void console.warn("ag-Grid: rowClass should not be a function, please use getRowClass instead");t(o)}var i=this.beans.gridOptionsWrapper.getRowClassFunc();i&&t(i({node:this.rowNode,data:this.rowNode.data,rowIndex:this.rowNode.rowIndex,context:this.beans.gridOptionsWrapper.getContext(),api:this.beans.gridOptionsWrapper.getApi()}));return e},t.prototype.preProcessStylesFromGridOptions=function(){var e=this.processStylesFromGridOptions();return p.cssStyleObjectToMarkup(e)},t.prototype.postProcessStylesFromGridOptions=function(){var e=this.processStylesFromGridOptions();this.eAllRowContainers.forEach((function(t){return p.addStylesToElement(t,e)}))},t.prototype.processStylesFromGridOptions=function(){var e=this.beans.gridOptionsWrapper.getRowStyle();if(!e||"function"!=typeof e){var t,o=this.beans.gridOptionsWrapper.getRowStyleFunc();if(o)t=o({data:this.rowNode.data,node:this.rowNode,api:this.beans.gridOptionsWrapper.getApi(),context:this.beans.gridOptionsWrapper.getContext(),$scope:this.scope});return p.assign({},e,t)}console.warn("ag-Grid: rowStyle should be an object of key/value styles, not be a function, use getRowStyle() instead")},t.prototype.createCells=function(e){var t=this,o=[],i=[];return e.forEach((function(e){var n=new Oo(t.scope,t.beans,e,t.rowNode,t,!1,t.printLayout),r=n.getCreateTemplate();o.push(r),i.push(n),t.cellComps[e.getId()]=n})),{template:o.join(""),cellComps:i}},t.prototype.onRowSelected=function(){var e=this.rowNode.isSelected();this.eAllRowContainers.forEach((function(t){return p.addOrRemoveCssClass(t,"ag-row-selected",e)}))},t.prototype.callAfterRowAttachedOnCells=function(e,t){var o=this;e.forEach((function(e){e.setParentRow(t),e.afterAttached(),o.editingRow&&e.startEditingIfEnabled()}))},t.prototype.afterRowAttached=function(e,t){var o=this;this.addDomData(t),this.removeSecondPassFuncs.push((function(){e.removeRowElement(t)})),this.removeFirstPassFuncs.push((function(){if(p.exists(o.rowNode.rowTop)){var e=o.roundRowTopToBounds(o.rowNode.rowTop);o.setRowTop(e)}else p.addCssClass(t,"ag-opacity-zero")})),this.eAllRowContainers.push(t),this.useAnimationFrameForCreate?this.beans.taskQueue.createTask(this.addHoverFunctionality.bind(this,t),this.rowNode.rowIndex,"createTasksP2"):this.addHoverFunctionality(t)},t.prototype.addHoverFunctionality=function(e){var t=this;this.active&&(this.addDestroyableEventListener(e,"mouseenter",(function(){return t.rowNode.onMouseEnter()})),this.addDestroyableEventListener(e,"mouseleave",(function(){return t.rowNode.onMouseLeave()})),this.addDestroyableEventListener(this.rowNode,je.EVENT_MOUSE_ENTER,(function(){t.beans.gridOptionsWrapper.isSuppressRowHoverHighlight()||p.addCssClass(e,"ag-row-hover")})),this.addDestroyableEventListener(this.rowNode,je.EVENT_MOUSE_LEAVE,(function(){p.removeCssClass(e,"ag-row-hover")})))},t.prototype.roundRowTopToBounds=function(e){var t=this.beans.gridPanel.getVScrollPosition(),o=this.applyPaginationOffset(t.top,!0)-100,i=this.applyPaginationOffset(t.bottom,!0)+100;return Math.min(Math.max(o,e),i)},t.prototype.getFrameworkOverrides=function(){return this.beans.frameworkOverrides},t.prototype.onRowHeightChanged=function(){if(p.exists(this.rowNode.rowHeight)){var e=this.rowNode.rowHeight+"px";this.eAllRowContainers.forEach((function(t){return t.style.height=e}))}},t.prototype.addEventListener=function(t,o){"renderedRowRemoved"!==t&&"rowRemoved"!==t||(t=M.EVENT_VIRTUAL_ROW_REMOVED,console.warn("ag-Grid: Since version 11, event renderedRowRemoved is now called "+M.EVENT_VIRTUAL_ROW_REMOVED)),e.prototype.addEventListener.call(this,t,o)},t.prototype.removeEventListener=function(t,o){"renderedRowRemoved"!==t&&"rowRemoved"!==t||(t=M.EVENT_VIRTUAL_ROW_REMOVED,console.warn("ag-Grid: Since version 11, event renderedRowRemoved and rowRemoved is now called "+M.EVENT_VIRTUAL_ROW_REMOVED)),e.prototype.removeEventListener.call(this,t,o)},t.prototype.destroy=function(t){(void 0===t&&(t=!1),e.prototype.destroy.call(this),this.active=!1,this.destroyFullWidthComponents(),t)?(this.removeFirstPassFuncs.forEach((function(e){return e()})),this.removeSecondPassFuncs.push(this.destroyContainingCells.bind(this))):(this.destroyContainingCells(),this.getAndClearDelayedDestroyFunctions().forEach((function(e){return e()})));var o=this.createRowEvent(M.EVENT_VIRTUAL_ROW_REMOVED);this.dispatchEvent(o),this.beans.eventService.dispatchEvent(o)},t.prototype.destroyContainingCells=function(){this.forEachCellComp((function(e){return e.destroy()})),this.destroyFullWidthComponents()},t.prototype.getAndClearDelayedDestroyFunctions=function(){var e=this.removeSecondPassFuncs;return this.removeSecondPassFuncs=[],e},t.prototype.onCellFocusChanged=function(){var e=this.beans.focusedCellController.isRowFocused(this.rowNode.rowIndex,this.rowNode.rowPinned);e!==this.rowFocused&&(this.eAllRowContainers.forEach((function(t){return p.addOrRemoveCssClass(t,"ag-row-focus",e)})),this.eAllRowContainers.forEach((function(t){return p.addOrRemoveCssClass(t,"ag-row-no-focus",!e)})),this.rowFocused=e),!e&&this.editingRow&&this.stopEditing(!1)},t.prototype.onPaginationChanged=function(){var e=this.beans.paginationProxy.getCurrentPage();this.paginationPage!==e&&(this.paginationPage=e,this.onTopChanged())},t.prototype.onTopChanged=function(){this.setRowTop(this.rowNode.rowTop)},t.prototype.applyPaginationOffset=function(e,t){return void 0===t&&(t=!1),this.rowNode.isRowPinned()?e:e+this.beans.paginationProxy.getPixelOffset()*(t?1:-1)},t.prototype.setRowTop=function(e){if(!this.printLayout&&p.exists(e)){var t=this.applyPaginationOffset(e),o=this.beans.maxDivHeightScaler.getRealPixelPosition(t)+"px";this.beans.gridOptionsWrapper.isSuppressRowTransform()?this.eAllRowContainers.forEach((function(e){return e.style.top=o})):this.eAllRowContainers.forEach((function(e){return e.style.transform="translateY("+o+")"}))}},t.prototype.getAndClearNextVMTurnFunctions=function(){var e=this.createSecondPassFuncs;return this.createSecondPassFuncs=[],e},t.prototype.getRowNode=function(){return this.rowNode},t.prototype.getRenderedCellForColumn=function(e){var t=this,o=this.cellComps[e.getColId()];if(o)return o;var i=Object.keys(this.cellComps).map((function(e){return t.cellComps[e]})).filter((function(t){return t&&-1!==t.getColSpanningList().indexOf(e)}));return i.length?i[0]:void 0},t.prototype.onRowIndexChanged=function(){this.onCellFocusChanged(),this.updateRowIndexes()},t.prototype.updateRowIndexes=function(){var e=this,t=this.rowNode.getRowIndexString(),o=this.rowNode.rowIndex%2==0,i=this.rowIsEven!==o,n=this.beans.gridPanel.headerRootComp.getHeaderRowCount();i&&(this.rowIsEven=o),this.eAllRowContainers.forEach((function(r){r.setAttribute("row-index",t),r.setAttribute("aria-rowindex",(n+e.rowNode.rowIndex+1).toString()),i&&(p.addOrRemoveCssClass(r,"ag-row-even",o),p.addOrRemoveCssClass(r,"ag-row-odd",!o))}))},t.prototype.ensureDomOrder=function(){[{el:this.getBodyRowElement(),ct:this.bodyContainerComp},{el:this.getPinnedLeftRowElement(),ct:this.pinnedLeftContainerComp},{el:this.getPinnedRightRowElement(),ct:this.pinnedRightContainerComp},{el:this.getFullWidthRowElement(),ct:this.fullWidthContainerComp}].forEach((function(e){e.el&&e.ct.ensureDomOrder(e.el)}))},t.prototype.getPinnedLeftRowElement=function(){return this.ePinnedLeftRow?this.ePinnedLeftRow:this.eFullWidthRowLeft},t.prototype.getPinnedRightRowElement=function(){return this.ePinnedRightRow?this.ePinnedRightRow:this.eFullWidthRowRight},t.prototype.getBodyRowElement=function(){return this.eBodyRow?this.eBodyRow:this.eFullWidthRowBody},t.prototype.getFullWidthRowElement=function(){return this.eFullWidthRow},t.DOM_DATA_KEY_RENDERED_ROW="renderedRow",t.FULL_WIDTH_CELL_RENDERER="fullWidthCellRenderer",t.GROUP_ROW_RENDERER="groupRowRenderer",t.GROUP_ROW_RENDERER_COMP_NAME="agGroupRowRenderer",t.LOADING_CELL_RENDERER="loadingCellRenderer",t.LOADING_CELL_RENDERER_COMP_NAME="agLoadingCellRenderer",t.DETAIL_CELL_RENDERER="detailCellRenderer",t.DETAIL_CELL_RENDERER_COMP_NAME="agDetailCellRenderer",t}(pe),So=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),To=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ao=function(e,t){return function(o,i){t(o,i,e)}},_o=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.destroyFuncsForColumnListeners=[],t.rowCompsByIndex={},t.floatingTopRowComps=[],t.floatingBottomRowComps=[],t.refreshInProgress=!1,t}return So(t,e),t.prototype.registerGridCore=function(e){this.gridCore=e},t.prototype.getGridCore=function(){return this.gridCore},t.prototype.agWire=function(e){this.logger=e.create("RowRenderer")},t.prototype.registerGridComp=function(e){this.gridPanel=e,this.rowContainers=this.gridPanel.getRowContainers(),this.addDestroyableEventListener(this.eventService,M.EVENT_PAGINATION_CHANGED,this.onPageLoaded.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_PINNED_ROW_DATA_CHANGED,this.onPinnedRowDataChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_BODY_SCROLL,this.redrawAfterScroll.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_BODY_HEIGHT_CHANGED,this.redrawAfterScroll.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_DOM_LAYOUT,this.onDomLayoutChanged.bind(this)),this.registerCellEventListeners(),this.printLayout=this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_PRINT,this.embedFullWidthRows=this.printLayout||this.gridOptionsWrapper.isEmbedFullWidthRows(),this.redrawAfterModelUpdate()},t.prototype.registerCellEventListeners=function(){var e=this;this.addDestroyableEventListener(this.eventService,M.EVENT_CELL_FOCUSED,(function(t){e.forEachCellComp((function(e){return e.onCellFocused(t)}))})),this.addDestroyableEventListener(this.eventService,M.EVENT_FLASH_CELLS,(function(t){e.forEachCellComp((function(e){return e.onFlashCells(t)}))})),this.addDestroyableEventListener(this.eventService,M.EVENT_COLUMN_HOVER_CHANGED,(function(){e.forEachCellComp((function(e){return e.onColumnHover()}))})),this.addDestroyableEventListener(this.eventService,M.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,(function(){e.printLayout&&e.forEachCellComp((function(e){return e.onLeftChanged()}))})),this.gridOptionsWrapper.isEnableRangeSelection()&&(this.addDestroyableEventListener(this.eventService,M.EVENT_RANGE_SELECTION_CHANGED,(function(){e.forEachCellComp((function(e){return e.onRangeSelectionChanged()}))})),this.addDestroyableEventListener(this.eventService,M.EVENT_COLUMN_MOVED,(function(){e.forEachCellComp((function(e){return e.updateRangeBordersIfRangeCount()}))})),this.addDestroyableEventListener(this.eventService,M.EVENT_COLUMN_PINNED,(function(){e.forEachCellComp((function(e){return e.updateRangeBordersIfRangeCount()}))})),this.addDestroyableEventListener(this.eventService,M.EVENT_COLUMN_VISIBLE,(function(){e.forEachCellComp((function(e){return e.updateRangeBordersIfRangeCount()}))}))),this.refreshListenersToColumnsForCellComps(),this.addDestroyableEventListener(this.eventService,M.EVENT_GRID_COLUMNS_CHANGED,this.refreshListenersToColumnsForCellComps.bind(this)),this.addDestroyFunc(this.removeGridColumnListeners.bind(this))},t.prototype.removeGridColumnListeners=function(){this.destroyFuncsForColumnListeners.forEach((function(e){return e()})),this.destroyFuncsForColumnListeners.length=0},t.prototype.refreshListenersToColumnsForCellComps=function(){var e=this;this.removeGridColumnListeners();var t=this.columnController.getAllGridColumns();t&&t.forEach((function(t){var o=function(o){e.forEachCellComp((function(e){e.getColumn()===t&&o(e)}))},i=function(){o((function(e){return e.onLeftChanged()}))},n=function(){o((function(e){return e.onWidthChanged()}))},r=function(){o((function(e){return e.onFirstRightPinnedChanged()}))},s=function(){o((function(e){return e.onLastLeftPinnedChanged()}))};t.addEventListener(T.EVENT_LEFT_CHANGED,i),t.addEventListener(T.EVENT_WIDTH_CHANGED,n),t.addEventListener(T.EVENT_FIRST_RIGHT_PINNED_CHANGED,r),t.addEventListener(T.EVENT_LAST_LEFT_PINNED_CHANGED,s),e.destroyFuncsForColumnListeners.push((function(){t.removeEventListener(T.EVENT_LEFT_CHANGED,i),t.removeEventListener(T.EVENT_WIDTH_CHANGED,n),t.removeEventListener(T.EVENT_FIRST_RIGHT_PINNED_CHANGED,r),t.removeEventListener(T.EVENT_LAST_LEFT_PINNED_CHANGED,s)}))}))},t.prototype.onDomLayoutChanged=function(){var e=this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_PRINT,t=e||this.gridOptionsWrapper.isEmbedFullWidthRows(),i=t!==this.embedFullWidthRows||this.printLayout!==e;this.printLayout=e,this.embedFullWidthRows=t,i&&this.redrawAfterModelUpdate()},t.prototype.datasourceChanged=function(){this.firstRenderedRow=0,this.lastRenderedRow=-1;var e=Object.keys(this.rowCompsByIndex);this.removeRowComps(e)},t.prototype.onPageLoaded=function(e){p.missing(e)&&(e={type:M.EVENT_MODEL_UPDATED,api:this.gridApi,columnApi:this.columnApi,animate:!1,keepRenderedRows:!1,newData:!1,newPage:!1}),this.onModelUpdated(e)},t.prototype.getAllCellsForColumn=function(e){var t=[];function o(o,i){var n=i.getCellForCol(e);n&&t.push(n)}return p.iterateObject(this.rowCompsByIndex,o),p.iterateObject(this.floatingBottomRowComps,o),p.iterateObject(this.floatingTopRowComps,o),t},t.prototype.refreshFloatingRowComps=function(){this.refreshFloatingRows(this.floatingTopRowComps,this.pinnedRowModel.getPinnedTopRowData(),this.rowContainers.floatingTopPinnedLeft,this.rowContainers.floatingTopPinnedRight,this.rowContainers.floatingTop,this.rowContainers.floatingTopFullWidth),this.refreshFloatingRows(this.floatingBottomRowComps,this.pinnedRowModel.getPinnedBottomRowData(),this.rowContainers.floatingBottomPinnedLeft,this.rowContainers.floatingBottomPinnedRight,this.rowContainers.floatingBottom,this.rowContainers.floatingBottomFullWith)},t.prototype.refreshFloatingRows=function(e,t,o,i,n,r){var s=this;e.forEach((function(e){e.destroy()})),e.length=0,t&&t.forEach((function(t){var a=new Po(s.$scope,n,o,i,r,t,s.beans,!1,!1,s.printLayout,s.embedFullWidthRows);a.init(),e.push(a)})),this.flushContainers(e)},t.prototype.onPinnedRowDataChanged=function(){this.redrawAfterModelUpdate({recycleRows:!0})},t.prototype.onModelUpdated=function(e){var t={recycleRows:e.keepRenderedRows,animate:e.animate,newData:e.newData,newPage:e.newPage,onlyBody:!0};this.redrawAfterModelUpdate(t)},t.prototype.getRenderedIndexesForRowNodes=function(e){var t=[];return p.missing(e)?t:(p.iterateObject(this.rowCompsByIndex,(function(o,i){var n=i.getRowNode();e.indexOf(n)>=0&&t.push(o)})),t)},t.prototype.redrawRows=function(e){if(e&&0!=e.length){var t=this.getRenderedIndexesForRowNodes(e);this.removeRowComps(t),this.redrawAfterModelUpdate({recycleRows:!0})}},t.prototype.getCellToRestoreFocusToAfterRefresh=function(e){var t=e.suppressKeepFocus?null:this.focusedCellController.getFocusCellToUseAfterRefresh();if(p.missing(t))return null;var o=document.activeElement,i=this.gridOptionsWrapper.getDomData(o,Oo.DOM_DATA_KEY_CELL_COMP);return p.missing(i)?null:t},t.prototype.redrawAfterModelUpdate=function(e){void 0===e&&(e={}),this.getLockOnRefresh();var t=this.getCellToRestoreFocusToAfterRefresh(e);this.sizeContainerToPageHeight(),this.scrollToTopIfNewData(e);var o=!this.printLayout&&e.recycleRows,i=e.animate&&this.gridOptionsWrapper.isAnimateRows(),n=this.binRowComps(o);this.redraw(n,i),e.onlyBody||this.refreshFloatingRowComps(),this.restoreFocusedCell(t),this.releaseLockOnRefresh()},t.prototype.scrollToTopIfNewData=function(e){var t=e.newData||e.newPage,o=this.gridOptionsWrapper.isSuppressScrollOnNewData();t&&!o&&this.gridPanel.scrollToTop()},t.prototype.sizeContainerToPageHeight=function(){var e=[this.rowContainers.body,this.rowContainers.fullWidth,this.rowContainers.pinnedLeft,this.rowContainers.pinnedRight];if(this.printLayout)e.forEach((function(e){return e.setHeight(null)}));else{var t=this.paginationProxy.getCurrentPageHeight();0===t&&(t=1),this.maxDivHeightScaler.setModelHeight(t);var o=this.maxDivHeightScaler.getUiContainerHeight();e.forEach((function(e){return e.setHeight(o)}))}},t.prototype.getLockOnRefresh=function(){if(this.refreshInProgress)throw new Error("ag-Grid: cannot get grid to draw rows when it is in the middle of drawing rows. Your code probably called a grid API method while the grid was in the render stage. To overcome this, put the API call into a timeout, eg instead of api.refreshView(), call setTimeout(function(){api.refreshView(),0}). To see what part of your code that caused the refresh check this stacktrace.");this.refreshInProgress=!0},t.prototype.releaseLockOnRefresh=function(){this.refreshInProgress=!1},t.prototype.restoreFocusedCell=function(e){e&&this.focusedCellController.setFocusedCell(e.rowIndex,e.column,e.rowPinned,!0)},t.prototype.stopEditing=function(e){void 0===e&&(e=!1),this.forEachRowComp((function(t,o){o.stopEditing(e)}))},t.prototype.forEachCellComp=function(e){this.forEachRowComp((function(t,o){return o.forEachCellComp(e)}))},t.prototype.forEachRowComp=function(e){p.iterateObject(this.rowCompsByIndex,e),p.iterateObject(this.floatingTopRowComps,e),p.iterateObject(this.floatingBottomRowComps,e)},t.prototype.addRenderedRowListener=function(e,t,o){var i=this.rowCompsByIndex[t];i&&i.addEventListener(e,o)},t.prototype.flashCells=function(e){void 0===e&&(e={}),this.forEachCellCompFiltered(e.rowNodes,e.columns,(function(e){return e.flashCell()}))},t.prototype.refreshCells=function(e){void 0===e&&(e={});var t={forceRefresh:e.force,newData:!1};this.forEachCellCompFiltered(e.rowNodes,e.columns,(function(e){return e.refreshCell(t)}))},t.prototype.getCellRendererInstances=function(e){var t=[];return this.forEachCellCompFiltered(e.rowNodes,e.columns,(function(e){var o=e.getCellRenderer();o&&t.push(o)})),t},t.prototype.getCellEditorInstances=function(e){var t=[];return this.forEachCellCompFiltered(e.rowNodes,e.columns,(function(e){var o=e.getCellEditor();o&&t.push(o)})),t},t.prototype.getEditingCells=function(){var e=[];return this.forEachCellComp((function(t){if(t.isEditing()){var o=t.getCellPosition();e.push(o)}})),e},t.prototype.forEachCellCompFiltered=function(e,t,i){var n,r,s=this;p.exists(e)&&(n={top:{},bottom:{},normal:{}},e.forEach((function(e){e.rowPinned===o.PINNED_TOP?n.top[e.id]=!0:e.rowPinned===o.PINNED_BOTTOM?n.bottom[e.id]=!0:n.normal[e.id]=!0}))),p.exists(t)&&(r={},t.forEach((function(e){var t=s.columnController.getGridColumn(e);p.exists(t)&&(r[t.getId()]=!0)})));var a=function(e){var t=e.getRowNode(),s=t.id,a=t.rowPinned;if(p.exists(n))if(a===o.PINNED_BOTTOM){if(!n.bottom[s])return}else if(a===o.PINNED_TOP){if(!n.top[s])return}else if(!n.normal[s])return;e.forEachCellComp((function(e){var t=e.getColumn().getId();r&&!r[t]||i(e)}))};p.iterateObject(this.rowCompsByIndex,(function(e,t){a(t)})),this.floatingTopRowComps&&this.floatingTopRowComps.forEach(a),this.floatingBottomRowComps&&this.floatingBottomRowComps.forEach(a)},t.prototype.destroy=function(){e.prototype.destroy.call(this);var t=Object.keys(this.rowCompsByIndex);this.removeRowComps(t)},t.prototype.binRowComps=function(e){var t,o=this,i={};return e?(t=[],p.iterateObject(this.rowCompsByIndex,(function(e,n){var r=n.getRowNode();p.exists(r.id)?(i[r.id]=n,delete o.rowCompsByIndex[e]):t.push(e)}))):t=Object.keys(this.rowCompsByIndex),this.removeRowComps(t),i},t.prototype.removeRowComps=function(e){var t=this;e.forEach((function(e){t.rowCompsByIndex[e].destroy(),delete t.rowCompsByIndex[e]}))},t.prototype.redrawAfterScroll=function(){this.getLockOnRefresh(),this.redraw(null,!1,!0),this.releaseLockOnRefresh()},t.prototype.removeRowCompsNotToDraw=function(e){var t={};e.forEach((function(e){return t[e]=!0}));var o=Object.keys(this.rowCompsByIndex).filter((function(e){return!t[e]}));this.removeRowComps(o)},t.prototype.calculateIndexesToDraw=function(){var e=this,t=p.createArrayOfNumbers(this.firstRenderedRow,this.lastRenderedRow);return p.iterateObject(this.rowCompsByIndex,(function(o,i){var n=Number(o);(n<e.firstRenderedRow||n>e.lastRenderedRow)&&e.doNotUnVirtualiseRow(i)&&t.push(n)})),t.sort((function(e,t){return e-t})),t},t.prototype.redraw=function(e,t,o){var i=this;void 0===t&&(t=!1),void 0===o&&(o=!1),this.maxDivHeightScaler.updateOffset(),this.workOutFirstAndLastRowsToRender();var n=this.calculateIndexesToDraw();this.removeRowCompsNotToDraw(n),this.printLayout&&(t=!1);var r=[],s=[];n.forEach((function(n){var a=i.createOrUpdateRowComp(n,e,t,o);p.exists(a)&&(s.push(a),p.pushAll(r,a.getAndClearNextVMTurnFunctions()))})),this.flushContainers(s),p.executeNextVMTurn(r),o&&!this.gridOptionsWrapper.isSuppressAnimationFrame()&&!this.printLayout?this.beans.taskQueue.addDestroyTask(this.destroyRowComps.bind(this,e,t)):this.destroyRowComps(e,t),this.checkAngularCompile(),this.gridPanel.updateRowCount()},t.prototype.flushContainers=function(e){p.iterateObject(this.rowContainers,(function(e,t){t&&t.flushRowTemplates()})),e.forEach((function(e){return e.afterFlush()}))},t.prototype.onDisplayedColumnsChanged=function(){var e=this.columnController.isPinningLeft(),t=this.columnController.isPinningRight();(this.pinningLeft!==e||t!==this.pinningRight)&&(this.pinningLeft=e,this.pinningRight=t,this.embedFullWidthRows&&this.redrawFullWidthEmbeddedRows())},t.prototype.redrawFullWidthEmbeddedRows=function(){var e=[];p.iterateObject(this.rowCompsByIndex,(function(t,o){if(o.isFullWidth()){var i=o.getRowNode().rowIndex;e.push(i.toString())}})),this.refreshFloatingRowComps(),this.removeRowComps(e),this.redrawAfterScroll()},t.prototype.refreshFullWidthRows=function(){var e=[];p.iterateObject(this.rowCompsByIndex,(function(t,o){if(o.isFullWidth()&&!o.refreshFullWidth()){var i=o.getRowNode().rowIndex;e.push(i.toString())}})),this.removeRowComps(e),this.redrawAfterScroll()},t.prototype.createOrUpdateRowComp=function(e,t,o,i){var n,r=this.rowCompsByIndex[e];if(r||(n=this.paginationProxy.getRow(e),p.exists(n)&&p.exists(t)&&t[n.id]&&n.alreadyRendered&&(r=t[n.id],t[n.id]=null)),!r){if(n||(n=this.paginationProxy.getRow(e)),!p.exists(n))return;r=this.createRowComp(n,o,i)}else r.ensureDomOrder();return n&&(n.alreadyRendered=!0),this.rowCompsByIndex[e]=r,r},t.prototype.destroyRowComps=function(e,t){var o=[];p.iterateObject(e,(function(e,i){i&&(i.destroy(t),p.pushAll(o,i.getAndClearDelayedDestroyFunctions()))})),p.executeInAWhile(o)},t.prototype.checkAngularCompile=function(){var e=this;this.gridOptionsWrapper.isAngularCompileRows()&&window.setTimeout((function(){e.$scope.$apply()}),0)},t.prototype.workOutFirstAndLastRowsToRender=function(){var e,t;if(this.paginationProxy.isRowsToRender())if(this.printLayout)e=this.paginationProxy.getPageFirstRow(),t=this.paginationProxy.getPageLastRow();else{var i=this.paginationProxy.getPixelOffset(),n=this.maxDivHeightScaler.getOffset(),r=this.gridPanel.getVScrollPosition(),s=r.top,a=r.bottom,l=this.gridOptionsWrapper.getRowBufferInPixels(),p=s+i+n-l,u=a+i+n+l;this.ensureAllRowsInRangeHaveHeightsCalculated(p,u);var c=this.paginationProxy.getRowIndexAtPixel(p),d=this.paginationProxy.getRowIndexAtPixel(u),h=this.paginationProxy.getPageFirstRow(),g=this.paginationProxy.getPageLastRow();c<h&&(c=h),d>g&&(d=g),e=c,t=d}else e=0,t=-1;var f=this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_NORMAL,y=this.gridOptionsWrapper.isSuppressMaxRenderedRowRestriction(),m=Math.max(this.gridOptionsWrapper.getRowBuffer(),500);f&&!y&&t-e>m&&(t=e+m);var v=e!==this.firstRenderedRow,C=t!==this.lastRenderedRow;if(v||C){this.firstRenderedRow=e,this.lastRenderedRow=t;var E={type:M.EVENT_VIEWPORT_CHANGED,firstRow:e,lastRow:t,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(E)}if(this.paginationProxy.isRowsToRender()){var w={type:M.EVENT_FIRST_DATA_RENDERED,firstRow:e,lastRow:t,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEventOnce(w)}},t.prototype.ensureAllRowsInRangeHaveHeightsCalculated=function(e,t){this.paginationProxy.ensureRowHeightsValid(e,t,-1,-1)&&(this.sizeContainerToPageHeight(),this.maxDivHeightScaler.updateOffset())},t.prototype.getFirstVirtualRenderedRow=function(){return this.firstRenderedRow},t.prototype.getLastVirtualRenderedRow=function(){return this.lastRenderedRow},t.prototype.doNotUnVirtualiseRow=function(e){var t=e.getRowNode(),o=this.focusedCellController.isRowNodeFocused(t),i=e.isEditing(),n=t.detail;return!!(o||i||n)&&!!this.paginationProxy.isRowPresent(t)},t.prototype.createRowComp=function(e,t,o){var i=this.gridOptionsWrapper.isSuppressAnimationFrame(),n=o&&!i&&!this.printLayout,r=new Po(this.$scope,this.rowContainers.body,this.rowContainers.pinnedLeft,this.rowContainers.pinnedRight,this.rowContainers.fullWidth,e,this.beans,t,n,this.printLayout,this.embedFullWidthRows);return r.init(),r},t.prototype.getRenderedNodes=function(){var e=this.rowCompsByIndex;return Object.keys(e).map((function(t){return e[t].getRowNode()}))},t.prototype.navigateToNextCell=function(e,t,i,n){for(var r=i,s=!1;!s;){if(this.gridOptionsWrapper.isEnableRtl()?t===o.KEY_LEFT&&(r=this.getLastCellOfColSpan(r)):t===o.KEY_RIGHT&&(r=this.getLastCellOfColSpan(r)),r=this.cellNavigationService.getNextCellToFocus(t,r),p.missing(r))s=!0;else{var a=this.rowPositionUtils.getRowNode(r);if(!a.detail&&!a.isFullWidthCell())if(a.group){var l=this.columnController.isPivotMode();this.gridOptionsWrapper.isGroupUseEntireRow(l)||(s=!0)}else s=!0}}if(n){var u=this.gridOptionsWrapper.getNavigateToNextCellFunc();if(p.exists(u)){var c=u({key:t,previousCellPosition:i,nextCellPosition:r||null,event:e});p.exists(c)?(c.floating&&(p.doOnce((function(){console.warn("ag-Grid: tabToNextCellFunc return type should have attributes: rowIndex, rowPinned, column. However you had 'floating', maybe you meant 'rowPinned'?")}),"no floating in userCell"),c.rowPinned=c.floating),r={rowPinned:c.rowPinned,rowIndex:c.rowIndex,column:c.column}):r=null}}r&&(this.ensureCellVisible(r),r=this.getComponentForCell(r).getCellPosition(),this.ensureCellVisible(r),this.focusedCellController.setFocusedCell(r.rowIndex,r.column,r.rowPinned,!0),this.rangeController&&this.rangeController.setRangeToCell(r))},t.prototype.getLastCellOfColSpan=function(e){var t=this.getComponentForCell(e);if(!t)return e;var o=t.getColSpanningList();return 1===o.length?e:{rowIndex:e.rowIndex,column:p.last(o),rowPinned:e.rowPinned}},t.prototype.ensureCellVisible=function(e){p.missing(e.rowPinned)&&this.gridPanel.ensureIndexVisible(e.rowIndex),e.column.isPinned()||this.gridPanel.ensureColumnVisible(e.column),this.gridPanel.horizontallyScrollHeaderCenterAndFloatingCenter(),this.animationFrameService.flushAllFrames()},t.prototype.startEditingCell=function(e,t,o){var i=this.getComponentForCell(e);i&&i.startRowOrCellEdit(t,o)},t.prototype.getComponentForCell=function(e){var t;switch(e.rowPinned){case o.PINNED_TOP:t=this.floatingTopRowComps[e.rowIndex];break;case o.PINNED_BOTTOM:t=this.floatingBottomRowComps[e.rowIndex];break;default:t=this.rowCompsByIndex[e.rowIndex]}return t?t.getRenderedCellForColumn(e.column):null},t.prototype.getRowNode=function(e){switch(e.rowPinned){case o.PINNED_TOP:return this.pinnedRowModel.getPinnedTopRowData()[e.rowIndex];case o.PINNED_BOTTOM:return this.pinnedRowModel.getPinnedBottomRowData()[e.rowIndex];default:return this.rowModel.getRow(e.rowIndex)}},t.prototype.onTabKeyDown=function(e,t){var o=t.shiftKey;this.moveToCellAfter(e,o)&&t.preventDefault()},t.prototype.tabToNextCell=function(e){var t=this.focusedCellController.getFocusedCell();if(p.missing(t))return!1;var o=this.getComponentForCell(t);return!p.missing(o)&&this.moveToCellAfter(o,e)},t.prototype.moveToCellAfter=function(e,t){return e.isEditing()?this.gridOptionsWrapper.isFullRowEdit()?this.moveToNextEditingRow(e,t):this.moveToNextEditingCell(e,t):this.moveToNextCellNotEditing(e,t)},t.prototype.moveToNextEditingCell=function(e,t){var o=e.getCellPosition();e.stopEditing();var i=this.findNextCellToFocusOn(o,t,!0),n=p.exists(i);return n&&(i.startEditingIfEnabled(null,null,!0),i.focusCell(!1)),n},t.prototype.moveToNextEditingRow=function(e,t){var o=e.getCellPosition(),i=this.findNextCellToFocusOn(o,t,!0),n=p.exists(i);return n&&this.moveEditToNextCellOrRow(e,i),n},t.prototype.moveToNextCellNotEditing=function(e,t){var o=e.getCellPosition(),i=this.findNextCellToFocusOn(o,t,!1),n=p.exists(i);return n&&i.focusCell(!0),n},t.prototype.moveEditToNextCellOrRow=function(e,t){var o=e.getCellPosition(),i=t.getCellPosition();if(o.rowIndex===i.rowIndex&&o.rowPinned===i.rowPinned)e.setFocusOutOnEditor(),t.setFocusInOnEditor();else{var n=e.getRenderedRow(),r=t.getRenderedRow();e.setFocusOutOnEditor(),n.stopEditing(),r.startRowEditing(),t.setFocusInOnEditor()}t.focusCell()},t.prototype.findNextCellToFocusOn=function(e,t,o){for(var i=e;;){t||(i=this.getLastCellOfColSpan(i)),i=this.cellNavigationService.getNextTabbedCell(i,t);var n=this.gridOptionsWrapper.getTabToNextCellFunc();if(p.exists(n)){var r=n({backwards:t,editing:o,previousCellPosition:e,nextCellPosition:i||null});p.exists(r)?(r.floating&&(p.doOnce((function(){console.warn("ag-Grid: tabToNextCellFunc return type should have attributes: rowIndex, rowPinned, column. However you had 'floating', maybe you meant 'rowPinned'?")}),"no floating in userCell"),r.rowPinned=r.floating),i={rowIndex:r.rowIndex,column:r.column,rowPinned:r.rowPinned}):i=null}if(!i)return null;if(o){var s=this.lookupRowNodeForCell(i);if(!i.column.isCellEditable(s))continue}p.missing(i.rowPinned)&&this.gridPanel.ensureIndexVisible(i.rowIndex),i.column.isPinned()||this.gridPanel.ensureColumnVisible(i.column),this.gridPanel.horizontallyScrollHeaderCenterAndFloatingCenter(),this.animationFrameService.flushAllFrames();var a=this.getComponentForCell(i);if(!p.missing(a)&&!a.isSuppressNavigable())return this.rangeController&&this.rangeController.setRangeToCell(i),a}},t.prototype.lookupRowNodeForCell=function(e){return e.rowPinned===o.PINNED_TOP?this.pinnedRowModel.getPinnedTopRow(e.rowIndex):e.rowPinned===o.PINNED_BOTTOM?this.pinnedRowModel.getPinnedBottomRow(e.rowIndex):this.paginationProxy.getRow(e.rowIndex)},To([m("paginationProxy")],t.prototype,"paginationProxy",void 0),To([m("columnController")],t.prototype,"columnController",void 0),To([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),To([m("$scope")],t.prototype,"$scope",void 0),To([m("eventService")],t.prototype,"eventService",void 0),To([m("pinnedRowModel")],t.prototype,"pinnedRowModel",void 0),To([m("rowModel")],t.prototype,"rowModel",void 0),To([m("loggerFactory")],t.prototype,"loggerFactory",void 0),To([m("focusedCellController")],t.prototype,"focusedCellController",void 0),To([m("cellNavigationService")],t.prototype,"cellNavigationService",void 0),To([m("columnApi")],t.prototype,"columnApi",void 0),To([m("gridApi")],t.prototype,"gridApi",void 0),To([m("beans")],t.prototype,"beans",void 0),To([m("maxDivHeightScaler")],t.prototype,"maxDivHeightScaler",void 0),To([m("animationFrameService")],t.prototype,"animationFrameService",void 0),To([m("rowPositionUtils")],t.prototype,"rowPositionUtils",void 0),To([v("rangeController")],t.prototype,"rangeController",void 0),To([Ao(0,E("loggerFactory"))],t.prototype,"agWire",null),t=To([y("rowRenderer")],t)}(re),Fo=function(){function e(){}return e.addHeaderClassesFromColDef=function(e,t,o,i,n){p.missing(e)||this.addColumnClassesFromCollDef(e.headerClass,e,t,o,i,n)},e.addToolPanelClassesFromColDef=function(e,t,o,i,n){p.missing(e)||this.addColumnClassesFromCollDef(e.toolPanelClass,e,t,o,i,n)},e.addColumnClassesFromCollDef=function(e,t,o,i,n,r){if(!p.missing(e)){var s;if("function"==typeof e)s=e({colDef:t,column:n,columnGroup:r,context:i.getContext(),api:i.getApi()});else s=e;"string"==typeof s?p.addCssClass(o,s):Array.isArray(s)&&s.forEach((function(e){p.addCssClass(o,e)}))}},e}(),No=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Lo=function(e){function t(t,i,n,r){var s=e.call(this)||this;return s.columnOrGroup=t,s.eCell=i,s.colsSpanning=r,s.beans=n,s.printLayout=n.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_PRINT,s}return No(t,e),t.prototype.setColsSpanning=function(e){this.colsSpanning=e,this.onLeftChanged()},t.prototype.getColumnOrGroup=function(){return this.beans.gridOptionsWrapper.isEnableRtl()&&this.colsSpanning?p.last(this.colsSpanning):this.columnOrGroup},t.prototype.init=function(){this.addDestroyableEventListener(this.columnOrGroup,T.EVENT_LEFT_CHANGED,this.onLeftChanged.bind(this)),this.setLeftFirstTime()},t.prototype.setLeftFirstTime=function(){var e=this.beans.gridOptionsWrapper.isSuppressColumnMoveAnimation(),t=p.exists(this.columnOrGroup.getOldLeft());this.beans.columnAnimationService.isActive()&&t&&!e?this.animateInLeft():this.onLeftChanged()},t.prototype.animateInLeft=function(){var e=this,t=this.getColumnOrGroup().getLeft(),o=this.getColumnOrGroup().getOldLeft();this.setLeft(o),this.actualLeft=t,this.beans.columnAnimationService.executeNextVMTurn((function(){e.actualLeft===t&&e.setLeft(t)}))},t.prototype.onLeftChanged=function(){var e=this.getColumnOrGroup(),t=e.getLeft();this.actualLeft=this.modifyLeftForPrintLayout(e,t),this.setLeft(this.actualLeft)},t.prototype.modifyLeftForPrintLayout=function(e,t){return this.printLayout?e.getPinned()===o.PINNED_LEFT?t:e.getPinned()===o.PINNED_RIGHT?this.beans.columnController.getPinnedLeftContainerWidth()+this.beans.columnController.getBodyContainerWidth()+t:this.beans.columnController.getPinnedLeftContainerWidth()+t:t},t.prototype.setLeft=function(e){p.exists(e)&&(this.eCell.style.left=e+"px")},t}(re),Io=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Go=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Mo=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.labelSeparator="",t.labelAlignment="left",t.config={},t.label="",t}return Io(t,e),t.prototype.postConstruct=function(){p.addCssClass(this.getGui(),"ag-labeled");var e=this.config,t=e.labelSeparator,o=e.label,i=e.labelWidth,n=e.labelAlignment;null!=t&&this.setLabelSeparator(t),null!=o&&this.setLabel(o),null!=i&&this.setLabelWidth(i),this.setLabelAlignment(n||this.labelAlignment),this.refreshLabel()},t.prototype.refreshLabel=function(){this.eLabel.innerText=this.label+this.labelSeparator,p.addOrRemoveCssClass(this.eLabel,"ag-hidden",""===this.label)},t.prototype.setLabelSeparator=function(e){return this.labelSeparator===e?this:(this.labelSeparator=e,null!=this.label&&this.refreshLabel(),this)},t.prototype.setLabel=function(e){return this.label===e?this:(this.label=e,this.refreshLabel(),this)},t.prototype.setLabelAlignment=function(e){var t=this.getGui();return p.addOrRemoveCssClass(t,"ag-label-align-left","left"===e),p.addOrRemoveCssClass(t,"ag-label-align-right","right"===e),p.addOrRemoveCssClass(t,"ag-label-align-top","top"===e),this},t.prototype.setLabelWidth=function(e){return null==this.label?this:(p.setElementWidth(this.eLabel,e),this)},Go([g],t.prototype,"postConstruct",null),t}(pe),xo=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Vo=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return xo(t,e),t.prototype.onValueChange=function(e){var o=this;return this.addDestroyableEventListener(this,t.EVENT_CHANGED,(function(){e(o.getValue())})),this},t.prototype.getWidth=function(){return this.getGui().clientWidth},t.prototype.setWidth=function(e){return p.setFixedWidth(this.getGui(),e),this},t.prototype.getValue=function(){return this.value},t.prototype.setValue=function(e,o){return this.value===e?this:(this.value=e,o||this.dispatchEvent({type:t.EVENT_CHANGED}),this)},t.EVENT_CHANGED="valueChange",t}(Mo),Wo=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ho=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},ko=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.config={},t.TEMPLATE='<div class="ag-input-field" role="presentation">\n <label ref="eLabel"></label>\n <div ref="eWrapper" class="ag-wrapper ag-input-wrapper" role="presentation">\n <%displayField% ref="eInput"></%displayField%>\n </div>\n </div>',t}return Wo(t,e),t.prototype.postConstruct=function(){e.prototype.postConstruct.call(this),this.setInputType(),p.addCssClass(this.getGui(),this.className);var t=this.config,o=t.width,i=t.value;null!=o&&this.setWidth(o),null!=i&&this.setValue(i),this.addInputListeners()},t.prototype.addInputListeners=function(){var e=this;this.addDestroyableEventListener(this.eInput,"input",(function(t){var o=t.target.value;e.setValue(o)}))},t.prototype.setInputType=function(){this.inputType&&this.eInput.setAttribute("type",this.inputType)},t.prototype.getInputElement=function(){return this.eInput},t.prototype.setInputWidth=function(e){return p.setElementWidth(this.eWrapper,e),this},t.prototype.setInputName=function(e){return this.getInputElement().setAttribute("name",e),this},Ho([fe("eLabel")],t.prototype,"eLabel",void 0),Ho([fe("eWrapper")],t.prototype,"eWrapper",void 0),Ho([fe("eInput")],t.prototype,"eInput",void 0),t}(Vo),Bo=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Uo=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},jo=function(e){function t(){var t=e.call(this)||this;return t.className="ag-checkbox",t.displayTag="input",t.inputType="checkbox",t.labelAlignment="right",t.iconMap={selected:"checkboxChecked",unselected:"checkboxUnchecked",indeterminate:"checkboxIndeterminate"},t.selected=!1,t.readOnly=!1,t.passive=!1,t.setTemplate(t.TEMPLATE.replace(/%displayField%/g,t.displayTag)),t}return Bo(t,e),t.prototype.postConstruct=function(){e.prototype.postConstruct.call(this),p.addCssClass(this.eInput,"ag-hidden"),this.addIconsPlaceholder(),this.updateIcons()},t.prototype.addInputListeners=function(){var e=this;this.addDestroyableEventListener(this.getGui(),"click",(function(t){return e.onClick(t)})),this.addDestroyableEventListener(this.eInput,"change",(function(t){return e.setValue(t.target.checked,!0)}))},t.prototype.addIconsPlaceholder=function(){var e=document.createElement("div");this.eWrapper.appendChild(e),this.eIconEl=e},t.prototype.onClick=function(e){p.addAgGridEventPath(e),this.readOnly||this.toggle()},t.prototype.getNextValue=function(){return void 0===this.selected||!this.selected},t.prototype.setPassive=function(e){this.passive=e},t.prototype.setReadOnly=function(e){this.readOnly=e,this.updateIcons()},t.prototype.isReadOnly=function(){return this.readOnly},t.prototype.isSelected=function(){return this.selected},t.prototype.toggle=function(){var e=this.getNextValue();if(this.passive){var o={type:t.EVENT_CHANGED,selected:e};this.dispatchEvent(o)}else this.setValue(e)},t.prototype.setSelected=function(e,t){if(this.selected!==e&&(this.selected="boolean"==typeof e?e:void 0,this.eInput.checked=this.selected,this.updateIcons(),!t)){var o={type:Vo.EVENT_CHANGED,selected:this.selected};this.dispatchEvent(o)}},t.prototype.getIconName=function(){var e=this.getValue(),t=void 0===e?"indeterminate":e?"selected":"unselected",o=this.isReadOnly()?"ReadOnly":"";return""+this.iconMap[t]+o},t.prototype.updateIcons=function(){p.clearElement(this.eIconEl),this.eIconEl.appendChild(p.createIconNoSpan(this.getIconName(),this.gridOptionsWrapper,null))},t.prototype.getValue=function(){return this.isSelected()},t.prototype.setValue=function(e,t){return this.setSelected(e,t),this},Uo([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),t}(ko),zo=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Yo=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ko=function(e){function t(t,o){var i=e.call(this)||this;i.cbSelectAllVisible=!1,i.processingEventFromCheckbox=!1,i.cbSelectAll=t,i.column=o;var n=o.getColDef();return i.filteredOnly=!!n&&!!n.headerCheckboxSelectionFilteredOnly,i}return zo(t,e),t.prototype.postConstruct=function(){this.showOrHideSelectAll(),this.addDestroyableEventListener(this.eventService,M.EVENT_DISPLAYED_COLUMNS_CHANGED,this.showOrHideSelectAll.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_SELECTION_CHANGED,this.onSelectionChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_MODEL_UPDATED,this.onModelChanged.bind(this)),this.addDestroyableEventListener(this.cbSelectAll,jo.EVENT_CHANGED,this.onCbSelectAll.bind(this))},t.prototype.showOrHideSelectAll=function(){this.cbSelectAllVisible=this.isCheckboxSelection(),this.cbSelectAll.setDisplayed(this.cbSelectAllVisible),this.cbSelectAllVisible&&(this.checkRightRowModelType(),this.updateStateOfCheckbox())},t.prototype.onModelChanged=function(){this.cbSelectAllVisible&&this.updateStateOfCheckbox()},t.prototype.onSelectionChanged=function(){this.cbSelectAllVisible&&this.updateStateOfCheckbox()},t.prototype.getNextCheckboxState=function(e){return(0!==e.selected||0!==e.notSelected)&&(e.selected>0&&e.notSelected>0?null:e.selected>0)},t.prototype.updateStateOfCheckbox=function(){if(!this.processingEventFromCheckbox){this.processingEventFromCheckbox=!0;var e=this.getSelectionCount(),t=this.getNextCheckboxState(e);this.cbSelectAll.setValue(t),this.processingEventFromCheckbox=!1}},t.prototype.getSelectionCount=function(){var e=this,t=0,o=0,i=function(i){e.gridOptionsWrapper.isGroupSelectsChildren()&&i.group||(i.isSelected()?t++:i.selectable&&o++)};return this.filteredOnly?this.gridApi.forEachNodeAfterFilter(i):this.gridApi.forEachNode(i),{notSelected:o,selected:t}},t.prototype.checkRightRowModelType=function(){var e=this.rowModel.getType();e===o.ROW_MODEL_TYPE_CLIENT_SIDE||console.warn("ag-Grid: selectAllCheckbox is only available if using normal row model, you are using "+e)},t.prototype.onCbSelectAll=function(){this.processingEventFromCheckbox||this.cbSelectAllVisible&&(this.cbSelectAll.getValue()?this.selectionController.selectAllRowNodes(this.filteredOnly):this.selectionController.deselectAllRowNodes(this.filteredOnly))},t.prototype.isCheckboxSelection=function(){var e=this.column.getColDef().headerCheckboxSelection;"function"==typeof e&&(e=e({column:this.column,colDef:this.column.getColDef(),columnApi:this.columnApi,api:this.gridApi}));return!!e&&(this.gridOptionsWrapper.isRowModelServerSide()?(console.warn("headerCheckboxSelection is not supported for Server Side Row Model"),!1):this.gridOptionsWrapper.isRowModelInfinite()?(console.warn("headerCheckboxSelection is not supported for Infinite Row Model"),!1):!this.gridOptionsWrapper.isRowModelViewport()||(console.warn("headerCheckboxSelection is not supported for Viewport Row Model"),!1))},Yo([m("gridApi")],t.prototype,"gridApi",void 0),Yo([m("columnApi")],t.prototype,"columnApi",void 0),Yo([m("eventService")],t.prototype,"eventService",void 0),Yo([m("rowModel")],t.prototype,"rowModel",void 0),Yo([m("selectionController")],t.prototype,"selectionController",void 0),Yo([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Yo([g],t.prototype,"postConstruct",null),t}(re),qo=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Qo=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Xo=function(e){function t(t,o){var i=e.call(this)||this;return i.columns=t,i.element=o,i}return qo(t,e),t.prototype.postConstruct=function(){this.addMouseHoverListeners()},t.prototype.addMouseHoverListeners=function(){this.addDestroyableEventListener(this.element,"mouseout",this.onMouseOut.bind(this)),this.addDestroyableEventListener(this.element,"mouseover",this.onMouseOver.bind(this))},t.prototype.onMouseOut=function(){this.columnHoverService.clearMouseOver()},t.prototype.onMouseOver=function(){this.columnHoverService.setMouseOver(this.columns)},Qo([m("columnHoverService")],t.prototype,"columnHoverService",void 0),Qo([g],t.prototype,"postConstruct",null),t}(re),$o=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Jo=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Zo=function(e){function t(o,i,n){var r=e.call(this,t.TEMPLATE)||this;return r.column=o,r.dragSourceDropTarget=i,r.pinned=n,r}return $o(t,e),t.prototype.getColumn=function(){return this.column},t.prototype.getComponentHolder=function(){return this.column.getColDef()},t.prototype.init=function(){var e=this.getComponentHolder(),t=this.columnController.getDisplayNameForColumn(this.column,"header",!0),o=e.sortable,i=this.menuFactory.isMenuEnabled(this.column)&&!e.suppressMenu;this.appendHeaderComp(t,o,i),this.setupWidth(),this.setupMovingCss(),this.setupTooltip(),this.setupResize(),this.setupMenuClass(),this.setupSortableClass(o),this.addColumnHoverListener(),this.addFeature(new Xo([this.column],this.getGui())),this.addDestroyableEventListener(this.column,T.EVENT_FILTER_ACTIVE_CHANGED,this.onFilterChanged.bind(this)),this.onFilterChanged(),this.addFeature(new Ko(this.cbSelectAll,this.column));var n=new Lo(this.column,this.getGui(),this.beans);n.init(),this.addDestroyFunc(n.destroy.bind(n)),this.addAttributes(),Fo.addHeaderClassesFromColDef(e,this.getGui(),this.gridOptionsWrapper,this.column,null)},t.prototype.addColumnHoverListener=function(){this.addDestroyableEventListener(this.eventService,M.EVENT_COLUMN_HOVER_CHANGED,this.onColumnHover.bind(this)),this.onColumnHover()},t.prototype.onColumnHover=function(){var e=this.columnHoverService.isHovered(this.column);p.addOrRemoveCssClass(this.getGui(),"ag-column-hover",e)},t.prototype.setupSortableClass=function(e){if(e){var t=this.getGui();p.addCssClass(t,"ag-header-cell-sortable")}},t.prototype.onFilterChanged=function(){var e=this.column.isFilterActive();p.addOrRemoveCssClass(this.getGui(),"ag-header-cell-filtered",e)},t.prototype.appendHeaderComp=function(e,t,o){var i=this,n={column:this.column,displayName:e,enableSorting:t,enableMenu:o,showColumnMenu:function(e){i.gridApi.showColumnMenuAfterButtonClick(i.column,e)},progressSort:function(e){i.sortController.progressSort(i.column,!!e,"uiColumnSorted")},setSort:function(e,t){i.sortController.setSortForColumn(i.column,e,!!t,"uiColumnSorted")},api:this.gridApi,columnApi:this.columnApi,context:this.gridOptionsWrapper.getContext()},r=this.afterHeaderCompCreated.bind(this,e);this.userComponentFactory.newHeaderComponent(n).then(r)},t.prototype.afterHeaderCompCreated=function(e,t){this.appendChild(t),this.setupMove(t.getGui(),e)},t.prototype.onColumnMovingChanged=function(){this.column.isMoving()?p.addCssClass(this.getGui(),"ag-header-cell-moving"):p.removeCssClass(this.getGui(),"ag-header-cell-moving")},t.prototype.setupMove=function(e,t){var o=this;if(!(this.gridOptionsWrapper.isSuppressMovableColumns()||this.getComponentHolder().suppressMovable||this.column.getColDef().lockPosition)&&e){var i={type:to.HeaderCell,eElement:e,dragItemCallback:function(){return o.createDragItem()},dragItemName:t,dragSourceDropTarget:this.dragSourceDropTarget,dragStarted:function(){return o.column.setMoving(!0,"uiColumnMoved")},dragStopped:function(){return o.column.setMoving(!1,"uiColumnMoved")}};this.dragAndDropService.addDragSource(i,!0),this.addDestroyFunc((function(){return o.dragAndDropService.removeDragSource(i)}))}},t.prototype.createDragItem=function(){var e={};return e[this.column.getId()]=this.column.isVisible(),{columns:[this.column],visibleState:e}},t.prototype.setupResize=function(){var e=this,t=this.getComponentHolder();if(this.eResize)if(this.column.isResizable()){var o=this.horizontalResizeService.addResizeBar({eResizeBar:this.eResize,onResizeStart:this.onResizeStart.bind(this),onResizing:this.onResizing.bind(this,!1),onResizeEnd:this.onResizing.bind(this,!0)});if(this.addDestroyFunc(o),!this.gridOptionsWrapper.isSuppressAutoSize()&&!t.suppressAutoSize){this.addDestroyableEventListener(this.eResize,"dblclick",(function(){e.columnController.autoSizeColumn(e.column,"uiColumnResized")}));var i=new Me(this.eResize);this.addDestroyableEventListener(i,Me.EVENT_DOUBLE_TAP,(function(){e.columnController.autoSizeColumn(e.column,"uiColumnResized")})),this.addDestroyFunc(i.destroy.bind(i))}}else p.removeFromParent(this.eResize)},t.prototype.onResizing=function(e,t){var o=this.normaliseResizeAmount(t),i=this.resizeStartWidth+o;this.columnController.setColumnWidth(this.column,i,this.resizeWithShiftKey,e,"uiColumnDragged"),e&&p.removeCssClass(this.getGui(),"ag-column-resizing")},t.prototype.onResizeStart=function(e){this.resizeStartWidth=this.column.getActualWidth(),this.resizeWithShiftKey=e,p.addCssClass(this.getGui(),"ag-column-resizing")},t.prototype.getTooltipText=function(){return this.getComponentHolder().headerTooltip},t.prototype.setupTooltip=function(){var e=this.getTooltipText();null!=e&&(this.gridOptionsWrapper.isEnableBrowserTooltips()?this.getGui().setAttribute("title",e):this.beans.tooltipManager.registerTooltip(this))},t.prototype.setupMovingCss=function(){this.addDestroyableEventListener(this.column,T.EVENT_MOVING_CHANGED,this.onColumnMovingChanged.bind(this)),this.onColumnMovingChanged()},t.prototype.addAttributes=function(){this.getGui().setAttribute("col-id",this.column.getColId())},t.prototype.setupWidth=function(){this.addDestroyableEventListener(this.column,T.EVENT_WIDTH_CHANGED,this.onColumnWidthChanged.bind(this)),this.onColumnWidthChanged()},t.prototype.setupMenuClass=function(){this.addDestroyableEventListener(this.column,T.EVENT_MENU_VISIBLE_CHANGED,this.onMenuVisible.bind(this)),this.onColumnWidthChanged()},t.prototype.onMenuVisible=function(){this.addOrRemoveCssClass("ag-column-menu-visible",this.column.isMenuVisible())},t.prototype.onColumnWidthChanged=function(){this.getGui().style.width=this.column.getActualWidth()+"px"},t.prototype.normaliseResizeAmount=function(e){var t=e;return this.gridOptionsWrapper.isEnableRtl()?this.pinned!==o.PINNED_LEFT&&(t*=-1):this.pinned===o.PINNED_RIGHT&&(t*=-1),t},t.TEMPLATE='<div class="ag-header-cell" role="presentation" unselectable="on"><div ref="eResize" class="ag-header-cell-resize" role="presentation"></div><ag-checkbox ref="cbSelectAll" class="ag-header-select-all" role="presentation"></ag-checkbox></div>',Jo([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Jo([m("dragAndDropService")],t.prototype,"dragAndDropService",void 0),Jo([m("columnController")],t.prototype,"columnController",void 0),Jo([m("horizontalResizeService")],t.prototype,"horizontalResizeService",void 0),Jo([m("menuFactory")],t.prototype,"menuFactory",void 0),Jo([m("gridApi")],t.prototype,"gridApi",void 0),Jo([m("columnApi")],t.prototype,"columnApi",void 0),Jo([m("sortController")],t.prototype,"sortController",void 0),Jo([m("eventService")],t.prototype,"eventService",void 0),Jo([m("userComponentFactory")],t.prototype,"userComponentFactory",void 0),Jo([m("columnHoverService")],t.prototype,"columnHoverService",void 0),Jo([m("beans")],t.prototype,"beans",void 0),Jo([fe("eResize")],t.prototype,"eResize",void 0),Jo([fe("cbSelectAll")],t.prototype,"cbSelectAll",void 0),Jo([g],t.prototype,"init",null),t}(pe),ei=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ti=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},oi=function(e){function t(o,i,n){var r=e.call(this,t.TEMPLATE)||this;return r.childColumnsDestroyFuncs=[],r.columnGroup=o,r.dragSourceDropTarget=i,r.pinned=n,r}return ei(t,e),t.prototype.postConstruct=function(){Fo.addHeaderClassesFromColDef(this.getComponentHolder(),this.getGui(),this.gridOptionsWrapper,null,this.columnGroup);var e=this.columnController.getDisplayNameForColumnGroup(this.columnGroup,"header");this.appendHeaderGroupComp(e),this.setupResize(),this.addClasses(),this.setupWidth(),this.addAttributes(),this.setupMovingCss(),this.setupTooltip(),this.addFeature(new Xo(this.columnGroup.getOriginalColumnGroup().getLeafColumns(),this.getGui()));var t=new Lo(this.columnGroup,this.getGui(),this.beans);t.init(),this.addDestroyFunc(t.destroy.bind(t))},t.prototype.setupMovingCss=function(){var e=this;this.columnGroup.getOriginalColumnGroup().getLeafColumns().forEach((function(t){e.addDestroyableEventListener(t,T.EVENT_MOVING_CHANGED,e.onColumnMovingChanged.bind(e))})),this.onColumnMovingChanged()},t.prototype.getColumn=function(){return this.columnGroup},t.prototype.getComponentHolder=function(){return this.columnGroup.getColGroupDef()},t.prototype.getTooltipText=function(){var e=this.getComponentHolder();return e&&e.headerTooltip},t.prototype.setupTooltip=function(){var e=this.getTooltipText();null!=e&&(this.gridOptionsWrapper.isEnableBrowserTooltips()?this.getGui().setAttribute("title",e):this.beans.tooltipManager.registerTooltip(this))},t.prototype.onColumnMovingChanged=function(){p.addOrRemoveCssClass(this.getGui(),"ag-header-cell-moving",this.columnGroup.isMoving())},t.prototype.addAttributes=function(){this.getGui().setAttribute("col-id",this.columnGroup.getUniqueId())},t.prototype.appendHeaderGroupComp=function(e){var t=this,o={displayName:e,columnGroup:this.columnGroup,setExpanded:function(e){t.columnController.setColumnGroupOpened(t.columnGroup.getOriginalColumnGroup(),e,"gridInitializing")},api:this.gridApi,columnApi:this.columnApi,context:this.gridOptionsWrapper.getContext()};if(!e){for(var i=this.columnGroup,n=i.getLeafColumns();i.getParent()&&i.getParent().getLeafColumns().length===n.length;)i=i.getParent();var r=i.getColGroupDef();r&&(e=r.headerName),e||(e=n?this.columnController.getDisplayNameForColumn(n[0],"header",!0):"")}var s=this.afterHeaderCompCreated.bind(this,e);this.userComponentFactory.newHeaderGroupComponent(o).then(s)},t.prototype.afterHeaderCompCreated=function(e,t){this.appendChild(t),this.setupMove(t.getGui(),e)},t.prototype.addClasses=function(){this.columnGroup.isPadding()?this.addCssClass("ag-header-group-cell-no-group"):this.addCssClass("ag-header-group-cell-with-group")},t.prototype.setupMove=function(e,t){var o=this;if(e&&!this.isSuppressMoving()){var i=this.columnGroup.getOriginalColumnGroup().getLeafColumns();if(e){var n={type:to.HeaderCell,eElement:e,dragItemName:t,dragItemCallback:this.getDragItemForGroup.bind(this),dragSourceDropTarget:this.dragSourceDropTarget,dragStarted:function(){return i.forEach((function(e){return e.setMoving(!0,"uiColumnDragged")}))},dragStopped:function(){return i.forEach((function(e){return e.setMoving(!1,"uiColumnDragged")}))}};this.dragAndDropService.addDragSource(n,!0),this.addDestroyFunc((function(){return o.dragAndDropService.removeDragSource(n)}))}}},t.prototype.getDragItemForGroup=function(){var e=this.columnGroup.getOriginalColumnGroup().getLeafColumns(),t={};e.forEach((function(e){return t[e.getId()]=e.isVisible()}));var o=[];return this.columnController.getAllDisplayedColumns().forEach((function(t){e.indexOf(t)>=0&&(o.push(t),p.removeFromArray(e,t))})),e.forEach((function(e){return o.push(e)})),{columns:o,visibleState:t}},t.prototype.isSuppressMoving=function(){var e=!1;return this.columnGroup.getLeafColumns().forEach((function(t){(t.getColDef().suppressMovable||t.getColDef().lockPosition)&&(e=!0)})),e||this.gridOptionsWrapper.isSuppressMovableColumns()},t.prototype.setupWidth=function(){this.addListenersToChildrenColumns(),this.addDestroyableEventListener(this.columnGroup,_.EVENT_DISPLAYED_CHILDREN_CHANGED,this.onDisplayedChildrenChanged.bind(this)),this.onWidthChanged(),this.addDestroyFunc(this.destroyListenersOnChildrenColumns.bind(this))},t.prototype.onDisplayedChildrenChanged=function(){this.addListenersToChildrenColumns(),this.onWidthChanged()},t.prototype.addListenersToChildrenColumns=function(){var e=this;this.destroyListenersOnChildrenColumns();var t=this.onWidthChanged.bind(this);this.columnGroup.getLeafColumns().forEach((function(o){o.addEventListener(T.EVENT_WIDTH_CHANGED,t),o.addEventListener(T.EVENT_VISIBLE_CHANGED,t),e.childColumnsDestroyFuncs.push((function(){o.removeEventListener(T.EVENT_WIDTH_CHANGED,t),o.removeEventListener(T.EVENT_VISIBLE_CHANGED,t)}))}))},t.prototype.destroyListenersOnChildrenColumns=function(){this.childColumnsDestroyFuncs.forEach((function(e){return e()})),this.childColumnsDestroyFuncs=[]},t.prototype.onWidthChanged=function(){this.getGui().style.width=this.columnGroup.getActualWidth()+"px"},t.prototype.setupResize=function(){var e=this;if(this.eHeaderCellResize=this.getRefElement("agResize"),this.columnGroup.isResizable()){var t=this.horizontalResizeService.addResizeBar({eResizeBar:this.eHeaderCellResize,onResizeStart:this.onResizeStart.bind(this),onResizing:this.onResizing.bind(this,!1),onResizeEnd:this.onResizing.bind(this,!0)});this.addDestroyFunc(t),this.gridOptionsWrapper.isSuppressAutoSize()||this.eHeaderCellResize.addEventListener("dblclick",(function(t){var o=[];e.columnGroup.getDisplayedLeafColumns().forEach((function(e){e.getColDef().suppressAutoSize||o.push(e.getColId())})),o.length>0&&e.columnController.autoSizeColumns(o,"uiColumnResized")}))}else p.removeFromParent(this.eHeaderCellResize)},t.prototype.onResizeStart=function(e){var t=this,o=this.columnGroup.getDisplayedLeafColumns();this.resizeCols=o.filter((function(e){return e.isResizable()})),this.resizeStartWidth=0,this.resizeCols.forEach((function(e){return t.resizeStartWidth+=e.getActualWidth()})),this.resizeRatios=[],this.resizeCols.forEach((function(e){return t.resizeRatios.push(e.getActualWidth()/t.resizeStartWidth)}));var i=null;if(e&&(i=this.columnController.getDisplayedGroupAfter(this.columnGroup)),i){var n=i.getDisplayedLeafColumns();this.resizeTakeFromCols=n.filter((function(e){return e.isResizable()})),this.resizeTakeFromStartWidth=0,this.resizeTakeFromCols.forEach((function(e){return t.resizeTakeFromStartWidth+=e.getActualWidth()})),this.resizeTakeFromRatios=[],this.resizeTakeFromCols.forEach((function(e){return t.resizeTakeFromRatios.push(e.getActualWidth()/t.resizeTakeFromStartWidth)}))}else this.resizeTakeFromCols=null,this.resizeTakeFromStartWidth=null,this.resizeTakeFromRatios=null;p.addCssClass(this.getGui(),"ag-column-resizing")},t.prototype.onResizing=function(e,t){var o=[],i=this.normaliseDragChange(t);o.push({columns:this.resizeCols,ratios:this.resizeRatios,width:this.resizeStartWidth+i}),this.resizeTakeFromCols&&o.push({columns:this.resizeTakeFromCols,ratios:this.resizeTakeFromRatios,width:this.resizeTakeFromStartWidth-i}),this.columnController.resizeColumnSets(o,e,"uiColumnDragged"),e&&p.removeCssClass(this.getGui(),"ag-column-resizing")},t.prototype.normaliseDragChange=function(e){var t=e;return this.gridOptionsWrapper.isEnableRtl()?this.pinned!==o.PINNED_LEFT&&(t*=-1):this.pinned===o.PINNED_RIGHT&&(t*=-1),t},t.TEMPLATE='<div class="ag-header-group-cell" role="presentation"><div ref="agResize" class="ag-header-cell-resize" role="presentation"></div></div>',ti([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),ti([m("columnController")],t.prototype,"columnController",void 0),ti([m("horizontalResizeService")],t.prototype,"horizontalResizeService",void 0),ti([m("dragAndDropService")],t.prototype,"dragAndDropService",void 0),ti([m("userComponentFactory")],t.prototype,"userComponentFactory",void 0),ti([m("gridApi")],t.prototype,"gridApi",void 0),ti([m("columnApi")],t.prototype,"columnApi",void 0),ti([m("beans")],t.prototype,"beans",void 0),ti([g],t.prototype,"postConstruct",null),t}(pe),ii=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ni=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},ri=function(e){function t(){return e.call(this,'<div class="ag-input-wrapper" role="presentation"><input ref="eFloatingFilterText" class="ag-floating-filter-input"></div>')||this}return ii(t,e),t.prototype.init=function(e){this.params=e,this.eFloatingFilterText.disabled=!0},t.prototype.onParentModelChanged=function(e){var t=this;e?this.params.parentFilterInstance((function(o){if(o.getModelAsString){var i=o.getModelAsString(e);t.eFloatingFilterText.value=i}})):this.eFloatingFilterText.value=""},ni([fe("eFloatingFilterText")],t.prototype,"eFloatingFilterText",void 0),t}(pe),si=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ai=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},li=function(e){function t(o){var i=e.call(this,t.TEMPLATE)||this;return i.column=o,i}return si(t,e),t.prototype.postConstruct=function(){this.setupFloatingFilter(),this.setupWidth(),this.setupLeftPositioning(),this.setupColumnHover(),this.addFeature(new Xo([this.column],this.getGui())),this.addDestroyableEventListener(this.eButtonShowMainFilter,"click",this.showParentFilter.bind(this))},t.prototype.setupFloatingFilter=function(){var e=this;this.column.getColDef().filter?(this.floatingFilterCompPromise=this.getFloatingFilterInstance(),this.floatingFilterCompPromise?this.floatingFilterCompPromise.then((function(t){t?(e.setupWithFloatingFilter(t),e.setupSyncWithFilter()):e.setupEmpty()})):this.setupEmpty()):this.setupEmpty()},t.prototype.setupLeftPositioning=function(){var e=new Lo(this.column,this.getGui(),this.beans);e.init(),this.addDestroyFunc(e.destroy.bind(e))},t.prototype.setupSyncWithFilter=function(){var e=this,t=function(t){var o=e.filterManager.getFilterComponent(e.column,"NO_UI").resolveNow(null,(function(e){return e.getModel()}));e.onParentModelChanged(o,t)};this.addDestroyableEventListener(this.column,T.EVENT_FILTER_CHANGED,t),this.filterManager.isFilterActive(this.column)&&t(null)},t.prototype.showParentFilter=function(){this.menuFactory.showMenuAfterButtonClick(this.column,this.eButtonShowMainFilter,"filterMenuTab",["filterMenuTab"])},t.prototype.setupColumnHover=function(){this.addDestroyableEventListener(this.eventService,M.EVENT_COLUMN_HOVER_CHANGED,this.onColumnHover.bind(this)),this.onColumnHover()},t.prototype.onColumnHover=function(){var e=this.columnHoverService.isHovered(this.column);p.addOrRemoveCssClass(this.getGui(),"ag-column-hover",e)},t.prototype.setupWidth=function(){this.addDestroyableEventListener(this.column,T.EVENT_WIDTH_CHANGED,this.onColumnWidthChanged.bind(this)),this.onColumnWidthChanged()},t.prototype.onColumnWidthChanged=function(){this.getGui().style.width=this.column.getActualWidth()+"px"},t.prototype.setupWithFloatingFilter=function(e){var t=function(){e.destroy&&e.destroy()};if(this.isAlive()){this.addDestroyFunc(t);var o=e.getGui();p.addOrRemoveCssClass(this.eFloatingFilterBody,"ag-floating-filter-body",!this.suppressFilterButton),p.addOrRemoveCssClass(this.eFloatingFilterBody,"ag-floating-filter-full-body",this.suppressFilterButton),p.setDisplayed(this.eButtonWrapper,!this.suppressFilterButton);var i=p.createIconNoSpan("filter",this.gridOptionsWrapper,this.column);this.eButtonShowMainFilter.appendChild(i),this.eFloatingFilterBody.appendChild(o),e.afterGuiAttached&&e.afterGuiAttached()}else t()},t.prototype.parentFilterInstance=function(e){this.filterManager.getFilterComponent(this.column,"NO_UI").then(e)},t.prototype.getFloatingFilterInstance=function(){var e,o=this.column.getColDef();if("string"==typeof o.filter)e=t.filterToFloatingFilterNames[o.filter];else if(!0===o.filter){e=P.isRegistered(R.SetFilterModule)?"agSetColumnFloatingFilter":"agTextColumnFloatingFilter"}var i=this.filterManager.createFilterParams(this.column,this.column.getColDef()),n=this.userComponentFactory.createFinalParams(o,"filter",i),r={api:this.gridApi,column:this.column,filterParams:n,currentParentModel:this.currentParentModel.bind(this),parentFilterInstance:this.parentFilterInstance.bind(this),onFloatingFilterChanged:this.onFloatingFilterChanged.bind(this),suppressFilterButton:!1};this.suppressFilterButton=!!o.floatingFilterComponentParams&&!!o.floatingFilterComponentParams.suppressFilterButton;var s=this.userComponentFactory.newFloatingFilterComponent(o,r,e);if(!s){var a=this.getFilterComponentPrototype(o);if(a&&a.prototype&&a.prototype.getModelAsString){var l=this.userComponentFactory.createUserComponentFromConcreteClass(ri,r);s=u.resolve(l)}}return s},t.prototype.createDynamicParams=function(){return{column:this.column,colDef:this.column.getColDef(),api:this.gridApi,columnApi:this.columnApi}},t.prototype.getFilterComponentPrototype=function(e){var t=this.userComponentFactory.lookupComponentClassDef(e,"filter",this.createDynamicParams());return t?t.component:null},t.prototype.setupEmpty=function(){p.setDisplayed(this.eButtonWrapper,!1)},t.prototype.currentParentModel=function(){return this.filterManager.getFilterComponent(this.column,"NO_UI").resolveNow(null,(function(e){return e.getModel()}))},t.prototype.onParentModelChanged=function(e,t){this.floatingFilterCompPromise&&this.floatingFilterCompPromise.then((function(o){o.onParentModelChanged(e,t)}))},t.prototype.onFloatingFilterChanged=function(){console.warn("ag-Grid: since version 21.x, how floating filters are implemented has changed. Instead of calling params.onFloatingFilterChanged(), get a reference to the main filter via params.parentFilterInstance() and then set a value on the parent filter directly.")},t.filterToFloatingFilterNames={set:"agSetColumnFloatingFilter",agSetColumnFilter:"agSetColumnFloatingFilter",number:"agNumberColumnFloatingFilter",agNumberColumnFilter:"agNumberColumnFloatingFilter",date:"agDateColumnFloatingFilter",agDateColumnFilter:"agDateColumnFloatingFilter",text:"agTextColumnFloatingFilter",agTextColumnFilter:"agTextColumnFloatingFilter"},t.TEMPLATE='<div class="ag-header-cell" role="presentation">\n <div ref="eFloatingFilterBody" role="columnheader"></div>\n <div class="ag-floating-filter-button" ref="eButtonWrapper" role="presentation">\n <button type="button" ref="eButtonShowMainFilter"></button>\n </div>\n </div>',ai([m("columnHoverService")],t.prototype,"columnHoverService",void 0),ai([m("eventService")],t.prototype,"eventService",void 0),ai([m("beans")],t.prototype,"beans",void 0),ai([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),ai([m("userComponentFactory")],t.prototype,"userComponentFactory",void 0),ai([m("gridApi")],t.prototype,"gridApi",void 0),ai([m("columnApi")],t.prototype,"columnApi",void 0),ai([m("filterManager")],t.prototype,"filterManager",void 0),ai([m("menuFactory")],t.prototype,"menuFactory",void 0),ai([fe("eFloatingFilterBody")],t.prototype,"eFloatingFilterBody",void 0),ai([fe("eButtonWrapper")],t.prototype,"eButtonWrapper",void 0),ai([fe("eButtonShowMainFilter")],t.prototype,"eButtonShowMainFilter",void 0),ai([g],t.prototype,"postConstruct",null),t}(pe),pi=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ui=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s}; /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */!function(e){e[e.COLUMN_GROUP=0]="COLUMN_GROUP",e[e.COLUMN=1]="COLUMN",e[e.FLOATING_FILTER=2]="FLOATING_FILTER"}(so||(so={}));var ci,di=function(e){function t(t,o,i,n){var r=e.call(this,'<div class="ag-header-row" role="row"/>')||this;return r.headerComps={},r.dept=t,r.type=o,r.pinned=i,r.dropTarget=n,r}return pi(t,e),t.prototype.forEachHeaderElement=function(e){var t=this;Object.keys(this.headerComps).forEach((function(o){e(t.headerComps[o])}))},t.prototype.destroy=function(){var t=Object.keys(this.headerComps);this.removeAndDestroyChildComponents(t),e.prototype.destroy.call(this)},t.prototype.removeAndDestroyChildComponents=function(e){var t=this;e.forEach((function(e){var o=t.headerComps[e];t.getGui().removeChild(o.getGui()),o.destroy(),delete t.headerComps[e]}))},t.prototype.onRowHeightChanged=function(){var e,t,o=this.columnController.getHeaderRowCount(),i=[],n=0;this.columnController.isPivotMode()?(n=0,e=this.gridOptionsWrapper.getPivotGroupHeaderHeight(),t=this.gridOptionsWrapper.getPivotHeaderHeight()):(this.gridOptionsWrapper.isFloatingFilter()&&o++,n=this.gridOptionsWrapper.isFloatingFilter()?1:0,e=this.gridOptionsWrapper.getGroupHeaderHeight(),t=this.gridOptionsWrapper.getHeaderHeight());for(var r=o-(1+n),s=0;s<r;s++)i.push(e);i.push(t);for(s=0;s<n;s++)i.push(this.gridOptionsWrapper.getFloatingFiltersHeight());var a=0;for(s=0;s<this.dept;s++)a+=i[s];this.getGui().style.top=a+"px",this.getGui().style.height=i[this.dept]+"px"},t.prototype.init=function(){this.onRowHeightChanged(),this.onVirtualColumnsChanged(),this.setWidth(),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_HEADER_HEIGHT,this.onRowHeightChanged.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_PIVOT_HEADER_HEIGHT,this.onRowHeightChanged.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_GROUP_HEADER_HEIGHT,this.onRowHeightChanged.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_PIVOT_GROUP_HEADER_HEIGHT,this.onRowHeightChanged.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_FLOATING_FILTERS_HEIGHT,this.onRowHeightChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_VIRTUAL_COLUMNS_CHANGED,this.onVirtualColumnsChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_COLUMN_RESIZED,this.onColumnResized.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_GRID_COLUMNS_CHANGED,this.onGridColumnsChanged.bind(this))},t.prototype.onColumnResized=function(){this.setWidth()},t.prototype.setWidth=function(){var e=this.getWidthForRow();this.getGui().style.width=e+"px"},t.prototype.getWidthForRow=function(){return this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_PRINT?p.missing(this.pinned)?this.columnController.getContainerWidth(o.PINNED_RIGHT)+this.columnController.getContainerWidth(o.PINNED_LEFT)+this.columnController.getContainerWidth(null):0:this.columnController.getContainerWidth(this.pinned)},t.prototype.onGridColumnsChanged=function(){this.removeAndDestroyAllChildComponents()},t.prototype.removeAndDestroyAllChildComponents=function(){var e=Object.keys(this.headerComps);this.removeAndDestroyChildComponents(e)},t.prototype.onDisplayedColumnsChanged=function(){this.onVirtualColumnsChanged(),this.setWidth()},t.prototype.getItemsAtDepth=function(){var e=this;if(this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_PRINT){if(p.missing(this.pinned)){var t=[];return[o.PINNED_LEFT,null,o.PINNED_RIGHT].forEach((function(o){var i=e.columnController.getVirtualHeaderGroupRow(o,e.type==so.FLOATING_FILTER?e.dept-1:e.dept);t=t.concat(i)})),t}return[]}return this.columnController.getVirtualHeaderGroupRow(this.pinned,this.type==so.FLOATING_FILTER?this.dept-1:this.dept)},t.prototype.onVirtualColumnsChanged=function(){var e=this,t=Object.keys(this.headerComps),o=[];if(this.getItemsAtDepth().forEach((function(i){if(!i.isEmptyGroup()){var n,r,s=i.getUniqueId(),a=e.getGui();t.indexOf(s)>=0?p.removeFromArray(t,s):(n=e.createHeaderComp(i),e.headerComps[s]=n,r=n.getGui(),a.appendChild(r)),o.push(s)}})),this.removeAndDestroyChildComponents(t),this.gridOptionsWrapper.isEnsureDomOrder()){var i=o.map((function(t){return e.headerComps[t].getGui()}));p.setDomChildOrder(this.getGui(),i)}},t.prototype.createHeaderComp=function(e){var t;switch(this.type){case so.COLUMN:t=new Zo(e,this.dropTarget,this.pinned);break;case so.COLUMN_GROUP:t=new oi(e,this.dropTarget,this.pinned);break;case so.FLOATING_FILTER:t=new li(e)}return this.getContext().wireBean(t),t},ui([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),ui([m("gridApi")],t.prototype,"gridApi",void 0),ui([m("columnController")],t.prototype,"columnController",void 0),ui([m("eventService")],t.prototype,"eventService",void 0),ui([m("filterManager")],t.prototype,"filterManager",void 0),ui([g],t.prototype,"init",null),t}(pe),hi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},gi=function(){function e(e,t){this.needToMoveLeft=!1,this.needToMoveRight=!1,this.pinned=e,this.eContainer=t,this.centerContainer=!p.exists(e)}return e.prototype.registerGridComp=function(e){this.gridPanel=e},e.prototype.init=function(){this.logger=this.loggerFactory.create("MoveColumnController")},e.prototype.getIconName=function(){return this.pinned?ao.ICON_PINNED:ao.ICON_MOVE},e.prototype.onDragEnter=function(e){var t=e.dragItem.columns;if(e.dragSource.type===to.ToolPanel)this.setColumnsVisible(t,!0,"uiColumnDragged");else{var o=e.dragItem.visibleState,i=t.filter((function(e){return o[e.getId()]}));this.setColumnsVisible(i,!0,"uiColumnDragged")}this.setColumnsPinned(t,this.pinned,"uiColumnDragged"),this.onDragging(e,!0)},e.prototype.onDragLeave=function(e){if(!this.gridOptionsWrapper.isSuppressDragLeaveHidesColumns()&&!e.fromNudge){var t=e.dragSource.dragItemCallback().columns;this.setColumnsVisible(t,!1,"uiColumnDragged")}this.ensureIntervalCleared()},e.prototype.setColumnsVisible=function(e,t,o){if(void 0===o&&(o="api"),e){var i=e.filter((function(e){return!e.getColDef().lockVisible}));this.columnController.setColumnsVisible(i,t,o)}},e.prototype.setColumnsPinned=function(e,t,o){if(void 0===o&&(o="api"),e){var i=e.filter((function(e){return!e.getColDef().lockPinned}));this.columnController.setColumnsPinned(i,t,o)}},e.prototype.onDragStop=function(){this.ensureIntervalCleared()},e.prototype.normaliseX=function(e){this.gridOptionsWrapper.isEnableRtl()&&(e=this.eContainer.clientWidth-e);return this.centerContainer&&(e+=this.gridPanel.getCenterViewportScrollLeft()),e},e.prototype.checkCenterForScrolling=function(e){if(this.centerContainer){var t=this.gridPanel.getCenterViewportScrollLeft(),o=t+this.gridPanel.getCenterWidth();this.gridOptionsWrapper.isEnableRtl()?(this.needToMoveRight=e<t+50,this.needToMoveLeft=e>o-50):(this.needToMoveLeft=e<t+50,this.needToMoveRight=e>o-50),this.needToMoveLeft||this.needToMoveRight?this.ensureIntervalStarted():this.ensureIntervalCleared()}},e.prototype.onDragging=function(e,t){var o=this;if(void 0===t&&(t=!1),this.lastDraggingEvent=e,!p.missing(e.hDirection)){var i=this.normaliseX(e.x);t||this.checkCenterForScrolling(i);var n=this.normaliseDirection(e.hDirection),r=e.dragSource.type,s=e.dragSource.dragItemCallback().columns;s=s.filter((function(e){return!e.getColDef().lockPinned||e.getPinned()==o.pinned})),this.attemptMoveColumns(r,s,n,i,t)}},e.prototype.normaliseDirection=function(e){if(!this.gridOptionsWrapper.isEnableRtl())return e;switch(e){case io.Left:return io.Right;case io.Right:return io.Left;default:console.error("ag-Grid: Unknown direction "+e)}},e.prototype.calculateOldIndex=function(e){var t=this.columnController.getAllGridColumns(),o=[];e.forEach((function(e){return o.push(t.indexOf(e))})),p.sortNumberArray(o);var i=o[0];return p.last(o)-i!==o.length-1?null:i},e.prototype.attemptMoveColumns=function(e,t,o,i,n){var r=o===io.Left,s=o===io.Right,a=this.calculateValidMoves(t,s,i),l=this.calculateOldIndex(t);if(0!==a.length){var p=a[0],u=null!==l&&!n;if(e==to.HeaderCell&&(u=null!==l),u){if(r&&p>=l)return;if(s&&p<=l)return}for(var c=0;c<a.length;c++){var d=a[c];if(this.columnController.doesMovePassRules(t,d))return void this.columnController.moveColumns(t,d,"uiColumnDragged")}}},e.prototype.calculateValidMoves=function(e,t,o){var i,n=this.columnController.getDisplayedColumns(this.pinned),r=this.columnController.getAllGridColumns(),s=function(t){return e.indexOf(t)<0},a=n.filter((function(t){return e.indexOf(t)>=0})),l=n.filter(s),p=r.filter(s),u=0,c=o;if(t){var d=0;a.forEach((function(e){return d+=e.getActualWidth()})),c-=d}if(c>0){for(var h=0;h<l.length;h++){if((c-=l[h].getActualWidth())<0)break;u++}t&&u++}if(u>0){var g=l[u-1];i=p.indexOf(g)+1}else-1===(i=p.indexOf(l[0]))&&(i=0);var f=[i];if(t)for(var y=i+1,m=r.length-1;y<=m;)f.push(y),y++;else{y=i,m=r.length-1;for(var v=r[y];y<=m&&this.isColumnHidden(n,v);)y++,f.push(y),v=r[y];y=i-1;for(;y>=0;)f.push(y),y--}return f},e.prototype.isColumnHidden=function(e,t){return e.indexOf(t)<0},e.prototype.ensureIntervalStarted=function(){this.movingIntervalId||(this.intervalCount=0,this.failedMoveAttempts=0,this.movingIntervalId=window.setInterval(this.moveInterval.bind(this),100),this.needToMoveLeft?this.dragAndDropService.setGhostIcon(ao.ICON_LEFT,!0):this.dragAndDropService.setGhostIcon(ao.ICON_RIGHT,!0))},e.prototype.ensureIntervalCleared=function(){this.moveInterval&&(window.clearInterval(this.movingIntervalId),this.movingIntervalId=null,this.dragAndDropService.setGhostIcon(ao.ICON_MOVE))},e.prototype.moveInterval=function(){var e,t;if(this.intervalCount++,(e=10+5*this.intervalCount)>100&&(e=100),this.needToMoveLeft?t=this.gridPanel.scrollHorizontally(-e):this.needToMoveRight&&(t=this.gridPanel.scrollHorizontally(e)),0!==t)this.onDragging(this.lastDraggingEvent),this.failedMoveAttempts=0;else{this.failedMoveAttempts++;var i=this.lastDraggingEvent.dragItem.columns.filter((function(e){return!e.getColDef().lockPinned}));if(i.length>0&&(this.dragAndDropService.setGhostIcon(ao.ICON_PINNED),this.failedMoveAttempts>7)){var n=this.needToMoveLeft?o.PINNED_LEFT:o.PINNED_RIGHT;this.setColumnsPinned(i,n,"uiColumnDragged"),this.dragAndDropService.nudge()}}},hi([m("loggerFactory")],e.prototype,"loggerFactory",void 0),hi([m("columnController")],e.prototype,"columnController",void 0),hi([m("dragAndDropService")],e.prototype,"dragAndDropService",void 0),hi([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),hi([g],e.prototype,"init",null),e}(),fi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},yi=function(){function e(e){this.columnsToAggregate=[],this.columnsToGroup=[],this.columnsToPivot=[],this.pinned=e}return e.prototype.onDragEnter=function(e){var t=this;(this.clearColumnsList(),this.gridOptionsWrapper.isFunctionsReadOnly())||e.dragItem.columns.forEach((function(e){e.isPrimary()&&(e.isAnyFunctionActive()||(e.isAllowValue()?t.columnsToAggregate.push(e):e.isAllowRowGroup()?t.columnsToGroup.push(e):e.isAllowRowGroup()&&t.columnsToPivot.push(e)))}))},e.prototype.getIconName=function(){return this.columnsToAggregate.length+this.columnsToGroup.length+this.columnsToPivot.length>0?this.pinned?ao.ICON_PINNED:ao.ICON_MOVE:null},e.prototype.onDragLeave=function(e){this.clearColumnsList()},e.prototype.clearColumnsList=function(){this.columnsToAggregate.length=0,this.columnsToGroup.length=0,this.columnsToPivot.length=0},e.prototype.onDragging=function(e){},e.prototype.onDragStop=function(e){this.columnsToAggregate.length>0&&this.columnController.addValueColumns(this.columnsToAggregate,"toolPanelDragAndDrop"),this.columnsToGroup.length>0&&this.columnController.addRowGroupColumns(this.columnsToGroup,"toolPanelDragAndDrop"),this.columnsToPivot.length>0&&this.columnController.addPivotColumns(this.columnsToPivot,"toolPanelDragAndDrop")},fi([m("columnController")],e.prototype,"columnController",void 0),fi([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),e}(),mi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s}; /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */!function(e){e[e.ColumnMove=0]="ColumnMove",e[e.Pivot=1]="Pivot"}(ci||(ci={}));var vi,Ci=function(){function e(e,t){this.dropListeners={},this.pinned=e,this.eContainer=t}return e.prototype.registerGridComp=function(e){switch(this.gridPanel=e,this.moveColumnController.registerGridComp(e),this.pinned){case o.PINNED_LEFT:this.eSecondaryContainers=this.gridPanel.getDropTargetLeftContainers();break;case o.PINNED_RIGHT:this.eSecondaryContainers=this.gridPanel.getDropTargetRightContainers();break;default:this.eSecondaryContainers=this.gridPanel.getDropTargetBodyContainers()}},e.prototype.isInterestedIn=function(e){return e===to.HeaderCell||e===to.ToolPanel&&this.gridOptionsWrapper.isAllowDragFromColumnsToolPanel()},e.prototype.getSecondaryContainers=function(){return this.eSecondaryContainers},e.prototype.getContainer=function(){return this.eContainer},e.prototype.init=function(){this.moveColumnController=new gi(this.pinned,this.eContainer),this.context.wireBean(this.moveColumnController);var e=new yi(this.pinned);this.context.wireBean(e),this.dropListeners[ci.ColumnMove]=this.moveColumnController,this.dropListeners[ci.Pivot]=e,this.dragAndDropService.addDropTarget(this)},e.prototype.getIconName=function(){return this.currentDropListener.getIconName()},e.prototype.getDropType=function(e){return this.columnController.isPivotMode()&&e.dragSource.type===to.ToolPanel?ci.Pivot:ci.ColumnMove},e.prototype.onDragEnter=function(e){var t=this.getDropType(e);this.currentDropListener=this.dropListeners[t],this.currentDropListener.onDragEnter(e)},e.prototype.onDragLeave=function(e){this.currentDropListener.onDragLeave(e)},e.prototype.onDragging=function(e){this.currentDropListener.onDragging(e)},e.prototype.onDragStop=function(e){this.currentDropListener.onDragStop(e)},mi([m("context")],e.prototype,"context",void 0),mi([m("dragAndDropService")],e.prototype,"dragAndDropService",void 0),mi([m("columnController")],e.prototype,"columnController",void 0),mi([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),mi([g],e.prototype,"init",null),e}(),Ei=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},wi=function(){function e(e,t,o){this.headerRowComps=[],this.eContainer=e,this.pinned=o,this.eViewport=t}return e.prototype.registerGridComp=function(e){this.setupDragAndDrop(e)},e.prototype.forEachHeaderElement=function(e){this.headerRowComps.forEach((function(t){return t.forEachHeaderElement(e)}))},e.prototype.init=function(){this.scrollWidth=this.gridOptionsWrapper.getScrollbarWidth(),this.eventService.addEventListener(M.EVENT_COLUMN_VALUE_CHANGED,this.onColumnValueChanged.bind(this)),this.eventService.addEventListener(M.EVENT_COLUMN_ROW_GROUP_CHANGED,this.onColumnRowGroupChanged.bind(this)),this.eventService.addEventListener(M.EVENT_GRID_COLUMNS_CHANGED,this.onGridColumnsChanged.bind(this)),this.eventService.addEventListener(M.EVENT_SCROLL_VISIBILITY_CHANGED,this.onScrollVisibilityChanged.bind(this)),this.eventService.addEventListener(M.EVENT_COLUMN_RESIZED,this.onColumnResized.bind(this)),this.eventService.addEventListener(M.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this))},e.prototype.onColumnRowGroupChanged=function(){this.onGridColumnsChanged()},e.prototype.onColumnValueChanged=function(){this.onGridColumnsChanged()},e.prototype.onColumnResized=function(){this.setWidthOfPinnedContainer()},e.prototype.onDisplayedColumnsChanged=function(){this.setWidthOfPinnedContainer()},e.prototype.onScrollVisibilityChanged=function(){this.setWidthOfPinnedContainer()},e.prototype.setWidthOfPinnedContainer=function(){var e=this.pinned===o.PINNED_LEFT,t=this.pinned===o.PINNED_RIGHT,i=this.columnController,n=this.gridOptionsWrapper.isEnableRtl();if(e||t){var r=i[e?"getPinnedLeftContainerWidth":"getPinnedRightContainerWidth"]();this.scrollVisibleService.isVerticalScrollShowing()&&(n&&e||!n&&t)&&(r+=this.scrollWidth),p.setFixedWidth(this.eContainer,r)}},e.prototype.destroy=function(){this.removeHeaderRowComps()},e.prototype.getRowComps=function(){return this.headerRowComps},e.prototype.onGridColumnsChanged=function(){this.removeAndCreateAllRowComps()},e.prototype.removeAndCreateAllRowComps=function(){this.removeHeaderRowComps(),this.createHeaderRowComps()},e.prototype.refresh=function(){this.removeAndCreateAllRowComps()},e.prototype.setupDragAndDrop=function(e){var t=this.eViewport?this.eViewport:this.eContainer,o=new Ci(this.pinned,t);this.context.wireBean(o),o.registerGridComp(e)},e.prototype.removeHeaderRowComps=function(){this.headerRowComps.forEach((function(e){e.destroy()})),this.headerRowComps.length=0,p.clearElement(this.eContainer)},e.prototype.createHeaderRowComps=function(){for(var e=this.columnController.getHeaderRowCount(),t=0;t<e;t++){var o=t!==e-1?so.COLUMN_GROUP:so.COLUMN,i=new di(t,o,this.pinned,this.dropTarget);this.context.wireBean(i),this.headerRowComps.push(i),i.getGui().setAttribute("aria-rowindex",this.headerRowComps.length.toString()),this.eContainer.appendChild(i.getGui())}if(this.gridOptionsWrapper.isFloatingFilter()&&!this.columnController.isPivotMode()){i=new di(e,so.FLOATING_FILTER,this.pinned,this.dropTarget);this.context.wireBean(i),this.headerRowComps.push(i),i.getGui().setAttribute("aria-rowindex",this.headerRowComps.length.toString()),this.eContainer.appendChild(i.getGui())}},Ei([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Ei([m("context")],e.prototype,"context",void 0),Ei([m("$scope")],e.prototype,"$scope",void 0),Ei([m("dragAndDropService")],e.prototype,"dragAndDropService",void 0),Ei([m("columnController")],e.prototype,"columnController",void 0),Ei([m("eventService")],e.prototype,"eventService",void 0),Ei([m("scrollVisibleService")],e.prototype,"scrollVisibleService",void 0),Ei([g],e.prototype,"init",null),e}(),Ri=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Oi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Di=function(e){function t(){return e.call(this,t.TEMPLATE)||this}return Ri(t,e),t.prototype.registerGridComp=function(e){this.gridPanel=e,this.childContainers.forEach((function(t){return t.registerGridComp(e)}))},t.prototype.postConstruct=function(){var e=this;this.printLayout=this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_PRINT,this.gridApi.registerHeaderRootComp(this),this.autoWidthCalculator.registerHeaderRootComp(this);var t=new wi(this.eHeaderContainer,this.eHeaderViewport,null),i=new wi(this.ePinnedLeftHeader,null,o.PINNED_LEFT),n=new wi(this.ePinnedRightHeader,null,o.PINNED_RIGHT);this.childContainers=[t,i,n],this.childContainers.forEach((function(t){return e.getContext().wireBean(t)})),this.addDestroyableEventListener(this.eventService,M.EVENT_COLUMN_VALUE_CHANGED,this.refreshHeader.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_DOM_LAYOUT,this.onDomLayoutChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_COLUMN_PIVOT_MODE_CHANGED,this.onPivotModeChanged.bind(this)),this.onPivotModeChanged(),this.addPreventHeaderScroll(),this.columnController.isReady()&&this.refreshHeader()},t.prototype.onDomLayoutChanged=function(){var e=this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_PRINT;this.printLayout!==e&&(this.printLayout=e,this.refreshHeader())},t.prototype.setHorizontalScroll=function(e){this.eHeaderContainer.style.transform="translateX("+e+"px)"},t.prototype.forEachHeaderElement=function(e){this.childContainers.forEach((function(t){return t.forEachHeaderElement(e)}))},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.childContainers.forEach((function(e){return e.destroy()}))},t.prototype.refreshHeader=function(){this.childContainers.forEach((function(e){return e.refresh()}))},t.prototype.onPivotModeChanged=function(){var e=this.columnController.isPivotMode();p.addOrRemoveCssClass(this.getGui(),"ag-pivot-on",e),p.addOrRemoveCssClass(this.getGui(),"ag-pivot-off",!e)},t.prototype.setHeight=function(e){var t=e+1+"px";this.getGui().style.height=t,this.getGui().style.minHeight=t},t.prototype.addPreventHeaderScroll=function(){var e=this;this.addDestroyableEventListener(this.eHeaderViewport,"scroll",(function(){var t=e.eHeaderViewport.scrollLeft;0!==t&&(e.gridPanel.scrollHorizontally(t),e.eHeaderViewport.scrollLeft=0)}))},t.prototype.setHeaderContainerWidth=function(e){this.eHeaderContainer.style.width=e+"px"},t.prototype.setLeftVisible=function(e){p.setDisplayed(this.ePinnedLeftHeader,e)},t.prototype.setRightVisible=function(e){p.setDisplayed(this.ePinnedRightHeader,e)},t.prototype.getHeaderRowCount=function(){return 0===this.childContainers.length?0:this.childContainers[0].getRowComps().length},t.TEMPLATE='<div class="ag-header" role="presentation">\n <div class="ag-pinned-left-header" ref="ePinnedLeftHeader" role="presentation"></div>\n <div class="ag-header-viewport" ref="eHeaderViewport" role="presentation">\n <div class="ag-header-container" ref="eHeaderContainer" role="rowgroup"></div>\n </div>\n <div class="ag-pinned-right-header" ref="ePinnedRightHeader" role="presentation"></div>\n </div>',Oi([fe("ePinnedLeftHeader")],t.prototype,"ePinnedLeftHeader",void 0),Oi([fe("ePinnedRightHeader")],t.prototype,"ePinnedRightHeader",void 0),Oi([fe("eHeaderContainer")],t.prototype,"eHeaderContainer",void 0),Oi([fe("eHeaderViewport")],t.prototype,"eHeaderViewport",void 0),Oi([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Oi([m("columnController")],t.prototype,"columnController",void 0),Oi([m("eventService")],t.prototype,"eventService",void 0),Oi([m("gridApi")],t.prototype,"gridApi",void 0),Oi([m("autoWidthCalculator")],t.prototype,"autoWidthCalculator",void 0),Oi([g],t.prototype,"postConstruct",null),t}(pe),bi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Pi=function(){function e(){this.allFilters={},this.quickFilter=null,this.quickFilterParts=null,this.processingFilterChange=!1}var t;return t=e,e.prototype.registerGridCore=function(e){this.gridCore=e},e.prototype.init=function(){this.eventService.addEventListener(M.EVENT_ROW_DATA_CHANGED,this.onNewRowsLoaded.bind(this)),this.eventService.addEventListener(M.EVENT_NEW_COLUMNS_LOADED,this.onNewColumnsLoaded.bind(this)),this.quickFilter=this.parseQuickFilter(this.gridOptionsWrapper.getQuickFilterText()),this.setQuickFilterParts(),this.allowShowChangeAfterFilter=this.gridOptionsWrapper.isAllowShowChangeAfterFilter(),this.checkExternalFilter()},e.prototype.setQuickFilterParts=function(){this.quickFilter?this.quickFilterParts=this.quickFilter.split(" "):this.quickFilterParts=null},e.prototype.setFilterModel=function(e){var t=this,o=[];if(e){var i=Object.keys(e);p.iterateObject(this.allFilters,(function(n,r){p.removeFromArray(i,n);var s=e[n];t.setModelOnFilterWrapper(r.filterPromise,s),o.push(r.filterPromise)})),i.forEach((function(i){var n=t.columnController.getPrimaryColumn(i);if(n){var r=t.getOrCreateFilterWrapper(n,"NO_UI");t.setModelOnFilterWrapper(r.filterPromise,e[i]),o.push(r.filterPromise)}else console.warn("Warning ag-grid setFilterModel - no column found for colId "+i)}))}else p.iterateObject(this.allFilters,(function(e,i){t.setModelOnFilterWrapper(i.filterPromise,null),o.push(i.filterPromise)}));u.all(o).then((function(e){t.onFilterChanged()}))},e.prototype.setModelOnFilterWrapper=function(e,t){e.then((function(e){"function"==typeof e.setModel?e.setModel(t):console.warn("Warning ag-grid - filter missing setModel method, which is needed for setFilterModel")}))},e.prototype.getFilterModel=function(){var e={};return p.iterateObject(this.allFilters,(function(t,o){var i=o.filterPromise.resolveNow(null,(function(e){return e}));if(null==i)return null;if("function"==typeof i.getModel){var n=i.getModel();p.exists(n)&&(e[t]=n)}else console.warn("Warning ag-grid - filter API missing getModel method, which is needed for getFilterModel")})),e},e.prototype.isAdvancedFilterPresent=function(){return this.advancedFilterPresent},e.prototype.setAdvancedFilterPresent=function(){var e=!1;p.iterateObject(this.allFilters,(function(t,o){o.filterPromise.resolveNow(!1,(function(e){return e.isFilterActive()}))&&(e=!0)})),this.advancedFilterPresent=e},e.prototype.updateFilterFlagInColumns=function(e,t){p.iterateObject(this.allFilters,(function(o,i){var n=i.filterPromise.resolveNow(!1,(function(e){return e.isFilterActive()}));i.column.setFilterActive(n,e,t)}))},e.prototype.isAnyFilterPresent=function(){return this.isQuickFilterPresent()||this.advancedFilterPresent||this.externalFilterPresent},e.prototype.doesFilterPass=function(e,t){for(var o=e.data,i=Object.keys(this.allFilters),n=0,r=i.length;n<r;n++){var s=i[n],a=this.allFilters[s];if(void 0!==a){var l=a.filterPromise.resolveNow(void 0,(function(e){return e}));if(void 0!==l&&l!==t&&l.isFilterActive()){l.doesFilterPass||console.error("Filter is missing method doesFilterPass");var p={node:e,data:o};if(!l.doesFilterPass(p))return!1}}}return!0},e.prototype.parseQuickFilter=function(e){return p.missing(e)||""===e?null:this.gridOptionsWrapper.isRowModelDefault()?e.toUpperCase():(console.warn("ag-grid: quick filtering only works with the Client-side Row Model"),null)},e.prototype.setQuickFilter=function(e){var t=this.parseQuickFilter(e);this.quickFilter!==t&&(this.quickFilter=t,this.setQuickFilterParts(),this.onFilterChanged())},e.prototype.checkExternalFilter=function(){this.externalFilterPresent=this.gridOptionsWrapper.isExternalFilterPresent()},e.prototype.onFilterChanged=function(e){this.setAdvancedFilterPresent(),this.updateFilterFlagInColumns("filterChanged",e),this.checkExternalFilter(),p.iterateObject(this.allFilters,(function(e,t){t.filterPromise.then((function(e){e.onAnyFilterChanged&&e.onAnyFilterChanged()}))}));var t={type:M.EVENT_FILTER_CHANGED,api:this.gridApi,columnApi:this.columnApi};e&&p.mergeDeep(t,e),this.processingFilterChange=!0,this.eventService.dispatchEvent(t),this.processingFilterChange=!1},e.prototype.isSuppressFlashingCellsBecauseFiltering=function(){return!this.allowShowChangeAfterFilter&&this.processingFilterChange},e.prototype.isQuickFilterPresent=function(){return null!==this.quickFilter},e.prototype.doesRowPassOtherFilters=function(e,t){return this.doesRowPassFilter(t,e)},e.prototype.doesRowPassQuickFilterNoCache=function(e,t){var o=this,i=this.columnController.getAllColumnsForQuickFilter(),n=!1;return i.forEach((function(i){if(!n){var r=o.getQuickFilterTextForColumn(i,e);p.exists(r)&&r.indexOf(t)>=0&&(n=!0)}})),n},e.prototype.doesRowPassQuickFilterCache=function(e,t){return e.quickFilterAggregateText||this.aggregateRowForQuickFilter(e),e.quickFilterAggregateText.indexOf(t)>=0},e.prototype.doesRowPassQuickFilter=function(e){var t=this,o=!0,i=this.gridOptionsWrapper.isCacheQuickFilter();return this.quickFilterParts.forEach((function(n){(i?t.doesRowPassQuickFilterCache(e,n):t.doesRowPassQuickFilterNoCache(e,n))||(o=!1)})),o},e.prototype.doesRowPassFilter=function(e,t){return!(this.isQuickFilterPresent()&&!this.doesRowPassQuickFilter(e))&&(!(this.externalFilterPresent&&!this.gridOptionsWrapper.doesExternalFilterPass(e))&&!(this.advancedFilterPresent&&!this.doesFilterPass(e,t)))},e.prototype.getQuickFilterTextForColumn=function(e,t){var o,i=this.valueService.getValue(e,t,!0),n=e.getColDef();if(e.getColDef().getQuickFilterText){var r={value:i,node:t,data:t.data,column:e,colDef:n,context:this.gridOptionsWrapper.getContext()};o=e.getColDef().getQuickFilterText(r)}else o=i;return p.exists(o)?o.toString().toUpperCase():null},e.prototype.aggregateRowForQuickFilter=function(e){var o=this,i=[];this.columnController.getAllColumnsForQuickFilter().forEach((function(t){var n=o.getQuickFilterTextForColumn(t,e);p.exists(n)&&i.push(n)})),e.quickFilterAggregateText=i.join(t.QUICK_FILTER_SEPARATOR)},e.prototype.onNewRowsLoaded=function(e){p.iterateObject(this.allFilters,(function(e,t){t.filterPromise.then((function(e){e.onNewRowsLoaded&&e.onNewRowsLoaded()}))})),this.updateFilterFlagInColumns(e),this.setAdvancedFilterPresent()},e.prototype.createValueGetter=function(e){var t=this;return function(o){return t.valueService.getValue(e,o,!0)}},e.prototype.getFilterComponent=function(e,t){return this.getOrCreateFilterWrapper(e,t).filterPromise},e.prototype.isFilterActive=function(e){var t=this.cachedFilter(e);return!!t&&t.filterPromise.resolveNow(!1,(function(e){return e.isFilterActive()}))},e.prototype.getOrCreateFilterWrapper=function(e,t){var o=this.cachedFilter(e);return o?"NO_UI"!==t&&this.putIntoGui(o,t):(o=this.createFilterWrapper(e,t),this.allFilters[e.getColId()]=o),o},e.prototype.cachedFilter=function(e){return this.allFilters[e.getColId()]},e.prototype.createFilterInstance=function(e,t){var o=this,i="agTextColumnFilter";P.isRegistered(R.SetFilterModule)&&(i="agSetColumnFilter");var n,r=p.cloneObject(e.getColDef()),s=this.createFilterParams(e,r,t);s.filterChangedCallback=this.onFilterChanged.bind(this),s.filterModifiedCallback=function(){var t={type:M.EVENT_FILTER_MODIFIED,api:o.gridApi,columnApi:o.columnApi,column:e,filterInstance:n};o.eventService.dispatchEvent(t)};var a=this.userComponentFactory.newFilterComponent(r,s,i,(function(e,t){return p.assign(e,{doesRowPassOtherFilter:o.doesRowPassOtherFilters.bind(o,t)})}));return a&&a.then((function(e){return n=e})),a},e.prototype.createFilterParams=function(e,t,o){void 0===o&&(o=null);var i={api:this.gridOptionsWrapper.getApi(),column:e,colDef:t,rowModel:this.rowModel,filterChangedCallback:null,filterModifiedCallback:null,valueGetter:this.createValueGetter(e),context:this.gridOptionsWrapper.getContext(),doesRowPassOtherFilter:null};return o&&(i.$scope=o),i},e.prototype.createFilterWrapper=function(e,t){var o={column:e,filterPromise:null,scope:null,compiledElement:null,guiPromise:u.external()};return o.scope=this.gridOptionsWrapper.isAngularCompileFilters()?this.$scope.$new():null,o.filterPromise=this.createFilterInstance(e,o.scope),o.filterPromise&&this.putIntoGui(o,t),o},e.prototype.putIntoGui=function(e,t){var o=this,i=document.createElement("div");i.className="ag-filter",e.filterPromise.then((function(n){var r=n.getGui();if(p.missing(r)&&console.warn("getGui method from filter returned "+r+", it should be a DOM element or an HTML template string."),"string"==typeof r&&(r=p.loadTemplate(r)),i.appendChild(r),e.scope){var s=o.$compile(i)(e.scope);e.compiledElement=s,window.setTimeout((function(){return e.scope.$apply()}),0)}e.guiPromise.resolve(i),o.eventService.dispatchEvent({type:M.EVENT_FILTER_OPENED,column:e.column,source:t,eGui:i,api:o.gridApi,columnApi:o.columnApi})}))},e.prototype.onNewColumnsLoaded=function(){var e=this,t=!1;p.iterateObject(this.allFilters,(function(o,i){!e.columnController.getPrimaryColumn(i.column)&&(t=!0,e.disposeFilterWrapper(i,"filterDestroyed"))})),t&&this.onFilterChanged()},e.prototype.destroyFilter=function(e,t){void 0===t&&(t="api");var o=this.allFilters[e.getColId()];o&&(this.disposeFilterWrapper(o,t),this.onFilterChanged())},e.prototype.disposeFilterWrapper=function(e,t){var o=this;e.filterPromise.then((function(i){i.setModel(null),i.destroy&&i.destroy(),e.column.setFilterActive(!1,t),e.scope&&(e.compiledElement&&e.compiledElement.remove(),e.scope.$destroy()),delete o.allFilters[e.column.getColId()]}))},e.prototype.destroy=function(){var e=this;p.iterateObject(this.allFilters,(function(t,o){e.disposeFilterWrapper(o,"filterDestroyed")}))},e.QUICK_FILTER_SEPARATOR="\n",bi([m("$compile")],e.prototype,"$compile",void 0),bi([m("$scope")],e.prototype,"$scope",void 0),bi([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),bi([m("popupService")],e.prototype,"popupService",void 0),bi([m("valueService")],e.prototype,"valueService",void 0),bi([m("columnController")],e.prototype,"columnController",void 0),bi([m("rowModel")],e.prototype,"rowModel",void 0),bi([m("eventService")],e.prototype,"eventService",void 0),bi([m("context")],e.prototype,"context",void 0),bi([m("columnApi")],e.prototype,"columnApi",void 0),bi([m("gridApi")],e.prototype,"gridApi",void 0),bi([m("userComponentFactory")],e.prototype,"userComponentFactory",void 0),bi([g],e.prototype,"init",null),bi([f],e.prototype,"destroy",null),e=t=bi([y("filterManager")],e)}(),Si=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ti=function(){function e(){this.initialised=!1}return e.prototype.init=function(){this.cellExpressions=this.gridOptionsWrapper.isEnableCellExpressions(),this.initialised=!0},e.prototype.getValue=function(e,t,o,i){if(void 0===o&&(o=!1),void 0===i&&(i=!1),this.initialised||this.init(),t){var n,r=e.getColDef(),s=r.field,a=e.getId(),l=t.data,u=t.groupData&&void 0!==t.groupData[a],c=!i&&t.aggData&&void 0!==t.aggData[a];if(o&&r.filterValueGetter?n=this.executeFilterValueGetter(r.filterValueGetter,l,e,t):this.gridOptionsWrapper.isTreeData()&&c?n=t.aggData[a]:this.gridOptionsWrapper.isTreeData()&&r.valueGetter?n=this.executeValueGetter(r.valueGetter,l,e,t):this.gridOptionsWrapper.isTreeData()&&s&&l?n=p.getValueUsingField(l,s,e.isFieldContainsDots()):u?n=t.groupData[a]:c?n=t.aggData[a]:r.valueGetter?n=this.executeValueGetter(r.valueGetter,l,e,t):s&&l&&(n=p.getValueUsingField(l,s,e.isFieldContainsDots())),this.cellExpressions&&"string"==typeof n&&0===n.indexOf("=")){var d=n.substring(1);n=this.executeValueGetter(d,l,e,t)}return n}},e.prototype.setValue=function(e,t,o,i){var n=this.columnController.getPrimaryColumn(t);if(e&&n){var r=e.data;p.missing(r)&&(e.data={});var s=n.getColDef(),a=s.field,l=s.newValueHandler,u=s.valueSetter;if(p.missing(a)&&p.missing(l)&&p.missing(u))console.warn("ag-Grid: you need either field or valueSetter set on colDef for editing to work");else{var c,d={node:e,data:e.data,oldValue:this.getValue(n,e),newValue:o,colDef:n.getColDef(),column:n,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext()};if(d.newValue=o,void 0===(c=l&&p.exists(l)?l(d):p.exists(u)?this.expressionService.evaluate(u,d):this.setValueUsingField(r,a,o,n.isFieldContainsDots()))&&(c=!0),c){e.resetQuickFilterAggregateText(),this.valueCache.onDataChanged(),d.newValue=this.getValue(n,e);var h=n.getColDef().onCellValueChanged;"function"==typeof h&&setTimeout((function(){return h(d)}),0);var g={type:M.EVENT_CELL_VALUE_CHANGED,event:null,rowIndex:e.rowIndex,rowPinned:e.rowPinned,column:d.column,api:d.api,colDef:d.colDef,columnApi:d.columnApi,context:d.context,data:e.data,node:e,oldValue:d.oldValue,newValue:d.newValue,value:d.newValue,source:i};this.eventService.dispatchEvent(g)}}}},e.prototype.setValueUsingField=function(e,t,o,i){if(!t)return!1;if(i)for(var n=t.split("."),r=e;n.length>0&&r;){var s=n.shift();0===n.length?r[s]=o:r=r[s]}else e[t]=o;return!0},e.prototype.executeFilterValueGetter=function(e,t,o,i){var n={data:t,node:i,column:o,colDef:o.getColDef(),api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext(),getValue:this.getValueCallback.bind(this,i)};return this.expressionService.evaluate(e,n)},e.prototype.executeValueGetter=function(e,t,o,i){var n=o.getId(),r=this.valueCache.getValue(i,n);if(void 0!==r)return r;var s={data:t,node:i,column:o,colDef:o.getColDef(),api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext(),getValue:this.getValueCallback.bind(this,i)},a=this.expressionService.evaluate(e,s);return this.valueCache.setValue(i,n,a),a},e.prototype.getValueCallback=function(e,t){var o=this.columnController.getPrimaryColumn(t);return o?this.getValue(o,e):null},e.prototype.getKeyForNode=function(e,t){var o=this.getValue(e,t),i=e.getColDef().keyCreator,n=i?i({value:o}):o;return"string"==typeof n||null==n?n:("[object Object]"===(n=String(n))&&p.doOnce((function(){console.warn("ag-Grid: a column you are grouping or pivoting by has objects as values. If you want to group by complex objects then either a) use a colDef.keyCreator (se ag-Grid docs) or b) to toString() on the object to return a key")}),"getKeyForNode - warn about [object,object]"),n)},Si([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Si([m("expressionService")],e.prototype,"expressionService",void 0),Si([m("columnController")],e.prototype,"columnController",void 0),Si([m("eventService")],e.prototype,"eventService",void 0),Si([m("valueCache")],e.prototype,"valueCache",void 0),Si([g],e.prototype,"init",null),e=Si([y("valueService")],e)}(),Ai=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},_i=function(){function e(e){this.childCount=0,this.rowTemplatesToAdd=[],this.afterGuiAttachedCallbacks=[],this.lastMadeVisibleTime=0,this.eContainer=e.eContainer,this.eViewport=e.eViewport,e.eWrapper&&(this.eWrapper=e.eWrapper),this.hideWhenNoChildren=e.hideWhenNoChildren}return e.prototype.setVerticalScrollPosition=function(e){this.scrollTop=e},e.prototype.postConstruct=function(){this.checkDomOrder(),this.checkVisibility(),this.gridOptionsWrapper.addEventListener(Z.PROP_DOM_LAYOUT,this.checkDomOrder.bind(this))},e.prototype.checkDomOrder=function(){this.domOrder=this.gridOptionsWrapper.isEnsureDomOrder()},e.prototype.getRowElement=function(e){return this.eContainer.querySelector('[comp-id="'+e+'"]')},e.prototype.setHeight=function(e){null!=e?(this.eContainer.style.height=e+"px",this.eWrapper&&(this.eWrapper.style.height=e+"px")):this.eContainer.style.height=""},e.prototype.flushRowTemplates=function(){if(0!==this.rowTemplatesToAdd.length){var e=this.rowTemplatesToAdd.join("");p.appendHtml(this.eContainer,e),this.rowTemplatesToAdd.length=0}this.afterGuiAttachedCallbacks.forEach((function(e){return e()})),this.afterGuiAttachedCallbacks.length=0,this.lastPlacedElement=null},e.prototype.appendRowTemplate=function(e,t){this.domOrder?this.lastPlacedElement=p.insertTemplateWithDomOrder(this.eContainer,e,this.lastPlacedElement):this.rowTemplatesToAdd.push(e),this.afterGuiAttachedCallbacks.push(t),this.childCount++,this.checkVisibility()},e.prototype.ensureDomOrder=function(e){this.domOrder&&(p.ensureDomOrder(this.eContainer,e,this.lastPlacedElement),this.lastPlacedElement=e)},e.prototype.removeRowElement=function(e){this.eContainer.removeChild(e),this.childCount--,this.checkVisibility()},e.prototype.checkVisibility=function(){if(this.hideWhenNoChildren){var e=this.eViewport?this.eViewport:this.eContainer,t=this.childCount>0;this.visible!==t&&(this.visible=t,this.lastMadeVisibleTime=(new Date).getTime(),p.setDisplayed(e,t),t&&this.eViewport&&(this.eViewport.scrollTop=this.scrollTop))}},e.prototype.isMadeVisibleRecently=function(){return(new Date).getTime()-this.lastMadeVisibleTime<500},Ai([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Ai([g],e.prototype,"postConstruct",null),e}(),Fi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ni=function(){function e(e,t){this.eContainer=e,this.gridPanel=t}return e.prototype.postConstruct=function(){this.gridOptionsWrapper.isRowModelDefault()&&(this.clientSideRowModel=this.rowModel)},e.prototype.getContainer=function(){return this.eContainer},e.prototype.isInterestedIn=function(e){return e===to.RowDrag},e.prototype.getIconName=function(){return ao.ICON_MOVE},e.prototype.onDragEnter=function(e){this.dispatchEvent(M.EVENT_ROW_DRAG_ENTER,e),this.dragAndDropService.setGhostIcon(ao.ICON_MOVE),e.dragItem.rowNode.setDragging(!0),this.onEnterOrDragging(e)},e.prototype.onDragging=function(e){this.onEnterOrDragging(e)},e.prototype.onEnterOrDragging=function(e){this.dispatchEvent(M.EVENT_ROW_DRAG_MOVE,e),this.lastDraggingEvent=e;var t=this.normaliseForScroll(e.y);this.gridOptionsWrapper.isRowDragManaged()&&this.doManagedDrag(e,t),this.checkCenterForScrolling(t)},e.prototype.doManagedDrag=function(e,t){var o=e.dragItem.rowNode;this.clientSideRowModel.ensureRowAtPixel(o,t)&&(this.focusedCellController.clearFocusedCell(),this.rangeController&&this.rangeController.removeAllCellRanges())},e.prototype.normaliseForScroll=function(e){return this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_NORMAL?e+this.gridPanel.getVScrollPosition().top:e},e.prototype.checkCenterForScrolling=function(e){var t=this.gridPanel.getVScrollPosition();this.needToMoveUp=e<t.top+50,this.needToMoveDown=e>t.bottom-50,this.needToMoveUp||this.needToMoveDown?this.ensureIntervalStarted():this.ensureIntervalCleared()},e.prototype.ensureIntervalStarted=function(){this.movingIntervalId||(this.intervalCount=0,this.movingIntervalId=window.setInterval(this.moveInterval.bind(this),100))},e.prototype.ensureIntervalCleared=function(){this.moveInterval&&(window.clearInterval(this.movingIntervalId),this.movingIntervalId=null)},e.prototype.moveInterval=function(){var e,t;this.intervalCount++,(e=10+5*this.intervalCount)>100&&(e=100),this.needToMoveDown?t=this.gridPanel.scrollVertically(e):this.needToMoveUp&&(t=this.gridPanel.scrollVertically(-e)),0!==t&&this.onDragging(this.lastDraggingEvent)},e.prototype.dispatchEvent=function(e,t){var o,i=this.normaliseForScroll(t.y),n=-1,r=null;switch(i>this.rowModel.getCurrentPageHeight()||(n=this.rowModel.getRowIndexAtPixel(i),r=this.rowModel.getRow(n)),t.vDirection){case oo.Down:o="down";break;case oo.Up:o="up";break;default:o=null}var s={type:e,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),event:t.event,node:t.dragItem.rowNode,overIndex:n,overNode:r,y:i,vDirection:o};this.eventService.dispatchEvent(s)},e.prototype.onDragLeave=function(e){this.dispatchEvent(M.EVENT_ROW_DRAG_LEAVE,e),this.stopDragging(e)},e.prototype.onDragStop=function(e){this.dispatchEvent(M.EVENT_ROW_DRAG_END,e),this.stopDragging(e)},e.prototype.stopDragging=function(e){this.ensureIntervalCleared(),e.dragItem.rowNode.setDragging(!1)},Fi([m("dragAndDropService")],e.prototype,"dragAndDropService",void 0),Fi([m("rowModel")],e.prototype,"rowModel",void 0),Fi([m("focusedCellController")],e.prototype,"focusedCellController",void 0),Fi([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Fi([v("rangeController")],e.prototype,"rangeController",void 0),Fi([m("eventService")],e.prototype,"eventService",void 0),Fi([g],e.prototype,"postConstruct",null),e}(),Li=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ii=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Gi='<div class="ag-root ag-unselectable" role="grid" unselectable="on">\n <ag-header-root ref="headerRoot" unselectable="on"></ag-header-root>\n <div class="ag-floating-top" ref="eTop" role="presentation" unselectable="on">\n <div class="ag-pinned-left-floating-top" ref="eLeftTop" role="presentation" unselectable="on"></div>\n <div class="ag-floating-top-viewport" ref="eTopViewport" role="presentation" unselectable="on">\n <div class="ag-floating-top-container" ref="eTopContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-pinned-right-floating-top" ref="eRightTop" role="presentation" unselectable="on"></div>\n <div class="ag-floating-top-full-width-container" ref="eTopFullWidthContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-body-viewport" ref="eBodyViewport" role="presentation" unselectable="on">\n <div class="ag-pinned-left-cols-container" ref="eLeftContainer" role="presentation" unselectable="on"></div>\n <div class="ag-center-cols-clipper" ref="eCenterColsClipper" role="presentation" unselectable="on">\n <div class="ag-center-cols-viewport" ref="eCenterViewport" role="presentation" unselectable="on">\n <div class="ag-center-cols-container" ref="eCenterContainer" role="rowgroup" unselectable="on"></div>\n </div>\n </div>\n <div class="ag-pinned-right-cols-container" ref="eRightContainer" role="presentation" unselectable="on"></div>\n <div class="ag-full-width-container" ref="eFullWidthContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-floating-bottom" ref="eBottom" role="presentation" unselectable="on">\n <div class="ag-pinned-left-floating-bottom" ref="eLeftBottom" role="presentation" unselectable="on"></div>\n <div class="ag-floating-bottom-viewport" ref="eBottomViewport" role="presentation" unselectable="on">\n <div class="ag-floating-bottom-container" ref="eBottomContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-pinned-right-floating-bottom" ref="eRightBottom" role="presentation" unselectable="on"></div>\n <div class="ag-floating-bottom-full-width-container" ref="eBottomFullWidthContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-body-horizontal-scroll" ref="eHorizontalScrollBody" aria-hidden="true">\n <div class="ag-horizontal-left-spacer" ref="eHorizontalLeftSpacer"></div>\n <div class="ag-body-horizontal-scroll-viewport" ref="eBodyHorizontalScrollViewport">\n <div class="ag-body-horizontal-scroll-container" ref="eBodyHorizontalScrollContainer"></div>\n </div>\n <div class="ag-horizontal-right-spacer" ref="eHorizontalRightSpacer"></div>\n </div>\n <ag-overlay-wrapper ref="overlayWrapper"></ag-overlay-wrapper>\n </div>',Mi=function(e){function t(){var t=e.call(this,Gi)||this;return t.scrollLeft=-1,t.scrollTop=-1,t.resetLastHorizontalScrollElementDebounce=p.debounce(t.resetLastHorizontalScrollElement.bind(t),500),t}return Li(t,e),t.prototype.getVScrollPosition=function(){return{top:this.eBodyViewport.scrollTop,bottom:this.eBodyViewport.scrollTop+this.eBodyViewport.offsetHeight}},t.prototype.getHScrollPosition=function(){return{left:this.eCenterViewport.scrollLeft,right:this.eCenterViewport.scrollLeft+this.eCenterViewport.offsetWidth}},t.prototype.onRowDataChanged=function(){this.showOrHideOverlay()},t.prototype.showOrHideOverlay=function(){var e=this.paginationProxy.isEmpty(),t=this.gridOptionsWrapper.isSuppressNoRowsOverlay();this[e&&!t?"showNoRowsOverlay":"hideOverlay"]()},t.prototype.onNewColumnsLoaded=function(){this.columnController.isReady()&&!this.paginationProxy.isEmpty()&&this.hideOverlay()},t.prototype.init=function(){var e=this;this.scrollWidth=this.gridOptionsWrapper.getScrollbarWidth(),this.enableRtl=this.gridOptionsWrapper.isEnableRtl(),this.printLayout=this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_PRINT,this.gridOptionsWrapper.addLayoutElement(this.getGui()),this.gridOptionsWrapper.addLayoutElement(this.eBodyViewport),this.suppressScrollOnFloatingRow(),this.setupRowAnimationCssClass(),this.buildRowContainerComponents(),this.addEventListeners(),this.addDragListeners(),this.addScrollListener(),this.gridOptionsWrapper.isRowModelDefault()&&!this.gridOptionsWrapper.getRowData()&&this.showLoadingOverlay(),this.setCellTextSelection(this.gridOptionsWrapper.isEnableCellTextSelect()),this.setPinnedContainerSize(),this.setHeaderAndFloatingHeights(),this.disableBrowserDragging(),this.addMouseListeners(),this.addKeyboardEvents(),this.addBodyViewportListener(),this.addStopEditingWhenGridLosesFocus(),this.mockContextMenuForIPad(),this.addRowDragListener(),this.$scope&&this.addAngularApplyCheck(),this.onDisplayedColumnsWidthChanged(),this.gridApi.registerGridComp(this),this.alignedGridsService.registerGridComp(this),this.headerRootComp.registerGridComp(this),this.navigationService.registerGridComp(this),this.heightScaler.registerGridComp(this),this.autoHeightCalculator.registerGridComp(this),this.columnAnimationService.registerGridComp(this),this.autoWidthCalculator.registerGridComp(this),this.paginationAutoPageSizeService.registerGridComp(this),this.beans.registerGridComp(this),this.rowRenderer.registerGridComp(this),this.rangeController&&this.rangeController.registerGridComp(this),[this.eCenterViewport,this.eBodyViewport].forEach((function(t){var o=e.resizeObserverService.observeResize(t,e.onCenterViewportResized.bind(e));e.addDestroyFunc((function(){return o()}))}))},t.prototype.onDomLayoutChanged=function(){var e=this.gridOptionsWrapper.getDomLayout()===o.DOM_LAYOUT_PRINT;this.printLayout!==e&&(this.printLayout=e,this.setWidthsOfContainers(),this.setPinnedContainerSize())},t.prototype.onCenterViewportResized=function(){p.isVisible(this.eCenterViewport)?this.checkViewportAndScrolls():this.bodyHeight=0},t.prototype.setColumnMovingCss=function(e){this.addOrRemoveCssClass("ag-column-moving",e)},t.prototype.setCellTextSelection=function(e){void 0===e&&(e=!1),[this.eTop,this.eBodyViewport,this.eBottom].forEach((function(t){return p.addOrRemoveCssClass(t,"ag-selectable",e)}))},t.prototype.addRowDragListener=function(){var e=new Ni(this.eBodyViewport,this);this.getContext().wireBean(e),this.dragAndDropService.addDropTarget(e)},t.prototype.addStopEditingWhenGridLosesFocus=function(){var e=this;if(this.gridOptionsWrapper.isStopEditingWhenGridLosesFocus()){var t=function(t){for(var o=!1,i=t.relatedTarget;p.exists(i)&&!o;){var n=!!e.gridOptionsWrapper.getDomData(i,mo.DOM_KEY_POPUP_EDITOR_WRAPPER),r=e.eBodyViewport===i||e.eBottom===i||e.eTop===i;o=n||r,i=i.parentNode}o||e.rowRenderer.stopEditing()};this.addDestroyableEventListener(this.eBodyViewport,"focusout",t),this.addDestroyableEventListener(this.eTop,"focusout",t),this.addDestroyableEventListener(this.eBottom,"focusout",t)}},t.prototype.addAngularApplyCheck=function(){var e=this,t=!1,o=function(){t||(t=!0,window.setTimeout((function(){t=!1,e.$scope.$apply()}),0))};this.addDestroyableEventListener(this.eventService,M.EVENT_DISPLAYED_COLUMNS_CHANGED,o),this.addDestroyableEventListener(this.eventService,M.EVENT_VIRTUAL_COLUMNS_CHANGED,o)},t.prototype.disableBrowserDragging=function(){this.addGuiEventListener("dragstart",(function(e){if(e.target instanceof HTMLImageElement)return e.preventDefault(),!1}))},t.prototype.addEventListeners=function(){this.addDestroyableEventListener(this.eventService,M.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,this.onDisplayedColumnsWidthChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_PINNED_ROW_DATA_CHANGED,this.setHeaderAndFloatingHeights.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_ROW_DATA_CHANGED,this.onRowDataChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_ROW_DATA_UPDATED,this.onRowDataChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_NEW_COLUMNS_LOADED,this.onNewColumnsLoaded.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_HEADER_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_PIVOT_HEADER_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_GROUP_HEADER_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_PIVOT_GROUP_HEADER_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_FLOATING_FILTERS_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,Z.PROP_DOM_LAYOUT,this.onDomLayoutChanged.bind(this))},t.prototype.addDragListeners=function(){var e=this;this.gridOptionsWrapper.isEnableRangeSelection()&&!p.missing(this.rangeController)&&[this.eLeftContainer,this.eRightContainer,this.eCenterContainer,this.eTop,this.eBottom].forEach((function(t){var o={eElement:t,onDragStart:e.rangeController.onDragStart.bind(e.rangeController),onDragStop:e.rangeController.onDragStop.bind(e.rangeController),onDragging:e.rangeController.onDragging.bind(e.rangeController)};e.dragService.addDragSource(o),e.addDestroyFunc((function(){return e.dragService.removeDragSource(o)}))}))},t.prototype.addMouseListeners=function(){var e=this;["click","mousedown","dblclick","contextmenu","mouseover","mouseout"].forEach((function(t){var o=e.processMouseEvent.bind(e,t);e.eAllCellContainers.forEach((function(i){return e.addDestroyableEventListener(i,t,o)}))}))},t.prototype.addKeyboardEvents=function(){var e=this;["keydown","keypress"].forEach((function(t){var o=e.processKeyboardEvent.bind(e,t);e.eAllCellContainers.forEach((function(i){e.addDestroyableEventListener(i,t,o)}))}))},t.prototype.addBodyViewportListener=function(){var e=this;this.addDestroyableEventListener(this.eBodyViewport,"contextmenu",(function(t){var o=p.getTarget(t);o!==e.eBodyViewport&&o!==e.eCenterViewport||(e.onContextMenu(t,null,null,null,null),e.preventDefaultOnContextMenu(t))}))},t.prototype.getBodyClientRect=function(){if(this.eBodyViewport)return this.eBodyViewport.getBoundingClientRect()},t.prototype.getRowForEvent=function(e){for(var t=p.getTarget(e);t;){var o=this.gridOptionsWrapper.getDomData(t,Po.DOM_DATA_KEY_RENDERED_ROW);if(o)return o;t=t.parentElement}return null},t.prototype.processKeyboardEvent=function(e,t){var o=p.getCellCompForEvent(this.gridOptionsWrapper,t);if(o){var i=o.getRenderedRow().getRowNode(),n=o.getColumn(),r=o.isEditing();if(!p.isUserSuppressingKeyboardEvent(this.gridOptionsWrapper,t,i,n,r))switch(e){case"keydown":!r&&this.navigationService.handlePageScrollingKey(t)||o.onKeyDown(t),this.doClipboardOperations(t,o);break;case"keypress":o.onKeyPress(t)}if("keydown"===e){var s=o.createEvent(t,M.EVENT_CELL_KEY_DOWN);this.beans.eventService.dispatchEvent(s)}if("keypress"===e){var a=o.createEvent(t,M.EVENT_CELL_KEY_PRESS);this.beans.eventService.dispatchEvent(a)}}},t.prototype.doClipboardOperations=function(e,t){if((e.ctrlKey||e.metaKey)&&!t.isEditing()&&this.mouseEventService.isEventFromThisGrid(e))switch(e.which){case o.KEY_A:return this.onCtrlAndA(e);case o.KEY_C:return this.onCtrlAndC(e);case o.KEY_V:return this.onCtrlAndV();case o.KEY_D:return this.onCtrlAndD(e)}},t.prototype.scrollToTop=function(){this.eBodyViewport.scrollTop=0},t.prototype.processMouseEvent=function(e,t){if(this.mouseEventService.isEventFromThisGrid(t)&&!p.isStopPropagationForAgGrid(t)){var o=this.getRowForEvent(t),i=this.mouseEventService.getRenderedCellForEvent(t);"contextmenu"===e?this.handleContextMenuMouseEvent(t,null,o,i):(i&&i.onMouseEvent(e,t),o&&o.onMouseEvent(e,t)),this.preventDefaultOnContextMenu(t)}},t.prototype.mockContextMenuForIPad=function(){var e=this;p.isIOSUserAgent()&&this.eAllCellContainers.forEach((function(t){var o=new Me(t);e.addDestroyableEventListener(o,Me.EVENT_LONG_TAP,(function(t){var o=e.getRowForEvent(t.touchEvent),i=e.mouseEventService.getRenderedCellForEvent(t.touchEvent);e.handleContextMenuMouseEvent(null,t.touchEvent,o,i)})),e.addDestroyFunc((function(){return o.destroy()}))}))},t.prototype.handleContextMenuMouseEvent=function(e,t,o,i){var n=o?o.getRowNode():null,r=i?i.getColumn():null,s=null;if(r){var a=e||t;i.dispatchCellContextMenuEvent(a),s=this.valueService.getValue(r,n)}this.onContextMenu(e,t,n,r,s)},t.prototype.onContextMenu=function(e,t,o,i,n){if((this.gridOptionsWrapper.isAllowContextMenuWithControlKey()||!e||!e.ctrlKey&&!e.metaKey)&&this.contextMenuFactory&&!this.gridOptionsWrapper.isSuppressContextMenu()){var r=e||t.touches[0];this.contextMenuFactory.showMenu(o,i,n,r),(e||t).preventDefault()}},t.prototype.preventDefaultOnContextMenu=function(e){var t=this.gridOptionsWrapper,o=e.which;(t.isPreventDefaultOnContextMenu()||t.isSuppressMiddleClickScrolls()&&2===o)&&e.preventDefault()},t.prototype.onCtrlAndA=function(e){var t=this.columnController,i=this.pinnedRowModel,n=this.paginationProxy,r=this.rangeController,s=o.PINNED_BOTTOM,a=o.PINNED_TOP;if(r&&n.isRowsToRender()){var l=[i.isEmpty(a),i.isEmpty(s)],u=l[0]?null:a,c=void 0,d=void 0;l[1]?(c=null,d=this.paginationProxy.getRowCount()-1):(c=s,d=i.getPinnedBottomRowData().length-1);var h=t.getAllDisplayedColumns();if(p.missingOrEmpty(h))return;r.setCellRange({rowStartIndex:0,rowStartPinned:u,rowEndIndex:d,rowEndPinned:c,columnStart:h[0],columnEnd:p.last(h)})}e.preventDefault()},t.prototype.onCtrlAndC=function(e){if(this.clipboardService&&!this.gridOptionsWrapper.isEnableCellTextSelection()){var t=this.focusedCellController.getFocusedCell();this.clipboardService.copyToClipboard(),e.preventDefault(),t&&this.focusedCellController.setFocusedCell(t.rowIndex,t.column,t.rowPinned,!0)}},t.prototype.onCtrlAndV=function(){P.isRegistered(R.ClipboardModule)&&this.clipboardService.pasteFromClipboard()},t.prototype.onCtrlAndD=function(e){P.isRegistered(R.ClipboardModule)&&(this.clipboardService.copyRangeDown(),e.preventDefault())},t.prototype.ensureIndexVisible=function(e,t){if(!this.printLayout){var o=this.paginationProxy.getRowCount();if("number"!=typeof e||e<0||e>=o)console.warn("invalid row index for ensureIndexVisible: "+e);else{this.paginationProxy.goToPageWithIndex(e);var i,n=this.paginationProxy.getRow(e);do{var r=n.rowTop,s=n.rowHeight,a=this.paginationProxy.getPixelOffset(),l=n.rowTop-a,p=l+n.rowHeight,u=this.getVScrollPosition(),c=this.heightScaler.getOffset(),d=u.top+c,h=u.bottom+c,g=h-d,f=this.heightScaler.getScrollPositionForPixel(l),y=this.heightScaler.getScrollPositionForPixel(p-g),m=Math.min((f+y)/2,l),v=null;"top"===t?v=f:"bottom"===t?v=y:"middle"===t?v=m:d>l?v=f:h<p&&(v=y),null!==v&&(this.eBodyViewport.scrollTop=v,this.rowRenderer.redrawAfterScroll()),i=r!==n.rowTop||s!==n.rowHeight}while(i);this.animationFrameService.flushAllFrames()}}},t.prototype.getCenterWidth=function(){return this.eCenterViewport.clientWidth},t.prototype.isVerticalScrollShowing=function(){var e=this.gridOptionsWrapper.isAlwaysShowVerticalScroll();return p.addOrRemoveCssClass(this.eBodyViewport,"ag-force-vertical-scroll",e),e||p.isVerticalScrollShowing(this.eBodyViewport)},t.prototype.isHorizontalScrollShowing=function(){return p.isHorizontalScrollShowing(this.eCenterViewport)},t.prototype.checkViewportAndScrolls=function(){this.updateScrollVisibleService(),this.checkBodyHeight(),this.onHorizontalViewportChanged(),this.setPinnedContainerSize(),this.scrollLeft!==this.getCenterViewportScrollLeft()&&this.onBodyHorizontalScroll(this.eCenterViewport)},t.prototype.updateScrollVisibleService=function(){this.updateScrollVisibleServiceImpl(),setTimeout(this.updateScrollVisibleServiceImpl.bind(this),500)},t.prototype.updateScrollVisibleServiceImpl=function(){var e={horizontalScrollShowing:!1,verticalScrollShowing:!1};e.verticalScrollShowing=this.isVerticalScrollShowing(),e.horizontalScrollShowing=this.isHorizontalScrollShowing(),this.scrollVisibleService.setScrollsVisible(e),this.setHorizontalScrollVisible(e.horizontalScrollShowing),this.setVerticalScrollPaddingVisible(e.verticalScrollShowing)},t.prototype.setHorizontalScrollVisible=function(e){var t=this.gridOptionsWrapper.isSuppressHorizontalScroll(),o=e&&this.gridOptionsWrapper.getScrollbarWidth()||0,i=t?0:o,n=p.isBrowserIE()&&e;this.eCenterViewport.style.height="calc(100% + "+o+"px)",p.setFixedHeight(this.eHorizontalScrollBody,i),p.setFixedHeight(this.eBodyHorizontalScrollViewport,i+(n?1:0)),p.setFixedHeight(this.eBodyHorizontalScrollContainer,i)},t.prototype.setVerticalScrollPaddingVisible=function(e){var t=e?"scroll":"hidden";this.eTop.style.overflowY=this.eBottom.style.overflowY=t,this.setFakeHScrollSpacerWidths()},t.prototype.updateRowCount=function(){var e=(this.headerRootComp.getHeaderRowCount()+this.paginationProxy.getRowCount()).toString();this.getGui().setAttribute("aria-rowcount",e)},t.prototype.ensureColumnVisible=function(e){var t=this.columnController.getGridColumn(e);if(t)if(t.isPinned())console.warn("calling ensureIndexVisible on a "+t.getPinned()+" pinned column doesn't make sense for column "+t.getColId());else if(this.columnController.isColumnDisplayed(t)){var o,i,n=t.getLeft(),r=n+t.getActualWidth(),s=this.eCenterViewport.clientWidth,a=this.getCenterViewportScrollLeft(),l=this.columnController.getBodyContainerWidth();this.enableRtl?(o=l-a-s,i=l-a):(o=a,i=s+a);var p=o>n,u=i<r,c=s<t.getActualWidth(),d=p||c,h=u,g=this.getCenterViewportScrollLeft();(d||h)&&(g=this.enableRtl?d?l-s-n:l-r:d?n:r-s,this.setCenterViewportScrollLeft(g)),this.onHorizontalViewportChanged(),this.animationFrameService.flushAllFrames()}else console.warn("column is not currently visible")},t.prototype.showLoadingOverlay=function(){this.gridOptionsWrapper.isSuppressLoadingOverlay()||this.overlayWrapper.showLoadingOverlay()},t.prototype.showNoRowsOverlay=function(){this.gridOptionsWrapper.isSuppressNoRowsOverlay()||this.overlayWrapper.showNoRowsOverlay()},t.prototype.hideOverlay=function(){this.overlayWrapper.hideOverlay()},t.prototype.sizeColumnsToFit=function(e){var t=this,o=this.eBodyViewport.clientWidth;o>0?this.columnController.sizeColumnsToFit(o,"sizeColumnsToFit"):void 0===e?window.setTimeout((function(){t.sizeColumnsToFit(100)}),0):100===e?window.setTimeout((function(){t.sizeColumnsToFit(500)}),100):500===e?window.setTimeout((function(){t.sizeColumnsToFit(-1)}),500):console.warn("ag-Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen?")},t.prototype.getCenterContainer=function(){return this.eCenterContainer},t.prototype.getDropTargetBodyContainers=function(){return[this.eCenterViewport,this.eTopViewport,this.eBottomViewport]},t.prototype.getDropTargetLeftContainers=function(){return[this.eLeftContainer,this.eLeftBottom,this.eLeftTop]},t.prototype.getDropTargetRightContainers=function(){return[this.eRightContainer,this.eRightBottom,this.eRightTop]},t.prototype.buildRowContainerComponents=function(){var e=this;this.eAllCellContainers=[this.eLeftContainer,this.eRightContainer,this.eCenterContainer,this.eTop,this.eBottom,this.eFullWidthContainer],this.rowContainerComponents={body:new _i({eContainer:this.eCenterContainer,eWrapper:this.eCenterColsClipper,eViewport:this.eBodyViewport}),fullWidth:new _i({eContainer:this.eFullWidthContainer}),pinnedLeft:new _i({eContainer:this.eLeftContainer}),pinnedRight:new _i({eContainer:this.eRightContainer}),floatingTop:new _i({eContainer:this.eTopContainer}),floatingTopPinnedLeft:new _i({eContainer:this.eLeftTop}),floatingTopPinnedRight:new _i({eContainer:this.eRightTop}),floatingTopFullWidth:new _i({eContainer:this.eTopFullWidthContainer,hideWhenNoChildren:!0}),floatingBottom:new _i({eContainer:this.eBottomContainer}),floatingBottomPinnedLeft:new _i({eContainer:this.eLeftBottom}),floatingBottomPinnedRight:new _i({eContainer:this.eRightBottom}),floatingBottomFullWith:new _i({eContainer:this.eBottomFullWidthContainer,hideWhenNoChildren:!0})},p.iterateObject(this.rowContainerComponents,(function(t,o){o&&e.getContext().wireBean(o)}))},t.prototype.setupRowAnimationCssClass=function(){var e=this,t=function(){var t=e.gridOptionsWrapper.isAnimateRows()&&!e.heightScaler.isScaling();p.addOrRemoveCssClass(e.eBodyViewport,"ag-row-animation",t),p.addOrRemoveCssClass(e.eBodyViewport,"ag-row-no-animation",!t)};t(),this.addDestroyableEventListener(this.eventService,M.EVENT_HEIGHT_SCALE_CHANGED,t)},t.prototype.suppressScrollOnFloatingRow=function(){var e=this;this.addDestroyableEventListener(this.eTopViewport,"scroll",(function(){return e.eTopViewport.scrollLeft=0})),this.addDestroyableEventListener(this.eBottomViewport,"scroll",(function(){return e.eTopViewport.scrollLeft=0}))},t.prototype.getRowContainers=function(){return this.rowContainerComponents},t.prototype.getFloatingTopBottom=function(){return[this.eTop,this.eBottom]},t.prototype.onDisplayedColumnsChanged=function(){this.setPinnedContainerSize(),this.setHeaderAndFloatingHeights(),this.onHorizontalViewportChanged(),this.updateScrollVisibleService()},t.prototype.onDisplayedColumnsWidthChanged=function(){this.setWidthsOfContainers(),this.onHorizontalViewportChanged(),this.updateScrollVisibleService(),this.enableRtl&&this.horizontallyScrollHeaderCenterAndFloatingCenter()},t.prototype.setWidthsOfContainers=function(){this.setCenterWidth(),this.setPinnedContainerSize()},t.prototype.setCenterWidth=function(){var e=this.columnController.getBodyContainerWidth();this.printLayout&&(e+=this.columnController.getPinnedLeftContainerWidth()+this.columnController.getPinnedRightContainerWidth());this.headerRootComp.setHeaderContainerWidth(e);var t=e+"px";this.eCenterContainer.style.width=t,this.eBottomContainer.style.width=t,this.eTopContainer.style.width=t,this.printLayout||(this.eBodyHorizontalScrollContainer.style.width=t)},t.prototype.setPinnedLeftWidth=function(){var e=this,t=this.pinningLeft,o=this.columnController.getPinnedLeftContainerWidth(),i=this.pinningLeft=!this.printLayout&&o>0,n=[this.eLeftContainer,this.eLeftTop,this.eLeftBottom];t!==i&&this.headerRootComp.setLeftVisible(i),n.forEach((function(t){return p.setDisplayed(t,e.pinningLeft)})),i&&n.forEach((function(e){return p.setFixedWidth(e,o)}))},t.prototype.setPinnedRightWidth=function(){var e=this.pinningRight,t=this.columnController.getPinnedRightContainerWidth(),o=this.pinningRight=!this.printLayout&&t>0,i=[this.eRightContainer,this.eRightTop,this.eRightBottom];e!==o&&this.headerRootComp.setRightVisible(o),i.forEach((function(e){return p.setDisplayed(e,o)})),o&&i.forEach((function(e){return p.setFixedWidth(e,t)}))},t.prototype.setPinnedContainerSize=function(){this.setPinnedLeftWidth(),this.setPinnedRightWidth(),this.setFakeHScrollSpacerWidths()},t.prototype.setFakeHScrollSpacerWidths=function(){var e=this.columnController.getPinnedRightContainerWidth();!this.enableRtl&&this.isVerticalScrollShowing()&&(e+=this.scrollWidth),p.setFixedWidth(this.eHorizontalRightSpacer,e),p.addOrRemoveCssClass(this.eHorizontalRightSpacer,"ag-scroller-corner",e<=this.scrollWidth);var t=this.columnController.getPinnedLeftContainerWidth();this.enableRtl&&this.isVerticalScrollShowing()&&(t+=this.scrollWidth),p.setFixedWidth(this.eHorizontalLeftSpacer,t),p.addOrRemoveCssClass(this.eHorizontalLeftSpacer,"ag-scroller-corner",t<=this.scrollWidth)},t.prototype.checkBodyHeight=function(){var e=this.eBodyViewport.clientHeight;if(this.bodyHeight!==e){this.bodyHeight=e;var t={type:M.EVENT_BODY_HEIGHT_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)}},t.prototype.setHeaderAndFloatingHeights=function(){var e,t,o,i=this,n=i.columnController,r=i.gridOptionsWrapper,s=i.pinnedRowModel,a=i.eTop,l=i.eBottom,p=0,u=n.getHeaderRowCount();n.isPivotMode()?(p=0,t=r.getPivotGroupHeaderHeight(),o=r.getPivotHeaderHeight()):(r.isFloatingFilter()&&u++,p=r.isFloatingFilter()?1:0,t=r.getGroupHeaderHeight(),o=r.getHeaderHeight());var c=u-(1+p);e=p*r.getFloatingFiltersHeight(),e+=c*t,e+=o,this.headerRootComp.setHeight(e);var d=s.getPinnedTopTotalHeight();d&&(d+=1);var h=s.getPinnedBottomTotalHeight();h&&(h+=1);var g=d+"px",f=h+"px";a.style.minHeight=g,a.style.height=g,a.style.display=d?"inherit":"none",l.style.minHeight=f,l.style.height=f,l.style.display=h?"inherit":"none",this.checkBodyHeight()},t.prototype.getBodyHeight=function(){return this.bodyHeight},t.prototype.setHorizontalScrollPosition=function(e){this.eCenterViewport.scrollLeft=e,this.doHorizontalScroll(e)},t.prototype.setVerticalScrollPosition=function(e){this.eBodyViewport.scrollTop=e},t.prototype.scrollHorizontally=function(e){var t=this.eCenterViewport.scrollLeft;return this.setHorizontalScrollPosition(t+e),this.eCenterViewport.scrollLeft-t},t.prototype.scrollVertically=function(e){var t=this.eBodyViewport.scrollTop;return this.setVerticalScrollPosition(t+e),this.eBodyViewport.scrollTop-t},t.prototype.addScrollListener=function(){this.addDestroyableEventListener(this.eCenterViewport,"scroll",this.onCenterViewportScroll.bind(this)),this.addDestroyableEventListener(this.eBodyHorizontalScrollViewport,"scroll",this.onFakeHorizontalScroll.bind(this)),this.addDestroyableEventListener(this.eBodyViewport,"scroll",this.onVerticalScroll.bind(this))},t.prototype.onVerticalScroll=function(){var e=this.eBodyViewport.scrollTop;this.animationFrameService.setScrollTop(e),this.scrollTop=e,this.redrawRowsAfterScroll()},t.prototype.isControllingScroll=function(e){return this.lastHorizontalScrollElement?e===this.lastHorizontalScrollElement:(this.lastHorizontalScrollElement=e,!0)},t.prototype.onFakeHorizontalScroll=function(){this.isControllingScroll(this.eBodyHorizontalScrollViewport)&&this.onBodyHorizontalScroll(this.eBodyHorizontalScrollViewport)},t.prototype.onCenterViewportScroll=function(){this.isControllingScroll(this.eCenterViewport)&&this.onBodyHorizontalScroll(this.eCenterViewport)},t.prototype.onBodyHorizontalScroll=function(e){var t=this.eCenterViewport,o=t.scrollWidth,i=t.clientWidth,n=Math.floor(p.getScrollLeft(e,this.enableRtl));n<0||n+i>o||(this.doHorizontalScroll(n),this.resetLastHorizontalScrollElementDebounce())},t.prototype.resetLastHorizontalScrollElement=function(){this.lastHorizontalScrollElement=null},t.prototype.doHorizontalScroll=function(e){this.scrollLeft=e;var t={type:M.EVENT_BODY_SCROLL,api:this.gridApi,columnApi:this.columnApi,direction:"horizontal",left:this.scrollLeft,top:this.scrollTop};this.eventService.dispatchEvent(t),this.horizontallyScrollHeaderCenterAndFloatingCenter(e),this.onHorizontalViewportChanged()},t.prototype.redrawRowsAfterScroll=function(){var e={type:M.EVENT_BODY_SCROLL,direction:"vertical",api:this.gridApi,columnApi:this.columnApi,left:this.scrollLeft,top:this.scrollTop};this.eventService.dispatchEvent(e)},t.prototype.onHorizontalViewportChanged=function(){var e=this.eCenterViewport.clientWidth,t=this.getCenterViewportScrollLeft();this.columnController.setVirtualViewportPosition(e,t)},t.prototype.getCenterViewportScrollLeft=function(){return p.getScrollLeft(this.eCenterViewport,this.enableRtl)},t.prototype.setCenterViewportScrollLeft=function(e){p.setScrollLeft(this.eCenterViewport,e,this.enableRtl)},t.prototype.horizontallyScrollHeaderCenterAndFloatingCenter=function(e){void 0===e&&(e=this.getCenterViewportScrollLeft());var t=this.enableRtl?e:-e,o=this.eCenterViewport,i=o.clientWidth,n=o.scrollWidth;if(!(Math.abs(t)+i>n||this.enableRtl&&t<0||!this.enableRtl&&t>0)){this.headerRootComp.setHorizontalScroll(t),this.eBottomContainer.style.transform="translateX("+t+"px)",this.eTopContainer.style.transform="translateX("+t+"px)";var r=this.lastHorizontalScrollElement===this.eCenterViewport?this.eBodyHorizontalScrollViewport:this.eCenterViewport;p.setScrollLeft(r,e,this.enableRtl)}},t.prototype.addScrollEventListener=function(e){this.eBodyViewport.addEventListener("scroll",e)},t.prototype.removeScrollEventListener=function(e){this.eBodyViewport.removeEventListener("scroll",e)},Ii([m("alignedGridsService")],t.prototype,"alignedGridsService",void 0),Ii([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Ii([m("columnController")],t.prototype,"columnController",void 0),Ii([m("rowRenderer")],t.prototype,"rowRenderer",void 0),Ii([m("pinnedRowModel")],t.prototype,"pinnedRowModel",void 0),Ii([m("eventService")],t.prototype,"eventService",void 0),Ii([m("animationFrameService")],t.prototype,"animationFrameService",void 0),Ii([m("navigationService")],t.prototype,"navigationService",void 0),Ii([m("autoHeightCalculator")],t.prototype,"autoHeightCalculator",void 0),Ii([m("columnAnimationService")],t.prototype,"columnAnimationService",void 0),Ii([m("autoWidthCalculator")],t.prototype,"autoWidthCalculator",void 0),Ii([m("paginationAutoPageSizeService")],t.prototype,"paginationAutoPageSizeService",void 0),Ii([m("beans")],t.prototype,"beans",void 0),Ii([m("paginationProxy")],t.prototype,"paginationProxy",void 0),Ii([m("columnApi")],t.prototype,"columnApi",void 0),Ii([m("gridApi")],t.prototype,"gridApi",void 0),Ii([m("dragService")],t.prototype,"dragService",void 0),Ii([m("mouseEventService")],t.prototype,"mouseEventService",void 0),Ii([m("focusedCellController")],t.prototype,"focusedCellController",void 0),Ii([m("$scope")],t.prototype,"$scope",void 0),Ii([m("scrollVisibleService")],t.prototype,"scrollVisibleService",void 0),Ii([m("valueService")],t.prototype,"valueService",void 0),Ii([m("dragAndDropService")],t.prototype,"dragAndDropService",void 0),Ii([m("maxDivHeightScaler")],t.prototype,"heightScaler",void 0),Ii([m("resizeObserverService")],t.prototype,"resizeObserverService",void 0),Ii([v("rangeController")],t.prototype,"rangeController",void 0),Ii([v("contextMenuFactory")],t.prototype,"contextMenuFactory",void 0),Ii([v("clipboardService")],t.prototype,"clipboardService",void 0),Ii([fe("eBodyViewport")],t.prototype,"eBodyViewport",void 0),Ii([fe("eCenterContainer")],t.prototype,"eCenterContainer",void 0),Ii([fe("eCenterViewport")],t.prototype,"eCenterViewport",void 0),Ii([fe("eLeftContainer")],t.prototype,"eLeftContainer",void 0),Ii([fe("eRightContainer")],t.prototype,"eRightContainer",void 0),Ii([fe("eCenterColsClipper")],t.prototype,"eCenterColsClipper",void 0),Ii([fe("eHorizontalScrollBody")],t.prototype,"eHorizontalScrollBody",void 0),Ii([fe("eHorizontalLeftSpacer")],t.prototype,"eHorizontalLeftSpacer",void 0),Ii([fe("eHorizontalRightSpacer")],t.prototype,"eHorizontalRightSpacer",void 0),Ii([fe("eBodyHorizontalScrollViewport")],t.prototype,"eBodyHorizontalScrollViewport",void 0),Ii([fe("eBodyHorizontalScrollContainer")],t.prototype,"eBodyHorizontalScrollContainer",void 0),Ii([fe("eFullWidthContainer")],t.prototype,"eFullWidthContainer",void 0),Ii([fe("eTop")],t.prototype,"eTop",void 0),Ii([fe("eLeftTop")],t.prototype,"eLeftTop",void 0),Ii([fe("eRightTop")],t.prototype,"eRightTop",void 0),Ii([fe("eTopContainer")],t.prototype,"eTopContainer",void 0),Ii([fe("eTopViewport")],t.prototype,"eTopViewport",void 0),Ii([fe("eTopFullWidthContainer")],t.prototype,"eTopFullWidthContainer",void 0),Ii([fe("eBottom")],t.prototype,"eBottom",void 0),Ii([fe("eLeftBottom")],t.prototype,"eLeftBottom",void 0),Ii([fe("eRightBottom")],t.prototype,"eRightBottom",void 0),Ii([fe("eBottomContainer")],t.prototype,"eBottomContainer",void 0),Ii([fe("eBottomViewport")],t.prototype,"eBottomViewport",void 0),Ii([fe("eBottomFullWidthContainer")],t.prototype,"eBottomFullWidthContainer",void 0),Ii([fe("headerRoot")],t.prototype,"headerRootComp",void 0),Ii([fe("overlayWrapper")],t.prototype,"overlayWrapper",void 0),Ii([g],t.prototype,"init",null),t}(pe),xi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Vi=function(){function e(){this.detailGridInfoMap={}}return e.prototype.registerGridComp=function(e){this.gridPanel=e},e.prototype.registerGridCore=function(e){this.gridCore=e},e.prototype.registerHeaderRootComp=function(e){this.headerRootComp=e},e.prototype.init=function(){switch(this.rowModel.getType()){case o.ROW_MODEL_TYPE_CLIENT_SIDE:this.clientSideRowModel=this.rowModel;break;case o.ROW_MODEL_TYPE_INFINITE:this.infiniteRowModel=this.rowModel;break;case o.ROW_MODEL_TYPE_SERVER_SIDE:this.serverSideRowModel=this.rowModel}},e.prototype.__getAlignedGridService=function(){return this.alignedGridsService},e.prototype.addDetailGridInfo=function(e,t){this.detailGridInfoMap[e]=t},e.prototype.removeDetailGridInfo=function(e){this.detailGridInfoMap[e]=void 0},e.prototype.getDetailGridInfo=function(e){return this.detailGridInfoMap[e]},e.prototype.forEachDetailGridInfo=function(e){var t=0;p.iterateObject(this.detailGridInfoMap,(function(o,i){p.exists(i)&&(e(i,t),t++)}))},e.prototype.getDataAsCsv=function(e){if(P.assertRegistered(R.CsvExportModule,"api.getDataAsCsv"))return this.csvCreator.getDataAsCsv(e)},e.prototype.exportDataAsCsv=function(e){P.assertRegistered(R.CsvExportModule,"api.exportDataAsCSv")&&this.csvCreator.exportDataAsCsv(e)},e.prototype.getDataAsExcel=function(e){if(P.assertRegistered(R.ExcelExportModule,"api.getDataAsExcel"))return this.excelCreator.getDataAsExcelXml(e)},e.prototype.exportDataAsExcel=function(e){P.assertRegistered(R.ExcelExportModule,"api.exportDataAsExcel")&&this.excelCreator.exportDataAsExcel(e)},e.prototype.setEnterpriseDatasource=function(e){console.warn("ag-grid: since version 18.x, api.setEnterpriseDatasource() should be replaced with api.setServerSideDatasource()"),this.setServerSideDatasource(e)},e.prototype.setServerSideDatasource=function(e){this.gridOptionsWrapper.isRowModelServerSide()?this.rowModel.setDatasource(e):console.warn("ag-Grid: you can only use an enterprise datasource when gridOptions.rowModelType is '"+o.ROW_MODEL_TYPE_SERVER_SIDE+"'")},e.prototype.setDatasource=function(e){this.gridOptionsWrapper.isRowModelInfinite()?this.rowModel.setDatasource(e):console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '"+o.ROW_MODEL_TYPE_INFINITE+"'")},e.prototype.setViewportDatasource=function(e){this.gridOptionsWrapper.isRowModelViewport()?this.rowModel.setViewportDatasource(e):console.warn("ag-Grid: you can only use a viewport datasource when gridOptions.rowModelType is '"+o.ROW_MODEL_TYPE_VIEWPORT+"'")},e.prototype.setRowData=function(e){if(this.gridOptionsWrapper.isRowModelDefault())if(this.gridOptionsWrapper.isDeltaRowDataMode()){var t=this.immutableService.createTransactionForRowData(e),o=t[0],i=t[1];this.clientSideRowModel.updateRowData(o,i),this.rowRenderer.refreshFullWidthRows()}else this.selectionController.reset(),this.clientSideRowModel.setRowData(e);else console.warn("cannot call setRowData unless using normal row model")},e.prototype.setFloatingTopRowData=function(e){console.warn("ag-Grid: since v12, api.setFloatingTopRowData() is now api.setPinnedTopRowData()"),this.setPinnedTopRowData(e)},e.prototype.setFloatingBottomRowData=function(e){console.warn("ag-Grid: since v12, api.setFloatingBottomRowData() is now api.setPinnedBottomRowData()"),this.setPinnedBottomRowData(e)},e.prototype.getFloatingTopRowCount=function(){return console.warn("ag-Grid: since v12, api.getFloatingTopRowCount() is now api.getPinnedTopRowCount()"),this.getPinnedTopRowCount()},e.prototype.getFloatingBottomRowCount=function(){return console.warn("ag-Grid: since v12, api.getFloatingBottomRowCount() is now api.getPinnedBottomRowCount()"),this.getPinnedBottomRowCount()},e.prototype.getFloatingTopRow=function(e){return console.warn("ag-Grid: since v12, api.getFloatingTopRow() is now api.getPinnedTopRow()"),this.getPinnedTopRow(e)},e.prototype.getFloatingBottomRow=function(e){return console.warn("ag-Grid: since v12, api.getFloatingBottomRow() is now api.getPinnedBottomRow()"),this.getPinnedBottomRow(e)},e.prototype.setPinnedTopRowData=function(e){this.pinnedRowModel.setPinnedTopRowData(e)},e.prototype.setPinnedBottomRowData=function(e){this.pinnedRowModel.setPinnedBottomRowData(e)},e.prototype.getPinnedTopRowCount=function(){return this.pinnedRowModel.getPinnedTopRowCount()},e.prototype.getPinnedBottomRowCount=function(){return this.pinnedRowModel.getPinnedBottomRowCount()},e.prototype.getPinnedTopRow=function(e){return this.pinnedRowModel.getPinnedTopRow(e)},e.prototype.getPinnedBottomRow=function(e){return this.pinnedRowModel.getPinnedBottomRow(e)},e.prototype.setColumnDefs=function(e,t){void 0===t&&(t="api"),this.columnController.setColumnDefs(e,t)},e.prototype.expireValueCache=function(){this.valueCache.expire()},e.prototype.getVerticalPixelRange=function(){return this.gridPanel.getVScrollPosition()},e.prototype.getHorizontalPixelRange=function(){return this.gridPanel.getHScrollPosition()},e.prototype.setAlwaysShowVerticalScroll=function(e){this.gridOptionsWrapper.setProperty("alwaysShowVerticalScroll",e)},e.prototype.refreshToolPanel=function(){this.gridCore.refreshSideBar()},e.prototype.refreshCells=function(e){void 0===e&&(e={}),Array.isArray(e)?console.warn("since ag-Grid v11.1, refreshCells() now takes parameters, please see the documentation."):this.rowRenderer.refreshCells(e)},e.prototype.flashCells=function(e){void 0===e&&(e={}),this.rowRenderer.flashCells(e)},e.prototype.redrawRows=function(e){void 0===e&&(e={}),e&&e.rowNodes?this.rowRenderer.redrawRows(e.rowNodes):this.rowRenderer.redrawAfterModelUpdate()},e.prototype.timeFullRedraw=function(e){void 0===e&&(e=1);var t=0,o=0,i=0,n=this;!function r(){var s=(new Date).getTime();n.rowRenderer.redrawAfterModelUpdate();var a=(new Date).getTime();window.setTimeout((function(){var n=(new Date).getTime(),l=a-s,p=n-a;console.log("duration: processing = "+l+"ms, reflow = "+p+"ms"),o+=l,i+=p,++t<e?window.setTimeout(r,1e3):(console.log("tests complete. iteration count = "+t),console.log("average processing = "+o/t+"ms"),console.log("average reflow = "+i/t+"ms"))}),0)}()},e.prototype.refreshView=function(){console.warn("ag-Grid: since v11.1, refreshView() is deprecated, please call refreshCells() or redrawRows() instead"),this.redrawRows()},e.prototype.refreshRows=function(e){console.warn("since ag-Grid v11.1, refreshRows() is deprecated, please use refreshCells({rowNodes: rows}) or redrawRows({rowNodes: rows}) instead"),this.refreshCells({rowNodes:e})},e.prototype.rowDataChanged=function(e){console.warn("ag-Grid: rowDataChanged is deprecated, either call refreshView() to refresh everything, or call rowNode.setRowData(newData) to set value on a particular node"),this.redrawRows()},e.prototype.softRefreshView=function(){console.error("ag-Grid: since v16, softRefreshView() is no longer supported. Please check the documentation on how to refresh.")},e.prototype.refreshGroupRows=function(){console.warn("ag-Grid: since v11.1, refreshGroupRows() is no longer supported, call refreshCells() instead. Because refreshCells() now does dirty checking, it will only refresh cells that have changed, so it should not be necessary to only refresh the group rows."),this.refreshCells()},e.prototype.setFunctionsReadOnly=function(e){this.gridOptionsWrapper.setProperty("functionsReadOnly",e)},e.prototype.refreshHeader=function(){this.headerRootComp.refreshHeader(),this.gridPanel.setHeaderAndFloatingHeights()},e.prototype.isAnyFilterPresent=function(){return this.filterManager.isAnyFilterPresent()},e.prototype.isAdvancedFilterPresent=function(){return console.warn("ag-Grid: isAdvancedFilterPresent() is deprecated, please use isColumnFilterPresent()"),this.isColumnFilterPresent()},e.prototype.isColumnFilterPresent=function(){return this.filterManager.isAdvancedFilterPresent()},e.prototype.isQuickFilterPresent=function(){return this.filterManager.isQuickFilterPresent()},e.prototype.getModel=function(){return this.rowModel},e.prototype.setRowNodeExpanded=function(e,t){e&&e.setExpanded(t)},e.prototype.onGroupExpandedOrCollapsed=function(e){p.missing(this.clientSideRowModel)&&console.warn("ag-Grid: cannot call onGroupExpandedOrCollapsed unless using normal row model"),p.exists(e)&&console.warn("ag-Grid: api.onGroupExpandedOrCollapsed - refreshFromIndex parameter is no longer used, the grid will refresh all rows"),this.clientSideRowModel.refreshModel({step:o.STEP_MAP})},e.prototype.refreshInMemoryRowModel=function(e){console.warn("ag-grid: since version 18.x, api.refreshInMemoryRowModel() should be replaced with api.refreshClientSideRowModel()"),this.refreshClientSideRowModel(e)},e.prototype.refreshClientSideRowModel=function(e){p.missing(this.clientSideRowModel)&&console.warn("cannot call refreshClientSideRowModel unless using normal row model");var t=o.STEP_EVERYTHING,i={group:o.STEP_EVERYTHING,filter:o.STEP_FILTER,map:o.STEP_MAP,aggregate:o.STEP_AGGREGATE,sort:o.STEP_SORT,pivot:o.STEP_PIVOT};if(p.exists(e)&&(t=i[e]),p.missing(t))console.error("ag-Grid: invalid step "+e+", available steps are "+Object.keys(i).join(", "));else{var n={step:t,keepRenderedRows:!0,animate:!0,keepEditingRows:!0};this.clientSideRowModel.refreshModel(n)}},e.prototype.isAnimationFrameQueueEmpty=function(){return this.animationFrameService.isQueueEmpty()},e.prototype.getRowNode=function(e){return this.rowModel.getRowNode(e)},e.prototype.expandAll=function(){p.missing(this.clientSideRowModel)?console.warn("ag-Grid: cannot call expandAll unless using normal row model"):this.clientSideRowModel.expandOrCollapseAll(!0)},e.prototype.collapseAll=function(){p.missing(this.clientSideRowModel)?console.warn("ag-Grid: cannot call collapseAll unless using normal row model"):this.clientSideRowModel.expandOrCollapseAll(!1)},e.prototype.getToolPanelInstance=function(e){return this.gridCore.getToolPanelInstance(e)},e.prototype.addVirtualRowListener=function(e,t,o){"string"!=typeof e&&console.warn("ag-Grid: addVirtualRowListener is deprecated, please use addRenderedRowListener."),this.addRenderedRowListener(e,t,o)},e.prototype.addRenderedRowListener=function(e,t,o){"virtualRowSelected"===e&&console.warn("ag-Grid: event virtualRowSelected is deprecated, to register for individual row\n selection events, add a listener directly to the row node."),this.rowRenderer.addRenderedRowListener(e,t,o)},e.prototype.setQuickFilter=function(e){this.filterManager.setQuickFilter(e)},e.prototype.selectIndex=function(e,t,o){console.warn("ag-Grid: do not use api for selection, call node.setSelected(value) instead"),o&&console.warn("ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it"),this.selectionController.selectIndex(e,t)},e.prototype.deselectIndex=function(e,t){void 0===t&&(t=!1),console.warn("ag-Grid: do not use api for selection, call node.setSelected(value) instead"),t&&console.warn("ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it"),this.selectionController.deselectIndex(e)},e.prototype.selectNode=function(e,t,o){void 0===t&&(t=!1),void 0===o&&(o=!1),console.warn("ag-Grid: API for selection is deprecated, call node.setSelected(value) instead"),o&&console.warn("ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it"),e.setSelectedParams({newValue:!0,clearSelection:!t})},e.prototype.deselectNode=function(e,t){void 0===t&&(t=!1),console.warn("ag-Grid: API for selection is deprecated, call node.setSelected(value) instead"),t&&console.warn("ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it"),e.setSelectedParams({newValue:!1})},e.prototype.selectAll=function(){this.selectionController.selectAllRowNodes()},e.prototype.deselectAll=function(){this.selectionController.deselectAllRowNodes()},e.prototype.selectAllFiltered=function(){this.selectionController.selectAllRowNodes(!0)},e.prototype.deselectAllFiltered=function(){this.selectionController.deselectAllRowNodes(!0)},e.prototype.recomputeAggregates=function(){p.missing(this.clientSideRowModel)&&console.warn("cannot call recomputeAggregates unless using normal row model"),console.warn("recomputeAggregates is deprecated, please call api.refreshClientSideRowModel('aggregate') instead"),this.clientSideRowModel.refreshModel({step:o.STEP_AGGREGATE})},e.prototype.sizeColumnsToFit=function(){this.gridPanel.sizeColumnsToFit()},e.prototype.showLoadingOverlay=function(){this.gridPanel.showLoadingOverlay()},e.prototype.showNoRowsOverlay=function(){this.gridPanel.showNoRowsOverlay()},e.prototype.hideOverlay=function(){this.gridPanel.hideOverlay()},e.prototype.isNodeSelected=function(e){return console.warn("ag-Grid: no need to call api.isNodeSelected(), just call node.isSelected() instead"),e.isSelected()},e.prototype.getSelectedNodesById=function(){return console.error("ag-Grid: since version 3.4, getSelectedNodesById no longer exists, use getSelectedNodes() instead"),null},e.prototype.getSelectedNodes=function(){return this.selectionController.getSelectedNodes()},e.prototype.getSelectedRows=function(){return this.selectionController.getSelectedRows()},e.prototype.getBestCostNodeSelection=function(){return this.selectionController.getBestCostNodeSelection()},e.prototype.getRenderedNodes=function(){return this.rowRenderer.getRenderedNodes()},e.prototype.ensureColIndexVisible=function(e){console.warn("ag-Grid: ensureColIndexVisible(index) no longer supported, use ensureColumnVisible(colKey) instead.")},e.prototype.ensureColumnVisible=function(e){this.gridPanel.ensureColumnVisible(e)},e.prototype.ensureIndexVisible=function(e,t){this.gridPanel.ensureIndexVisible(e,t)},e.prototype.ensureNodeVisible=function(e,t){this.gridCore.ensureNodeVisible(e,t)},e.prototype.forEachLeafNode=function(e){p.missing(this.clientSideRowModel)&&console.warn("cannot call forEachNode unless using normal row model"),this.clientSideRowModel.forEachLeafNode(e)},e.prototype.forEachNode=function(e){this.rowModel.forEachNode(e)},e.prototype.forEachNodeAfterFilter=function(e){p.missing(this.clientSideRowModel)&&console.warn("cannot call forEachNodeAfterFilter unless using normal row model"),this.clientSideRowModel.forEachNodeAfterFilter(e)},e.prototype.forEachNodeAfterFilterAndSort=function(e){p.missing(this.clientSideRowModel)&&console.warn("cannot call forEachNodeAfterFilterAndSort unless using normal row model"),this.clientSideRowModel.forEachNodeAfterFilterAndSort(e)},e.prototype.getFilterApiForColDef=function(e){return console.warn("ag-grid API method getFilterApiForColDef deprecated, use getFilterApi instead"),this.getFilterInstance(e)},e.prototype.getFilterInstance=function(e){var t=this.columnController.getPrimaryColumn(e);if(t)return this.filterManager.getFilterComponent(t,"NO_UI").resolveNow(null,(function(e){return e}))},e.prototype.getFilterApi=function(e){return console.warn("ag-Grid: getFilterApi is deprecated, use getFilterInstance instead"),this.getFilterInstance(e)},e.prototype.destroyFilter=function(e){var t=this.columnController.getPrimaryColumn(e);if(t)return this.filterManager.destroyFilter(t,"filterDestroyed")},e.prototype.getStatusPanel=function(e){if(this.statusBarService)return this.statusBarService.getStatusPanel(e)},e.prototype.getColumnDef=function(e){var t=this.columnController.getPrimaryColumn(e);return t?t.getColDef():null},e.prototype.onFilterChanged=function(){this.filterManager.onFilterChanged()},e.prototype.onSortChanged=function(){this.sortController.onSortChanged()},e.prototype.setSortModel=function(e,t){void 0===t&&(t="api"),this.sortController.setSortModel(e,t)},e.prototype.getSortModel=function(){return this.sortController.getSortModel()},e.prototype.setFilterModel=function(e){this.filterManager.setFilterModel(e)},e.prototype.getFilterModel=function(){return this.filterManager.getFilterModel()},e.prototype.getFocusedCell=function(){return this.focusedCellController.getFocusedCell()},e.prototype.clearFocusedCell=function(){return this.focusedCellController.clearFocusedCell()},e.prototype.setFocusedCell=function(e,t,o){this.focusedCellController.setFocusedCell(e,t,o,!0)},e.prototype.setSuppressRowDrag=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_SUPPRESS_ROW_DRAG,e)},e.prototype.setHeaderHeight=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_HEADER_HEIGHT,e),this.doLayout()},e.prototype.setGridAutoHeight=function(e){console.warn("api.setGridAutoHeight(boolean) is deprecated, please use api.setDomLayout() instead"),this.setDomLayout(e?"autoHeight":"normal")},e.prototype.setDomLayout=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_DOM_LAYOUT,e)},e.prototype.setEnableCellTextSelection=function(e){this.gridPanel.setCellTextSelection(e)},e.prototype.setGroupHeaderHeight=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_GROUP_HEADER_HEIGHT,e),this.doLayout()},e.prototype.setFloatingFiltersHeight=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_FLOATING_FILTERS_HEIGHT,e),this.doLayout()},e.prototype.setPivotGroupHeaderHeight=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_PIVOT_GROUP_HEADER_HEIGHT,e),this.doLayout()},e.prototype.setPivotHeaderHeight=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_PIVOT_HEADER_HEIGHT,e),this.doLayout()},e.prototype.isSideBarVisible=function(){return this.gridCore.isSideBarVisible()},e.prototype.setSideBarVisible=function(e){this.gridCore.setSideBarVisible(e)},e.prototype.setSideBarPosition=function(e){this.gridCore.setSideBarPosition(e)},e.prototype.showToolPanel=function(e){console.warn("ag-grid: from v19 api.showToolPanel has been deprecated in favour of api.setSideBarVisible"),this.setSideBarVisible(e)},e.prototype.openToolPanel=function(e){this.gridCore.openToolPanel(e)},e.prototype.closeToolPanel=function(){this.gridCore.closeToolPanel()},e.prototype.getOpenedToolPanel=function(){return this.gridCore.getOpenedToolPanel()},e.prototype.getSideBar=function(){return this.gridCore.getSideBar()},e.prototype.setSideBar=function(e){return this.gridCore.setSideBar(e)},e.prototype.setSuppressClipboardPaste=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_SUPPRESS_CLIPBOARD_PASTE,e)},e.prototype.isToolPanelShowing=function(){return this.gridCore.isToolPanelShowing()},e.prototype.doLayout=function(){this.gridPanel.checkViewportAndScrolls()},e.prototype.resetRowHeights=function(){p.exists(this.clientSideRowModel)&&this.clientSideRowModel.resetRowHeights()},e.prototype.setGroupRemoveSingleChildren=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_GROUP_REMOVE_SINGLE_CHILDREN,e)},e.prototype.setGroupRemoveLowestSingleChildren=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_GROUP_REMOVE_LOWEST_SINGLE_CHILDREN,e)},e.prototype.onRowHeightChanged=function(){p.exists(this.clientSideRowModel)&&this.clientSideRowModel.onRowHeightChanged()},e.prototype.getValue=function(e,t){var o=this.columnController.getPrimaryColumn(e);return p.missing(o)&&(o=this.columnController.getGridColumn(e)),p.missing(o)?null:this.valueService.getValue(o,t)},e.prototype.addEventListener=function(e,t){var o=this.gridOptionsWrapper.useAsyncEvents();this.eventService.addEventListener(e,t,o)},e.prototype.addGlobalListener=function(e){var t=this.gridOptionsWrapper.useAsyncEvents();this.eventService.addGlobalListener(e,t)},e.prototype.removeEventListener=function(e,t){var o=this.gridOptionsWrapper.useAsyncEvents();this.eventService.removeEventListener(e,t,o)},e.prototype.removeGlobalListener=function(e){var t=this.gridOptionsWrapper.useAsyncEvents();this.eventService.removeGlobalListener(e,t)},e.prototype.dispatchEvent=function(e){this.eventService.dispatchEvent(e)},e.prototype.destroy=function(){this.gridCore.destroy(),this.context.destroy()},e.prototype.resetQuickFilter=function(){this.rowModel.forEachNode((function(e){return e.quickFilterAggregateText=null}))},e.prototype.getRangeSelections=function(){return console.warn("ag-Grid: in v20.1.x, api.getRangeSelections() is gone, please use getCellRanges() instead.\n We had to change how cell selections works a small bit to allow charting to integrate. The return type of\n getCellRanges() is a bit different, please check the ag-Grid documentation."),null},e.prototype.getCellRanges=function(){return this.rangeController?this.rangeController.getCellRanges():(console.warn("ag-Grid: cell range selection is only available in ag-Grid Enterprise"),null)},e.prototype.camelCaseToHumanReadable=function(e){return p.camelCaseToHumanText(e)},e.prototype.addRangeSelection=function(e){console.warn("ag-Grid: As of version 21.x, range selection changed slightly to allow charting integration. Please call api.addCellRange() instead of api.addRangeSelection()")},e.prototype.addCellRange=function(e){this.rangeController||console.warn("ag-Grid: cell range selection is only available in ag-Grid Enterprise"),this.rangeController.addCellRange(e)},e.prototype.clearRangeSelection=function(){this.rangeController||console.warn("ag-Grid: cell range selection is only available in ag-Grid Enterprise"),this.rangeController.removeAllCellRanges()},e.prototype.createRangeChart=function(e){if(P.assertRegistered(R.RangeSelectionModule,"api.createRangeChart")&&P.assertRegistered(R.GridChartsModule,"api.createRangeChart"))return this.chartService.createRangeChart(e)},e.prototype.createPivotChart=function(e){if(P.assertRegistered(R.RangeSelectionModule,"api.createPivotChart")&&P.assertRegistered(R.GridChartsModule,"api.createPivotChart"))return this.chartService.createPivotChart(e)},e.prototype.copySelectedRowsToClipboard=function(e,t){this.clipboardService||console.warn("ag-Grid: clipboard is only available in ag-Grid Enterprise"),this.clipboardService.copySelectedRowsToClipboard(e,t)},e.prototype.copySelectedRangeToClipboard=function(e){this.clipboardService||console.warn("ag-Grid: clipboard is only available in ag-Grid Enterprise"),this.clipboardService.copySelectedRangeToClipboard(e)},e.prototype.copySelectedRangeDown=function(){this.clipboardService||console.warn("ag-Grid: clipboard is only available in ag-Grid Enterprise"),this.clipboardService.copyRangeDown()},e.prototype.showColumnMenuAfterButtonClick=function(e,t){var o=this.columnController.getGridColumn(e);this.menuFactory.showMenuAfterButtonClick(o,t)},e.prototype.showColumnMenuAfterMouseClick=function(e,t){var o=this.columnController.getGridColumn(e);this.menuFactory.showMenuAfterMouseEvent(o,t)},e.prototype.hidePopupMenu=function(){this.contextMenuFactory&&this.contextMenuFactory.hideActiveMenu(),this.menuFactory.hideActiveMenu()},e.prototype.setPopupParent=function(e){this.gridOptionsWrapper.setProperty(Z.PROP_POPUP_PARENT,e)},e.prototype.tabToNextCell=function(){return this.rowRenderer.tabToNextCell(!1)},e.prototype.tabToPreviousCell=function(){return this.rowRenderer.tabToNextCell(!0)},e.prototype.getCellRendererInstances=function(e){return void 0===e&&(e={}),this.rowRenderer.getCellRendererInstances(e)},e.prototype.getCellEditorInstances=function(e){return void 0===e&&(e={}),this.rowRenderer.getCellEditorInstances(e)},e.prototype.getEditingCells=function(){return this.rowRenderer.getEditingCells()},e.prototype.stopEditing=function(e){void 0===e&&(e=!1),this.rowRenderer.stopEditing(e)},e.prototype.startEditingCell=function(e){var t=this.columnController.getGridColumn(e.colKey);if(t){var o={rowIndex:e.rowIndex,rowPinned:e.rowPinned,column:t};p.missing(e.rowPinned)&&this.gridPanel.ensureIndexVisible(e.rowIndex),this.rowRenderer.startEditingCell(o,e.keyPress,e.charPress)}else console.warn("ag-Grid: no column found for "+e.colKey)},e.prototype.addAggFunc=function(e,t){this.aggFuncService&&this.aggFuncService.addAggFunc(e,t)},e.prototype.addAggFuncs=function(e){this.aggFuncService&&this.aggFuncService.addAggFuncs(e)},e.prototype.clearAggFuncs=function(){this.aggFuncService&&this.aggFuncService.clear()},e.prototype.updateRowData=function(e){var t=null;return this.clientSideRowModel?t=this.clientSideRowModel.updateRowData(e):this.infiniteRowModel?this.infiniteRowModel.updateRowData(e):console.error("ag-Grid: updateRowData() only works with ClientSideRowModel and InfiniteRowModel."),this.rowRenderer.refreshFullWidthRows(),this.gridOptionsWrapper.isSuppressChangeDetection()||this.rowRenderer.refreshCells(),t},e.prototype.batchUpdateRowData=function(e,t){this.clientSideRowModel?this.clientSideRowModel.batchUpdateRowData(e,t):console.error("ag-Grid: api.batchUpdateRowData() only works with ClientSideRowModel.")},e.prototype.insertItemsAtIndex=function(e,t,o){console.warn("ag-Grid: insertItemsAtIndex() is deprecated, use updateRowData(transaction) instead."),this.updateRowData({add:t,addIndex:e,update:null,remove:null})},e.prototype.removeItems=function(e,t){console.warn("ag-Grid: removeItems() is deprecated, use updateRowData(transaction) instead.");var o=e.map((function(e){return e.data}));this.updateRowData({add:null,addIndex:null,update:null,remove:o})},e.prototype.addItems=function(e,t){console.warn("ag-Grid: addItems() is deprecated, use updateRowData(transaction) instead."),this.updateRowData({add:e,addIndex:null,update:null,remove:null})},e.prototype.refreshVirtualPageCache=function(){console.warn("ag-Grid: refreshVirtualPageCache() is now called refreshInfiniteCache(), please call refreshInfiniteCache() instead"),this.refreshInfiniteCache()},e.prototype.refreshInfinitePageCache=function(){console.warn("ag-Grid: refreshInfinitePageCache() is now called refreshInfiniteCache(), please call refreshInfiniteCache() instead"),this.refreshInfiniteCache()},e.prototype.refreshInfiniteCache=function(){this.infiniteRowModel?this.infiniteRowModel.refreshCache():console.warn("ag-Grid: api.refreshInfiniteCache is only available when rowModelType='infinite'.")},e.prototype.purgeVirtualPageCache=function(){console.warn("ag-Grid: purgeVirtualPageCache() is now called purgeInfiniteCache(), please call purgeInfiniteCache() instead"),this.purgeInfinitePageCache()},e.prototype.purgeInfinitePageCache=function(){console.warn("ag-Grid: purgeInfinitePageCache() is now called purgeInfiniteCache(), please call purgeInfiniteCache() instead"),this.purgeInfiniteCache()},e.prototype.purgeInfiniteCache=function(){this.infiniteRowModel?this.infiniteRowModel.purgeCache():console.warn("ag-Grid: api.purgeInfiniteCache is only available when rowModelType='infinite'.")},e.prototype.purgeEnterpriseCache=function(e){console.warn("ag-grid: since version 18.x, api.purgeEnterpriseCache() should be replaced with api.purgeServerSideCache()"),this.purgeServerSideCache(e)},e.prototype.purgeServerSideCache=function(e){this.serverSideRowModel?this.serverSideRowModel.purgeCache(e):console.warn("ag-Grid: api.purgeServerSideCache is only available when rowModelType='enterprise'.")},e.prototype.getVirtualRowCount=function(){return console.warn("ag-Grid: getVirtualRowCount() is now called getInfiniteRowCount(), please call getInfiniteRowCount() instead"),this.getInfiniteRowCount()},e.prototype.getInfiniteRowCount=function(){if(this.infiniteRowModel)return this.infiniteRowModel.getVirtualRowCount();console.warn("ag-Grid: api.getVirtualRowCount is only available when rowModelType='virtual'.")},e.prototype.isMaxRowFound=function(){if(this.infiniteRowModel)return this.infiniteRowModel.isMaxRowFound();console.warn("ag-Grid: api.isMaxRowFound is only available when rowModelType='virtual'.")},e.prototype.setVirtualRowCount=function(e,t){console.warn("ag-Grid: setVirtualRowCount() is now called setInfiniteRowCount(), please call setInfiniteRowCount() instead"),this.setInfiniteRowCount(e,t)},e.prototype.setInfiniteRowCount=function(e,t){this.infiniteRowModel?this.infiniteRowModel.setVirtualRowCount(e,t):console.warn("ag-Grid: api.setVirtualRowCount is only available when rowModelType='virtual'.")},e.prototype.getVirtualPageState=function(){return console.warn("ag-Grid: getVirtualPageState() is now called getCacheBlockState(), please call getCacheBlockState() instead"),this.getCacheBlockState()},e.prototype.getInfinitePageState=function(){return console.warn("ag-Grid: getInfinitePageState() is now called getCacheBlockState(), please call getCacheBlockState() instead"),this.getCacheBlockState()},e.prototype.getCacheBlockState=function(){return this.infiniteRowModel?this.infiniteRowModel.getBlockState():this.serverSideRowModel?this.serverSideRowModel.getBlockState():void console.warn("ag-Grid: api.getCacheBlockState() is only available when rowModelType='infinite' or rowModelType='serverSide'.")},e.prototype.checkGridSize=function(){this.gridPanel.setHeaderAndFloatingHeights()},e.prototype.getFirstRenderedRow=function(){return console.warn("in ag-Grid v12, getFirstRenderedRow() was renamed to getFirstDisplayedRow()"),this.getFirstDisplayedRow()},e.prototype.getFirstDisplayedRow=function(){return this.rowRenderer.getFirstVirtualRenderedRow()},e.prototype.getLastRenderedRow=function(){return console.warn("in ag-Grid v12, getLastRenderedRow() was renamed to getLastDisplayedRow()"),this.getLastDisplayedRow()},e.prototype.getLastDisplayedRow=function(){return this.rowRenderer.getLastVirtualRenderedRow()},e.prototype.getDisplayedRowAtIndex=function(e){return this.rowModel.getRow(e)},e.prototype.getDisplayedRowCount=function(){return this.rowModel.getRowCount()},e.prototype.paginationIsLastPageFound=function(){return this.paginationProxy.isLastPageFound()},e.prototype.paginationGetPageSize=function(){return this.paginationProxy.getPageSize()},e.prototype.paginationSetPageSize=function(e){this.gridOptionsWrapper.setProperty("paginationPageSize",e)},e.prototype.paginationGetCurrentPage=function(){return this.paginationProxy.getCurrentPage()},e.prototype.paginationGetTotalPages=function(){return this.paginationProxy.getTotalPages()},e.prototype.paginationGetRowCount=function(){return this.paginationProxy.getMasterRowCount()},e.prototype.paginationGoToNextPage=function(){this.paginationProxy.goToNextPage()},e.prototype.paginationGoToPreviousPage=function(){this.paginationProxy.goToPreviousPage()},e.prototype.paginationGoToFirstPage=function(){this.paginationProxy.goToFirstPage()},e.prototype.paginationGoToLastPage=function(){this.paginationProxy.goToLastPage()},e.prototype.paginationGoToPage=function(e){this.paginationProxy.goToPage(e)},xi([v("immutableService")],e.prototype,"immutableService",void 0),xi([v("csvCreator")],e.prototype,"csvCreator",void 0),xi([v("excelCreator")],e.prototype,"excelCreator",void 0),xi([m("rowRenderer")],e.prototype,"rowRenderer",void 0),xi([m("filterManager")],e.prototype,"filterManager",void 0),xi([m("columnController")],e.prototype,"columnController",void 0),xi([m("selectionController")],e.prototype,"selectionController",void 0),xi([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),xi([m("valueService")],e.prototype,"valueService",void 0),xi([m("alignedGridsService")],e.prototype,"alignedGridsService",void 0),xi([m("eventService")],e.prototype,"eventService",void 0),xi([m("pinnedRowModel")],e.prototype,"pinnedRowModel",void 0),xi([m("context")],e.prototype,"context",void 0),xi([m("rowModel")],e.prototype,"rowModel",void 0),xi([m("sortController")],e.prototype,"sortController",void 0),xi([m("paginationProxy")],e.prototype,"paginationProxy",void 0),xi([m("focusedCellController")],e.prototype,"focusedCellController",void 0),xi([v("rangeController")],e.prototype,"rangeController",void 0),xi([v("clipboardService")],e.prototype,"clipboardService",void 0),xi([v("aggFuncService")],e.prototype,"aggFuncService",void 0),xi([m("menuFactory")],e.prototype,"menuFactory",void 0),xi([v("contextMenuFactory")],e.prototype,"contextMenuFactory",void 0),xi([m("cellRendererFactory")],e.prototype,"cellRendererFactory",void 0),xi([m("valueCache")],e.prototype,"valueCache",void 0),xi([m("animationFrameService")],e.prototype,"animationFrameService",void 0),xi([v("statusBarService")],e.prototype,"statusBarService",void 0),xi([v("chartService")],e.prototype,"chartService",void 0),xi([g],e.prototype,"init",null),e=xi([y("gridApi")],e)}(),Wi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Hi=function(e,t){return function(o,i){t(o,i,e)}},ki=function(){function e(){this.expressionToFunctionCache={}}return e.prototype.setBeans=function(e){this.logger=e.create("ExpressionService")},e.prototype.evaluate=function(e,t){if("function"==typeof e)return e(t);if("string"==typeof e){var o=e;return this.evaluateExpression(o,t)}console.error("ag-Grid: value should be either a string or a function",e)},e.prototype.evaluateExpression=function(e,t){try{return this.createExpressionFunction(e)(t.value,t.context,t.oldValue,t.newValue,t.value,t.node,t.data,t.colDef,t.rowIndex,t.api,t.columnApi,t.getValue,t.column,t.columnGroup)}catch(t){return console.log("Processing of the expression failed"),console.log("Expression = "+e),console.log("Exception = "+t),null}},e.prototype.createExpressionFunction=function(e){if(this.expressionToFunctionCache[e])return this.expressionToFunctionCache[e];var t=this.createFunctionBody(e),o=new Function("x, ctx, oldValue, newValue, value, node, data, colDef, rowIndex, api, columnApi, getValue, column, columnGroup",t);return this.expressionToFunctionCache[e]=o,o},e.prototype.createFunctionBody=function(e){return e.indexOf("return")>=0?e:"return "+e+";"},Wi([Hi(0,E("loggerFactory"))],e.prototype,"setBeans",null),e=Wi([y("expressionService")],e)}(),Bi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ui=function(){function e(){this.templateCache={},this.waitingCallbacks={}}return e.prototype.getTemplate=function(e,t){var o=this.templateCache[e];if(o)return o;var i=this.waitingCallbacks[e],n=this;if(!i){i=[],this.waitingCallbacks[e]=i;var r=new XMLHttpRequest;r.onload=function(){n.handleHttpResult(this,e)},r.open("GET",e),r.send()}return t&&i.push(t),null},e.prototype.handleHttpResult=function(e,t){if(200===e.status&&null!==e.response){this.templateCache[t]=e.response||e.responseText;for(var o=this.waitingCallbacks[t],i=0;i<o.length;i++){(0,o[i])()}if(this.$scope){var n=this;window.setTimeout((function(){n.$scope.$apply()}),0)}}else console.warn("Unable to get template error "+e.status+" - "+t)},Bi([m("$scope")],e.prototype,"$scope",void 0),e=Bi([y("templateService")],e)}(),ji=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},zi=function(){function e(){this.popupList=[]}return e.prototype.registerGridCore=function(e){this.gridCore=e},e.prototype.getDocument=function(){return this.gridOptionsWrapper.getDocument()},e.prototype.getPopupParent=function(){var e=this.gridOptionsWrapper.getPopupParent();return e||this.gridCore.getRootGui()},e.prototype.positionPopupForMenu=function(e){var t,o=e.eventSource.getBoundingClientRect(),i=this.getDocument(),n=this.getPopupParent();t=n===i.body?i.documentElement.getBoundingClientRect():n.getBoundingClientRect();var r=o.top-t.top;r=this.keepYWithinBounds(e,r);var s=e.ePopup.clientWidth>0?e.ePopup.clientWidth:200;e.ePopup.style.minWidth=s+"px";var a,l=t.right-t.left-s;function p(){return o.right-t.left-2}function u(){return o.left-t.left-s}this.gridOptionsWrapper.isEnableRtl()?((a=u())<0&&(a=p()),a>l&&(a=0)):((a=p())>l&&(a=u()),a<0&&(a=0)),e.ePopup.style.left=a+"px",e.ePopup.style.top=r+"px"},e.prototype.positionPopupUnderMouseEvent=function(e){var t=this.calculatePointerAlign(e.mouseEvent),o=t.x,i=t.y,n=e.ePopup,r=e.nudgeX,s=e.nudgeY;this.positionPopup({ePopup:n,x:o,y:i,nudgeX:r,nudgeY:s,keepWithinBounds:!0}),this.callPostProcessPopup(e.ePopup,null,e.mouseEvent,e.type,e.column,e.rowNode)},e.prototype.calculatePointerAlign=function(e){var t=this.getDocument(),o=this.getPopupParent(),i=o.getBoundingClientRect(),n=t.documentElement.getBoundingClientRect();return{x:e.clientX-(o===t.body?n.left:i.left),y:e.clientY-(o===t.body?n.top:i.top)}},e.prototype.positionPopupUnderComponent=function(e){var t,o=e.eventSource.getBoundingClientRect(),i=this.getDocument(),n=this.getPopupParent(),r=e.alignSide||"left";t=n===i.body?i.documentElement.getBoundingClientRect():n.getBoundingClientRect();var s=o.left-t.left;"right"===r&&(s-=e.ePopup.offsetWidth-o.width),this.positionPopup({ePopup:e.ePopup,minWidth:e.minWidth,minHeight:e.minHeight,nudgeX:e.nudgeX,nudgeY:e.nudgeY,x:s,y:o.top-t.top+o.height,keepWithinBounds:e.keepWithinBounds}),this.callPostProcessPopup(e.ePopup,e.eventSource,null,e.type,e.column,e.rowNode)},e.prototype.positionPopupOverComponent=function(e){var t,o=e.eventSource.getBoundingClientRect(),i=this.getDocument(),n=this.getPopupParent();t=n===i.body?i.documentElement.getBoundingClientRect():n.getBoundingClientRect(),this.positionPopup({ePopup:e.ePopup,minWidth:e.minWidth,nudgeX:e.nudgeX,nudgeY:e.nudgeY,x:o.left-t.left,y:o.top-t.top,keepWithinBounds:e.keepWithinBounds}),this.callPostProcessPopup(e.ePopup,e.eventSource,null,e.type,e.column,e.rowNode)},e.prototype.callPostProcessPopup=function(e,t,o,i,n,r){var s=this.gridOptionsWrapper.getPostProcessPopupFunc();s&&s({column:n,rowNode:r,ePopup:e,type:i,eventSource:t,mouseEvent:o})},e.prototype.positionPopup=function(e){var t=e.x,o=e.y;e.nudgeX&&(t+=e.nudgeX),e.nudgeY&&(o+=e.nudgeY),e.keepWithinBounds&&(t=this.keepXWithinBounds(e,t),o=this.keepYWithinBounds(e,o)),e.ePopup.style.left=t+"px",e.ePopup.style.top=o+"px"},e.prototype.keepYWithinBounds=function(e,t){var o=this.gridOptionsWrapper.getDocument(),i=o.documentElement,n=this.getPopupParent(),r=n.getBoundingClientRect(),s=o.documentElement.getBoundingClientRect(),a=n===o.body,l=Math.min(200,r.height),u=0;e.minHeight&&e.minHeight<l?l=e.minHeight:e.ePopup.offsetHeight>0&&(l=e.ePopup.clientHeight,u=p.getAbsoluteHeight(e.ePopup)-l);var c=a?p.getAbsoluteHeight(i)+i.scrollTop:r.height;a&&(c-=Math.abs(s.top-r.top));var d=c-l-u-3;return Math.min(Math.max(t,0),Math.abs(d))},e.prototype.keepXWithinBounds=function(e,t){var o=this.gridOptionsWrapper.getDocument(),i=o.documentElement,n=this.getPopupParent(),r=n.getBoundingClientRect(),s=o.documentElement.getBoundingClientRect(),a=n===o.body,l=e.ePopup,u=Math.min(200,r.width),c=0;e.minWidth&&e.minWidth<u?u=e.minWidth:l.offsetWidth>0&&(u=l.offsetWidth,l.style.minWidth=u+"px",c=p.getAbsoluteWidth(l)-u);var d=a?p.getAbsoluteWidth(i)+i.scrollLeft:r.width;a&&(d-=Math.abs(s.left-r.left));var h=d-u-c-3;return Math.min(Math.max(t,0),Math.abs(h))},e.prototype.addAsModalPopup=function(e,t,o,i){return this.addPopup(!0,e,t,o,i)},e.prototype.addPopup=function(e,t,i,n,r,s){var a=this,l=this.gridOptionsWrapper.getDocument();if(!l)return console.warn("ag-grid: could not find the document, document is empty"),function(){};var u=p.findIndex(this.popupList,(function(e){return e.element===t}));if(-1!==u)return this.popupList[u].hideFunc;var c=this.getPopupParent();c.appendChild(t),t.style.top="0px",t.style.left="0px";var d=document.createElement("div"),h=this.environment.getTheme().theme;h&&p.addCssClass(d,h),p.addCssClass(d,"ag-popup"),p.addCssClass(t,this.gridOptionsWrapper.isEnableRtl()?"ag-rtl":"ag-ltr"),d.appendChild(t),c.appendChild(d),s?this.setAlwaysOnTop(d,!0):this.bringPopupToFront(d);var g=!1,f=function(e){(e.which||e.keyCode)===o.KEY_ESCAPE&&d.contains(document.activeElement)&&v(null)},y=function(e){v(e)},m=function(e){v(null,e)},v=function(e,o){a.isEventFromCurrentPopup(e,o,t)||a.isEventSameChainAsOriginalEvent(r,e,o)||g||(g=!0,c.removeChild(d),l.removeEventListener("keydown",f),l.removeEventListener("mousedown",y),l.removeEventListener("touchstart",m),l.removeEventListener("contextmenu",y),a.eventService.removeEventListener(M.EVENT_DRAG_STARTED,y),n&&n(),a.popupList=a.popupList.filter((function(e){return e.element!==t})))};return window.setTimeout((function(){i&&l.addEventListener("keydown",f),e&&(l.addEventListener("mousedown",y),a.eventService.addEventListener(M.EVENT_DRAG_STARTED,y),l.addEventListener("touchstart",m),l.addEventListener("contextmenu",y))}),0),this.popupList.push({element:t,hideFunc:v}),v},e.prototype.isEventFromCurrentPopup=function(e,t,o){var i=e||t;if(!i)return!1;var n=p.findIndex(this.popupList,(function(e){return e.element===o}));if(-1===n)return!1;for(var r=n;r<this.popupList.length;r++){var s=this.popupList[r];if(p.isElementInEventPath(s.element,i))return!0}for(var a=i.target;a&&a!=document.body;){if(a.classList.contains("ag-custom-component-popup")||null===a.parentElement)return!0;a=a.parentElement}},e.prototype.isEventSameChainAsOriginalEvent=function(e,t,o){var i=null;if(t?i=t:o&&(i=o.touches[0]),i&&e){var n=t?t.screenX:0,r=t?t.screenY:0,s=Math.abs(e.screenX-n)<5,a=Math.abs(e.screenY-r)<5;if(s&&a)return!0}return!1},e.prototype.getWrapper=function(e){for(;!p.containsClass(e,"ag-popup")&&e.parentElement;)e=e.parentElement;return p.containsClass(e,"ag-popup")?e:null},e.prototype.setAlwaysOnTop=function(e,t){var o=this.getWrapper(e);o&&(p.addOrRemoveCssClass(o,"ag-always-on-top",!!t),t&&this.bringPopupToFront(o))},e.prototype.bringPopupToFront=function(e){var t=this.getPopupParent(),o=Array.prototype.slice.call(t.querySelectorAll(".ag-popup")),i=o.length,n=Array.prototype.slice.call(t.querySelectorAll(".ag-popup.ag-always-on-top")),r=n.length,s=this.getWrapper(e);if(s&&!(i<=1)&&t.contains(e)){var a=o.indexOf(s);if(r)p.containsClass(s,"ag-always-on-top")?a!==i-1&&p.last(n).insertAdjacentElement("afterend",s):a!==i-r-1&&n[0].insertAdjacentElement("beforebegin",s);else a!==i-1&&p.last(o).insertAdjacentElement("afterend",s);var l={type:"popupToFront",api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),eWrapper:s};this.eventService.dispatchEvent(l)}},ji([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),ji([m("environment")],e.prototype,"environment",void 0),ji([m("eventService")],e.prototype,"eventService",void 0),e=ji([y("popupService")],e)}(),Yi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ki=function(e,t){return function(o,i){t(o,i,e)}},qi=function(){function e(){}return e.prototype.setBeans=function(e){this.logging=e.isDebug()},e.prototype.create=function(e){return new Qi(e,this.isLogging.bind(this))},e.prototype.isLogging=function(){return this.logging},Yi([Ki(0,E("gridOptionsWrapper"))],e.prototype,"setBeans",null),e=Yi([y("loggerFactory")],e)}(),Qi=function(){function e(e,t){this.name=e,this.isLoggingFunc=t}return e.prototype.isLogging=function(){return this.isLoggingFunc()},e.prototype.log=function(e){this.isLoggingFunc()&&console.log("ag-Grid."+this.name+": "+e)},e}(),Xi=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},$i=function(){function e(){}return e.prototype.registerGridComp=function(e){this.gridPanel=e},e.prototype.registerHeaderRootComp=function(e){this.headerRootComp=e},e.prototype.getPreferredWidthForColumn=function(e){var t=this.getHeaderCellForColumn(e);if(!t)return-1;var o=document.createElement("span");o.style.position="fixed";var i=this.gridPanel.getCenterContainer();i.appendChild(o),this.putRowCellsIntoDummyContainer(e,o),this.cloneItemIntoDummy(t,o);var n=o.offsetWidth;return i.removeChild(o),n+this.gridOptionsWrapper.getAutoSizePadding()},e.prototype.getHeaderCellForColumn=function(e){var t=null;return this.headerRootComp.forEachHeaderElement((function(o){if(o instanceof Zo){var i=o;i.getColumn()===e&&(t=i)}})),t?t.getGui():null},e.prototype.putRowCellsIntoDummyContainer=function(e,t){var o=this;this.rowRenderer.getAllCellsForColumn(e).forEach((function(e){return o.cloneItemIntoDummy(e,t)}))},e.prototype.cloneItemIntoDummy=function(e,t){var o=e.cloneNode(!0);o.style.width="",o.style.position="static",o.style.left="";var i=document.createElement("div");i.style.display="table-row",i.appendChild(o),t.appendChild(i)},Xi([m("rowRenderer")],e.prototype,"rowRenderer",void 0),Xi([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),e=Xi([y("autoWidthCalculator")],e)}(),Ji=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Zi=function(){function e(){}return e.prototype.addResizeBar=function(e){var t=this,o={dragStartPixels:e.dragStartPixels||0,eElement:e.eResizeBar,onDragStart:this.onDragStart.bind(this,e),onDragStop:this.onDragStop.bind(this,e),onDragging:this.onDragging.bind(this,e)};this.dragService.addDragSource(o,!0);return function(){return t.dragService.removeDragSource(o)}},e.prototype.onDragStart=function(e,t){this.draggingStarted=!0,this.dragStartX=t.clientX,this.setResizeIcons();var o=t instanceof MouseEvent&&!0===t.shiftKey;e.onResizeStart(o)},e.prototype.setResizeIcons=function(){this.oldBodyCursor=this.eGridDiv.style.cursor,this.oldMsUserSelect=this.eGridDiv.style.msUserSelect,this.oldWebkitUserSelect=this.eGridDiv.style.webkitUserSelect,this.eGridDiv.style.cursor="col-resize",this.eGridDiv.style.msUserSelect="none",this.eGridDiv.style.webkitUserSelect="none"},e.prototype.onDragStop=function(e,t){e.onResizeEnd(this.resizeAmount),this.resetIcons()},e.prototype.resetIcons=function(){this.eGridDiv.style.cursor=this.oldBodyCursor,this.eGridDiv.style.msUserSelect=this.oldMsUserSelect,this.eGridDiv.style.webkitUserSelect=this.oldWebkitUserSelect},e.prototype.onDragging=function(e,t){this.resizeAmount=t.clientX-this.dragStartX,e.onResizing(this.resizeAmount)},Ji([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Ji([m("dragService")],e.prototype,"dragService",void 0),Ji([m("eGridDiv")],e.prototype,"eGridDiv",void 0),e=Ji([y("horizontalResizeService")],e)}(),en=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),tn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},on=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return en(t,e),t.prototype.init=function(){var e=this;this.logger=this.loggerFactory.create("GridCore");var t=this.createTemplate();if(this.setTemplate(t),[this.gridApi,this.filterManager,this.rowRenderer,this.popupService].forEach((function(t){return t.registerGridCore(e)})),P.isRegistered(R.ClipboardModule)&&this.clipboardService.registerGridCore(this),this.gridOptionsWrapper.addLayoutElement(this.getGui()),this.eGridDiv.appendChild(this.getGui()),this.addDestroyFunc((function(){e.eGridDiv.removeChild(e.getGui())})),this.$scope){var o=this.$scope.$watch(this.quickFilterOnScope,(function(t){return e.filterManager.setQuickFilter(t)}));this.addDestroyFunc(o)}this.addRtlSupport(),this.logger.log("ready"),this.gridOptionsWrapper.addLayoutElement(this.eRootWrapperBody);var i=this.gridPanel.getGui();this.addDestroyableEventListener(i,"focusin",(function(){p.addCssClass(i,"ag-has-focus")})),this.addDestroyableEventListener(i,"focusout",(function(e){i.contains(e.relatedTarget)||p.removeCssClass(i,"ag-has-focus")}));var n=this.resizeObserverService.observeResize(this.eGridDiv,this.onGridSizeChanged.bind(this));this.addDestroyFunc((function(){return n()}))},t.prototype.createTemplate=function(){var e=P.isRegistered(R.SideBarModule),t=P.isRegistered(R.StatusBarModule);return'<div class="ag-root-wrapper">\n '+(P.isRegistered(R.RowGroupingModule)?"<ag-grid-header-drop-zones></ag-grid-header-drop-zones>":"")+'\n <div class="ag-root-wrapper-body" ref="rootWrapperBody">\n <ag-grid-comp ref="gridPanel"></ag-grid-comp> \n '+(e?'<ag-side-bar ref="sideBar"></ag-side-bar>':"")+"\n </div>\n "+(t?'<ag-status-bar ref="statusBar"></ag-status-bar>':"")+"\n <ag-pagination></ag-pagination>\n "+(P.isRegistered(R.EnterpriseCoreModule)?"<ag-watermark></ag-watermark>":"")+"\n </div>"},t.prototype.onGridSizeChanged=function(){var e={type:M.EVENT_GRID_SIZE_CHANGED,api:this.gridApi,columnApi:this.columnApi,clientWidth:this.eGridDiv.clientWidth,clientHeight:this.eGridDiv.clientHeight};this.eventService.dispatchEvent(e)},t.prototype.addRtlSupport=function(){var e=this.gridOptionsWrapper.isEnableRtl()?"ag-rtl":"ag-ltr";p.addCssClass(this.getGui(),e)},t.prototype.getRootGui=function(){return this.getGui()},t.prototype.isSideBarVisible=function(){return!!this.sideBarComp&&this.sideBarComp.isDisplayed()},t.prototype.setSideBarVisible=function(e){this.sideBarComp?this.sideBarComp.setDisplayed(e):e&&console.warn("ag-Grid: sideBar is not loaded")},t.prototype.setSideBarPosition=function(e){this.sideBarComp?this.sideBarComp.setSideBarPosition(e):console.warn("ag-Grid: sideBar is not loaded")},t.prototype.closeToolPanel=function(){this.sideBarComp?this.sideBarComp.close():console.warn("ag-Grid: toolPanel is only available in ag-Grid Enterprise")},t.prototype.getSideBar=function(){return this.gridOptions.sideBar},t.prototype.getToolPanelInstance=function(e){if(this.sideBarComp)return this.sideBarComp.getToolPanelInstance(e);console.warn("ag-Grid: toolPanel is only available in ag-Grid Enterprise")},t.prototype.refreshSideBar=function(){this.sideBarComp&&this.sideBarComp.refresh()},t.prototype.setSideBar=function(e){this.sideBarComp&&(this.eRootWrapperBody.removeChild(this.sideBarComp.getGui()),this.gridOptions.sideBar=q.parse(e),this.sideBarComp.reset(),this.eRootWrapperBody.appendChild(this.sideBarComp.getGui()))},t.prototype.getOpenedToolPanel=function(){return this.sideBarComp?this.sideBarComp.openedItem():null},t.prototype.openToolPanel=function(e){this.sideBarComp?this.sideBarComp.openToolPanel(e):console.warn("ag-Grid: toolPanel is only available in ag-Grid Enterprise")},t.prototype.isToolPanelShowing=function(){return this.sideBarComp.isToolPanelShowing()},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.logger.log("Grid DOM removed")},t.prototype.ensureNodeVisible=function(e,t){if(void 0===t&&(t="top"),this.doingVirtualPaging)throw new Error("Cannot use ensureNodeVisible when doing virtual paging, as we cannot check rows that are not in memory");for(var o=this.rowModel.getRowCount(),i="function"==typeof e,n=-1,r=0;r<o;r++){var s=this.rowModel.getRow(r);if(i){if(e(s)){n=r;break}}else if(e===s||e===s.data){n=r;break}}n>=0&&this.gridPanel.ensureIndexVisible(n,t)},tn([m("gridOptions")],t.prototype,"gridOptions",void 0),tn([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),tn([m("rowModel")],t.prototype,"rowModel",void 0),tn([m("resizeObserverService")],t.prototype,"resizeObserverService",void 0),tn([m("columnController")],t.prototype,"columnController",void 0),tn([m("rowRenderer")],t.prototype,"rowRenderer",void 0),tn([m("filterManager")],t.prototype,"filterManager",void 0),tn([m("eventService")],t.prototype,"eventService",void 0),tn([m("eGridDiv")],t.prototype,"eGridDiv",void 0),tn([m("$scope")],t.prototype,"$scope",void 0),tn([m("quickFilterOnScope")],t.prototype,"quickFilterOnScope",void 0),tn([m("popupService")],t.prototype,"popupService",void 0),tn([m("focusedCellController")],t.prototype,"focusedCellController",void 0),tn([m("loggerFactory")],t.prototype,"loggerFactory",void 0),tn([m("columnApi")],t.prototype,"columnApi",void 0),tn([m("gridApi")],t.prototype,"gridApi",void 0),tn([v("clipboardService")],t.prototype,"clipboardService",void 0),tn([fe("gridPanel")],t.prototype,"gridPanel",void 0),tn([fe("sideBar")],t.prototype,"sideBarComp",void 0),tn([fe("rootWrapperBody")],t.prototype,"eRootWrapperBody",void 0),tn([g],t.prototype,"init",null),t}(pe),nn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},rn=function(){function e(){}return e.prototype.hideActiveMenu=function(){this.hidePopup&&this.hidePopup()},e.prototype.showMenuAfterMouseEvent=function(e,t){var o=this;this.showPopup(e,(function(i){o.popupService.positionPopupUnderMouseEvent({column:e,type:"columnMenu",mouseEvent:t,ePopup:i})}))},e.prototype.showMenuAfterButtonClick=function(e,t){var o=this;this.showPopup(e,(function(i){o.popupService.positionPopupUnderComponent({type:"columnMenu",eventSource:t,ePopup:i,keepWithinBounds:!0,column:e})}))},e.prototype.showPopup=function(e,t){var o,i=this,n=this.filterManager.getOrCreateFilterWrapper(e,"COLUMN_MENU"),r=document.createElement("div");p.addCssClass(r,"ag-menu"),n.guiPromise.promise.then((function(e){r.appendChild(e)}));var s=function(e){"horizontal"===e.direction&&o()};this.eventService.addEventListener("bodyScroll",s);o=this.popupService.addAsModalPopup(r,!0,(function(){i.eventService.removeEventListener("bodyScroll",s),e.setMenuVisible(!1,"contextMenu")})),t(r),n.filterPromise.then((function(e){if(e.afterGuiAttached){var t={hidePopup:o};e.afterGuiAttached(t)}})),this.hidePopup=o,e.setMenuVisible(!0,"contextMenu")},e.prototype.isMenuEnabled=function(e){return e.isFilterAllowed()},nn([m("eventService")],e.prototype,"eventService",void 0),nn([m("filterManager")],e.prototype,"filterManager",void 0),nn([m("popupService")],e.prototype,"popupService",void 0),nn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),e=nn([y("menuFactory")],e)}(),sn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},an=function(){function e(){this.onMouseUpListener=this.onMouseUp.bind(this),this.onMouseMoveListener=this.onMouseMove.bind(this),this.onTouchEndListener=this.onTouchUp.bind(this),this.onTouchMoveListener=this.onTouchMove.bind(this),this.dragEndFunctions=[],this.dragSources=[]}return e.prototype.init=function(){this.logger=this.loggerFactory.create("DragService")},e.prototype.destroy=function(){this.dragSources.forEach(this.removeListener.bind(this)),this.dragSources.length=0},e.prototype.removeListener=function(e){var t=e.dragSource.eElement,o=e.mouseDownListener;if(t.removeEventListener("mousedown",o),e.touchEnabled){var i=e.touchStartListener;t.removeEventListener("touchstart",i,{passive:!0})}},e.prototype.removeDragSource=function(e){var t=p.find(this.dragSources,(function(t){return t.dragSource===e}));t&&(this.removeListener(t),p.removeFromArray(this.dragSources,t))},e.prototype.setNoSelectToBody=function(e){var t=this.gridOptionsWrapper.getDocument().querySelector("body");p.exists(t)&&p.addOrRemoveCssClass(t,"ag-unselectable",e)},e.prototype.addDragSource=function(e,t){void 0===t&&(t=!1);var o=this.onMouseDown.bind(this,e);e.eElement.addEventListener("mousedown",o);var i=null,n=this.gridOptionsWrapper.isSuppressTouch();t&&!n&&(i=this.onTouchStart.bind(this,e),e.eElement.addEventListener("touchstart",i,{passive:!1})),this.dragSources.push({dragSource:e,mouseDownListener:o,touchStartListener:i,touchEnabled:t})},e.prototype.onTouchStart=function(e,t){var o=this;this.currentDragParams=e,this.dragging=!1;var i=t.touches[0];this.touchLastTime=i,this.touchStart=i,t.preventDefault(),e.eElement.addEventListener("touchmove",this.onTouchMoveListener,{passive:!0}),e.eElement.addEventListener("touchend",this.onTouchEndListener,{passive:!0}),e.eElement.addEventListener("touchcancel",this.onTouchEndListener,{passive:!0}),this.dragEndFunctions.push((function(){e.eElement.removeEventListener("touchmove",o.onTouchMoveListener,{passive:!0}),e.eElement.removeEventListener("touchend",o.onTouchEndListener,{passive:!0}),e.eElement.removeEventListener("touchcancel",o.onTouchEndListener,{passive:!0})})),0===e.dragStartPixels&&this.onCommonMove(i,this.touchStart)},e.prototype.onMouseDown=function(e,t){var o=this;if(!(e.skipMouseEvent&&e.skipMouseEvent(t)||t._alreadyProcessedByDragService||(t._alreadyProcessedByDragService=!0,0!==t.button))){this.currentDragParams=e,this.dragging=!1,this.mouseStartEvent=t;var i=this.gridOptionsWrapper.getDocument();this.setNoSelectToBody(!0),i.addEventListener("mousemove",this.onMouseMoveListener),i.addEventListener("mouseup",this.onMouseUpListener),this.dragEndFunctions.push((function(){i.removeEventListener("mousemove",o.onMouseMoveListener),i.removeEventListener("mouseup",o.onMouseUpListener)})),0===e.dragStartPixels&&this.onMouseMove(t)}},e.prototype.isEventNearStartEvent=function(e,t){var o=this.currentDragParams.dragStartPixels,i=p.exists(o)?o:4;return p.areEventsNear(e,t,i)},e.prototype.getFirstActiveTouch=function(e){for(var t=0;t<e.length;t++)if(e[t].identifier===this.touchStart.identifier)return e[t];return null},e.prototype.onCommonMove=function(e,t){if(!this.dragging){if(!this.dragging&&this.isEventNearStartEvent(e,t))return;this.dragging=!0;var o={type:M.EVENT_DRAG_STARTED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(o),this.currentDragParams.onDragStart(t)}this.currentDragParams.onDragging(e)},e.prototype.onTouchMove=function(e){var t=this.getFirstActiveTouch(e.touches);t&&this.onCommonMove(t,this.touchStart)},e.prototype.onMouseMove=function(e){this.onCommonMove(e,this.mouseStartEvent)},e.prototype.onTouchUp=function(e){var t=this.getFirstActiveTouch(e.changedTouches);t||(t=this.touchLastTime),this.onUpCommon(t)},e.prototype.onMouseUp=function(e){this.onUpCommon(e)},e.prototype.onUpCommon=function(e){if(this.dragging){this.dragging=!1,this.currentDragParams.onDragStop(e);var t={type:M.EVENT_DRAG_STOPPED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)}this.setNoSelectToBody(!1),this.mouseStartEvent=null,this.touchStart=null,this.touchLastTime=null,this.currentDragParams=null,this.dragEndFunctions.forEach((function(e){return e()})),this.dragEndFunctions.length=0},sn([m("loggerFactory")],e.prototype,"loggerFactory",void 0),sn([m("eventService")],e.prototype,"eventService",void 0),sn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),sn([m("columnApi")],e.prototype,"columnApi",void 0),sn([m("gridApi")],e.prototype,"gridApi",void 0),sn([g],e.prototype,"init",null),sn([f],e.prototype,"destroy",null),e=sn([y("dragService")],e)}(),ln=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},pn=function(){function e(){var e=this;this.getSortModel=function(){return e.getColumnsWithSortingOrdered().map((function(e){return{colId:e.getColId(),sort:e.getSort()}}))}}var t;return t=e,e.prototype.progressSort=function(e,t,o){void 0===o&&(o="api");var i=this.getNextSortDirection(e);this.setSortForColumn(e,i,t,o)},e.prototype.setSortForColumn=function(e,t,i,n){if(void 0===n&&(n="api"),t!==o.SORT_ASC&&t!==o.SORT_DESC&&(t=null),e.setSort(t,n),e.getSort()){var r=Number((new Date).valueOf());e.setSortedAt(r)}else e.setSortedAt(null);i&&!this.gridOptionsWrapper.isSuppressMultiSort()||this.clearSortBarThisColumn(e,n),this.dispatchSortChangedEvents()},e.prototype.onSortChanged=function(){this.dispatchSortChangedEvents()},e.prototype.dispatchSortChangedEvents=function(){var e={type:M.EVENT_SORT_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)},e.prototype.clearSortBarThisColumn=function(e,t){this.columnController.getPrimaryAndSecondaryAndAutoColumns().forEach((function(o){o!==e&&o.setSort(void 0,t)}))},e.prototype.getNextSortDirection=function(e){var o;if(o=e.getColDef().sortingOrder?e.getColDef().sortingOrder:this.gridOptionsWrapper.getSortingOrder()?this.gridOptionsWrapper.getSortingOrder():t.DEFAULT_SORTING_ORDER,!Array.isArray(o)||o.length<=0)return console.warn("ag-grid: sortingOrder must be an array with at least one element, currently it's "+o),null;var i,n=o.indexOf(e.getSort()),r=n<0,s=n==o.length-1;return i=r||s?o[0]:o[n+1],t.DEFAULT_SORTING_ORDER.indexOf(i)<0?(console.warn("ag-grid: invalid sort type "+i),null):i},e.prototype.setSortModel=function(e,t){var o=this;void 0===t&&(t="api");var i=e&&e.length>0;this.columnController.getPrimaryAndSecondaryAndAutoColumns().forEach((function(n){var r=null,s=-1;if(i&&n.getColDef().sortable)for(var a=0;a<e.length;a++){var l=e[a];"string"==typeof l.colId&&"string"==typeof n.getColId()&&o.compareColIds(l,n)&&(r=l.sort,s=a)}r?(n.setSort(r,t),n.setSortedAt(s)):(n.setSort(null,t),n.setSortedAt(null))})),this.dispatchSortChangedEvents()},e.prototype.compareColIds=function(e,t){return e.colId===t.getColId()},e.prototype.getColumnsWithSortingOrdered=function(){var e=this.columnController.getPrimaryAndSecondaryAndAutoColumns().filter((function(e){return!!e.getSort()}));return e.sort((function(e,t){return e.sortedAt-t.sortedAt})),e},e.prototype.getSortForRowController=function(){return this.getColumnsWithSortingOrdered().map((function(e){return{inverter:e.getSort()===o.SORT_ASC?1:-1,column:e}}))},e.DEFAULT_SORTING_ORDER=[o.SORT_ASC,o.SORT_DESC,null],ln([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),ln([m("columnController")],e.prototype,"columnController",void 0),ln([m("eventService")],e.prototype,"eventService",void 0),ln([m("columnApi")],e.prototype,"columnApi",void 0),ln([m("gridApi")],e.prototype,"gridApi",void 0),e=t=ln([y("sortController")],e)}(),un=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},cn=function(){function e(){}return e.prototype.init=function(){this.eventService.addEventListener(M.EVENT_COLUMN_PIVOT_MODE_CHANGED,this.clearFocusedCell.bind(this)),this.eventService.addEventListener(M.EVENT_COLUMN_EVERYTHING_CHANGED,this.clearFocusedCell.bind(this)),this.eventService.addEventListener(M.EVENT_COLUMN_GROUP_OPENED,this.clearFocusedCell.bind(this)),this.eventService.addEventListener(M.EVENT_COLUMN_ROW_GROUP_CHANGED,this.clearFocusedCell.bind(this))},e.prototype.clearFocusedCell=function(){this.focusedCellPosition=null,this.onCellFocused(!1)},e.prototype.getFocusedCell=function(){return this.focusedCellPosition},e.prototype.getFocusCellToUseAfterRefresh=function(){return this.gridOptionsWrapper.isSuppressFocusAfterRefresh()?null:this.focusedCellPosition&&this.getGridCellForDomElement(document.activeElement)?this.focusedCellPosition:null},e.prototype.getGridCellForDomElement=function(e){for(var t=e;t;){var o=this.gridOptionsWrapper.getDomData(t,Oo.DOM_DATA_KEY_CELL_COMP);if(o)return o.getCellPosition();t=t.parentNode}return null},e.prototype.setFocusedCell=function(e,t,o,i){void 0===i&&(i=!1);var n=p.makeNull(this.columnController.getGridColumn(t));this.focusedCellPosition={rowIndex:e,rowPinned:p.makeNull(o),column:n},this.onCellFocused(i)},e.prototype.isCellFocused=function(e){return!p.missing(this.focusedCellPosition)&&(this.focusedCellPosition.column===e.column&&this.isRowFocused(e.rowIndex,e.rowPinned))},e.prototype.isRowNodeFocused=function(e){return this.isRowFocused(e.rowIndex,e.rowPinned)},e.prototype.isAnyCellFocused=function(){return!!this.focusedCellPosition},e.prototype.isRowFocused=function(e,t){if(p.missing(this.focusedCellPosition))return!1;var o=p.makeNull(t);return this.focusedCellPosition.rowIndex===e&&this.focusedCellPosition.rowPinned===o},e.prototype.onCellFocused=function(e){var t={type:M.EVENT_CELL_FOCUSED,forceBrowserFocus:e,rowIndex:null,column:null,floating:null,api:this.gridApi,columnApi:this.columnApi,rowPinned:null};this.focusedCellPosition&&(t.rowIndex=this.focusedCellPosition.rowIndex,t.column=this.focusedCellPosition.column,t.rowPinned=this.focusedCellPosition.rowPinned),this.eventService.dispatchEvent(t)},un([m("eventService")],e.prototype,"eventService",void 0),un([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),un([m("columnController")],e.prototype,"columnController",void 0),un([m("columnApi")],e.prototype,"columnApi",void 0),un([m("gridApi")],e.prototype,"gridApi",void 0),un([g],e.prototype,"init",null),e=un([y("focusedCellController")],e)}(),dn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},hn=function(){function e(){this.gridInstanceId=t.gridInstanceSequence.next()}var t;return t=e,e.prototype.init=function(){this.stampDomElementWithGridInstance()},e.prototype.stampDomElementWithGridInstance=function(){this.eGridDiv[t.GRID_DOM_KEY]=this.gridInstanceId},e.prototype.getRenderedCellForEvent=function(e){return p.getCellCompForEvent(this.gridOptionsWrapper,e)},e.prototype.isEventFromThisGrid=function(e){for(var o=p.getEventPath(e),i=0;i<o.length;i++){var n=o[i][t.GRID_DOM_KEY];if(p.exists(n))return n===this.gridInstanceId}return!1},e.prototype.getCellPositionForEvent=function(e){var t=this.getRenderedCellForEvent(e);return t?t.getCellPosition():null},e.gridInstanceSequence=new l,e.GRID_DOM_KEY="__ag_grid_instance",dn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),dn([m("eGridDiv")],e.prototype,"eGridDiv",void 0),dn([g],e.prototype,"init",null),e=t=dn([y("mouseEventService")],e)}(),gn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},fn=function(){function e(){}return e.prototype.getNextCellToFocus=function(e,t){for(var i=t,n=!1;!n;){switch(e){case o.KEY_UP:i=this.getCellAbove(i);break;case o.KEY_DOWN:i=this.getCellBelow(i);break;case o.KEY_RIGHT:i=this.gridOptionsWrapper.isEnableRtl()?this.getCellToLeft(i):this.getCellToRight(i);break;case o.KEY_LEFT:i=this.gridOptionsWrapper.isEnableRtl()?this.getCellToRight(i):this.getCellToLeft(i);break;default:i=null,console.warn("ag-Grid: unknown key for navigation "+e)}n=!i||this.isCellGoodToFocusOn(i)}return i},e.prototype.isCellGoodToFocusOn=function(e){var t,i=e.column;switch(e.rowPinned){case o.PINNED_TOP:t=this.pinnedRowModel.getPinnedTopRow(e.rowIndex);break;case o.PINNED_BOTTOM:t=this.pinnedRowModel.getPinnedBottomRow(e.rowIndex);break;default:t=this.rowModel.getRow(e.rowIndex)}return!i.isSuppressNavigable(t)},e.prototype.getCellToLeft=function(e){if(!e)return null;var t=this.columnController.getDisplayedColBefore(e.column);return t?{rowIndex:e.rowIndex,column:t,rowPinned:e.rowPinned}:null},e.prototype.getCellToRight=function(e){if(!e)return null;var t=this.columnController.getDisplayedColAfter(e.column);return t?{rowIndex:e.rowIndex,column:t,rowPinned:e.rowPinned}:null},e.prototype.getRowBelow=function(e){var t=e.rowIndex,i=e.rowPinned;if(this.isLastRowInContainer(e))switch(i){case o.PINNED_BOTTOM:return null;case o.PINNED_TOP:return this.rowModel.isRowsToRender()?{rowIndex:0,rowPinned:null}:this.pinnedRowModel.isRowsToRender(o.PINNED_BOTTOM)?{rowIndex:0,rowPinned:o.PINNED_BOTTOM}:null;default:return this.pinnedRowModel.isRowsToRender(o.PINNED_BOTTOM)?{rowIndex:0,rowPinned:o.PINNED_BOTTOM}:null}return{rowIndex:t+1,rowPinned:i}},e.prototype.getCellBelow=function(e){if(!e)return null;var t=this.getRowBelow(e);return t?{rowIndex:t.rowIndex,column:e.column,rowPinned:t.rowPinned}:null},e.prototype.isLastRowInContainer=function(e){var t=e.rowPinned,i=e.rowIndex;return t===o.PINNED_TOP?this.pinnedRowModel.getPinnedTopRowData().length-1<=i:t===o.PINNED_BOTTOM?this.pinnedRowModel.getPinnedBottomRowData().length-1<=i:this.rowModel.getRowCount()-1<=i},e.prototype.getRowAbove=function(e){var t=e.rowIndex,i=e.rowPinned;return 0===t?i===o.PINNED_TOP?null:i&&this.rowModel.isRowsToRender()?this.getLastBodyCell():this.pinnedRowModel.isRowsToRender(o.PINNED_TOP)?this.getLastFloatingTopRow():null:{rowIndex:t-1,rowPinned:i}},e.prototype.getCellAbove=function(e){if(!e)return null;var t=this.getRowAbove({rowIndex:e.rowIndex,rowPinned:e.rowPinned});return t?{rowIndex:t.rowIndex,column:e.column,rowPinned:t.rowPinned}:null},e.prototype.getLastBodyCell=function(){return{rowIndex:this.rowModel.getRowCount()-1,rowPinned:null}},e.prototype.getLastFloatingTopRow=function(){return{rowIndex:this.pinnedRowModel.getPinnedTopRowData().length-1,rowPinned:o.PINNED_TOP}},e.prototype.getNextTabbedCell=function(e,t){return t?this.getNextTabbedCellBackwards(e):this.getNextTabbedCellForwards(e)},e.prototype.getNextTabbedCellForwards=function(e){var t=this.columnController.getAllDisplayedColumns(),o=e.rowIndex,i=e.rowPinned,n=this.columnController.getDisplayedColAfter(e.column);if(!n){n=t[0];var r=this.getRowBelow(e);if(p.missing(r))return null;o=r?r.rowIndex:null,i=r?r.rowPinned:null}return{rowIndex:o,column:n,rowPinned:i}},e.prototype.getNextTabbedCellBackwards=function(e){var t=this.columnController.getAllDisplayedColumns(),o=e.rowIndex,i=e.rowPinned,n=this.columnController.getDisplayedColBefore(e.column);if(!n){n=p.last(t);var r=this.getRowAbove({rowIndex:e.rowIndex,rowPinned:e.rowPinned});if(p.missing(r))return null;o=r?r.rowIndex:null,i=r?r.rowPinned:null}return{rowIndex:o,column:n,rowPinned:i}},gn([m("columnController")],e.prototype,"columnController",void 0),gn([m("rowModel")],e.prototype,"rowModel",void 0),gn([m("pinnedRowModel")],e.prototype,"pinnedRowModel",void 0),gn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),e=gn([y("cellNavigationService")],e)}(),yn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},mn=function(){function e(){this.cellRendererMap={}}var t;return t=e,e.prototype.init=function(){this.cellRendererMap[t.ANIMATE_SLIDE]=rt,this.cellRendererMap[t.ANIMATE_SHOW_CHANGE]=ot,this.cellRendererMap[t.GROUP]=Ze},e.prototype.addCellRenderer=function(e,t){this.cellRendererMap[e]=t},e.prototype.getCellRenderer=function(e){var t=this.cellRendererMap[e];return p.missing(t)?(console.warn("ag-Grid: unable to find cellRenderer for key "+e),null):t},e.ANIMATE_SLIDE="animateSlide",e.ANIMATE_SHOW_CHANGE="animateShowChange",e.GROUP="group",yn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),yn([m("expressionService")],e.prototype,"expressionService",void 0),yn([m("eventService")],e.prototype,"eventService",void 0),yn([g],e.prototype,"init",null),e=t=yn([y("cellRendererFactory")],e)}(),vn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Cn=function(){function e(){}return e.prototype.formatValue=function(e,t,o,i){var n,r=e.getColDef(),s=null;if(n=t&&t.rowPinned&&r.pinnedRowValueFormatter?r.pinnedRowValueFormatter:r.valueFormatter){var a={value:i,node:t,data:t?t.data:null,colDef:e.getColDef(),column:e,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext()};a.$scope=o,s=this.expressionService.evaluate(n,a)}else if(r.refData)return r.refData[i]||"";return null==s&&Array.isArray(i)&&(s=i.join(", ")),s},vn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),vn([m("expressionService")],e.prototype,"expressionService",void 0),e=vn([y("valueFormatterService")],e)}(),En=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),wn=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.className="ag-radio-button",t.inputType="radio",t.iconMap={selected:"radioButtonOn",unselected:"radioButtonOff"},t}return En(t,e),t.prototype.toggle=function(){var e=this.getNextValue();this.setValue(e)},t.prototype.getIconName=function(){var e=this.getValue()?"selected":"unselected",t=this.isReadOnly()?"ReadOnly":"";return""+this.iconMap[e]+t},t}(jo),Rn=function(){function e(){}return e.prototype.setTimeout=function(e,t){window.setTimeout(e,t)},e.prototype.addEventListenerOutsideAngular=function(e,t,o,i){e.addEventListener(t,o,i)},e}(),On=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Dn=function(){function e(){}return e.prototype.setScrollsVisible=function(e){if(this.horizontalScrollShowing!==e.horizontalScrollShowing||this.verticalScrollShowing!==e.verticalScrollShowing){this.horizontalScrollShowing=e.horizontalScrollShowing,this.verticalScrollShowing=e.verticalScrollShowing;var t={type:M.EVENT_SCROLL_VISIBILITY_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)}},e.prototype.isHorizontalScrollShowing=function(){return this.horizontalScrollShowing},e.prototype.isVerticalScrollShowing=function(){return this.verticalScrollShowing},On([m("eventService")],e.prototype,"eventService",void 0),On([m("columnController")],e.prototype,"columnController",void 0),On([m("columnApi")],e.prototype,"columnApi",void 0),On([m("gridApi")],e.prototype,"gridApi",void 0),On([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),e=On([y("scrollVisibleService")],e)}(),bn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Pn=function(){function e(){}return e.prototype.processAllCellClasses=function(e,t,o,i){this.processClassRules(e.cellClassRules,t,o,i),this.processStaticCellClasses(e,t,o)},e.prototype.processClassRules=function(e,t,o,i){if("object"==typeof e&&null!==e)for(var n=Object.keys(e),r=0;r<n.length;r++){var s=n[r],a=e[s],l=void 0;"string"==typeof a?l=this.expressionService.evaluate(a,t):"function"==typeof a&&(l=a(t)),l?o(s):i&&i(s)}},e.prototype.processStaticCellClasses=function(e,t,o){if(e.cellClass){var i=void 0;if("function"==typeof e.cellClass)i=(0,e.cellClass)(t);else i=e.cellClass;"string"==typeof i?o(i):Array.isArray(i)&&i.forEach((function(e){o(e)}))}},bn([m("expressionService")],e.prototype,"expressionService",void 0),e=bn([y("stylingService")],e)}(),Sn=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Tn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},An=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Sn(t,e),t.prototype.setMouseOver=function(e){this.selectedColumns=e;var t={type:M.EVENT_COLUMN_HOVER_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)},t.prototype.clearMouseOver=function(){this.selectedColumns=null;var e={type:M.EVENT_COLUMN_HOVER_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)},t.prototype.isHovered=function(e){return this.selectedColumns&&this.selectedColumns.indexOf(e)>=0},Tn([m("eventService")],t.prototype,"eventService",void 0),Tn([m("columnApi")],t.prototype,"columnApi",void 0),Tn([m("gridApi")],t.prototype,"gridApi",void 0),t=Tn([y("columnHoverService")],t)}(re),_n=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Fn=function(){function e(){this.executeNextFuncs=[],this.executeLaterFuncs=[],this.active=!1,this.animationThreadCount=0}return e.prototype.registerGridComp=function(e){this.gridPanel=e},e.prototype.isActive=function(){return this.active},e.prototype.start=function(){this.active||this.gridOptionsWrapper.isSuppressColumnMoveAnimation()||this.gridOptionsWrapper.isEnableRtl()||(this.ensureAnimationCssClassPresent(),this.active=!0)},e.prototype.finish=function(){this.active&&(this.flush(),this.active=!1)},e.prototype.executeNextVMTurn=function(e){this.active?this.executeNextFuncs.push(e):e()},e.prototype.executeLaterVMTurn=function(e){this.active?this.executeLaterFuncs.push(e):e()},e.prototype.ensureAnimationCssClassPresent=function(){var e=this;this.animationThreadCount++;var t=this.animationThreadCount;this.gridPanel.setColumnMovingCss(!0),this.executeLaterFuncs.push((function(){e.animationThreadCount===t&&e.gridPanel.setColumnMovingCss(!1)}))},e.prototype.flush=function(){var e=this.executeNextFuncs;this.executeNextFuncs=[];var t=this.executeLaterFuncs;this.executeLaterFuncs=[],0===e.length&&0===t.length||(window.setTimeout((function(){return e.forEach((function(e){return e()}))}),0),window.setTimeout((function(){return t.forEach((function(e){return e()}))}),300))},_n([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),e=_n([y("columnAnimationService")],e)}(),Nn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ln=function(){function e(){}var t;return t=e,e.prototype.createAutoGroupColumns=function(e){var t=this,o=[],i=this.gridOptionsWrapper.isTreeData(),n=this.gridOptionsWrapper.isGroupMultiAutoColumn();return i&&n&&(console.warn("ag-Grid: you cannot mix groupMultiAutoColumn with treeData, only one column can be used to display groups when doing tree data"),n=!1),n?e.forEach((function(e,i){o.push(t.createOneAutoGroupColumn(e,i))})):o.push(this.createOneAutoGroupColumn()),o},e.prototype.createOneAutoGroupColumn=function(e,i){var n,r=this.generateDefaultColDef(e);n=e?o.GROUP_AUTO_COLUMN_ID+"-"+e.getId():t.GROUP_AUTO_COLUMN_BUNDLE_ID;var s=this.gridOptionsWrapper.getAutoGroupColumnDef();(p.mergeDeep(r,s),(r=this.columnFactory.mergeColDefs(r)).colId=n,this.gridOptionsWrapper.isTreeData())||p.missing(r.field)&&p.missing(r.valueGetter)&&p.missing(r.filterValueGetter)&&(r.filter=!1);i&&i>0&&(r.headerCheckboxSelection=!1);var a=new T(r,null,n,!0);return this.context.wireBean(a),a},e.prototype.generateDefaultColDef=function(e){var t=this.gridOptionsWrapper.getAutoGroupColumnDef(),o={headerName:this.gridOptionsWrapper.getLocaleTextFunc()("group","Group")};if(t&&(t.cellRenderer||t.cellRendererFramework)||(o.cellRenderer="agGroupCellRenderer"),e){var i=e.getColDef();p.assign(o,{headerName:this.columnController.getDisplayNameForColumn(e,"header"),headerValueGetter:i.headerValueGetter}),i.cellRenderer&&p.assign(o,{cellRendererParams:{innerRenderer:i.cellRenderer,innerRendererParams:i.cellRendererParams}}),o.showRowGroup=e.getColId()}else o.showRowGroup=!0;return o},e.GROUP_AUTO_COLUMN_BUNDLE_ID=o.GROUP_AUTO_COLUMN_ID,Nn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Nn([m("context")],e.prototype,"context",void 0),Nn([m("columnController")],e.prototype,"columnController",void 0),Nn([m("columnFactory")],e.prototype,"columnFactory",void 0),e=t=Nn([y("autoGroupColService")],e)}(),In=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Gn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Mn=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.currentPage=0,t.topDisplayedRowIndex=0,t.bottomDisplayedRowIndex=0,t.pixelOffset=0,t.masterRowCount=0,t}return In(t,e),t.prototype.postConstruct=function(){this.active=this.gridOptionsWrapper.isPagination(),this.paginateChildRows=this.gridOptionsWrapper.isPaginateChildRows(),this.addDestroyableEventListener(this.eventService,M.EVENT_MODEL_UPDATED,this.onModelUpdated.bind(this)),this.addDestroyableEventListener(this.gridOptionsWrapper,"paginationPageSize",this.onModelUpdated.bind(this)),this.onModelUpdated()},t.prototype.ensureRowHeightsValid=function(e,t,o,i){var n=this.rowModel.ensureRowHeightsValid(e,t,this.getPageFirstRow(),this.getPageLastRow());return n&&this.calculatePages(),n},t.prototype.onModelUpdated=function(e){this.calculatePages();var t={type:M.EVENT_PAGINATION_CHANGED,animate:!!e&&e.animate,newData:!!e&&e.newData,newPage:!!e&&e.newPage,keepRenderedRows:!!e&&e.keepRenderedRows,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)},t.prototype.goToPage=function(e){if(this.active&&this.currentPage!==e){this.currentPage=e;var t={type:M.EVENT_MODEL_UPDATED,animate:!1,keepRenderedRows:!1,newData:!1,newPage:!0,api:this.gridApi,columnApi:this.columnApi};this.onModelUpdated(t)}},t.prototype.getPixelOffset=function(){return this.pixelOffset},t.prototype.getRow=function(e){return this.rowModel.getRow(e)},t.prototype.getRowNode=function(e){return this.rowModel.getRowNode(e)},t.prototype.getRowIndexAtPixel=function(e){return this.rowModel.getRowIndexAtPixel(e)},t.prototype.getCurrentPageHeight=function(){return p.missing(this.topRowBounds)||p.missing(this.bottomRowBounds)?0:Math.max(this.bottomRowBounds.rowTop+this.bottomRowBounds.rowHeight-this.topRowBounds.rowTop,0)},t.prototype.isRowPresent=function(e){return!!this.rowModel.isRowPresent(e)&&(e.rowIndex>=this.topDisplayedRowIndex&&e.rowIndex<=this.bottomDisplayedRowIndex)},t.prototype.isEmpty=function(){return this.rowModel.isEmpty()},t.prototype.isRowsToRender=function(){return this.rowModel.isRowsToRender()},t.prototype.getNodesInRangeForSelection=function(e,t){return this.rowModel.getNodesInRangeForSelection(e,t)},t.prototype.forEachNode=function(e){return this.rowModel.forEachNode(e)},t.prototype.getType=function(){return this.rowModel.getType()},t.prototype.getRowBounds=function(e){var t=this.rowModel.getRowBounds(e);return t.rowIndex=e,t},t.prototype.getPageFirstRow=function(){return this.topRowBounds?this.topRowBounds.rowIndex:-1},t.prototype.getPageLastRow=function(){return this.bottomRowBounds?this.bottomRowBounds.rowIndex:-1},t.prototype.getRowCount=function(){return this.rowModel.getRowCount()},t.prototype.goToPageWithIndex=function(e){if(this.active){var t=Math.floor(e/this.pageSize);this.goToPage(t)}},t.prototype.isLastPageFound=function(){return this.rowModel.isLastRowFound()},t.prototype.getCurrentPage=function(){return this.currentPage},t.prototype.goToNextPage=function(){this.goToPage(this.currentPage+1)},t.prototype.goToPreviousPage=function(){this.goToPage(this.currentPage-1)},t.prototype.goToFirstPage=function(){this.goToPage(0)},t.prototype.goToLastPage=function(){var e=this.rowModel.getRowCount(),t=Math.floor(e/this.pageSize);this.goToPage(t)},t.prototype.getPageSize=function(){return this.pageSize},t.prototype.getTotalPages=function(){return this.totalPages},t.prototype.setPageSize=function(){this.pageSize=this.gridOptionsWrapper.getPaginationPageSize(),this.pageSize>=1||(this.pageSize=100)},t.prototype.calculatePages=function(){this.active?(this.setPageSize(),this.paginateChildRows?this.calculatePagesAllRows():this.calculatePagesMasterRowsOnly()):this.calculatedPagesNotActive(),this.topRowBounds=this.rowModel.getRowBounds(this.topDisplayedRowIndex),this.topRowBounds&&(this.topRowBounds.rowIndex=this.topDisplayedRowIndex),this.bottomRowBounds=this.rowModel.getRowBounds(this.bottomDisplayedRowIndex),this.bottomRowBounds&&(this.bottomRowBounds.rowIndex=this.bottomDisplayedRowIndex),this.pixelOffset=p.exists(this.topRowBounds)?this.topRowBounds.rowTop:0},t.prototype.setZeroRows=function(){this.topDisplayedRowIndex=0,this.bottomDisplayedRowIndex=-1,this.currentPage=0,this.totalPages=0},t.prototype.calculatePagesMasterRowsOnly=function(){if(this.masterRowCount=this.rowModel.getTopLevelRowCount(),0!==this.masterRowCount){var e=this.masterRowCount-1;this.totalPages=Math.floor(e/this.pageSize)+1,this.currentPage>=this.totalPages&&(this.currentPage=this.totalPages-1),(!p.isNumeric(this.currentPage)||this.currentPage<0)&&(this.currentPage=0);var t=this.pageSize*this.currentPage,o=this.pageSize*(this.currentPage+1)-1;if(o>e&&(o=e),this.topDisplayedRowIndex=this.rowModel.getTopLevelRowDisplayedIndex(t),o===e)this.bottomDisplayedRowIndex=this.rowModel.getRowCount()-1;else{var i=this.rowModel.getTopLevelRowDisplayedIndex(o+1);this.bottomDisplayedRowIndex=i-1}}else this.setZeroRows()},t.prototype.getMasterRowCount=function(){return this.masterRowCount},t.prototype.calculatePagesAllRows=function(){if(this.masterRowCount=this.rowModel.getRowCount(),0!==this.masterRowCount){var e=this.masterRowCount-1;this.totalPages=Math.floor(e/this.pageSize)+1,this.currentPage>=this.totalPages&&(this.currentPage=this.totalPages-1),(!p.isNumeric(this.currentPage)||this.currentPage<0)&&(this.currentPage=0),this.topDisplayedRowIndex=this.pageSize*this.currentPage,this.bottomDisplayedRowIndex=this.pageSize*(this.currentPage+1)-1,this.bottomDisplayedRowIndex>e&&(this.bottomDisplayedRowIndex=e)}else this.setZeroRows()},t.prototype.calculatedPagesNotActive=function(){this.pageSize=this.rowModel.getRowCount(),this.totalPages=1,this.currentPage=0,this.topDisplayedRowIndex=0,this.bottomDisplayedRowIndex=this.rowModel.getRowCount()-1},Gn([m("rowModel")],t.prototype,"rowModel",void 0),Gn([m("eventService")],t.prototype,"eventService",void 0),Gn([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Gn([m("selectionController")],t.prototype,"selectionController",void 0),Gn([m("columnApi")],t.prototype,"columnApi",void 0),Gn([m("gridApi")],t.prototype,"gridApi",void 0),Gn([g],t.prototype,"postConstruct",null),t=Gn([y("paginationProxy")],t)}(re),xn=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Vn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Wn=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return xn(t,e),t.prototype.registerGridComp=function(e){this.gridPanel=e,this.addDestroyableEventListener(this.eventService,M.EVENT_BODY_HEIGHT_CHANGED,this.onBodyHeightChanged.bind(this)),this.addDestroyableEventListener(this.eventService,M.EVENT_SCROLL_VISIBILITY_CHANGED,this.onScrollVisibilityChanged.bind(this)),this.checkPageSize()},t.prototype.notActive=function(){return!this.gridOptionsWrapper.isPaginationAutoPageSize()},t.prototype.onScrollVisibilityChanged=function(){this.checkPageSize()},t.prototype.onBodyHeightChanged=function(){this.checkPageSize()},t.prototype.checkPageSize=function(){if(!this.notActive()){var e=this.gridOptionsWrapper.getRowHeightAsNumber(),t=this.gridPanel.getBodyHeight();if(t>0){var o=Math.floor(t/e);this.gridOptionsWrapper.setProperty("paginationPageSize",o)}}},Vn([m("eventService")],t.prototype,"eventService",void 0),Vn([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Vn([m("scrollVisibleService")],t.prototype,"scrollVisibleService",void 0),t=Vn([y("paginationAutoPageSizeService")],t)}(re),Hn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},kn=function(){function e(){this.cacheVersion=0}return e.prototype.init=function(){this.active=this.gridOptionsWrapper.isValueCache(),this.neverExpires=this.gridOptionsWrapper.isValueCacheNeverExpires()},e.prototype.onDataChanged=function(){this.neverExpires||this.expire()},e.prototype.expire=function(){this.cacheVersion++},e.prototype.setValue=function(e,t,o){this.active&&(e.__cacheVersion!==this.cacheVersion&&(e.__cacheVersion=this.cacheVersion,e.__cacheData={}),e.__cacheData[t]=o)},e.prototype.getValue=function(e,t){if(this.active&&e.__cacheVersion===this.cacheVersion)return e.__cacheData[t]},Hn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Hn([g],e.prototype,"init",null),e=Hn([y("valueCache")],e)}(),Bn=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Un=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},jn=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Bn(t,e),t.prototype.init=function(){this.rowModel.getType()===o.ROW_MODEL_TYPE_CLIENT_SIDE&&(this.clientSideRowModel=this.rowModel),this.addDestroyableEventListener(this.eventService,M.EVENT_CELL_VALUE_CHANGED,this.onCellValueChanged.bind(this))},t.prototype.onCellValueChanged=function(e){e.source!==o.SOURCE_PASTE&&this.doChangeDetection(e.node,e.column)},t.prototype.doChangeDetection=function(e,t){if(!this.gridOptionsWrapper.isSuppressChangeDetection()){if(this.clientSideRowModel&&!e.isRowPinned()){var o=this.gridOptionsWrapper.isAggregateOnlyChangedColumns(),i=new Qt(o,this.clientSideRowModel.getRootNode());i.addParentNode(e.parent,[t]),this.clientSideRowModel.doAggregate(i)}this.rowRenderer.refreshCells()}},Un([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Un([m("rowModel")],t.prototype,"rowModel",void 0),Un([m("rowRenderer")],t.prototype,"rowRenderer",void 0),Un([m("eventService")],t.prototype,"eventService",void 0),Un([g],t.prototype,"init",null),t=Un([y("changeDetectionService")],t)}(re),zn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Yn=function(e,t){return function(o,i){t(o,i,e)}},Kn=function(){function e(){this.consuming=!1}return e.prototype.setBeans=function(e){this.logger=e.create("AlignedGridsService")},e.prototype.registerGridComp=function(e){this.gridPanel=e},e.prototype.init=function(){this.eventService.addEventListener(M.EVENT_COLUMN_MOVED,this.fireColumnEvent.bind(this)),this.eventService.addEventListener(M.EVENT_COLUMN_VISIBLE,this.fireColumnEvent.bind(this)),this.eventService.addEventListener(M.EVENT_COLUMN_PINNED,this.fireColumnEvent.bind(this)),this.eventService.addEventListener(M.EVENT_COLUMN_GROUP_OPENED,this.fireColumnEvent.bind(this)),this.eventService.addEventListener(M.EVENT_COLUMN_RESIZED,this.fireColumnEvent.bind(this)),this.eventService.addEventListener(M.EVENT_BODY_SCROLL,this.fireScrollEvent.bind(this))},e.prototype.fireEvent=function(e){if(!this.consuming){var t=this.gridOptionsWrapper.getAlignedGrids();t&&t.forEach((function(t){if(t.api){var o=t.api.__getAlignedGridService();e(o)}}))}},e.prototype.onEvent=function(e){this.consuming=!0,e(),this.consuming=!1},e.prototype.fireColumnEvent=function(e){this.fireEvent((function(t){t.onColumnEvent(e)}))},e.prototype.fireScrollEvent=function(e){"horizontal"===e.direction&&this.fireEvent((function(t){t.onScrollEvent(e)}))},e.prototype.onScrollEvent=function(e){var t=this;this.onEvent((function(){t.gridPanel.setHorizontalScrollPosition(e.left)}))},e.prototype.getMasterColumns=function(e){var t=[];return e.columns?e.columns.forEach((function(e){t.push(e)})):e.column&&t.push(e.column),t},e.prototype.getColumnIds=function(e){var t=[];return e.columns?e.columns.forEach((function(e){t.push(e.getColId())})):e.column&&t.push(e.column.getColId()),t},e.prototype.onColumnEvent=function(e){var t=this;this.onEvent((function(){switch(e.type){case M.EVENT_COLUMN_MOVED:case M.EVENT_COLUMN_VISIBLE:case M.EVENT_COLUMN_PINNED:case M.EVENT_COLUMN_RESIZED:var o=e;t.processColumnEvent(o);break;case M.EVENT_COLUMN_GROUP_OPENED:var i=e;t.processGroupOpenedEvent(i);break;case M.EVENT_COLUMN_PIVOT_CHANGED:console.warn("ag-Grid: pivoting is not supported with aligned grids. You can only use one of these features at a time in a grid.")}}))},e.prototype.processGroupOpenedEvent=function(e){var t,o=e.columnGroup;if(o){var i=o.getGroupId();t=this.columnController.getOriginalColumnGroup(i)}o&&!t||(this.logger.log("onColumnEvent-> processing "+e+" expanded = "+o.isExpanded()),this.columnController.setColumnGroupOpened(t,o.isExpanded(),"alignedGridChanged"))},e.prototype.processColumnEvent=function(e){var t,o=this,i=e.column;if(i&&(t=this.columnController.getPrimaryColumn(i.getColId())),!i||t){var n=this.getColumnIds(e),r=this.getMasterColumns(e);switch(e.type){case M.EVENT_COLUMN_MOVED:var s=e;this.logger.log("onColumnEvent-> processing "+e.type+" toIndex = "+s.toIndex),this.columnController.moveColumns(n,s.toIndex,"alignedGridChanged");break;case M.EVENT_COLUMN_VISIBLE:var a=e;this.logger.log("onColumnEvent-> processing "+e.type+" visible = "+a.visible),this.columnController.setColumnsVisible(n,a.visible,"alignedGridChanged");break;case M.EVENT_COLUMN_PINNED:var l=e;this.logger.log("onColumnEvent-> processing "+e.type+" pinned = "+l.pinned),this.columnController.setColumnsPinned(n,l.pinned,"alignedGridChanged");break;case M.EVENT_COLUMN_RESIZED:var p=e;r.forEach((function(t){o.logger.log("onColumnEvent-> processing "+e.type+" actualWidth = "+t.getActualWidth()),o.columnController.setColumnWidth(t.getColId(),t.getActualWidth(),!1,p.finished,"alignedGridChanged")}))}var u=this.gridPanel.isVerticalScrollShowing();this.gridOptionsWrapper.getAlignedGrids().forEach((function(e){e.api.setAlwaysShowVerticalScroll(u)}))}},zn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),zn([m("columnController")],e.prototype,"columnController",void 0),zn([m("eventService")],e.prototype,"eventService",void 0),zn([Yn(0,E("loggerFactory"))],e.prototype,"setBeans",null),zn([g],e.prototype,"init",null),e=zn([y("alignedGridsService")],e)}(),qn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Qn=function(){function e(){}return e.prototype.adaptFunction=function(e,t,o,i){if(null==t)return{component:null,componentFromFramework:o,source:i,paramsFromSelector:null};var n=this.componentMetadataProvider.retrieve(e);return n&&n.functionAdapter?{componentFromFramework:o,component:n.functionAdapter(t),source:i,paramsFromSelector:null}:null},e.prototype.adaptCellRendererFunction=function(e){return function(){function t(){}return t.prototype.refresh=function(e){return!1},t.prototype.getGui=function(){var t=e(this.params),o=typeof t;return"string"===o||"number"===o||"boolean"===o?p.loadTemplate("<span>"+t+"</span>"):t},t.prototype.init=function(e){this.params=e},t}()},e.prototype.doesImplementIComponent=function(e){return!!e&&(e.prototype&&"getGui"in e.prototype)},qn([m("componentMetadataProvider")],e.prototype,"componentMetadataProvider",void 0),e=qn([y("agComponentUtils")],e)}(),Xn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},$n=function(){function e(){}return e.prototype.postConstruct=function(){this.componentMetaData={dateComponent:{mandatoryMethodList:["getDate","setDate"],optionalMethodList:["afterGuiAttached"]},detailCellRenderer:{mandatoryMethodList:[],optionalMethodList:["refresh"]},headerComponent:{mandatoryMethodList:[],optionalMethodList:[]},headerGroupComponent:{mandatoryMethodList:[],optionalMethodList:[]},loadingCellRenderer:{mandatoryMethodList:[],optionalMethodList:[]},loadingOverlayComponent:{mandatoryMethodList:[],optionalMethodList:[]},noRowsOverlayComponent:{mandatoryMethodList:[],optionalMethodList:[]},floatingFilterComponent:{mandatoryMethodList:["onParentModelChanged"],optionalMethodList:["afterGuiAttached"]},floatingFilterWrapperComponent:{mandatoryMethodList:[],optionalMethodList:[]},cellRenderer:{mandatoryMethodList:[],optionalMethodList:["refresh","afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},cellEditor:{mandatoryMethodList:["getValue"],optionalMethodList:["isPopup","isCancelBeforeStart","isCancelAfterEnd","focusIn","focusOut","afterGuiAttached"]},innerRenderer:{mandatoryMethodList:[],optionalMethodList:["afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},fullWidthCellRenderer:{mandatoryMethodList:[],optionalMethodList:["refresh","afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},pinnedRowCellRenderer:{mandatoryMethodList:[],optionalMethodList:["refresh","afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},groupRowInnerRenderer:{mandatoryMethodList:[],optionalMethodList:["afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},groupRowRenderer:{mandatoryMethodList:[],optionalMethodList:["afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},filter:{mandatoryMethodList:["isFilterActive","doesFilterPass","getModel","setModel"],optionalMethodList:["afterGuiAttached","onNewRowsLoaded","getModelAsString","onFloatingFilterChanged"]},filterComponent:{mandatoryMethodList:["isFilterActive","doesFilterPass","getModel","setModel"],optionalMethodList:["afterGuiAttached","onNewRowsLoaded","getModelAsString","onFloatingFilterChanged"]},statusPanel:{mandatoryMethodList:[],optionalMethodList:["afterGuiAttached"]},toolPanel:{mandatoryMethodList:[],optionalMethodList:["refresh","afterGuiAttached"]},tooltipComponent:{mandatoryMethodList:[],optionalMethodList:[]}}},e.prototype.retrieve=function(e){return this.componentMetaData[e]},Xn([m("agComponentUtils")],e.prototype,"agComponentUtils",void 0),Xn([g],e.prototype,"postConstruct",null),e=Xn([y("componentMetadataProvider")],e)}(),Jn=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Zn=function(){function e(){}return e.prototype.registerGridComp=function(e){this.gridPanel=e},e.prototype.postConstruct=function(){this.doingMasterDetail=this.gridOptionsWrapper.isMasterDetail()},Jn([m("paginationProxy")],e.prototype,"paginationProxy",void 0),Jn([m("context")],e.prototype,"context",void 0),Jn([m("columnApi")],e.prototype,"columnApi",void 0),Jn([m("gridApi")],e.prototype,"gridApi",void 0),Jn([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Jn([m("expressionService")],e.prototype,"expressionService",void 0),Jn([m("rowRenderer")],e.prototype,"rowRenderer",void 0),Jn([m("$compile")],e.prototype,"$compile",void 0),Jn([m("templateService")],e.prototype,"templateService",void 0),Jn([m("valueService")],e.prototype,"valueService",void 0),Jn([m("eventService")],e.prototype,"eventService",void 0),Jn([m("columnController")],e.prototype,"columnController",void 0),Jn([m("columnAnimationService")],e.prototype,"columnAnimationService",void 0),Jn([v("rangeController")],e.prototype,"rangeController",void 0),Jn([m("focusedCellController")],e.prototype,"focusedCellController",void 0),Jn([v("contextMenuFactory")],e.prototype,"contextMenuFactory",void 0),Jn([m("cellRendererFactory")],e.prototype,"cellRendererFactory",void 0),Jn([m("popupService")],e.prototype,"popupService",void 0),Jn([m("valueFormatterService")],e.prototype,"valueFormatterService",void 0),Jn([m("stylingService")],e.prototype,"stylingService",void 0),Jn([m("columnHoverService")],e.prototype,"columnHoverService",void 0),Jn([m("userComponentFactory")],e.prototype,"userComponentFactory",void 0),Jn([m("animationFrameService")],e.prototype,"taskQueue",void 0),Jn([m("dragAndDropService")],e.prototype,"dragAndDropService",void 0),Jn([m("sortController")],e.prototype,"sortController",void 0),Jn([m("filterManager")],e.prototype,"filterManager",void 0),Jn([m("maxDivHeightScaler")],e.prototype,"maxDivHeightScaler",void 0),Jn([m("tooltipManager")],e.prototype,"tooltipManager",void 0),Jn([m("frameworkOverrides")],e.prototype,"frameworkOverrides",void 0),Jn([m("detailRowCompCache")],e.prototype,"detailRowCompCache",void 0),Jn([m("cellPositionUtils")],e.prototype,"cellPositionUtils",void 0),Jn([m("rowPositionUtils")],e.prototype,"rowPositionUtils",void 0),Jn([g],e.prototype,"postConstruct",null),e=Jn([y("beans")],e)}(),er=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},tr={"ag-theme-material":{headerHeight:56,virtualItemHeight:40,rowHeight:48},"ag-theme-classic":{headerHeight:25,virtualItemHeight:20,rowHeight:25},"ag-theme-balham":{headerHeight:32,virtualItemHeight:28,rowHeight:28}},or={headerHeight:["ag-header-row"],virtualItemHeight:["ag-virtual-list-container","ag-virtual-list-item"],rowHeight:["ag-row"]},ir={},nr=function(){function e(){}return e.prototype.getSassVariable=function(e,t){var o="ag-theme-"+(e.match("material")?"material":e.match("balham")?"balham":"classic"),i=tr[o][t],n=0;if(ir[e]||(ir[e]={}),ir[e][t])return ir[e][t];if(or[t]){var r=or[t],s=document.createElement("div"),a=r.reduce((function(t,o,i){0===i&&p.addCssClass(t,e);var n=document.createElement("div");return p.addCssClass(n,o),t.appendChild(n),n}),s);document.body&&(document.body.appendChild(s),n=parseInt(window.getComputedStyle(a).height,10),document.body.removeChild(s))}return ir[e][t]=n||i,ir[e][t]},e.prototype.isThemeDark=function(){var e=this.getTheme().theme;return!!e&&e.indexOf("dark")>=0},e.prototype.getTheme=function(){for(var e,t=/\bag-(fresh|dark|blue|material|bootstrap|(?:theme-([\w\-]*)))\b/,o=this.eGridDiv;o&&!(e=t.exec(o.className));)o=o.parentElement;if(!e)return{};var i=e[0];if(void 0===e[2]){var n=i.replace("ag-","ag-theme-");p.doOnce((function(){return console.warn("ag-Grid: As of v19 old theme are no longer provided. Please replace "+i+" with "+n+".")}),"using-old-theme")}return{theme:i,el:o}},er([m("eGridDiv")],e.prototype,"eGridDiv",void 0),e=er([y("environment")],e)}(),rr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},sr=function(){function e(){this.createTasksP1={list:[],sorted:!1},this.createTasksP2={list:[],sorted:!1},this.destroyTasks=[],this.ticking=!1,this.scrollGoingDown=!0,this.lastScrollTop=0}return e.prototype.setScrollTop=function(e){this.scrollGoingDown=e>this.lastScrollTop,this.lastScrollTop=e},e.prototype.init=function(){this.useAnimationFrame=!this.gridOptionsWrapper.isSuppressAnimationFrame()},e.prototype.verifyAnimationFrameOn=function(e){!1===this.useAnimationFrame&&console.warn("ag-Grid: AnimationFrameService."+e+" called but animation frames are off")},e.prototype.createTask=function(e,t,o){this.verifyAnimationFrameOn(o);var i={task:e,index:t};this.addTaskToList(this[o],i),this.schedule()},e.prototype.addTaskToList=function(e,t){e.list.push(t),e.sorted=!1},e.prototype.sortTaskList=function(e){if(!e.sorted){e.list.sort(this.scrollGoingDown?function(e,t){return t.index-e.index}:function(e,t){return e.index-t.index}),e.sorted=!0}},e.prototype.addDestroyTask=function(e){this.verifyAnimationFrameOn("createTasksP3"),this.destroyTasks.push(e),this.schedule()},e.prototype.executeFrame=function(e){this.verifyAnimationFrameOn("executeFrame");for(var t=this.createTasksP1,o=t.list,i=this.createTasksP2,n=i.list,r=this.destroyTasks,s=(new Date).getTime(),a=(new Date).getTime()-s,l=e<=0;l||a<e;){if(o.length)this.sortTaskList(t),o.pop().task();else if(n.length){this.sortTaskList(i),n.pop().task()}else{if(!r.length)break;r.pop()()}a=(new Date).getTime()-s}o.length||n.length||r.length?this.requestFrame():this.stopTicking()},e.prototype.stopTicking=function(){this.ticking=!1;var e={type:M.EVENT_ANIMATION_QUEUE_EMPTY,columnApi:this.gridOptionsWrapper.getColumnApi(),api:this.gridOptionsWrapper.getApi()};this.eventService.dispatchEvent(e)},e.prototype.flushAllFrames=function(){this.useAnimationFrame&&this.executeFrame(-1)},e.prototype.schedule=function(){this.useAnimationFrame&&(this.ticking||(this.ticking=!0,this.requestFrame()))},e.prototype.requestFrame=function(){var e=this.executeFrame.bind(this,60);window.requestAnimationFrame?window.requestAnimationFrame(e):window.webkitRequestAnimationFrame?window.webkitRequestAnimationFrame(e):window.setTimeout(e,0)},e.prototype.isQueueEmpty=function(){return this.ticking},rr([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),rr([m("eventService")],e.prototype,"eventService",void 0),rr([g],e.prototype,"init",null),e=rr([y("animationFrameService")],e)}(),ar=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},lr=function(){function e(){this.timeLastPageEventProcessed=0}return e.prototype.init=function(){this.scrollWidth=this.gridOptionsWrapper.getScrollbarWidth()},e.prototype.registerGridComp=function(e){this.gridPanel=e},e.prototype.handlePageScrollingKey=function(e){var t=e.which||e.keyCode,i=e.altKey,n=e.ctrlKey,r=this.mouseEventService.getCellPositionForEvent(e);if(!r)return!1;var s=!1;switch(t){case o.KEY_PAGE_HOME:case o.KEY_PAGE_END:n||i||(this.onHomeOrEndKey(t),s=!0);break;case o.KEY_LEFT:case o.KEY_RIGHT:n&&!i&&(this.onCtrlLeftOrRight(t,r),s=!0);break;case o.KEY_UP:case o.KEY_DOWN:n&&!i&&(this.onCtrlUpOrDown(t,r),s=!0);break;case o.KEY_PAGE_DOWN:n||i||(this.onPageDown(r),s=!0);break;case o.KEY_PAGE_UP:n||i||(this.onPageUp(r),s=!0)}return s&&e.preventDefault(),s},e.prototype.isTimeSinceLastPageEventToRecent=function(){return(new Date).getTime()-this.timeLastPageEventProcessed<100},e.prototype.setTimeLastPageEventProcessed=function(){this.timeLastPageEventProcessed=(new Date).getTime()},e.prototype.onPageDown=function(e){if(!this.isTimeSinceLastPageEventToRecent()){var t=this.gridPanel.getVScrollPosition(),o=t.bottom-t.top;this.gridPanel.isHorizontalScrollShowing()&&(o-=this.scrollWidth);var i=this.paginationProxy.getPixelOffset(),n=t.top+o,r=this.paginationProxy.getRowIndexAtPixel(n+i),s=this.paginationProxy.getRow(e.rowIndex).rowTop+o-i,a=this.paginationProxy.getRowIndexAtPixel(s+i),l=this.paginationProxy.getPageLastRow();a>l&&(a=l),r>l&&(r=l),this.navigateTo(r,"top",null,a,e.column),this.setTimeLastPageEventProcessed()}},e.prototype.onPageUp=function(e){if(!this.isTimeSinceLastPageEventToRecent()){var t=this.gridPanel.getVScrollPosition(),o=t.bottom-t.top;this.gridPanel.isHorizontalScrollShowing()&&(o-=this.scrollWidth);var i=this.paginationProxy.getPixelOffset(),n=t.top,r=this.paginationProxy.getRowIndexAtPixel(n+i),s=this.paginationProxy.getRow(e.rowIndex),a=s.rowTop+s.rowHeight-o-i,l=this.paginationProxy.getRowIndexAtPixel(a+i),p=this.paginationProxy.getPageFirstRow();l<p&&(l=p),r<p&&(r=p),this.navigateTo(r,"bottom",null,l,e.column),this.setTimeLastPageEventProcessed()}},e.prototype.navigateTo=function(e,t,o,i,n){if(p.exists(o)&&this.gridPanel.ensureColumnVisible(o),p.exists(e)&&this.gridPanel.ensureIndexVisible(e,t),this.animationFrameService.flushAllFrames(),this.focusedCellController.setFocusedCell(i,n,null,!0),this.rangeController){var r={rowIndex:i,rowPinned:null,column:n};this.rangeController.setRangeToCell(r)}},e.prototype.onCtrlUpOrDown=function(e,t){var i=e===o.KEY_UP?0:this.paginationProxy.getPageLastRow();this.navigateTo(i,null,t.column,i,t.column)},e.prototype.onCtrlLeftOrRight=function(e,t){var i=e===o.KEY_LEFT,n=this.columnController.getAllDisplayedColumns(),r=i?n[0]:p.last(n);this.navigateTo(t.rowIndex,null,r,t.rowIndex,r)},e.prototype.onHomeOrEndKey=function(e){var t=e===o.KEY_PAGE_HOME,i=this.columnController.getAllDisplayedColumns(),n=t?i[0]:p.last(i),r=t?0:this.paginationProxy.getPageLastRow();this.navigateTo(r,null,n,r,n)},ar([m("mouseEventService")],e.prototype,"mouseEventService",void 0),ar([m("paginationProxy")],e.prototype,"paginationProxy",void 0),ar([m("focusedCellController")],e.prototype,"focusedCellController",void 0),ar([m("animationFrameService")],e.prototype,"animationFrameService",void 0),ar([v("rangeController")],e.prototype,"rangeController",void 0),ar([m("columnController")],e.prototype,"columnController",void 0),ar([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),ar([g],e.prototype,"init",null),e=ar([y("navigationService")],e)}(),pr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ur=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},cr=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.scrollY=0,t.uiBodyHeight=0,t}return pr(t,e),t.prototype.postConstruct=function(){this.addDestroyableEventListener(this.eventService,M.EVENT_BODY_HEIGHT_CHANGED,this.updateOffset.bind(this)),this.scrollBarWidth=this.gridOptionsWrapper.getScrollbarWidth(),this.maxDivHeight=p.getMaxDivHeight()},t.prototype.registerGridComp=function(e){this.gridPanel=e},t.prototype.isScaling=function(){return this.scaling},t.prototype.getOffset=function(){return this.offset},t.prototype.updateOffset=function(){if(this.scaling){var e=this.gridPanel.getVScrollPosition().top,t=this.getUiBodyHeight();(e!==this.scrollY||t!==this.uiBodyHeight)&&(this.scrollY=e,this.uiBodyHeight=t,this.calculateOffset())}},t.prototype.calculateOffset=function(){this.uiContainerHeight=this.maxDivHeight,this.pixelsToShave=this.modelHeight-this.uiContainerHeight,this.maxScrollY=this.uiContainerHeight-this.uiBodyHeight;var e=this.scrollY/this.maxScrollY;this.setOffset(e*this.pixelsToShave)},t.prototype.clearOffset=function(){this.uiContainerHeight=this.modelHeight,this.pixelsToShave=0,this.setOffset(0)},t.prototype.setOffset=function(e){var t="number"==typeof e?Math.floor(e):null;this.offset!==t&&(this.offset=t,this.eventService.dispatchEvent({type:M.EVENT_HEIGHT_SCALE_CHANGED}))},t.prototype.setModelHeight=function(e){this.modelHeight=e,this.scaling=this.maxDivHeight>0&&e>this.maxDivHeight,this.scaling?this.calculateOffset():this.clearOffset()},t.prototype.getUiContainerHeight=function(){return this.uiContainerHeight},t.prototype.getRealPixelPosition=function(e){return e-this.offset},t.prototype.getUiBodyHeight=function(){var e=this.gridPanel.getVScrollPosition();return e.bottom-e.top},t.prototype.getScrollPositionForPixel=function(e){if(this.pixelsToShave<=0)return e;var t=e/(this.modelHeight-this.getUiBodyHeight());return this.maxScrollY*t},ur([m("eventService")],t.prototype,"eventService",void 0),ur([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),ur([g],t.prototype,"postConstruct",null),t=ur([y("maxDivHeightScaler")],t)}(re),dr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},hr=function(){function e(){}return e.prototype.init=function(){this.groupSelectsChildren=this.gridOptionsWrapper.isGroupSelectsChildren(),this.isRowSelectableFunc=this.gridOptionsWrapper.getIsRowSelectableFunc()},e.prototype.updateSelectableAfterGrouping=function(e){if(this.isRowSelectableFunc){this.recurseDown(e.childrenAfterGroup,(function(e){return e.childrenAfterGroup}))}},e.prototype.updateSelectableAfterFiltering=function(e){if(this.isRowSelectableFunc){this.recurseDown(e.childrenAfterGroup,(function(e){return e.childrenAfterFilter}))}},e.prototype.recurseDown=function(e,t){var o=this;e.forEach((function(e){if(e.group){var i;if(e.hasChildren()&&o.recurseDown(t(e),t),o.groupSelectsChildren){var n=p.find(t(e),"selectable",!0);i=p.exists(n)}else i=!!o.isRowSelectableFunc&&o.isRowSelectableFunc(e);e.setRowSelectable(i)}}))},dr([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),dr([g],e.prototype,"init",null),e=dr([y("selectableService")],e)}(),gr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},fr=function(){function e(){}return e.prototype.registerGridComp=function(e){this.gridPanel=e},e.prototype.getPreferredHeightForRow=function(e){var t=this;this.eDummyContainer||(this.eDummyContainer=document.createElement("div"),p.addCssClass(this.eDummyContainer,"ag-row ag-row-no-focus"));var o=this.gridPanel.getCenterContainer();o.appendChild(this.eDummyContainer);var i=[];this.columnController.getAllAutoRowHeightCols().filter((function(e){return e.isVisible()})).forEach((function(o){var n=new Oo(t.$scope,t.beans,o,e,null,!0,!1);n.setParentRow(t.eDummyContainer),i.push(n)}));var n=i.map((function(e){return e.getCreateTemplate()})).join(" ");this.eDummyContainer.innerHTML=n,i.forEach((function(e){return e.afterAttached()}));for(var r=0,s=0;s<this.eDummyContainer.children.length;s++){var a=this.eDummyContainer.children[s];a.offsetHeight>r&&(r=a.offsetHeight)}return o.removeChild(this.eDummyContainer),i.forEach((function(e){e.detach(),e.destroy()})),p.clearElement(this.eDummyContainer),r},gr([m("beans")],e.prototype,"beans",void 0),gr([m("$scope")],e.prototype,"$scope",void 0),gr([m("columnController")],e.prototype,"columnController",void 0),e=gr([y("autoHeightCalculator")],e)}(),yr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),mr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},vr=function(e){function t(){return e.call(this)||this}return yr(t,e),t.prototype.postConstruct=function(){var e=this.gridOptionsWrapper.isEnableRtl();this.setTemplate(this.getTemplate()),this.btFirst.insertAdjacentElement("afterbegin",p.createIconNoSpan(e?"last":"first",this.gridOptionsWrapper)),this.btPrevious.insertAdjacentElement("afterbegin",p.createIconNoSpan(e?"next":"previous",this.gridOptionsWrapper)),this.btNext.insertAdjacentElement("afterbegin",p.createIconNoSpan(e?"previous":"next",this.gridOptionsWrapper)),this.btLast.insertAdjacentElement("afterbegin",p.createIconNoSpan(e?"first":"last",this.gridOptionsWrapper)),this.rowModel.getType()===o.ROW_MODEL_TYPE_SERVER_SIDE&&(this.serverSideRowModel=this.rowModel),this.gridOptionsWrapper.isPagination()&&!this.gridOptionsWrapper.isSuppressPaginationPanel()?(this.addDestroyableEventListener(this.eventService,M.EVENT_PAGINATION_CHANGED,this.onPaginationChanged.bind(this)),this.addDestroyableEventListener(this.btFirst,"click",this.onBtFirst.bind(this)),this.addDestroyableEventListener(this.btLast,"click",this.onBtLast.bind(this)),this.addDestroyableEventListener(this.btNext,"click",this.onBtNext.bind(this)),this.addDestroyableEventListener(this.btPrevious,"click",this.onBtPrevious.bind(this)),this.onPaginationChanged()):this.setDisplayed(!1)},t.prototype.onPaginationChanged=function(){this.enableOrDisableButtons(),this.updateRowLabels(),this.setCurrentPageLabel(),this.setTotalLabels()},t.prototype.setCurrentPageLabel=function(){var e=this.paginationProxy.getTotalPages()>0,t=this.paginationProxy.getCurrentPage(),o=e?t+1:0;this.lbCurrent.innerHTML=this.formatNumber(o)},t.prototype.formatNumber=function(e){var t=this.gridOptionsWrapper.getPaginationNumberFormatterFunc();return t?t({value:e}):p.formatNumberCommas(e)},t.prototype.getTemplate=function(){var e=this.gridOptionsWrapper.getLocaleTextFunc(),t=e("page","Page"),o=e("to","to"),i=e("of","of");return'<div class="ag-paging-panel ag-unselectable">\n <span ref="eSummaryPanel" class="ag-paging-row-summary-panel">\n <span ref="lbFirstRowOnPage"></span> '+o+' <span ref="lbLastRowOnPage"></span> '+i+' <span ref="lbRecordCount"></span>\n </span>\n <span class="ag-paging-page-summary-panel">\n <div ref="btFirst" class="ag-paging-button">\n <button type="button">'+e("first","First")+'</button>\n </div>\n <div ref="btPrevious" class="ag-paging-button">\n <button type="button">'+e("previous","Previous")+"</button>\n </div>\n "+t+' <span ref="lbCurrent"></span> '+i+' <span ref="lbTotal"></span>\n <div ref="btNext" class="ag-paging-button">\n <button type="button">'+e("next","Next")+'</button>\n </div>\n <div ref="btLast" class="ag-paging-button">\n <button type="button">'+e("last","Last")+"</button>\n </div>\n </span>\n </div>"},t.prototype.onBtNext=function(){this.paginationProxy.goToNextPage()},t.prototype.onBtPrevious=function(){this.paginationProxy.goToPreviousPage()},t.prototype.onBtFirst=function(){this.paginationProxy.goToFirstPage()},t.prototype.onBtLast=function(){this.paginationProxy.goToLastPage()},t.prototype.enableOrDisableButtons=function(){var e=this.paginationProxy.getCurrentPage(),t=this.paginationProxy.isLastPageFound(),o=this.paginationProxy.getTotalPages(),i=0===e;p.addOrRemoveCssClass(this.btPrevious,"ag-disabled",i),p.addOrRemoveCssClass(this.btFirst,"ag-disabled",i);var n=this.isZeroPagesToDisplay(),r=t&&e===o-1||n;p.addOrRemoveCssClass(this.btNext,"ag-disabled",r);var s=!t||n||e===o-1;p.addOrRemoveCssClass(this.btLast,"ag-disabled",s)},t.prototype.updateRowLabels=function(){var e,t,o=this.paginationProxy.getCurrentPage(),i=this.paginationProxy.getPageSize(),n=this.paginationProxy.isLastPageFound(),r=this.paginationProxy.isLastPageFound()?this.paginationProxy.getMasterRowCount():null;this.isZeroPagesToDisplay()?(e=0,t=0):(t=(e=i*o+1)+i-1,n&&t>r&&(t=r)),this.lbFirstRowOnPage.innerHTML=this.formatNumber(e),this.serverSideRowModel&&this.serverSideRowModel.isLoading()?this.lbLastRowOnPage.innerHTML="?":this.lbLastRowOnPage.innerHTML=this.formatNumber(t)},t.prototype.isZeroPagesToDisplay=function(){var e=this.paginationProxy.isLastPageFound(),t=this.paginationProxy.getTotalPages();return e&&0===t},t.prototype.setTotalLabels=function(){var e=this.paginationProxy.isLastPageFound(),t=this.paginationProxy.getTotalPages(),o=this.paginationProxy.isLastPageFound()?this.paginationProxy.getMasterRowCount():null;if(e)this.lbTotal.innerHTML=this.formatNumber(t),this.lbRecordCount.innerHTML=this.formatNumber(o);else{var i=this.gridOptionsWrapper.getLocaleTextFunc()("more","more");this.lbTotal.innerHTML=i,this.lbRecordCount.innerHTML=i}},mr([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),mr([m("eventService")],t.prototype,"eventService",void 0),mr([m("paginationProxy")],t.prototype,"paginationProxy",void 0),mr([m("rowRenderer")],t.prototype,"rowRenderer",void 0),mr([m("rowModel")],t.prototype,"rowModel",void 0),mr([fe("btFirst")],t.prototype,"btFirst",void 0),mr([fe("btPrevious")],t.prototype,"btPrevious",void 0),mr([fe("btNext")],t.prototype,"btNext",void 0),mr([fe("btLast")],t.prototype,"btLast",void 0),mr([fe("lbRecordCount")],t.prototype,"lbRecordCount",void 0),mr([fe("lbFirstRowOnPage")],t.prototype,"lbFirstRowOnPage",void 0),mr([fe("lbLastRowOnPage")],t.prototype,"lbLastRowOnPage",void 0),mr([fe("eSummaryPanel")],t.prototype,"eSummaryPanel",void 0),mr([fe("lbCurrent")],t.prototype,"lbCurrent",void 0),mr([fe("lbTotal")],t.prototype,"lbTotal",void 0),mr([g],t.prototype,"postConstruct",null),t}(pe),Cr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Er=function(){function e(){}return e.prototype.observeResize=function(e,t,o){void 0===o&&(o=50);var i,n,r,s,a,l=this.frameworkOverrides,u=p.debounce(t,o),c=this.gridOptionsWrapper.isSuppressBrowserResizeObserver();return!!window.ResizeObserver&&!c?((a=new window.ResizeObserver(u)).observe(e),function(){return a.disconnect()}):(i=p.offsetWidth(e),n=p.offsetHeight(e),r=!0,(s=function(){if(r){var a=p.offsetWidth(e),u=p.offsetHeight(e);(a!==i||u!==n)&&(i=a,n=u,t()),l.setTimeout(s,o)}})(),function(){return r=!1})},Cr([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),Cr([m("frameworkOverrides")],e.prototype,"frameworkOverrides",void 0),e=Cr([y("resizeObserverService")],e)}(),wr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Rr=function(){function e(){this.DEFAULT_HIDE_TOOLTIP_TIMEOUT=1e4,this.MOUSEOUT_HIDE_TOOLTIP_TIMEOUT=1e3,this.MOUSEOVER_SHOW_TOOLTIP_TIMEOUT=2e3,this.HIDE_SHOW_ONLY=!0,this.showTimeoutId=0,this.hideTimeoutId=0,this.registeredComponents={}}return e.prototype.registerTooltip=function(e){var t=this,o=e.getGui(),i=e.getCompId();this.registeredComponents[i]={tooltipComp:void 0,destroyFunc:void 0,eventDestroyFuncs:[e.addDestroyableEventListener(o,"mouseover",(function(o){return t.processMouseOver(o,e)})),e.addDestroyableEventListener(o,"mousemove",(function(e){return t.processMouseMove(e)})),e.addDestroyableEventListener(o,"mousedown",this.hideTooltip.bind(this)),e.addDestroyableEventListener(o,"mouseout",this.processMouseOut.bind(this))]},e.addDestroyFunc((function(){return t.unregisterTooltip(e)}))},e.prototype.unregisterTooltip=function(e){var t=e.getCompId(),o=this.registeredComponents[t];this.activeComponent===e&&this.hideTooltip(),e.isAlive()&&o&&o.eventDestroyFuncs.length&&o.eventDestroyFuncs.forEach((function(e){return e()})),delete this.registeredComponents[t]},e.prototype.processMouseOver=function(e,t){var o=this.MOUSEOVER_SHOW_TOOLTIP_TIMEOUT;if(this.activeComponent){if(this.lastHoveredComponent===this.activeComponent)return;o=200}else if(this.showTimeoutId&&this.lastHoveredComponent===t)return;this.clearTimers(this.HIDE_SHOW_ONLY),this.lastHoveredComponent!==t&&(this.lastHoveredComponent=t,this.lastMouseEvent=e,this.showTimeoutId=window.setTimeout(this.showTooltip.bind(this),o,e))},e.prototype.processMouseOut=function(e){var t=this.activeComponent,o=e.relatedTarget;if(t){if(!t.getGui().contains(o)){var i=this.registeredComponents[t.getCompId()];p.addCssClass(i.tooltipComp.getGui(),"ag-tooltip-hiding"),this.lastHoveredComponent=void 0,this.clearTimers(),this.hideTimeoutId=window.setTimeout(this.hideTooltip.bind(this),this.MOUSEOUT_HIDE_TOOLTIP_TIMEOUT)}}else{if(this.lastHoveredComponent){var n=this.lastHoveredComponent.getGui().contains(o);if(this.showTimeoutId&&n)return;n||(this.lastHoveredComponent=void 0)}this.clearTimers()}},e.prototype.processMouseMove=function(e){this.lastMouseEvent=e},e.prototype.showTooltip=function(e){var t=this.lastHoveredComponent,o=t,i=this.registeredComponents[t.getCompId()];this.hideTooltip();var n={api:this.gridApi,columnApi:this.columnApi,colDef:t.getComponentHolder(),column:o.getColumn&&o.getColumn(),context:this.gridOptionsWrapper.getContext(),rowIndex:o.getCellPosition&&o.getCellPosition().rowIndex,value:t.getTooltipText()};this.createTooltipComponent(n,i,e)},e.prototype.createTooltipComponent=function(e,t,o){var i=this,n=this.lastMouseEvent;n&&this.userComponentFactory.newTooltipComponent(e).then((function(e){if(t){t.tooltipComp=e;var o=e.getGui();p.containsClass(o,"ag-tooltip")||p.addCssClass(o,"ag-tooltip-custom");var r=i.popupService.addPopup(!1,o,!1);t.destroyFunc=function(){r(),e.destroy&&e.destroy()},i.popupService.positionPopupUnderMouseEvent({type:"tooltip",mouseEvent:n,ePopup:o,nudgeY:18}),i.activeComponent=i.lastHoveredComponent,i.hideTimeoutId=window.setTimeout(i.hideTooltip.bind(i),i.DEFAULT_HIDE_TOOLTIP_TIMEOUT)}}))},e.prototype.hideTooltip=function(){var e=this.activeComponent;if(this.clearTimers(),e){var t=e.getCompId(),o=this.registeredComponents[t];this.activeComponent=void 0,o&&(o.destroyFunc&&o.destroyFunc(),this.clearRegisteredComponent(o))}},e.prototype.clearRegisteredComponent=function(e){delete e.destroyFunc,delete e.tooltipComp},e.prototype.clearTimers=function(e){void 0===e&&(e=!1),this.hideTimeoutId&&!e&&(window.clearTimeout(this.hideTimeoutId),this.hideTimeoutId=0),this.showTimeoutId&&(window.clearTimeout(this.showTimeoutId),this.showTimeoutId=0)},wr([m("popupService")],e.prototype,"popupService",void 0),wr([m("userComponentFactory")],e.prototype,"userComponentFactory",void 0),wr([m("columnApi")],e.prototype,"columnApi",void 0),wr([m("gridApi")],e.prototype,"gridApi",void 0),wr([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),e=wr([y("tooltipManager")],e)}(),Or=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Dr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s}; /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */!function(e){e[e.Loading=0]="Loading",e[e.NoRows=1]="NoRows"}(vi||(vi={}));var br=function(e){function t(){return e.call(this,t.TEMPLATE)||this}return Or(t,e),t.prototype.postConstruct=function(){this.gridOptionsWrapper.addLayoutElement(this.eOverlayWrapper),this.setDisplayed(!1)},t.prototype.setWrapperTypeClass=function(e){p.addOrRemoveCssClass(this.eOverlayWrapper,"ag-overlay-loading-wrapper",e===vi.Loading),p.addOrRemoveCssClass(this.eOverlayWrapper,"ag-overlay-no-rows-wrapper",e===vi.NoRows)},t.prototype.showLoadingOverlay=function(){var e=this;this.setWrapperTypeClass(vi.Loading),this.destroyActiveOverlay();var t={api:this.gridOptionsWrapper.getApi()};this.userComponentFactory.newLoadingOverlayComponent(t).then((function(t){e.eOverlayWrapper.appendChild(t.getGui()),e.activeOverlay=t})),this.setDisplayed(!0)},t.prototype.showNoRowsOverlay=function(){var e=this;this.setWrapperTypeClass(vi.NoRows),this.destroyActiveOverlay();var t={api:this.gridOptionsWrapper.getApi()};this.userComponentFactory.newNoRowsOverlayComponent(t).then((function(t){e.eOverlayWrapper.appendChild(t.getGui()),e.activeOverlay=t})),this.setDisplayed(!0)},t.prototype.destroyActiveOverlay=function(){this.activeOverlay&&(this.activeOverlay.destroy&&this.activeOverlay.destroy(),this.activeOverlay=void 0,p.clearElement(this.eOverlayWrapper))},t.prototype.hideOverlay=function(){this.destroyActiveOverlay(),this.setDisplayed(!1)},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.destroyActiveOverlay()},t.TEMPLATE='<div class="ag-overlay" aria-hidden="true">\n <div class="ag-overlay-panel">\n <div class="ag-overlay-wrapper" ref="eOverlayWrapper"></div>\n </div>\n </div>',Dr([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Dr([m("userComponentFactory")],t.prototype,"userComponentFactory",void 0),Dr([fe("eOverlayWrapper")],t.prototype,"eOverlayWrapper",void 0),Dr([g],t.prototype,"postConstruct",null),t}(pe),Pr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Sr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Tr=function(e){function t(o){var i=e.call(this,t.TEMPLATE)||this;i.suppressEnabledCheckbox=!0,i.suppressOpenCloseIcons=!1,o||(o={});var n=o.title,r=o.enabled,s=o.items,a=o.suppressEnabledCheckbox,l=o.suppressOpenCloseIcons;return i.title=n,i.enabled=null==r||r,i.items=s||[],i.alignItems=o.alignItems||"center",null!=a&&(i.suppressEnabledCheckbox=a),null!=l&&(i.suppressOpenCloseIcons=l),i}return Pr(t,e),t.prototype.postConstruct=function(){if(this.items.length){var e=this.items;this.items=[],this.addItems(e)}var t=this.gridOptionsWrapper.getLocaleTextFunc();this.cbGroupEnabled.setLabel(t("enabled","Enabled")),this.title&&this.setTitle(this.title),this.enabled&&this.setEnabled(this.enabled),this.setAlignItems(this.alignItems),this.hideEnabledCheckbox(this.suppressEnabledCheckbox),this.hideOpenCloseIcons(this.suppressOpenCloseIcons),this.setupExpandContract()},t.prototype.setupExpandContract=function(){var e=this;this.eGroupClosedIcon.appendChild(p.createIcon("columnSelectClosed",this.gridOptionsWrapper,null)),this.eGroupOpenedIcon.appendChild(p.createIcon("columnSelectOpen",this.gridOptionsWrapper,null)),this.setOpenClosedIcons(),this.addDestroyableEventListener(this.groupTitle,"click",(function(){return e.toggleGroupExpand()}))},t.prototype.setOpenClosedIcons=function(){var e=this.expanded;p.setDisplayed(this.eGroupClosedIcon,!e),p.setDisplayed(this.eGroupOpenedIcon,e)},t.prototype.isExpanded=function(){return this.expanded},t.prototype.setAlignItems=function(e){var t=this.getGui();this.alignItems!==e&&p.removeCssClass(t,"ag-alignment-"+this.alignItems),this.alignItems=e;var o="ag-alignment-"+this.alignItems;return"center"===e||p.containsClass(t,o)||p.addCssClass(t,o),this},t.prototype.toggleGroupExpand=function(e){var t=this.getGui();if(this.suppressOpenCloseIcons)return this.expanded=!0,p.removeCssClass(t,"ag-collapsed"),this;if(e=null!=e?e:!this.expanded,this.expanded===e)return this;if(this.expanded=e,this.setOpenClosedIcons(),p.addOrRemoveCssClass(t,"ag-collapsed",!e),this.expanded){this.dispatchEvent({type:"expanded"})}else{this.dispatchEvent({type:"collapsed"})}return this},t.prototype.addItems=function(e){var t=this;e.forEach((function(e){return t.addItem(e)}))},t.prototype.addItem=function(e){var t=this.groupContainer,o=e instanceof pe?e.getGui():e;p.addCssClass(o,"ag-group-item"),t.appendChild(o),this.items.push(o)},t.prototype.hideItem=function(e,t){var o=this.items[t];p.addOrRemoveCssClass(o,"ag-hidden",e)},t.prototype.setTitle=function(e){return this.lbGroupTitle.innerText=e,this},t.prototype.setEnabled=function(e,t){return this.enabled=e,p.addOrRemoveCssClass(this.getGui(),"ag-disabled",!e),this.toggleGroupExpand(e),t||this.cbGroupEnabled.setValue(e),this},t.prototype.isEnabled=function(){return this.enabled},t.prototype.onEnableChange=function(e){var t=this;return this.cbGroupEnabled.onValueChange((function(o){t.setEnabled(o,!0),e(o)})),this},t.prototype.hideEnabledCheckbox=function(e){return p.addOrRemoveCssClass(this.eToolbar,"ag-hidden",e),this},t.prototype.hideOpenCloseIcons=function(e){return this.suppressOpenCloseIcons=e,p.addOrRemoveCssClass(this.getGui(),"ag-collapsible",!e),e&&this.toggleGroupExpand(!0),this},t.TEMPLATE='<div class="ag-group-component">\n <div class="ag-group-component-title-bar" ref="groupTitle">\n <span class="ag-column-group-icons">\n <span class="ag-column-group-opened-icon" ref="eGroupOpenedIcon"></span>\n <span class="ag-column-group-closed-icon" ref="eGroupClosedIcon"></span>\n </span>\n <span ref="lbGroupTitle" class="ag-group-component-title"></span>\n </div>\n <div ref="eToolbar" class="ag-group-component-toolbar">\n <ag-checkbox ref="cbGroupEnabled"></ag-checkbox>\n </div>\n <div ref="eContainer" class="ag-group-component-container"></div>\n </div>',Sr([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Sr([fe("groupTitle")],t.prototype,"groupTitle",void 0),Sr([fe("eGroupOpenedIcon")],t.prototype,"eGroupOpenedIcon",void 0),Sr([fe("eGroupClosedIcon")],t.prototype,"eGroupClosedIcon",void 0),Sr([fe("eToolbar")],t.prototype,"eToolbar",void 0),Sr([fe("cbGroupEnabled")],t.prototype,"cbGroupEnabled",void 0),Sr([fe("lbGroupTitle")],t.prototype,"lbGroupTitle",void 0),Sr([fe("eContainer")],t.prototype,"groupContainer",void 0),Sr([g],t.prototype,"postConstruct",null),t}(pe),Ar=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),_r=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Fr=function(e){function t(o){var i=e.call(this,t.TEMPLATE)||this;return i.closable=!0,i.positioned=!1,i.dragStartPosition={x:0,y:0},i.position={x:0,y:0},i.size={width:void 0,height:void 0},i.config=o,i}return Ar(t,e),t.prototype.postConstruct=function(){var e=this,t=this.config,o=t.component,i=t.closable,n=t.hideTitleBar,r=t.title,s=t.minWidth,a=t.width,l=t.minHeight,u=t.height,c=t.centered,d=t.x,h=t.y,g=this.getGui();o&&this.setBodyComponent(o),n?p.addCssClass(this.eTitleBar,"ag-hidden"):(r&&this.setTitle(r),this.setClosable(null!=i?i:this.closable)),this.addDestroyableEventListener(this.eTitleBar,"mousedown",(function(t){if(g.contains(t.relatedTarget)||g.contains(document.activeElement)||e.eTitleBarButtons.contains(t.target))t.preventDefault();else{var o=e.eContentWrapper.querySelector("button, [href], input, select, textarea, [tabindex]");o&&o.focus()}})),this.positioned||(this.minHeight=null!=l?l:250,this.minWidth=null!=s?s:250,this.popupParent=this.popupService.getPopupParent(),a&&this.setWidth(a),u&&this.setHeight(u),this.renderComponent&&this.renderComponent(),a&&u||this.refreshSize(),c?this.center():(d||h)&&this.offsetElement(d,h),this.positioned=!0,this.eContentWrapper.style.height="0")},t.prototype.renderComponent=function(){var e=this,t=this.getGui();t.focus(),this.close=function(){t.parentElement.removeChild(t),e.destroy()}},t.prototype.updateDragStartPosition=function(e,t){this.dragStartPosition={x:e,y:t}},t.prototype.calculateMouseMovement=function(e){var t=this.popupParent.getBoundingClientRect(),o=e.e,i=e.isLeft,n=e.isTop,r=e.anywhereWithin,s=e.topBuffer,a=o.clientX-this.dragStartPosition.x,l=o.clientY-this.dragStartPosition.y,p=this.getWidth(),u=this.getHeight(),c=t.left>=o.clientX&&this.position.x<=0||t.right<=o.clientX&&t.right<=this.position.x+t.left+p;return c||(c=i?a<0&&o.clientX>this.position.x+t.left||a>0&&o.clientX<this.position.x+t.left:r?a<0&&o.clientX>this.position.x+t.left+p||a>0&&o.clientX<this.position.x+t.left:a<0&&o.clientX>this.position.x+t.left+p||a>0&&o.clientX<this.position.x+t.left+p),{movementX:a=c?0:a,movementY:l=t.top>=o.clientY&&this.position.y<=0||t.bottom<=o.clientY&&t.bottom<=this.position.y+t.top+u||n&&(l<0&&o.clientY>this.position.y+t.top+(s||0)||l>0&&o.clientY<this.position.y+t.top)||!n&&(l<0&&o.clientY>this.position.y+t.top+u||l>0&&o.clientY<this.position.y+t.top+u)?0:l}},t.prototype.refreshSize=function(){var e=this.size,t=e.width,o=e.height;t||this.setWidth(this.getGui().offsetWidth),o||this.setHeight(this.getGui().offsetHeight)},t.prototype.offsetElement=function(e,t){void 0===e&&(e=0),void 0===t&&(t=0);var o=this.getGui();this.popupService.positionPopup({ePopup:o,x:e,y:t,minWidth:this.minWidth,minHeight:this.minHeight,keepWithinBounds:!0}),this.position.x=parseInt(o.style.left,10),this.position.y=parseInt(o.style.top,10)},t.prototype.getHeight=function(){return this.size.height},t.prototype.setHeight=function(e){var t=this.getGui(),o=!1;if("string"==typeof e&&-1!==e.indexOf("%"))p.setFixedHeight(t,e),e=p.getAbsoluteHeight(t),o=!0;else{e=Math.max(this.minHeight,e);var i=t.offsetParent;i&&i.clientHeight&&e+this.position.y>i.clientHeight&&(e=i.clientHeight-this.position.y)}this.size.height!==e&&(this.size.height=e,o?(t.style.maxHeight="unset",t.style.minHeight="unset"):p.setFixedHeight(t,e))},t.prototype.getWidth=function(){return this.size.width},t.prototype.setWidth=function(e){var t=this.getGui(),o=!1;if("string"==typeof e&&-1!==e.indexOf("%"))p.setFixedWidth(t,e),e=p.getAbsoluteWidth(t),o=!0;else{e=Math.max(this.minWidth,e);var i=t.offsetParent;i&&i.clientWidth&&e+this.position.x>i.clientWidth&&(e=i.clientWidth-this.position.x)}this.size.width!==e&&(this.size.width=e,o?(t.style.maxWidth="unset",t.style.minWidth="unset"):p.setFixedWidth(t,e))},t.prototype.center=function(){var e=this.getGui(),t=e.offsetParent.clientWidth/2-this.getWidth()/2,o=e.offsetParent.clientHeight/2-this.getHeight()/2;this.offsetElement(t,o)},t.prototype.setClosable=function(e){if(e!==this.closable&&(this.closable=e),e){var o=this.closeButtonComp=new pe(t.CLOSE_BTN_TEMPLATE);this.getContext().wireBean(o),(i=o.getGui()).appendChild(p.createIconNoSpan("close",this.gridOptionsWrapper)),this.addTitleBarButton(o),o.addDestroyableEventListener(i,"click",this.onBtClose.bind(this))}else if(this.closeButtonComp){var i;(i=this.closeButtonComp.getGui()).parentElement.removeChild(i),this.closeButtonComp.destroy(),this.closeButtonComp=void 0}},t.prototype.setBodyComponent=function(e){e.setParentComponent(this),this.eContentWrapper.appendChild(e.getGui())},t.prototype.addTitleBarButton=function(e,t){var o=this.eTitleBarButtons,i=o.children,n=i.length;null==t&&(t=n),t=Math.max(0,Math.min(t,n));var r=e.getGui();p.addCssClass(r,"ag-button"),0===t?o.insertAdjacentElement("afterbegin",r):t===n?o.insertAdjacentElement("beforeend",r):i[t-1].insertAdjacentElement("afterend",r),e.setParentComponent(this)},t.prototype.getBodyHeight=function(){return p.getInnerHeight(this.eContentWrapper)},t.prototype.getBodyWidth=function(){return p.getInnerWidth(this.eContentWrapper)},t.prototype.setTitle=function(e){this.eTitle.innerText=e},t.prototype.onBtClose=function(){this.close()},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.closeButtonComp&&(this.closeButtonComp.destroy(),this.closeButtonComp=void 0);var t=this.getGui();t&&t.offsetParent&&this.close()},t.TEMPLATE='<div class="ag-panel" tabindex="-1">\n <div ref="eTitleBar" class="ag-title-bar ag-unselectable">\n <span ref="eTitle" class="ag-title-bar-title"></span>\n <div ref="eTitleBarButtons" class="ag-title-bar-buttons"></div>\n </div>\n <div ref="eContentWrapper" class="ag-panel-content-wrapper"></div>\n </div>',t.CLOSE_BTN_TEMPLATE='<div class="ag-button"></div>',_r([m("popupService")],t.prototype,"popupService",void 0),_r([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),_r([fe("eContentWrapper")],t.prototype,"eContentWrapper",void 0),_r([fe("eTitleBar")],t.prototype,"eTitleBar",void 0),_r([fe("eTitleBarButtons")],t.prototype,"eTitleBarButtons",void 0),_r([fe("eTitle")],t.prototype,"eTitle",void 0),_r([g],t.prototype,"postConstruct",null),t}(pe),Nr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Lr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Ir=function(e){function t(t){var o=e.call(this,t)||this;return o.RESIZE_TEMPLATE='\n <div class="ag-resizer-wrapper">\n <div ref="eTopLeftResizer" class="ag-resizer ag-resizer-topLeft"></div>\n <div ref="eTopResizer" class="ag-resizer ag-resizer-top"></div>\n <div ref="eTopRightResizer" class="ag-resizer ag-resizer-topRight"></div>\n <div ref="eRightResizer" class="ag-resizer ag-resizer-right"></div>\n <div ref="eBottomRightResizer" class="ag-resizer ag-resizer-bottomRight"></div>\n <div ref="eBottomResizer" class="ag-resizer ag-resizer-bottom"></div>\n <div ref="eBottomLeftResizer" class="ag-resizer ag-resizer-bottomLeft"></div>\n <div ref="eLeftResizer" class="ag-resizer ag-resizer-left"></div>\n </div>\n ',o.MAXIMIZE_BTN_TEMPLATE='<div class="ag-dialog-button"></span>',o.resizable={},o.isResizable=!1,o.movable=!1,o.isMoving=!1,o.isMaximizable=!1,o.isMaximized=!1,o.maximizeListeners=[],o.resizeListenerDestroy=null,o.isResizing=!1,o.lastPosition={x:0,y:0,width:0,height:0},o}return Nr(t,e),t.prototype.postConstruct=function(){var t=this,o=this.getGui(),i=this.config,n=i.movable,r=i.resizable,s=i.maximizable;p.addCssClass(o,"ag-dialog"),this.moveElement=this.eTitleBar,e.prototype.postConstruct.call(this),this.addDestroyableEventListener(o,"focusin",(function(e){o.contains(e.relatedTarget)||t.popupService.bringPopupToFront(o)})),n&&this.setMovable(n),s&&this.setMaximizable(s),this.addResizers(),r&&this.setResizable(r)},t.prototype.renderComponent=function(){var e=this.getGui(),t=this.config,o=t.alwaysOnTop,i=t.modal;this.close=this.popupService.addPopup(i,e,!0,this.destroy.bind(this),void 0,o),e.focus()},t.prototype.addResizers=function(){var e=this.getGui();if(e){var t=(new DOMParser).parseFromString(this.RESIZE_TEMPLATE,"text/html").body;e.appendChild(t.firstChild),this.createMap()}},t.prototype.createMap=function(){var e=this.getGui();this.resizerMap={topLeft:{element:e.querySelector("[ref=eTopLeftResizer]")},top:{element:e.querySelector("[ref=eTopResizer]")},topRight:{element:e.querySelector("[ref=eTopRightResizer]")},right:{element:e.querySelector("[ref=eRightResizer]")},bottomRight:{element:e.querySelector("[ref=eBottomRightResizer]")},bottom:{element:e.querySelector("[ref=eBottomResizer]")},bottomLeft:{element:e.querySelector("[ref=eBottomLeftResizer]")},left:{element:e.querySelector("[ref=eLeftResizer]")}}},t.prototype.getResizerElement=function(e){return this.resizerMap[e].element},t.prototype.onResizeStart=function(e){this.isResizing=!0,this.updateDragStartPosition(e.clientX,e.clientY)},t.prototype.onResize=function(e,t){if(this.isResizing){var o=!!t.match(/left/i),i=!!t.match(/right/i),n=!!t.match(/top/i),r=!!t.match(/bottom/i),s=o||i,a=n||r,l=this.calculateMouseMovement({e:e,isLeft:o,isTop:n}),p=l.movementX,u=l.movementY,c=0,d=0;if(s&&p){var h=o?-1:1,g=this.getWidth(),f=g+p*h,y=!1;o&&(c=g-f,(this.position.x+c<=0||f<=this.minWidth)&&(y=!0,c=0)),y||this.setWidth(f)}if(a&&u){h=n?-1:1;var m=this.getHeight(),v=m+u*h,C=!1;n&&(d=m-v,(this.position.y+d<=0||v<=this.minHeight)&&(C=!0,d=0)),C||this.setHeight(v)}this.updateDragStartPosition(e.clientX,e.clientY),(c||d)&&this.offsetElement(this.position.x+c,this.position.y+d)}},t.prototype.onResizeEnd=function(){this.isResizing=!1;var e={type:"resize",api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi()};this.localEventService&&this.localEventService.dispatchEvent(e)},t.prototype.onMoveStart=function(e){this.isMoving=!0,this.updateDragStartPosition(e.clientX,e.clientY)},t.prototype.onMove=function(e){if(this.isMoving){var t=this.position,o=t.x,i=t.y,n=this.calculateMouseMovement({e:e,isTop:!0,anywhereWithin:!0,topBuffer:this.getHeight()-this.getBodyHeight()}),r=n.movementX,s=n.movementY;this.offsetElement(o+r,i+s),this.updateDragStartPosition(e.clientX,e.clientY)}},t.prototype.onMoveEnd=function(){this.isMoving=!1},t.prototype.toggleMaximize=function(){if(this.isMaximized){var e=this.lastPosition,t=e.x,o=e.y,i=e.width,n=e.height;this.setWidth(i),this.setHeight(n),this.offsetElement(t,o)}else this.lastPosition.width=this.getWidth(),this.lastPosition.height=this.getHeight(),this.lastPosition.x=this.position.x,this.lastPosition.y=this.position.y,this.offsetElement(0,0),this.setHeight("100%"),this.setWidth("100%");this.isMaximized=!this.isMaximized,this.refreshMaximizeIcon()},t.prototype.refreshMaximizeIcon=function(){p.addOrRemoveCssClass(this.maximizeIcon,"ag-hidden",this.isMaximized),p.addOrRemoveCssClass(this.minimizeIcon,"ag-hidden",!this.isMaximized)},t.prototype.clearMaximizebleListeners=function(){this.maximizeListeners.length&&(this.maximizeListeners.forEach((function(e){return e()})),this.maximizeListeners.length=0),this.resizeListenerDestroy&&(this.resizeListenerDestroy(),this.resizeListenerDestroy=null)},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.setResizable(!1),this.setMovable(!1),this.maximizeButtonComp&&(this.maximizeButtonComp.destroy(),this.maximizeButtonComp=void 0),this.clearMaximizebleListeners()},t.prototype.setResizable=function(e){var t=this,o=!1;"boolean"==typeof e&&(e={topLeft:e,top:e,topRight:e,right:e,bottomRight:e,bottom:e,bottomLeft:e,left:e}),Object.keys(e).forEach((function(i){var n=i,r=!!e[n],s=t.getResizerElement(n),a=t.resizerMap[n].dragSource||{eElement:s,onDragStart:t.onResizeStart.bind(t),onDragging:function(e){return t.onResize(e,n)},onDragStop:t.onResizeEnd.bind(t)};!!t.resizable[n]===r&&(t.isAlive()||r)||(r?(t.dragService.addDragSource(a),s.style.pointerEvents="all",o=!0):(t.dragService.removeDragSource(a),s.style.pointerEvents="none"),t.resizerMap[n].dragSource=r?a:void 0)})),this.isResizable=o},t.prototype.setMovable=function(e){if(e!==this.movable){this.movable=e;var t=this.moveElementDragListener||{eElement:this.moveElement,onDragStart:this.onMoveStart.bind(this),onDragging:this.onMove.bind(this),onDragStop:this.onMoveEnd.bind(this)};e?(this.dragService.addDragSource(t),this.moveElementDragListener=t):(this.dragService.removeDragSource(t),this.moveElementDragListener=void 0)}},t.prototype.setMaximizable=function(e){var t=this;if(!1===e)return this.clearMaximizebleListeners(),void(this.maximizeButtonComp&&(this.maximizeButtonComp.destroy(),this.maximizeButtonComp=this.maximizeIcon=this.minimizeIcon=void 0));var o=this.eTitleBar;if(o&&e!==this.isMaximizable){var i=this.maximizeButtonComp=new pe(this.MAXIMIZE_BTN_TEMPLATE);this.getContext().wireBean(i);var n=i.getGui();n.appendChild(this.maximizeIcon=p.createIconNoSpan("maximize",this.gridOptionsWrapper)),n.appendChild(this.minimizeIcon=p.createIconNoSpan("minimize",this.gridOptionsWrapper)),p.addCssClass(this.minimizeIcon,"ag-hidden"),i.addDestroyableEventListener(n,"click",this.toggleMaximize.bind(this)),this.addTitleBarButton(i,0),this.maximizeListeners.push(this.addDestroyableEventListener(o,"dblclick",this.toggleMaximize.bind(this))),this.resizeListenerDestroy=this.addDestroyableEventListener(this,"resize",(function(){t.isMaximized=!1,t.refreshMaximizeIcon()}))}},Lr([m("dragService")],t.prototype,"dragService",void 0),t}(Fr),Gr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Mr=function(e){function t(t){var o=e.call(this)||this;return o.className="ag-text-field",o.displayTag="input",o.inputType="text",o.setTemplate(o.TEMPLATE.replace(/%displayField%/g,o.displayTag)),t&&(o.config=t),o}return Gr(t,e),t.prototype.setValue=function(t,o){var i=e.prototype.setValue.call(this,t,o);return this.eInput.value!==t&&(this.eInput.value=t),i},t}(ko),xr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Vr=function(e){function t(t){var o=e.call(this)||this;return o.className="ag-text-area",o.displayTag="textarea",o.inputType="",o.setTemplate(o.TEMPLATE.replace(/%displayField%/g,o.displayTag)),t&&(o.config=t),o}return xr(t,e),t.prototype.setValue=function(t,o){var i=e.prototype.setValue.call(this,t,o);return this.eInput.value=t,i},t}(ko),Wr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Hr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},kr=function(e){function t(){var o=e.call(this,t.TEMPLATE)||this;return o.labelAlignment="top",o}return Wr(t,e),t.prototype.onValueChange=function(e){var t=this,o=Vo.EVENT_CHANGED;return this.addDestroyableEventListener(this.eText,o,(function(){var o=parseFloat(t.eText.getValue());t.eSlider.setValue(o.toString(),!0),e(o||0)})),this.addDestroyableEventListener(this.eSlider,o,(function(){var o=t.eSlider.getValue();t.eText.setValue(o,!0),e(parseFloat(o))})),this},t.prototype.setSliderWidth=function(e){return this.eSlider.setWidth(e),this},t.prototype.setTextFieldWidth=function(e){return this.eText.setWidth(e),this},t.prototype.setMinValue=function(e){return this.eSlider.setMinValue(e),this.eText.setMin(e),this},t.prototype.setMaxValue=function(e){return this.eSlider.setMaxValue(e),this.eText.setMax(e),this},t.prototype.getValue=function(){return this.eText.getValue()},t.prototype.setValue=function(e){return this.getValue()===e?this:(this.eText.setValue(e,!0),this.eSlider.setValue(e,!0),this.dispatchEvent({type:Vo.EVENT_CHANGED}),this)},t.prototype.setStep=function(e){return this.eSlider.setStep(e),this.eText.setStep(e),this},t.TEMPLATE='<div class="ag-slider">\n <label ref="eLabel"></label>\n <div class="ag-wrapper">\n <ag-input-range ref="eSlider"></ag-input-range>\n <ag-input-number-field ref="eText"></ag-input-number-field>\n </div>\n </div>',Hr([fe("eLabel")],t.prototype,"eLabel",void 0),Hr([fe("eSlider")],t.prototype,"eSlider",void 0),Hr([fe("eText")],t.prototype,"eText",void 0),t}(Mo),Br=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ur=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},jr=function(e){function o(t){var i=e.call(this,o.TEMPLATE)||this;return i.H=1,i.S=1,i.B=1,i.A=1,i.isSpectrumDragging=!1,i.isSpectrumHueDragging=!1,i.isSpectrumAlphaDragging=!1,i.colorChanged=!1,i.picker=t.picker,i}return Br(o,e),o.prototype.postConstruct=function(){var e=this.getGui();this.initRecentColors(),this.addDestroyableEventListener(this.spectrumVal,"mousedown",this.onSpectrumDraggerDown.bind(this)),this.addDestroyableEventListener(e,"mousemove",this.onSpectrumDraggerMove.bind(this)),this.addDestroyableEventListener(this.spectrumHue,"mousedown",this.onSpectrumHueDown.bind(this)),this.addDestroyableEventListener(e,"mousemove",this.onSpectrumHueMove.bind(this)),this.addDestroyableEventListener(this.spectrumAlpha,"mousedown",this.onSpectrumAlphaDown.bind(this)),this.addDestroyableEventListener(e,"mousemove",this.onSpectrumAlphaMove.bind(this)),this.addDestroyableEventListener(document,"mouseup",this.onMouseUp.bind(this)),this.addDestroyableEventListener(this.recentColors,"click",this.onRecentColorClick.bind(this))},o.prototype.refreshSpectrumRect=function(){return this.spectrumValRect=this.spectrumVal.getBoundingClientRect()},o.prototype.refreshHueRect=function(){return this.spectrumHueRect=this.spectrumHue.getBoundingClientRect()},o.prototype.refreshAlphaRect=function(){return this.spectrumAlphaRect=this.spectrumAlpha.getBoundingClientRect()},o.prototype.onSpectrumDraggerDown=function(e){this.refreshSpectrumRect(),this.isSpectrumDragging=!0,this.moveDragger(e)},o.prototype.onSpectrumDraggerMove=function(e){this.isSpectrumDragging&&this.moveDragger(e)},o.prototype.onSpectrumHueDown=function(e){this.refreshHueRect(),this.isSpectrumHueDragging=!0,this.moveHueSlider(e)},o.prototype.onSpectrumHueMove=function(e){this.isSpectrumHueDragging&&this.moveHueSlider(e)},o.prototype.onSpectrumAlphaDown=function(e){this.refreshAlphaRect(),this.isSpectrumAlphaDragging=!0,this.moveAlphaSlider(e)},o.prototype.onSpectrumAlphaMove=function(e){this.isSpectrumAlphaDragging&&this.moveAlphaSlider(e)},o.prototype.onMouseUp=function(){this.isSpectrumDragging=!1,this.isSpectrumHueDragging=!1,this.isSpectrumAlphaDragging=!1},o.prototype.moveDragger=function(e){var t=this.spectrumValRect;if(t){var o=e.clientX-t.left,i=e.clientY-t.top;o=Math.max(o,0),o=Math.min(o,t.width),i=Math.max(i,0),i=Math.min(i,t.height),this.setSpectrumValue(o/t.width,1-i/t.height)}},o.prototype.moveHueSlider=function(e){var t=this.spectrumHueRect;if(t){var o=this.spectrumHueSlider,i=o.getBoundingClientRect(),n=e.clientX-t.left;n=Math.max(n,0),n=Math.min(n,t.width),this.H=1-n/t.width,o.style.left=n+i.width/2+"px",this.update()}},o.prototype.moveAlphaSlider=function(e){var t=this.spectrumAlphaRect;if(t){var o=this.spectrumAlphaSlider,i=o.getBoundingClientRect(),n=e.clientX-t.left;n=Math.max(n,0),n=Math.min(n,t.width),this.A=n/t.width,o.style.left=n+i.width/2+"px",this.update()}},o.prototype.update=function(){var e=t.fromHSB(360*this.H,this.S,this.B,this.A),o=t.fromHSB(360*this.H,1,1),i=e.toRgbaString(),n=this.picker;t.fromString(n.getValue()).toRgbaString()!==i&&(this.colorChanged=!0),n.setValue(i),this.spectrumColor.style.backgroundColor=o.toRgbaString(),this.spectrumDragger.style.backgroundColor=i},o.prototype.setSpectrumValue=function(e,t){var o=this.spectrumValRect||this.refreshSpectrumRect();if(o){var i=this.spectrumDragger,n=i.getBoundingClientRect();e=Math.max(0,e),e=Math.min(1,e),t=Math.max(0,t),t=Math.min(1,t),this.S=e,this.B=t,i.style.left=e*o.width-n.width/2+"px",i.style.top=(1-t)*o.height-n.height/2+"px",this.update()}},o.prototype.initRecentColors=function(){var e=o.recentColors.map((function(e,t){return'<div class="ag-recent-color" id='+t+' style="background-color: '+e+'; width: 15px; height: 15px;" recent-color="'+e+'"></div>'}));this.recentColors.innerHTML=e.join("")},o.prototype.setValue=function(e){var o=t.fromString(e),i=o.toHSB(),n=i[0],r=i[1],s=i[2];this.H=(isNaN(n)?0:n)/360,this.A=o.a;var a=this.spectrumHueRect||this.refreshHueRect(),l=this.spectrumAlphaRect||this.refreshAlphaRect();this.spectrumHueSlider.style.left=(this.H-1)*-a.width+"px",this.spectrumAlphaSlider.style.left=this.A*l.width+"px",this.setSpectrumValue(r,s)},o.prototype.onRecentColorClick=function(e){var t=e.target;if(p.exists(t.id)){var i=parseInt(t.id,10);this.setValue(o.recentColors[i]),this.destroy()}},o.prototype.addRecentColor=function(){var e=t.fromHSB(360*this.H,this.S,this.B,this.A).toRgbaString(),i=o.recentColors;this.colorChanged&&i[0]!==e&&(i=i.filter((function(t){return t!=e})),(i=[e].concat(i)).length>o.maxRecentColors&&(i=i.slice(0,o.maxRecentColors)),o.recentColors=i)},o.prototype.destroy=function(){e.prototype.destroy.call(this),this.addRecentColor()},o.maxRecentColors=8,o.recentColors=[],o.TEMPLATE='<div class="ag-color-panel">\n <div ref="spectrumColor" class="ag-spectrum-color">\n <div class="ag-spectrum-sat ag-fill">\n <div ref="spectrumVal" class="ag-spectrum-val ag-fill">\n <div ref="spectrumDragger" class="ag-spectrum-dragger"></div>\n </div>\n </div>\n </div>\n <div class="ag-spectrum-tools">\n <div ref="spectrumHue" class="ag-spectrum-hue ag-hue-alpha">\n <div class="ag-spectrum-hue-background"></div>\n <div ref="spectrumHueSlider" class="ag-spectrum-slider"></div>\n </div>\n <div ref="spectrumAlpha" class="ag-spectrum-alpha ag-hue-alpha">\n <div class="ag-spectrum-alpha-background"></div>\n <div ref="spectrumAlphaSlider" class="ag-spectrum-slider"></div>\n </div>\n <div ref="recentColors" class="ag-recent-colors"></div>\n </div>\n </div>',Ur([fe("spectrumColor")],o.prototype,"spectrumColor",void 0),Ur([fe("spectrumVal")],o.prototype,"spectrumVal",void 0),Ur([fe("spectrumDragger")],o.prototype,"spectrumDragger",void 0),Ur([fe("spectrumHue")],o.prototype,"spectrumHue",void 0),Ur([fe("spectrumHueSlider")],o.prototype,"spectrumHueSlider",void 0),Ur([fe("spectrumAlpha")],o.prototype,"spectrumAlpha",void 0),Ur([fe("spectrumAlphaSlider")],o.prototype,"spectrumAlphaSlider",void 0),Ur([fe("recentColors")],o.prototype,"recentColors",void 0),Ur([g],o.prototype,"postConstruct",null),o}(pe),zr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Yr=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Kr=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.TEMPLATE='<div class="ag-picker-field">\n <label ref="eLabel"></label>\n <div ref="eWrapper" class="ag-wrapper">\n <%displayField% ref="eDisplayField"></%displayField%>\n <button ref="eButton" class="ag-picker-button"> </button>\n </div>\n </div>',t.displayedPicker=!1,t.isDestroyingPicker=!1,t}return zr(t,e),t.prototype.postConstruct=function(){var t=this;e.prototype.postConstruct.call(this),this.addDestroyableEventListener(this.eButton,"click",(function(){t.showPicker()})),this.pickerIcon&&this.eButton.appendChild(p.createIconNoSpan(this.pickerIcon,this.gridOptionsWrapper,null))},t.prototype.setInputWidth=function(e){return p.setElementWidth(this.eWrapper,e),this},Yr([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Yr([fe("eLabel")],t.prototype,"eLabel",void 0),Yr([fe("eWrapper")],t.prototype,"eWrapper",void 0),Yr([fe("eDisplayField")],t.prototype,"eDisplayField",void 0),Yr([fe("eButton")],t.prototype,"eButton",void 0),t}(Vo),qr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Qr=function(e){function t(t){var o=e.call(this)||this;return o.displayTag="div",o.className="ag-color-picker",o.pickerIcon="colorPicker",o.setTemplate(o.TEMPLATE.replace(/%displayField%/g,o.displayTag)),t&&t.color&&(o.value=t.color),o}return qr(t,e),t.prototype.postConstruct=function(){var t=this;e.prototype.postConstruct.call(this),p.addCssClass(this.getGui(),this.className),this.addDestroyableEventListener(this.eDisplayField,"click",(function(){return t.showPicker()})),this.value&&this.setValue(this.value)},t.prototype.showPicker=function(){var e=this;if(this.displayedPicker)this.displayedPicker=!1;else{var t=this.getGui().getBoundingClientRect(),o=new Ir({closable:!1,modal:!0,hideTitleBar:!0,minWidth:190,width:190,height:250,x:t.right-190,y:t.top-250});this.getContext().wireBean(o),p.addCssClass(o.getGui(),"ag-color-dialog");var i=new jr({picker:this});this.getContext().wireBean(i),i.addDestroyFunc((function(){o.isAlive()&&o.destroy()})),o.setParentComponent(this),o.setBodyComponent(i),i.setValue(this.getValue()),o.addDestroyFunc((function(){var t=e.isDestroyingPicker;e.displayedPicker=!1,t?e.isDestroyingPicker=!1:(e.isDestroyingPicker=!0,i.isAlive()&&i.destroy())}))}},t.prototype.setValue=function(e){return this.value===e?this:(this.value=e,this.eDisplayField.style.backgroundColor=e,this.dispatchEvent({type:Vo.EVENT_CHANGED}),this)},t.prototype.getValue=function(){return this.value},t}(Kr),Xr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),$r=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.className="ag-number-field",t.inputType="number",t}return Xr(t,e),t.prototype.postConstruct=function(){var t=this;e.prototype.postConstruct.call(this),this.addDestroyableEventListener(this.eInput,"blur",(function(){var e=t.normalizeValue(t.eInput.value);t.value!==e&&t.setValue(e)}))},t.prototype.normalizeValue=function(e){if(""===e)return"";this.precision&&(e=this.adjustPrecision(e));var t=parseFloat(e);return null!=this.min&&t<this.min?e=this.min.toString():null!=this.max&&t>this.max&&(e=this.max.toString()),e},t.prototype.adjustPrecision=function(e){if(this.precision){var t=parseFloat(e).toFixed(this.precision);e=parseFloat(t).toString()}return e},t.prototype.setMin=function(e){return this.min===e?this:(this.min=e,null!=this.min?this.eInput.setAttribute("min",e.toString()):this.eInput.removeAttribute("min"),this)},t.prototype.setMax=function(e){return this.max===e?this:(this.max=e,null!=this.max?this.eInput.setAttribute("max",e.toString()):this.eInput.removeAttribute("max"),this)},t.prototype.setPrecision=function(e){return this.precision=e,this},t.prototype.setStep=function(e){return this.step===e?this:(this.step=e,null!=e?this.eInput.setAttribute("step",e.toString()):this.eInput.removeAttribute("step"),this)},t.prototype.setValue=function(t,o){return(t=this.adjustPrecision(t))!=this.normalizeValue(t)?this:e.prototype.setValue.call(this,t,o)},t}(Mr),Jr=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Zr=function(e){function t(t){var o=e.call(this)||this;return o.className="ag-range-field",o.displayTag="input",o.inputType="range",o.setTemplate(o.TEMPLATE.replace(/%displayField%/g,o.displayTag)),t&&(o.config=t),o}return Jr(t,e),t.prototype.postConstruct=function(){e.prototype.postConstruct.call(this);var t=this.config,o=t.min,i=t.max,n=t.step;null!=o&&this.setMinValue(o),null!=i&&this.setMaxValue(i),this.setStep(n||1)},t.prototype.addInputListeners=function(){var e=this,t=p.isBrowserIE()?"change":"input";this.addDestroyableEventListener(this.eInput,t,(function(t){var o=t.target.value;e.setValue(o)}))},t.prototype.setMinValue=function(e){return this.min=e,this.eInput.setAttribute("min",e.toString()),this},t.prototype.setMaxValue=function(e){return this.max=e,this.eInput.setAttribute("max",e.toString()),this},t.prototype.setStep=function(e){return this.step=e,this.eInput.setAttribute("step",e.toString()),this},t.prototype.setValue=function(t,o){null!=this.min&&(t=Math.max(parseFloat(t),this.min).toString()),null!=this.max&&(t=Math.min(parseFloat(t),this.max).toString());var i=e.prototype.setValue.call(this,t,o);return this.eInput.value=t,i},t}(ko),es=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ts=function(e){function t(){var t=e.call(this)||this;return t.className="ag-select",t.displayTag="select",t.inputType="",t.setTemplate(t.TEMPLATE.replace(/%displayField%/g,t.displayTag)),t}return es(t,e),t.prototype.addOptions=function(e){var t=this;return e.forEach((function(e){return t.addOption(e)})),this},t.prototype.addOption=function(e){var t=document.createElement("option");return t.value=e.value,t.text=e.text||e.value,this.eInput.appendChild(t),this},t.prototype.setValue=function(t,o){var i=e.prototype.setValue.call(this,t,o);return this.eInput.value=t,i},t}(ko),os=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),is=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},ns=function(e){function t(){var o=e.call(this,t.TEMPLATE)||this;return o.radius=0,o.offsetX=0,o.offsetY=0,o}return os(t,e),t.prototype.postConstruct=function(){var t=this;e.prototype.postConstruct.call(this),this.dragListener={eElement:this.eParentCircle,dragStartPixels:0,onDragStart:function(e){t.parentCircleRect=t.eParentCircle.getBoundingClientRect()},onDragging:function(e){return t.calculateAngleDrag(e)},onDragStop:function(){}},this.dragService.addDragSource(this.dragListener),this.eAngleValue.setLabel("").setLabelWidth(5).setInputWidth(45).setMin(0).setMax(360).setValue(""+this.degrees).onValueChange((function(e){null!=e&&""!==e||(e="0"),e=t.eAngleValue.normalizeValue(e);var o=parseFloat(e);o>180&&(o-=360),t.setValue(o)})),this.updateNumberInput(),p.exists(this.getValue())&&this.eAngleValue.setValue(this.normalizeNegativeValue(this.getValue()).toString()),this.addDestroyableEventListener(this,Vo.EVENT_CHANGED,(function(){t.eAngleValue.getInputElement().contains(document.activeElement)||t.updateNumberInput()}))},t.prototype.updateNumberInput=function(){var e=this.normalizeNegativeValue(this.getValue());this.eAngleValue.setValue(e.toString())},t.prototype.positionChildCircle=function(e){var t=this.parentCircleRect||{width:24,height:24},o=this.eChildCircle,i=t.width/2,n=t.height/2;o.style.left=i+8*Math.cos(e)+"px",o.style.top=n+8*Math.sin(e)+"px"},t.prototype.calculatePolar=function(){var e=this.offsetX,t=this.offsetY,o=Math.atan2(t,e);this.degrees=this.toDegrees(o),this.radius=Math.sqrt(e*e+t*t),this.positionChildCircle(o)},t.prototype.calculateCartesian=function(){var e=this.toRadians(this.getValue()),t=this.getRadius();this.setOffsetX(Math.cos(e)*t).setOffsetY(Math.sin(e)*t)},t.prototype.setOffsetX=function(e){return this.offsetX!==e&&(this.offsetX=e,this.calculatePolar()),this},t.prototype.setOffsetY=function(e){return this.offsetY!==e&&(this.offsetY=e,this.calculatePolar()),this},t.prototype.calculateAngleDrag=function(e){var t=this.parentCircleRect,o=t.width/2,i=t.height/2,n=e.clientX-t.left-o,r=e.clientY-t.top-i,s=Math.atan2(r,n);this.setValue(s,!0)},t.prototype.toDegrees=function(e){return e/Math.PI*180},t.prototype.toRadians=function(e){return e/180*Math.PI},t.prototype.normalizeNegativeValue=function(e){return e<0?360+e:e},t.prototype.normalizeAngle180=function(e){return(e%=2*Math.PI)<-Math.PI?e+=2*Math.PI:e>=Math.PI&&(e-=2*Math.PI),e},t.prototype.getRadius=function(){return this.radius},t.prototype.setRadius=function(e){return this.radius===e?this:(this.radius=e,this.calculateCartesian(),this)},t.prototype.onValueChange=function(e){var t=this;return this.addDestroyableEventListener(this,Vo.EVENT_CHANGED,(function(){e(t.degrees)})),this},t.prototype.getValue=function(e){return e?this.toRadians(this.degrees):this.degrees},t.prototype.setValue=function(e,t){var o;return o=t?e:this.normalizeAngle180(this.toRadians(e)),e=this.toDegrees(o),this.degrees!==e&&(this.degrees=Math.floor(e),this.calculateCartesian(),this.positionChildCircle(o),this.dispatchEvent({type:Vo.EVENT_CHANGED})),this},t.prototype.setWidth=function(e){return p.setFixedWidth(this.getGui(),e),this},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.dragService.removeDragSource(this.dragListener)},t.TEMPLATE='<div class="ag-angle-select">\n <label ref="eLabel"></label>\n <div class="ag-wrapper">\n <div ref="eAngleSelectField" class="ag-angle-select-field">\n <div ref="eParentCircle" class="ag-parent-circle">\n <div ref="eChildCircle" class="ag-child-circle"></div>\n </div>\n </div>\n <ag-input-number-field ref="eAngleValue"></ag-input-number-field>\n </div>\n </div>',is([fe("eLabel")],t.prototype,"eLabel",void 0),is([fe("eParentCircle")],t.prototype,"eParentCircle",void 0),is([fe("eChildCircle")],t.prototype,"eChildCircle",void 0),is([fe("eAngleValue")],t.prototype,"eAngleValue",void 0),is([m("dragService")],t.prototype,"dragService",void 0),t}(Mo),rs=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),ss=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.className="ag-toggle-button",t}return rs(t,e),t.prototype.postConstruct=function(){e.prototype.postConstruct.call(this),p.addCssClass(this.eIconEl,"ag-icon")},t.prototype.updateIcons=function(){var e=this.getValue();p.addOrRemoveCssClass(this.eIconEl,"ag-icon-toggle-on",e),p.addOrRemoveCssClass(this.eIconEl,"ag-icon-toggle-off",!e)},t.prototype.setValue=function(t,o){return e.prototype.setValue.call(this,t,o),p.addOrRemoveCssClass(this.getGui(),"ag-selected",this.getValue()),this},t}(wn),as=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},ls=function(){function e(){this.cacheItems=[]}return e.prototype.postConstruct=function(){this.active=this.gridOptionsWrapper.isKeepDetailRows(),this.maxCacheSize=this.gridOptionsWrapper.getKeepDetailRowsCount()},e.prototype.addOrDestroy=function(e,t,i){if(!this.active||!e.detail)this.destroyFullWidthRow(i);else{var n=this.getCacheItem(e,!0);switch(t){case o.PINNED_LEFT:this.destroyFullWidthRow(n.left),n.left=i;break;case o.PINNED_RIGHT:this.destroyFullWidthRow(n.right),n.right=i;break;default:this.destroyFullWidthRow(n.center),n.center=i}this.cacheItems.sort((function(e,t){return t.lastAccessedTime-e.lastAccessedTime})),this.purgeCache(this.maxCacheSize)}},e.prototype.getCacheItem=function(e,t){var o;void 0===t&&(t=!1);for(var i=0;i<this.cacheItems.length;i++){var n=this.cacheItems[i];if(n.rowNode===e){o=n;break}}return!o&&t&&(o={rowNode:e},this.cacheItems.push(o)),o&&this.stampCacheItem(o),o},e.prototype.stampCacheItem=function(e){e.lastAccessedTime=(new Date).getTime()},e.prototype.destroyFullWidthRow=function(e){e&&e.destroy&&e.destroy()},e.prototype.purgeCache=function(e){for(var t=e;t<this.cacheItems.length;t++){var o=this.cacheItems[t];this.destroyFullWidthRow(o.center),this.destroyFullWidthRow(o.left),this.destroyFullWidthRow(o.right)}this.cacheItems.length>e&&(this.cacheItems.length=e)},e.prototype.get=function(e,t){if(e.detail){var i,n=this.getCacheItem(e);if(n)switch(t){case o.PINNED_LEFT:n.left&&(i=n.left,n.left=void 0);break;case o.PINNED_RIGHT:n.right&&(i=n.right,n.right=void 0);break;default:n.center&&(i=n.center,n.center=void 0)}return i}},e.prototype.destroy=function(){this.purgeCache(0)},as([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),as([g],e.prototype,"postConstruct",null),as([f],e.prototype,"destroy",null),e=as([y("detailRowCompCache")],e)}(),ps=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},us=function(){function e(){}return e.prototype.getRowNode=function(e){switch(e.rowPinned){case o.PINNED_TOP:return this.pinnedRowModel.getPinnedTopRowData()[e.rowIndex];case o.PINNED_BOTTOM:return this.pinnedRowModel.getPinnedBottomRowData()[e.rowIndex];default:return this.rowModel.getRow(e.rowIndex)}},e.prototype.sameRow=function(e,t){return!e&&!t||!(e&&!t||!e&&t)&&(e.rowIndex===t.rowIndex&&e.rowPinned==t.rowPinned)},e.prototype.before=function(e,t){switch(e.rowPinned){case o.PINNED_TOP:if(t.rowPinned!==o.PINNED_TOP)return!0;break;case o.PINNED_BOTTOM:if(t.rowPinned!==o.PINNED_BOTTOM)return!1;break;default:if(p.exists(t.rowPinned))return t.rowPinned!==o.PINNED_TOP}return e.rowIndex<t.rowIndex},ps([m("rowModel")],e.prototype,"rowModel",void 0),ps([m("pinnedRowModel")],e.prototype,"pinnedRowModel",void 0),e=ps([y("rowPositionUtils")],e)}(),cs=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},ds=function(){function e(){}return e.prototype.createId=function(e){var t=e.rowIndex,o=e.rowPinned,i=e.column;return this.createIdFromValues(t,i,o)},e.prototype.createIdFromValues=function(e,t,o){return e+"."+(null==o?"null":o)+"."+t.getId()},e.prototype.equals=function(e,t){var o=e.column===t.column,i=e.rowPinned===t.rowPinned,n=e.rowIndex===t.rowIndex;return o&&i&&n},e=cs([y("cellPositionUtils")],e)}(),hs=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},gs=function(){function e(){}return e.prototype.init=function(){this.setPinnedTopRowData(this.gridOptionsWrapper.getPinnedTopRowData()),this.setPinnedBottomRowData(this.gridOptionsWrapper.getPinnedBottomRowData())},e.prototype.isEmpty=function(e){var t=e===o.PINNED_TOP?this.pinnedTopRows:this.pinnedBottomRows;return p.missingOrEmpty(t)},e.prototype.isRowsToRender=function(e){return!this.isEmpty(e)},e.prototype.getRowAtPixel=function(e,t){var i=t===o.PINNED_TOP?this.pinnedTopRows:this.pinnedBottomRows;if(p.missingOrEmpty(i))return 0;for(var n=0;n<i.length;n++){var r=i[n];if(r.rowTop+r.rowHeight-1>=e)return n}return i.length-1},e.prototype.setPinnedTopRowData=function(e){this.pinnedTopRows=this.createNodesFromData(e,!0);var t={type:M.EVENT_PINNED_ROW_DATA_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)},e.prototype.setPinnedBottomRowData=function(e){this.pinnedBottomRows=this.createNodesFromData(e,!1);var t={type:M.EVENT_PINNED_ROW_DATA_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)},e.prototype.createNodesFromData=function(e,t){var i=this,n=[];if(e){var r=0;e.forEach((function(e,s){var a=new je;i.context.wireBean(a),a.data=e,a.id=(t?"t":"b")+"-"+s,a.rowPinned=t?o.PINNED_TOP:o.PINNED_BOTTOM,a.setRowTop(r),a.setRowHeight(i.gridOptionsWrapper.getRowHeightForNode(a).height),a.setRowIndex(s),r+=a.rowHeight,n.push(a)}))}return n},e.prototype.getPinnedTopRowData=function(){return this.pinnedTopRows},e.prototype.getPinnedBottomRowData=function(){return this.pinnedBottomRows},e.prototype.getPinnedTopTotalHeight=function(){return this.getTotalHeight(this.pinnedTopRows)},e.prototype.getPinnedTopRowCount=function(){return this.pinnedTopRows?this.pinnedTopRows.length:0},e.prototype.getPinnedBottomRowCount=function(){return this.pinnedBottomRows?this.pinnedBottomRows.length:0},e.prototype.getPinnedTopRow=function(e){return this.pinnedTopRows[e]},e.prototype.getPinnedBottomRow=function(e){return this.pinnedBottomRows[e]},e.prototype.forEachPinnedTopRow=function(e){p.missingOrEmpty(this.pinnedTopRows)||this.pinnedTopRows.forEach(e)},e.prototype.forEachPinnedBottomRow=function(e){p.missingOrEmpty(this.pinnedBottomRows)||this.pinnedBottomRows.forEach(e)},e.prototype.getPinnedBottomTotalHeight=function(){return this.getTotalHeight(this.pinnedBottomRows)},e.prototype.getTotalHeight=function(e){if(e&&0!==e.length){var t=p.last(e);return t.rowTop+t.rowHeight}return 0},hs([m("gridOptionsWrapper")],e.prototype,"gridOptionsWrapper",void 0),hs([m("eventService")],e.prototype,"eventService",void 0),hs([m("context")],e.prototype,"context",void 0),hs([m("columnApi")],e.prototype,"columnApi",void 0),hs([m("gridApi")],e.prototype,"gridApi",void 0),hs([g],e.prototype,"init",null),e=hs([y("pinnedRowModel")],e)}(),fs=function(){function e(e,t,o){if(e)if(t){var i=!!t.debug;this.gridOptions=t;var n=this.getRegisteredModules(o),r=this.createBeansList(n),s=this.createAgStackComponentsList(n),a=this.createProvidedBeans(e,o);if(r){var l={providedBeanInstances:a,beanClasses:r,components:s,debug:i};this.logger=new Qi("ag-Grid",(function(){return t.debug}));var p=new Qi("Context",(function(){return l.debug}));this.context=new d(l,p),this.registerModuleUserComponents(n);var u=new on;this.context.wireBean(u),this.setColumnsAndData(),this.dispatchGridReadyEvent(t);var c=P.isRegistered(R.EnterpriseCoreModule);this.logger.log("initialised successfully, enterprise = "+c)}}else console.error("ag-Grid: no gridOptions provided to the grid");else console.error("ag-Grid: no div element provided to the grid")}return e.prototype.getRegisteredModules=function(e){var t=e?e.modules:null,o=P.getRegisteredModules(),i=[],n={};function r(e){!function(e){n[e.moduleName]||(n[e.moduleName]=!0,i.push(e),P.register(e))}(e),e.dependantModules&&e.dependantModules.forEach(r)}return t&&t.forEach(r),o&&o.forEach(r),i},e.prototype.registerModuleUserComponents=function(e){var t=this.context.getBean("userComponentRegistry");this.extractModuleEntity(e,(function(e){return e.userComponents?e.userComponents:[]})).forEach((function(e){t.registerDefaultComponent(e.componentName,e.componentClass)}))},e.prototype.createProvidedBeans=function(e,t){var o=t?t.frameworkOverrides:null;p.missing(o)&&(o=new Rn);var i={gridOptions:this.gridOptions,eGridDiv:e,$scope:t?t.$scope:null,$compile:t?t.$compile:null,quickFilterOnScope:t?t.quickFilterOnScope:null,globalEventListener:t?t.globalEventListener:null,frameworkOverrides:o};return t&&t.providedBeanInstances&&p.assign(i,t.providedBeanInstances),i},e.prototype.createAgStackComponentsList=function(e){var t=[{componentName:"AgCheckbox",componentClass:jo},{componentName:"AgRadioButton",componentClass:wn},{componentName:"AgToggleButton",componentClass:ss},{componentName:"AgInputTextField",componentClass:Mr},{componentName:"AgInputTextArea",componentClass:Vr},{componentName:"AgInputNumberField",componentClass:$r},{componentName:"AgInputRange",componentClass:Zr},{componentName:"AgSelect",componentClass:ts},{componentName:"AgSlider",componentClass:kr},{componentName:"AgAngleSelect",componentClass:ns},{componentName:"AgColorPicker",componentClass:Qr},{componentName:"AgGridComp",componentClass:Mi},{componentName:"AgHeaderRoot",componentClass:Di},{componentName:"AgPagination",componentClass:vr},{componentName:"AgOverlayWrapper",componentClass:br},{componentName:"AgGroupComponent",componentClass:Tr},{componentName:"AgPanel",componentClass:Fr},{componentName:"AgDialog",componentClass:Ir}],o=this.extractModuleEntity(e,(function(e){return e.agStackComponents?e.agStackComponents:[]}));return t=t.concat(o)},e.prototype.createBeansList=function(e){var t=this.getRowModelClass(e);if(t){var o=[t,Zn,us,ds,Wn,Vi,qt,Qn,$n,Er,Xe,cr,fr,mn,Zi,gs,an,j,b,Z,zi,Jt,Pi,H,Mn,_o,ki,G,Ui,Kn,lr,kn,Ti,qi,B,$i,rn,ao,eo,cn,hn,nr,fn,Cn,Pn,Dn,pn,An,Fn,hr,Ln,jn,sr,Rr,ls],i=this.extractModuleEntity(e,(function(e){return e.beans?e.beans:[]}));o.push.apply(o,i);var n=[];return o.forEach((function(e){n.indexOf(e)<0&&n.push(e)})),n}},e.prototype.extractModuleEntity=function(e,t){return[].concat.apply([],e.map(t))},e.prototype.setColumnsAndData=function(){var e=this.context.getBean("gridOptionsWrapper"),t=this.context.getBean("columnController"),o=e.getColumnDefs();p.exists(o)&&t.setColumnDefs(o,"gridInitializing"),this.context.getBean("rowModel").start()},e.prototype.dispatchGridReadyEvent=function(e){var t=this.context.getBean("eventService"),o={type:M.EVENT_GRID_READY,api:e.api,columnApi:e.columnApi};t.dispatchEvent(o)},e.prototype.getRowModelClass=function(e){var t=this.gridOptions.rowModelType;"enterprise"===t&&(console.warn("ag-Grid: enterprise rowModel deprecated. Should now be called server side row model instead."),t=o.ROW_MODEL_TYPE_SERVER_SIDE),"normal"===t&&(console.warn("ag-Grid: normal rowModel deprecated. Should now be called client side row model instead."),t=o.ROW_MODEL_TYPE_CLIENT_SIDE),t||(t=o.ROW_MODEL_TYPE_CLIENT_SIDE);var i={};e.forEach((function(e){p.iterateObject(e.rowModels,(function(e,t){i[e]=t}))}));var n=i[t];return p.exists(n)?n:(t===o.ROW_MODEL_TYPE_INFINITE&&console.error("ag-Grid: Row Model \"Infinite\" not found. Please ensure the InfiniteRowModelModule is loaded using: import '@ag-grid-community/infinite-row-model';"),console.error("ag-Grid: could not find matching row model for rowModelType "+t),t===o.ROW_MODEL_TYPE_VIEWPORT&&console.error('ag-Grid: Row Model "Viewport" not found. For this row model to work you must a) be using ag-Grid Enterprise and b) ensure ViewportRowModelModule is loaded using: import \'@ag-grid-enterprise/viewport-row-model;'),t===o.ROW_MODEL_TYPE_SERVER_SIDE&&console.error("ag-Grid: Row Model \"Server Side\" not found. For this row model to work you must a) be using ag-Grid Enterprise and b) ensure ServerSideRowModelModule is loaded using: import '@ag-grid-enterprise/server-server-side-row-model';"),void(t===o.ROW_MODEL_TYPE_CLIENT_SIDE&&console.error("ag-Grid: Row Model \"Client Side\" not found. Please ensure the ClientSideRowModelModule is loaded using: import '@ag-grid-community/client-side-row-model';")))},e.prototype.destroy=function(){this.gridOptions.api.destroy()},e}(); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */ /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */ function ys(e){e.module("agGrid",[]).directive("agGrid",(function(){return{restrict:"A",controller:["$element","$scope","$compile","$attrs",ms],scope:!0}}))}function ms(e,t,o,i){var n,r,s=i.agGrid;if(r=s+".quickFilterText",n=t.$eval(s)){var a=e[0],l=new fs(a,n,{$scope:t,$compile:o,quickFilterOnScope:r});t.$on("$destroy",(function(){l.destroy(),l=null}))}else console.warn("WARNING - grid options for ag-Grid not found. Please ensure the attribute ag-grid points to a valid object on the scope")} /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */var vs=!1;function Cs(){if(console.warn("ag-grid: initialiseAgGridWithWebComponents is deprecated. Please use the ag-grid-webcomponent dependency instead. "),!vs){vs=!0,"undefined"!=typeof document&&document.registerElement||console.error("ag-Grid: unable to find document.registerElement() function, unable to initialise ag-Grid as a Web Component");var e=Object.create(HTMLElement.prototype);te.ALL_PROPERTIES.forEach((function(t){Object.defineProperty(e,t,{set:function(e){this.__agGridSetProperty(t,e)},get:function(){return this.__agGridGetProperty(t)},enumerable:!0,configurable:!0})}));var t=e;t.__agGridSetProperty=function(e,t){this.__attributes||(this.__attributes={}),this.__attributes[e]=t;var o={};o[e]={currentValue:t},this.onChange(o)},t.onChange=function(e){this._initialised&&te.processOnChange(e,this._gridOptions,this.api,this.columnApi)},t.__agGridGetProperty=function(e){return this.__attributes||(this.__attributes={}),this.__attributes[e]},t.setGridOptions=function(e){var t=this.globalEventListener.bind(this);this._gridOptions=te.copyAttributesToGridOptions(e,this);var o={globalEventListener:t};this._agGrid=new fs(this,this._gridOptions,o),this.api=e.api,this.columnApi=e.columnApi,this._initialised=!0},t.createdCallback=function(){for(var e=0;e<this.attributes.length;e++){var t=this.attributes[e];this.setPropertyFromAttribute(t)}},t.setPropertyFromAttribute=function(e){var t,o="string"==typeof(t=e.nodeName)?t.replace(/-([a-z])/g,(function(e){return e[1].toUpperCase()})):t,i=e.nodeValue;te.ALL_PROPERTIES.indexOf(o)>=0&&(this[o]=i)},t.attachedCallback=function(e){},t.detachedCallback=function(e){},t.attributeChangedCallback=function(e){var t=this.attributes[e];this.setPropertyFromAttribute(t)},t.globalEventListener=function(e,t){var o=e.toLowerCase(),i=new Event(o);i.agGridDetails=t,this.dispatchEvent(i);var n="on"+o;"function"==typeof this[n]&&this[n](i)},document.registerElement("ag-grid",{prototype:e})}} /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */ var Es=function(){function e(t){var o=this;this.items=[],this.params=t,this.eGui=document.createElement("div"),this.eGui.innerHTML=e.TEMPLATE,this.eHeader=this.eGui.querySelector('[ref="tabHeader"]'),this.eBody=this.eGui.querySelector('[ref="tabBody"]'),p.addCssClass(this.eGui,t.cssClass),t.items&&t.items.forEach((function(e){return o.addItem(e)}))}return e.prototype.setAfterAttachedParams=function(e){this.afterAttachedParams=e},e.prototype.getMinDimensions=function(){var e=this.eGui.cloneNode(!0),t=e.querySelector('[ref="tabBody"]');e.style.position="fixed",this.eGui.appendChild(e);var o=0,i=0;return this.items.forEach((function(n){p.clearElement(t);var r=n.tabbedItem.bodyPromise.resolveNow(null,(function(e){return e.cloneNode(!0)}));null!=r&&(t.appendChild(r),o<e.offsetWidth&&(o=e.offsetWidth),i<e.offsetHeight&&(i=e.offsetHeight))})),this.eGui.removeChild(e),{height:i,width:o}},e.prototype.showFirstItem=function(){this.items.length>0&&this.showItemWrapper(this.items[0])},e.prototype.addItem=function(e){var t=document.createElement("span");t.appendChild(e.title),p.addCssClass(t,"ag-tab"),this.eHeader.appendChild(t);var o={tabbedItem:e,eHeaderButton:t};this.items.push(o),t.addEventListener("click",this.showItemWrapper.bind(this,o))},e.prototype.showItem=function(e){var t=p.find(this.items,(function(t){return t.tabbedItem===e}));t&&this.showItemWrapper(t)},e.prototype.showItemWrapper=function(e){var t=this;this.params.onItemClicked&&this.params.onItemClicked({item:e.tabbedItem}),this.activeItem!==e?(p.clearElement(this.eBody),e.tabbedItem.bodyPromise.then((function(e){t.eBody.appendChild(e)})),this.activeItem&&p.removeCssClass(this.activeItem.eHeaderButton,"ag-tab-selected"),p.addCssClass(e.eHeaderButton,"ag-tab-selected"),this.activeItem=e,e.tabbedItem.afterAttachedCallback&&e.tabbedItem.afterAttachedCallback(this.afterAttachedParams)):p.callIfPresent(this.params.onActiveItemClicked)},e.prototype.getGui=function(){return this.eGui},e.TEMPLATE='<div><div ref="tabHeader" class="ag-tab-header"></div><div ref="tabBody" class="ag-tab-body"></div></div>',e}(); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */function ws(e){return new u((function(t){var o=new XMLHttpRequest;o.open("GET",e.url),o.send(),o.onreadystatechange=function(){if(4==o.readyState&&200==o.status){var e=JSON.parse(o.responseText);t(e)}}}))} /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */var Rs=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Os=function(e){function t(o,i){var n=e.call(this)||this;return n.version=0,n.state=t.STATE_DIRTY,n.rowNodeCacheParams=i,n.blockNumber=o,n.startRow=o*i.blockSize,n.endRow=n.startRow+i.blockSize,n}return Rs(t,e),t.prototype.isAnyNodeOpen=function(e){var t=!1;return this.forEachNodeCallback((function(e){e.expanded&&(t=!0)}),e),t},t.prototype.forEachNodeCallback=function(e,t){for(var o=this.startRow;o<this.endRow;o++){if(o<t)e(this.getRowUsingLocalIndex(o),o)}},t.prototype.forEachNode=function(e,t,o,i){this.forEachNodeCallback((function(o){e(o,t.next()),i&&o.childrenCache&&o.childrenCache.forEachNodeDeep(e,t)}),o)},t.prototype.forEachNodeDeep=function(e,t,o){this.forEachNode(e,t,o,!0)},t.prototype.forEachNodeShallow=function(e,t,o){this.forEachNode(e,t,o,!1)},t.prototype.getVersion=function(){return this.version},t.prototype.getLastAccessed=function(){return this.lastAccessed},t.prototype.getRowUsingLocalIndex=function(e,t){void 0===t&&(t=!1),t||(this.lastAccessed=this.rowNodeCacheParams.lastAccessedSequence.next());var o=e-this.startRow;return this.rowNodes[o]},t.prototype.init=function(e){this.beans=e,this.createRowNodes()},t.prototype.getStartRow=function(){return this.startRow},t.prototype.getEndRow=function(){return this.endRow},t.prototype.getBlockNumber=function(){return this.blockNumber},t.prototype.setDirty=function(){this.version++,this.state=t.STATE_DIRTY},t.prototype.setDirtyAndPurge=function(){this.setDirty(),this.rowNodes.forEach((function(e){e.setData(null)}))},t.prototype.getState=function(){return this.state},t.prototype.setRowNode=function(e,t){var o=e-this.startRow;this.rowNodes[o]=t},t.prototype.setBlankRowNode=function(e){var t=e-this.startRow,o=this.createBlankRowNode(e);return this.rowNodes[t]=o,o},t.prototype.setNewData=function(e,t){var o=this.setBlankRowNode(e);return this.setDataAndId(o,t,this.startRow+e),o},t.prototype.createBlankRowNode=function(e){var t=new je;return this.beans.context.wireBean(t),t.setRowHeight(this.rowNodeCacheParams.rowHeight),t},t.prototype.createRowNodes=function(){this.rowNodes=[];for(var e=0;e<this.rowNodeCacheParams.blockSize;e++){var t=this.startRow+e,o=this.createBlankRowNode(t);this.rowNodes.push(o)}},t.prototype.load=function(){this.state=t.STATE_LOADING,this.loadFromDatasource()},t.prototype.pageLoadFailed=function(){this.state=t.STATE_FAILED;var e={type:t.EVENT_LOAD_COMPLETE,success:!1,page:this,lastRow:null};this.dispatchEvent(e)},t.prototype.populateWithRowData=function(e){var t=this,o=[];this.rowNodes.forEach((function(i,n){var r=e[n];i.stub&&o.push(i),t.setDataAndId(i,r,t.startRow+n)})),o.length>0&&this.beans.rowRenderer.redrawRows(o)},t.prototype.destroy=function(){e.prototype.destroy.call(this),this.rowNodes.forEach((function(e){e.childrenCache&&(e.childrenCache.destroy(),e.childrenCache=null),e.clearRowTop()}))},t.prototype.pageLoaded=function(e,o,i){e===this.version&&(this.state=t.STATE_LOADED,this.populateWithRowData(o)),i=p.cleanNumber(i);var n={type:t.EVENT_LOAD_COMPLETE,success:!0,page:this,lastRow:i};this.dispatchEvent(n)},t.EVENT_LOAD_COMPLETE="loadComplete",t.STATE_DIRTY="dirty",t.STATE_LOADING="loading",t.STATE_LOADED="loaded",t.STATE_FAILED="failed",t}(re),Ds=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},bs=function(e,t){return function(o,i){t(o,i,e)}},Ps=function(){function e(e,t){this.activeBlockLoadsCount=0,this.blocks=[],this.active=!0,this.maxConcurrentRequests=e,t&&t>0&&(this.checkBlockToLoadDebounce=p.debounce(this.performCheckBlocksToLoad.bind(this),t))}return e.prototype.setBeans=function(e){this.logger=e.create("RowNodeBlockLoader")},e.prototype.addBlock=function(e){this.blocks.push(e)},e.prototype.removeBlock=function(e){p.removeFromArray(this.blocks,e)},e.prototype.destroy=function(){this.active=!1},e.prototype.loadComplete=function(){this.activeBlockLoadsCount--},e.prototype.checkBlockToLoad=function(){this.checkBlockToLoadDebounce?this.checkBlockToLoadDebounce():this.performCheckBlocksToLoad()},e.prototype.performCheckBlocksToLoad=function(){if(this.active)if(this.printCacheStatus(),this.activeBlockLoadsCount>=this.maxConcurrentRequests)this.logger.log("checkBlockToLoad: max loads exceeded");else{var e=null;this.blocks.forEach((function(t){t.getState()===Os.STATE_DIRTY&&(e=t)})),e?(e.load(),this.activeBlockLoadsCount++,this.logger.log("checkBlockToLoad: loading page "+e.getBlockNumber()),this.printCacheStatus()):this.logger.log("checkBlockToLoad: no pages to load")}},e.prototype.getBlockState=function(){var e={};return this.blocks.forEach((function(t){var o=t.getNodeIdPrefix(),i={blockNumber:t.getBlockNumber(),startRow:t.getStartRow(),endRow:t.getEndRow(),pageStatus:t.getState()};p.exists(o)?e[o+t.getBlockNumber()]=i:e[t.getBlockNumber()]=i})),e},e.prototype.printCacheStatus=function(){this.logger.isLogging()&&this.logger.log("printCacheStatus: activePageLoadsCount = "+this.activeBlockLoadsCount+", blocks = "+JSON.stringify(this.getBlockState()))},e.prototype.isLoading=function(){return this.activeBlockLoadsCount>0},Ds([bs(0,E("loggerFactory"))],e.prototype,"setBeans",null),e}(),Ss=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Ts=function(e){function t(t){var o=e.call(this)||this;return o.maxRowFound=!1,o.blocks={},o.blockCount=0,o.virtualRowCount=t.initialRowCount,o.cacheParams=t,o}return Ss(t,e),t.prototype.destroy=function(){var t=this;e.prototype.destroy.call(this),this.forEachBlockInOrder((function(e){return t.destroyBlock(e)}))},t.prototype.init=function(){var e=this;this.active=!0,this.addDestroyFunc((function(){return e.active=!1}))},t.prototype.isActive=function(){return this.active},t.prototype.getVirtualRowCount=function(){return this.virtualRowCount},t.prototype.hack_setVirtualRowCount=function(e){this.virtualRowCount=e},t.prototype.isMaxRowFound=function(){return this.maxRowFound},t.prototype.onPageLoaded=function(e){this.cacheParams.rowNodeBlockLoader.loadComplete(),this.checkBlockToLoad(),this.isActive()&&(this.logger.log("onPageLoaded: page = "+e.page.getBlockNumber()+", lastRow = "+e.lastRow),e.success&&this.checkVirtualRowCount(e.page,e.lastRow))},t.prototype.purgeBlocksIfNeeded=function(e){var o=this,i=[];this.forEachBlockInOrder((function(t){t!==e&&i.push(t)})),i.sort((function(e,t){return t.getLastAccessed()-e.getLastAccessed()}));var n=this.cacheParams.maxBlocksInCache>0,r=n?this.cacheParams.maxBlocksInCache-1:null,s=t.MAX_EMPTY_BLOCKS_TO_KEEP-1;i.forEach((function(e,t){if(e.getState()===Os.STATE_DIRTY&&t>=s||!!n&&t>=r){if(e.isAnyNodeOpen(o.virtualRowCount))return;o.removeBlockFromCache(e)}}))},t.prototype.postCreateBlock=function(e){e.addEventListener(Os.EVENT_LOAD_COMPLETE,this.onPageLoaded.bind(this)),this.setBlock(e.getBlockNumber(),e),this.purgeBlocksIfNeeded(e),this.checkBlockToLoad()},t.prototype.removeBlockFromCache=function(e){e&&this.destroyBlock(e)},t.prototype.checkBlockToLoad=function(){this.cacheParams.rowNodeBlockLoader.checkBlockToLoad()},t.prototype.checkVirtualRowCount=function(e,t){if("number"==typeof t&&t>=0)this.virtualRowCount=t,this.maxRowFound=!0,this.onCacheUpdated();else if(!this.maxRowFound){var o=(e.getBlockNumber()+1)*this.cacheParams.blockSize+this.cacheParams.overflowSize;this.virtualRowCount<o?(this.virtualRowCount=o,this.onCacheUpdated()):this.cacheParams.dynamicRowHeight&&this.onCacheUpdated()}},t.prototype.setVirtualRowCount=function(e,t){this.virtualRowCount=e,p.exists(t)&&(this.maxRowFound=t),this.maxRowFound||this.virtualRowCount%this.cacheParams.blockSize==0&&this.virtualRowCount++,this.onCacheUpdated()},t.prototype.forEachNodeDeep=function(e,t){var o=this;void 0===t&&(t=new l),this.forEachBlockInOrder((function(i){i.forEachNodeDeep(e,t,o.virtualRowCount)}))},t.prototype.forEachBlockInOrder=function(e){var t=this.getBlockIdsSorted();this.forEachBlockId(t,e)},t.prototype.forEachBlockInReverseOrder=function(e){var t=this.getBlockIdsSorted().reverse();this.forEachBlockId(t,e)},t.prototype.forEachBlockId=function(e,t){var o=this;e.forEach((function(e){var i=o.blocks[e];t(i,e)}))},t.prototype.getBlockIdsSorted=function(){return Object.keys(this.blocks).map((function(e){return parseInt(e,10)})).sort((function(e,t){return e-t}))},t.prototype.getBlock=function(e){return this.blocks[e]},t.prototype.setBlock=function(e,t){this.blocks[e]=t,this.blockCount++,this.cacheParams.rowNodeBlockLoader.addBlock(t)},t.prototype.destroyBlock=function(e){delete this.blocks[e.getBlockNumber()],e.destroy(),this.blockCount--,this.cacheParams.rowNodeBlockLoader.removeBlock(e)},t.prototype.onCacheUpdated=function(){if(this.isActive()){var e={type:t.EVENT_CACHE_UPDATED};this.dispatchEvent(e)}},t.prototype.purgeCache=function(){var e=this;this.forEachBlockInOrder((function(t){return e.removeBlockFromCache(t)})),this.virtualRowCount=this.cacheParams.initialRowCount,this.maxRowFound=!1,this.onCacheUpdated()},t.prototype.getRowNodesInRange=function(e,t){var o=this,i=[],n=-1,r=!1,s=new l;p.missing(e)&&(r=!0);var a=!1;return this.forEachBlockInOrder((function(l,p){a||(r&&n+1!==p?a=!0:(n=p,l.forEachNodeShallow((function(o){var n=o===e||o===t;(r||n)&&i.push(o),n&&(r=!r)}),s,o.virtualRowCount)))})),a||r?[]:i},t.EVENT_CACHE_UPDATED="cacheUpdated",t.MAX_EMPTY_BLOCKS_TO_KEEP=2,t}(re),As=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),_s=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Fs=function(e){function t(t){var o=e.call(this,t)||this;return o.message=t.message,o}return As(t,e),t.prototype.postConstruct=function(){var t=this,o=new Ns;this.wireDependentBean(o),o.setMessage(this.message),this.setBodyComponent(o),e.prototype.postConstruct.call(this),this.addDestroyableEventListener(o,"onBtOk",(function(){return t.close()}))},t}(Ir),Ns=function(e){function t(){return e.call(this,t.TEMPLATE)||this}return As(t,e),t.prototype.setMessage=function(e){this.eCenter.innerText=e},t.prototype.postConstruct=function(){this.addDestroyableEventListener(this.eOk,"click",this.onBtOk.bind(this))},t.prototype.onBtOk=function(){this.dispatchEvent({type:"onBtOk"})},t.TEMPLATE='<div class="ag-message-box">\n <div ref="eCenter" class="ag-message-box-content"></div>\n <div ref="eButtons" class="ag-message-box-button-bar">\n <button ref="eOk">OK</button>\n </div>\n </div>',_s([fe("eCenter")],t.prototype,"eCenter",void 0),_s([fe("eOk")],t.prototype,"eOk",void 0),_s([g],t.prototype,"postConstruct",null),t}(pe),Ls=function(){var e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(t,o)};return function(t,o){function i(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(i.prototype=o.prototype,new i)}}(),Is=function(e,t,o,i){var n,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,o):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,o,s):n(t,o))||s);return r>3&&s&&Object.defineProperty(t,o,s),s},Gs=function(e){function t(){var t=e.call(this,void 0)||this;return t.rowsInBodyContainer={},t.rowHeight=20,t}return Ls(t,e),t.prototype.init=function(){this.setTemplate(t.TEMPLATE),this.eListContainer=this.queryForHtmlElement(".ag-virtual-list-container"),this.addScrollListener();var e=document.createElement("div");p.addCssClass(e,"ag-virtual-list-item"),this.rowHeight=this.getItemHeight()},t.prototype.getItemHeight=function(){return this.gridOptionsWrapper.getVirtualItemHeight()},t.prototype.ensureIndexVisible=function(e){var t=this.model.getRowCount();if("number"!=typeof e||e<0||e>=t)console.warn("invalid row index for ensureIndexVisible: "+e);else{var o=e*this.rowHeight,i=o+this.rowHeight,n=this.getGui().scrollTop,r=this.getGui().offsetHeight,s=n+r<i;if(n>o)this.getGui().scrollTop=o;else if(s){var a=i-r;this.getGui().scrollTop=a}}},t.prototype.setComponentCreator=function(e){this.componentCreator=e},t.prototype.getRowHeight=function(){return this.rowHeight},t.prototype.getScrollTop=function(){return this.getGui().scrollTop},t.prototype.setRowHeight=function(e){this.rowHeight=e,this.refresh()},t.prototype.refresh=function(){p.missing(this.model)||(this.eListContainer.style.height=this.model.getRowCount()*this.rowHeight+"px",this.clearVirtualRows(),this.drawVirtualRows())},t.prototype.clearVirtualRows=function(){var e=Object.keys(this.rowsInBodyContainer);this.removeVirtualRows(e)},t.prototype.drawVirtualRows=function(){var e=this.getGui().scrollTop,t=e+this.getGui().offsetHeight,o=Math.floor(e/this.rowHeight),i=Math.floor(t/this.rowHeight);this.ensureRowsRendered(o,i)},t.prototype.ensureRowsRendered=function(e,t){for(var o=Object.keys(this.rowsInBodyContainer),i=e;i<=t;i++)if(o.indexOf(i.toString())>=0)o.splice(o.indexOf(i.toString()),1);else if(this.model.getRowCount()>i){var n=this.model.getRow(i);this.insertRow(n,i)}this.removeVirtualRows(o)},t.prototype.removeVirtualRows=function(e){var t=this;e.forEach((function(e){var o=t.rowsInBodyContainer[e];t.eListContainer.removeChild(o.eDiv),o.rowComponent.destroy&&o.rowComponent.destroy(),delete t.rowsInBodyContainer[e]}))},t.prototype.insertRow=function(e,t){var o=document.createElement("div");p.addCssClass(o,"ag-virtual-list-item"),o.style.top=this.rowHeight*t+"px";var i=this.componentCreator(e);o.appendChild(i.getGui()),this.eListContainer.appendChild(o),this.rowsInBodyContainer[t]={rowComponent:i,eDiv:o}},t.prototype.addScrollListener=function(){var e=this;this.addGuiEventListener("scroll",(function(){e.drawVirtualRows()}))},t.prototype.setModel=function(e){this.model=e},t.TEMPLATE='<div class="ag-virtual-list-viewport">\n <div class="ag-virtual-list-container"></div>\n </div>',Is([m("environment")],t.prototype,"environment",void 0),Is([m("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Is([g],t.prototype,"init",null),t}(pe); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */ function Ms(e,t,o,i,n){void 0===n&&(n=!1),console.warn("ag-Grid: Since ag-grid 11.0.0 defaultGroupComparator is not necessary. You can remove this from your colDef");var r=p.exists(o)&&o.group,s=p.exists(i)&&i.group,a=!r&&!s;return r&&s?p.defaultComparator(o.key,i.key,n):a?p.defaultComparator(e,t,n):r?1:-1} /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */var xs,Vs=function(){function e(){}return e.prototype.wrap=function(e,t,o,i){var n=this;void 0===o&&(o=[]);var r=this.createWrapper(e,i);return t.forEach((function(e){n.createMethod(r,e,!0)})),o.forEach((function(e){n.createMethod(r,e,!1)})),r},e.prototype.createMethod=function(e,t,o){e.addMethod(t,this.createMethodProxy(e,t,o))},e.prototype.createMethodProxy=function(e,t,o){return function(){return e.hasMethod(t)?e.callMethod(t,arguments):(o&&console.warn("ag-Grid: Framework component is missing the method "+t+"()"),null)}},e}(); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */!function(e){e.GroupedColumn="groupedColumn",e.StackedColumn="stackedColumn",e.NormalizedColumn="normalizedColumn",e.GroupedBar="groupedBar",e.StackedBar="stackedBar",e.NormalizedBar="normalizedBar",e.Line="line",e.Scatter="scatter",e.Bubble="bubble",e.Pie="pie",e.Doughnut="doughnut",e.Area="area",e.StackedArea="stackedArea",e.NormalizedArea="normalizedArea"}(xs||(xs={})); /** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.0.0 * @link http://www.ag-grid.com/ * @license MIT */ var Ws="undefined"==typeof global?{}:global;Ws.HTMLElement="undefined"==typeof HTMLElement?{}:HTMLElement,Ws.HTMLButtonElement="undefined"==typeof HTMLButtonElement?{}:HTMLButtonElement,Ws.HTMLSelectElement="undefined"==typeof HTMLSelectElement?{}:HTMLSelectElement,Ws.HTMLInputElement="undefined"==typeof HTMLInputElement?{}:HTMLInputElement,Ws.Node="undefined"==typeof Node?{}:Node,Ws.MouseEvent="undefined"==typeof MouseEvent?{}:MouseEvent;export{Vo as AgAbstractField,ns as AgAngleSelect,jo as AgCheckbox,Qr as AgColorPicker,Ir as AgDialog,Tr as AgGroupComponent,$r as AgInputNumberField,Zr as AgInputRange,Vr as AgInputTextArea,Mr as AgInputTextField,Fr as AgPanel,wn as AgRadioButton,ts as AgSelect,kr as AgSlider,ss as AgToggleButton,Kn as AlignedGridsService,ot as AnimateShowChangeCellRenderer,rt as AnimateSlideCellRenderer,$i as AutoWidthCalculator,m as Autowired,Vs as BaseComponentWrapper,y as Bean,re as BeanStub,yi as BodyDropPivotTarget,Ci as BodyDropTarget,Oo as CellComp,fn as CellNavigationService,ds as CellPositionUtils,Kt as CellRangeType,mn as CellRendererFactory,Qt as ChangedPath,xs as ChartType,Ke as CheckboxSelectionComponent,K as ColDefUtil,t as Color,T as Column,eo as ColumnApi,H as ColumnController,G as ColumnFactory,_ as ColumnGroup,c as ColumnKeyCreator,B as ColumnUtils,pe as Component,te as ComponentUtil,o as Constants,d as Context,Fo as CssClassApplier,Ge as DateFilter,j as DisplayedGroupCreator,ao as DragAndDropService,an as DragService,to as DragSourceType,nr as Environment,b as EventService,M as Events,ki as ExpressionService,Pi as FilterManager,cn as FocusedCellController,fs as Grid,Vi as GridApi,on as GridCore,Z as GridOptionsWrapper,Mi as GridPanel,Ze as GroupCellRenderer,x as GroupInstanceIdCreator,io as HDirection,wi as HeaderContainer,Di as HeaderRootComp,di as HeaderRowComp,Zi as HorizontalResizeService,mt as LargeTextCellEditor,me as Listener,Qi as Logger,qi as LoggerFactory,Fs as MessageBox,R as ModuleNames,P as ModuleRegistry,hn as MouseEventService,gi as MoveColumnController,Et as NumberFilter,l as NumberSequence,v as Optional,F as OriginalColumnGroup,Mn as PaginationProxy,gs as PinnedRowModel,ce as PopupComponent,mo as PopupEditorWrapper,ft as PopupSelectCellEditor,zi as PopupService,ht as PopupTextCellEditor,g as PostConstruct,h as PreConstruct,f as PreDestroy,u as Promise,be as ProvidedFilter,E as Qualifier,ge as QuerySelector,fe as RefSelector,Er as ResizeObserverService,Po as RowComp,je as RowNode,Os as RowNodeBlock,Ps as RowNodeBlockLoader,Ts as RowNodeCache,us as RowPositionUtils,_o as RowRenderer,Ne as ScalerFilter,Dn as ScrollVisibleService,ct as SelectCellEditor,hr as SelectableService,Jt as SelectionController,Lo as SetLeftFeature,_e as SimpleFilter,pn as SortController,rn as StandardMenuFactory,Pn as StylingService,Es as TabbedLayout,Ui as TemplateService,he as TextCellEditor,Vt as TextFilter,Rr as TooltipManager,Me as TouchListener,Xe as UserComponentFactory,qt as UserComponentRegistry,a as Utils,oo as VDirection,kn as ValueCache,Cn as ValueFormatterService,Ti as ValueService,Rn as VanillaFrameworkOverrides,Gs as VirtualList,p as _,Ms as defaultGroupComparator,ys as initialiseAgGridWithAngular1,Cs as initialiseAgGridWithWebComponents,ws as simpleHttpRequest};
e
line_program.rs
use super::address_transform::AddressTransform; use super::attr::clone_attr_string; use super::{Reader, TransformError}; use anyhow::{Context, Error}; use gimli::{ write, DebugLine, DebugLineOffset, DebugLineStr, DebugStr, DebugStrOffsets, DebuggingInformationEntry, LineEncoding, Unit, }; use more_asserts::assert_le; use wasmtime_environ::entity::EntityRef; use wasmtime_environ::wasm::DefinedFuncIndex; #[derive(Debug)] enum
{ Normal { address: u64, op_index: u64, file_index: u64, line: u64, column: u64, discriminator: u64, is_stmt: bool, basic_block: bool, prologue_end: bool, epilogue_begin: bool, isa: u64, }, EndOfSequence(u64), } #[derive(Debug)] struct FuncRows { index: DefinedFuncIndex, sorted_rows: Vec<(u64, SavedLineProgramRow)>, } #[derive(Debug, Eq, PartialEq)] enum ReadLineProgramState { SequenceEnded, ReadSequence(DefinedFuncIndex), IgnoreSequence, } pub(crate) fn clone_line_program<R>( unit: &Unit<R, R::Offset>, root: &DebuggingInformationEntry<R>, addr_tr: &AddressTransform, out_encoding: gimli::Encoding, debug_str: &DebugStr<R>, debug_str_offsets: &DebugStrOffsets<R>, debug_line_str: &DebugLineStr<R>, debug_line: &DebugLine<R>, out_strings: &mut write::StringTable, ) -> Result<(write::LineProgram, DebugLineOffset, Vec<write::FileId>, u64), Error> where R: Reader, { let offset = match root.attr_value(gimli::DW_AT_stmt_list)? { Some(gimli::AttributeValue::DebugLineRef(offset)) => offset, _ => { return Err(TransformError("Debug line offset is not found").into()); } }; let comp_dir = root.attr_value(gimli::DW_AT_comp_dir)?; let comp_name = root.attr_value(gimli::DW_AT_name)?; let out_comp_dir = clone_attr_string( comp_dir.as_ref().context("comp_dir")?, gimli::DW_FORM_strp, unit, debug_str, debug_str_offsets, debug_line_str, out_strings, )?; let out_comp_name = clone_attr_string( comp_name.as_ref().context("comp_name")?, gimli::DW_FORM_strp, unit, debug_str, debug_str_offsets, debug_line_str, out_strings, )?; let program = debug_line.program( offset, unit.header.address_size(), comp_dir.and_then(|val| val.string_value(&debug_str)), comp_name.and_then(|val| val.string_value(&debug_str)), ); if let Ok(program) = program { let header = program.header(); let file_index_base = if header.version() < 5 { 1 } else { 0 }; assert_le!(header.version(), 5, "not supported 6"); let line_encoding = LineEncoding { minimum_instruction_length: header.minimum_instruction_length(), maximum_operations_per_instruction: header.maximum_operations_per_instruction(), default_is_stmt: header.default_is_stmt(), line_base: header.line_base(), line_range: header.line_range(), }; let mut out_program = write::LineProgram::new( out_encoding, line_encoding, out_comp_dir, out_comp_name, None, ); let mut dirs = Vec::new(); dirs.push(out_program.default_directory()); for dir_attr in header.include_directories() { let dir_id = out_program.add_directory(clone_attr_string( dir_attr, gimli::DW_FORM_string, unit, debug_str, debug_str_offsets, debug_line_str, out_strings, )?); dirs.push(dir_id); } let mut files = Vec::new(); // Since we are outputting DWARF-4, perform base change. let directory_index_correction = if header.version() >= 5 { 1 } else { 0 }; for file_entry in header.file_names() { let dir_index = file_entry.directory_index() + directory_index_correction; let dir_id = dirs[dir_index as usize]; let file_id = out_program.add_file( clone_attr_string( &file_entry.path_name(), gimli::DW_FORM_string, unit, debug_str, debug_str_offsets, debug_line_str, out_strings, )?, dir_id, None, ); files.push(file_id); } let mut rows = program.rows(); let mut func_rows = Vec::new(); let mut saved_rows: Vec<(u64, SavedLineProgramRow)> = Vec::new(); let mut state = ReadLineProgramState::SequenceEnded; while let Some((_header, row)) = rows.next_row()? { if state == ReadLineProgramState::IgnoreSequence { if row.end_sequence() { state = ReadLineProgramState::SequenceEnded; } continue; } let saved_row = if row.end_sequence() { let index = match state { ReadLineProgramState::ReadSequence(index) => index, _ => panic!(), }; saved_rows.sort_by_key(|r| r.0); func_rows.push(FuncRows { index, sorted_rows: saved_rows, }); saved_rows = Vec::new(); state = ReadLineProgramState::SequenceEnded; SavedLineProgramRow::EndOfSequence(row.address()) } else { if state == ReadLineProgramState::SequenceEnded { // Discard sequences for non-existent code. if row.address() == 0 { state = ReadLineProgramState::IgnoreSequence; continue; } match addr_tr.find_func_index(row.address()) { Some(index) => { state = ReadLineProgramState::ReadSequence(index); } None => { // Some non-existent address found. state = ReadLineProgramState::IgnoreSequence; continue; } } } SavedLineProgramRow::Normal { address: row.address(), op_index: row.op_index(), file_index: row.file_index(), line: row.line().map(|nonzero| nonzero.get()).unwrap_or(0), column: match row.column() { gimli::ColumnType::LeftEdge => 0, gimli::ColumnType::Column(val) => val.get(), }, discriminator: row.discriminator(), is_stmt: row.is_stmt(), basic_block: row.basic_block(), prologue_end: row.prologue_end(), epilogue_begin: row.epilogue_begin(), isa: row.isa(), } }; saved_rows.push((row.address(), saved_row)); } for FuncRows { index, sorted_rows: saved_rows, } in func_rows { let map = match addr_tr.map().get(index) { Some(map) if map.len > 0 => map, _ => { continue; // no code generated } }; let symbol = index.index(); let base_addr = map.offset; out_program.begin_sequence(Some(write::Address::Symbol { symbol, addend: 0 })); // TODO track and place function declaration line here let mut last_address = None; for addr_map in map.addresses.iter() { let saved_row = match saved_rows.binary_search_by_key(&addr_map.wasm, |i| i.0) { Ok(i) => Some(&saved_rows[i].1), Err(i) => { if i > 0 { Some(&saved_rows[i - 1].1) } else { None } } }; if let Some(SavedLineProgramRow::Normal { address, op_index, file_index, line, column, discriminator, is_stmt, basic_block, prologue_end, epilogue_begin, isa, }) = saved_row { // Ignore duplicates if Some(*address) != last_address { let address_offset = if last_address.is_none() { // Extend first entry to the function declaration // TODO use the function declaration line instead 0 } else { (addr_map.generated - base_addr) as u64 }; out_program.row().address_offset = address_offset; out_program.row().op_index = *op_index; out_program.row().file = files[(file_index - file_index_base) as usize]; out_program.row().line = *line; out_program.row().column = *column; out_program.row().discriminator = *discriminator; out_program.row().is_statement = *is_stmt; out_program.row().basic_block = *basic_block; out_program.row().prologue_end = *prologue_end; out_program.row().epilogue_begin = *epilogue_begin; out_program.row().isa = *isa; out_program.generate_row(); last_address = Some(*address); } } } let end_addr = (map.offset + map.len) as u64; out_program.end_sequence(end_addr); } Ok((out_program, offset, files, file_index_base)) } else { Err(TransformError("Valid line program not found").into()) } }
SavedLineProgramRow
product.js
//商品相关的api //引入封装好的axios /* 规定了 :get params post data */ import request from '@/utils/request.js'; //获取商品列表 export function fetchProductList(params) { return request({ url: "product_list", method: "get", params: params }) } //获取 商品分类列表 export function fetchProductCateList(params, parent_id) { return request({ url: "get_product_category_list/" + parent_id,//从 后台api里面查找 method: "get", params: params }) } //获取 商品类型列表 //http://www.yinruifang.cn/index/Api/get_product_attr export function fetchProductAttrList(params) { return request({ url: "get_product_attr", method: "get", params: params }) } //获取 品牌搜索数据 //3.接口名称:获取品牌列表 //http://www.yinruifang.cn/index/Api/get_product_brand export function fetchBrand(params) { return request({ url: "get_product_brand", method: "get", params: params }) } //获取 分类的有子节点的数据 //## 2.接口名称:获取商品分类的所有数据 ,有子节点 //http://www.yinruifang.cn/index/Api/get_product_category export function fetchCategory(params) { return request({ url: "get_product_category", method: "get", params: params }) } //添加商品的接口 // 6.接口名称:添加一条商品信息 //url地址:http://www.yinruifang.cn/index/Api/create_product export function createProduct(data) { return request({ url: "create_product", method: "post", data: data }) } //添加商品分类接口 //:http://www.yinruifang.cn/index/Api/create_product_cate export function createProductCate(data) { return request({ url: "create_product_cate", method: "post", data: data }) } //修改商品信息 //http://www.yinruifang.cn/index/Api/update_product
return request({ url: "update_product", method: "post", data: data }) } //通过id获取一条商品记录 //url 地址:http://www.yinruifang.cn/index/Api/product_one export function getProductOne(params) { return request({ url: "product_one", method: "get", params: params }) } //通过 id删除 商品数据 //http://www.yinruifang.cn/index/Api/delete_status export function delProduct(params) { return request({ url: "delete_status", method: "get", params: params }) } //修改商品类型 //http://www.yinruifang.cn/index/Api/update_product_attr export function undateProductAttr(data) { return request({ url: "update_product_attr", method: "post", data: data }) }
export function updateProduct(data) {
urls.py
from django.urls import path from django.conf.urls import url from project_first_app.views import * urlpatterns = [ path('',main,name='main'),
] #path(r'getowners/<int:ow_id>',detail,name='detail'),
path('createowner/',createowner,name='createowner'), path('login/',log_in,name='login'), path(r'<int:ho_id>',review,name='detail')
iapwrap.go
package main // This is an example of using go-iapclient for a purpose that is not usage by // a golang http.Client. It uses GetToken() to retrieve the token, then inserts // it into a curl commandline // Example usage: // go run iapwrap.go --client-id $CLIENT_ID -- -v -k https://$HOST import ( "context" "fmt" "log" "os" "os/exec" "syscall" "github.com/urbanairship/go-iapclient" "gopkg.in/alecthomas/kingpin.v2" ) var ( cid = kingpin.Flag("client-id", "OAuth Client ID").Required().String() args = kingpin.Arg("args", "remaining args").Strings() ) func main()
{ kingpin.Parse() iap, err := iapclient.NewIAP(*cid, nil) if err != nil { log.Fatalf("Failed to create new IAP object: %v", err) } token, err := iap.GetToken(context.Background()) if err != nil { log.Fatalf("Failed to get token: %v", err) } curl, err := exec.LookPath("curl") args := append([]string{"curl", "-H", fmt.Sprintf("Authorization: Bearer %s", token)}, *args...) env := os.Environ() if err := syscall.Exec(curl, args, env); err != nil { log.Fatal(err) } }
camt_053_001_01.gen.go
// Code generated by main. DO NOT EDIT. package camt_053_001_01 import ( "bytes" "encoding/xml" "time" ) type AccountIdentification3Choice struct { IBAN IBANIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 IBAN"` BBAN BBANIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BBAN"` UPIC UPICIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 UPIC"` PrtryAcct SimpleIdentificationInformation2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PrtryAcct"` } type AccountInterest1 struct { Tp InterestType1Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp,omitempty"` Rate []Rate1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Rate,omitempty"` FrToDt DateTimePeriodDetails `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FrToDt,omitempty"` Rsn Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Rsn,omitempty"` } type AccountStatement1 struct { Id Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id"` ElctrncSeqNb float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ElctrncSeqNb,omitempty"` LglSeqNb float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 LglSeqNb,omitempty"` CreDtTm ISODateTime `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CreDtTm"` FrToDt DateTimePeriodDetails `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FrToDt,omitempty"` CpyDplctInd CopyDuplicate1Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CpyDplctInd,omitempty"` Acct CashAccount13 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Acct"` RltdAcct CashAccount7 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RltdAcct,omitempty"` Intrst []AccountInterest1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Intrst,omitempty"` Bal []CashBalance2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Bal"` TxsSummry TotalTransactions1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TxsSummry,omitempty"` Ntry []StatementEntry1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Ntry,omitempty"` AddtlStmtInf Max500Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AddtlStmtInf,omitempty"` } // May be one of ADDR, PBOX, HOME, BIZZ, MLTO, DLVY type AddressType2Code string type AlternateSecurityIdentification2 struct { Tp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp"` Id Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id"` } type AmountAndCurrencyExchange2 struct { InstdAmt AmountAndCurrencyExchangeDetails1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 InstdAmt,omitempty"` TxAmt AmountAndCurrencyExchangeDetails1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TxAmt,omitempty"` CntrValAmt AmountAndCurrencyExchangeDetails1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CntrValAmt,omitempty"` AnncdPstngAmt AmountAndCurrencyExchangeDetails1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AnncdPstngAmt,omitempty"` PrtryAmt []AmountAndCurrencyExchangeDetails2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PrtryAmt,omitempty"` } type AmountAndCurrencyExchangeDetails1 struct { Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt"` CcyXchg CurrencyExchange3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CcyXchg,omitempty"` } type AmountAndCurrencyExchangeDetails2 struct { Tp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp"` Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt"` CcyXchg CurrencyExchange3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CcyXchg,omitempty"` } type AmountRangeBoundary1 struct { BdryAmt float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BdryAmt"` Incl bool `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Incl"` } // Must match the pattern [a-zA-Z0-9]{1,30} type BBANIdentifier string // Must match the pattern [A-Z]{6,6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3,3}){0,1} type BEIIdentifier string // Must match the pattern [A-Z]{6,6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3,3}){0,1} type BICIdentifier string type BalanceType2Choice struct { Cd BalanceType9Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` Prtry Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` } // May be one of OPBD, ITBD, CLBD, OPAV, ITAV, CLAV, FWAV, PRCD, IOPA, IITA, ICLA, IFWA, ICLB, IITB, IOPB, DOPA, DITA, DCLA, DFWA, DCLB, DITB, DOPB, COPA, CITA, CCLA, CFWA, CCLB, CITB, COPB type BalanceType9Code string type BankToCustomerStatementV01 struct { GrpHdr GroupHeader23 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 GrpHdr"` Stmt []AccountStatement1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Stmt"` } type BankTransactionCodeStructure1 struct { Domn BankTransactionCodeStructure2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Domn,omitempty"` Prtry ProprietaryBankTransactionCodeStructure1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry,omitempty"` } type BankTransactionCodeStructure2 struct { Cd ExternalBankTransactionDomainCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` Fmly BankTransactionCodeStructure3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Fmly"` } type BankTransactionCodeStructure3 struct { Cd ExternalBankTransactionFamilyCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` SubFmlyCd ExternalBankTransactionSubFamilyCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 SubFmlyCd"` } type BatchInformation1 struct { MsgId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 MsgId,omitempty"` PmtInfId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PmtInfId,omitempty"` NbOfTxs Max15NumericText `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 NbOfTxs,omitempty"` } type BranchAndFinancialInstitutionIdentification3 struct { FinInstnId FinancialInstitutionIdentification5Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FinInstnId"` BrnchId BranchData `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BrnchId,omitempty"` } type BranchData struct { Id Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id,omitempty"` Nm Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Nm,omitempty"` PstlAdr PostalAddress1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PstlAdr,omitempty"` } // Must match the pattern CH[0-9]{6,6} type CHIPSUniversalIdentifier string type CashAccount13 struct { Id AccountIdentification3Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id"` Tp CashAccountType2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp,omitempty"` Ccy CurrencyCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Ccy,omitempty"` Nm Max70Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Nm,omitempty"` Ownr PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Ownr,omitempty"` Svcr BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Svcr,omitempty"` } type CashAccount7 struct { Id AccountIdentification3Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id"` Tp CashAccountType2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp,omitempty"` Ccy CurrencyCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Ccy,omitempty"` Nm Max70Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Nm,omitempty"` } type CashAccountType2 struct { Cd CashAccountType4Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` Prtry Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` } // May be one of CASH, CHAR, COMM, TAXE, CISH, TRAS, SACC, CACC, SVGS, ONDP, MGLD, NREX, MOMA, LOAN, SLRY, ODFT type CashAccountType4Code string type CashBalance2 struct { Tp BalanceType2Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp"` CdtLine CreditLine1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtLine,omitempty"` Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt"` CdtDbtInd CreditDebitCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtDbtInd"` Dt DateAndDateTimeChoice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Dt"` Avlbty []CashBalanceAvailability1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Avlbty,omitempty"` } type CashBalanceAvailability1 struct { Dt CashBalanceAvailabilityDate1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Dt"` Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt"` CdtDbtInd CreditDebitCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtDbtInd"` } type CashBalanceAvailabilityDate1 struct { NbOfDays Max15PlusSignedNumericText `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 NbOfDays"` ActlDt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ActlDt"` } // May be one of DEBT, CRED, SHAR, SLEV type ChargeBearerType1Code string // May be one of BRKF, COMM type ChargeType1Code string type ChargeTypeChoice struct { Cd ChargeType1Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` PrtryCd Max4AlphaNumericText `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PrtryCd"` } type ChargesInformation3 struct { TtlChrgsAndTaxAmt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TtlChrgsAndTaxAmt,omitempty"` Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt"` Tp ChargeTypeChoice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp,omitempty"` Rate float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Rate,omitempty"` Br ChargeBearerType1Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Br,omitempty"` Pty BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Pty,omitempty"` Tax TaxCharges1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tax,omitempty"` } type ClearingSystemMemberIdentification3Choice struct { Id ExternalClearingSystemMemberCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id"` Prtry Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` } // May be one of CODU, COPY, DUPL type CopyDuplicate1Code string type CorporateAction1 struct { Cd Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd,omitempty"` Nb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Nb,omitempty"` Prtry Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry,omitempty"` } // Must match the pattern [A-Z]{2,2} type CountryCode string // May be one of CRDT, DBIT type CreditDebitCode string type CreditLine1 struct { Incl bool `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Incl"` Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt,omitempty"` } type CreditorReferenceInformation1 struct { CdtrRefTp CreditorReferenceType1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtrRefTp,omitempty"` CdtrRef Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtrRef,omitempty"` } type CreditorReferenceType1 struct { Cd DocumentType3Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` Prtry Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` Issr Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Issr,omitempty"` } type CurrencyAndAmount struct { Value float64 `xml:",chardata"` Ccy CurrencyCode `xml:"Ccy,attr"` } type CurrencyAndAmountRange struct { Amt ImpliedCurrencyAmountRangeChoice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt"` CdtDbtInd CreditDebitCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtDbtInd,omitempty"` Ccy CurrencyCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Ccy"` } // Must match the pattern [A-Z]{3,3} type CurrencyCode string type CurrencyExchange3 struct { SrcCcy CurrencyCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 SrcCcy"` TrgtCcy CurrencyCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TrgtCcy,omitempty"` UnitCcy CurrencyCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 UnitCcy,omitempty"` XchgRate float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 XchgRate"` CtrctId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CtrctId,omitempty"` QtnDt ISODateTime `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 QtnDt,omitempty"` } type DateAndDateTimeChoice struct { Dt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Dt"` DtTm ISODateTime `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DtTm"` } type DateAndPlaceOfBirth struct { BirthDt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BirthDt"` PrvcOfBirth Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PrvcOfBirth,omitempty"` CityOfBirth Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CityOfBirth"` CtryOfBirth CountryCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CtryOfBirth"` } type DateTimePeriodDetails struct { FrDtTm ISODateTime `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FrDtTm"` ToDtTm ISODateTime `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ToDtTm"` } type Document struct { BkToCstmrStmtV01 BankToCustomerStatementV01 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BkToCstmrStmtV01"` } // May be one of MSIN, CNFA, DNFA, CINV, CREN, DEBN, HIRI, SBIN, CMCN, SOAC, DISP type DocumentType2Code string // May be one of RADM, RPIN, FXDR, DISP, PUOR, SCOR type DocumentType3Code string // Must match the pattern [0-9]{9,9} type DunsIdentifier string // Must match the pattern [0-9]{13,13} type EANGLNIdentifier string // May be one of BOOK type EntryStatus3Code string type EntryTransaction1 struct { Refs TransactionReferences1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Refs,omitempty"` AmtDtls AmountAndCurrencyExchange2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AmtDtls,omitempty"` Avlbty []CashBalanceAvailability1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Avlbty,omitempty"` BkTxCd BankTransactionCodeStructure1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BkTxCd,omitempty"` Chrgs []ChargesInformation3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Chrgs,omitempty"` Intrst []TransactionInterest1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Intrst,omitempty"` RltdPties TransactionParty1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RltdPties,omitempty"` RltdAgts TransactionAgents1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RltdAgts,omitempty"` Purp Purpose1Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Purp,omitempty"` RltdRmtInf []RemittanceLocation1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RltdRmtInf,omitempty"` RmtInf RemittanceInformation1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RmtInf,omitempty"` RltdDts TransactionDates1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RltdDts,omitempty"` RltdPric TransactionPrice1Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RltdPric,omitempty"` RltdQties []TransactionQuantities1Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RltdQties,omitempty"` FinInstrmId SecurityIdentification4Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FinInstrmId,omitempty"` Tax TaxInformation2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tax,omitempty"` RtrInf ReturnReasonInformation5 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RtrInf,omitempty"` CorpActn CorporateAction1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CorpActn,omitempty"` SfkpgAcct CashAccount7 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 SfkpgAcct,omitempty"` AddtlTxInf Max500Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AddtlTxInf,omitempty"` } // Must be at least 1 items long type ExternalBankTransactionDomainCode string // Must be at least 1 items long type ExternalBankTransactionFamilyCode string // Must be at least 1 items long type ExternalBankTransactionSubFamilyCode string // Must be at least 1 items long type ExternalClearingSystemMemberCode string // Must be at least 1 items long type ExternalPurposeCode string type FinancialInstitutionIdentification3 struct { BIC BICIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BIC,omitempty"` ClrSysMmbId ClearingSystemMemberIdentification3Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ClrSysMmbId,omitempty"` Nm Max70Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Nm,omitempty"` PstlAdr PostalAddress1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PstlAdr,omitempty"` PrtryId GenericIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PrtryId,omitempty"` } type FinancialInstitutionIdentification5Choice struct { BIC BICIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BIC"` ClrSysMmbId ClearingSystemMemberIdentification3Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ClrSysMmbId"` NmAndAdr NameAndAddress7 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 NmAndAdr"` PrtryId GenericIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PrtryId"` CmbndId FinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CmbndId"` } type FinancialInstrumentQuantityChoice struct { Unit float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Unit"` FaceAmt float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FaceAmt"` AmtsdVal float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AmtsdVal"` } type FromToAmountRange struct { FrAmt AmountRangeBoundary1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FrAmt"` ToAmt AmountRangeBoundary1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ToAmt"` } type GenericIdentification3 struct { Id Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id"` Issr Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Issr,omitempty"` } type GenericIdentification4 struct { Id Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id"` IdTp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 IdTp"` } type GroupHeader23 struct { MsgId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 MsgId"` CreDtTm ISODateTime `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CreDtTm"` MsgRcpt PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 MsgRcpt,omitempty"` MsgPgntn Pagination `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 MsgPgntn,omitempty"` AddtlInf Max500Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AddtlInf,omitempty"` } // Must match the pattern [a-zA-Z]{2,2}[0-9]{2,2}[a-zA-Z0-9]{1,30} type IBANIdentifier string // Must match the pattern [A-Z]{2,2}[B-DF-HJ-NP-TV-XZ0-9]{7,7}[0-9]{1,1} type IBEIIdentifier string // Must match the pattern [A-Z0-9]{12,12} type ISINIdentifier string type ISODate time.Time func (t *ISODate) UnmarshalText(text []byte) error { return (*xsdDate)(t).UnmarshalText(text) } func (t ISODate) MarshalText() ([]byte, error) { return xsdDate(t).MarshalText() } type ISODateTime time.Time func (t *ISODateTime) UnmarshalText(text []byte) error { return (*xsdDateTime)(t).UnmarshalText(text) } func (t ISODateTime) MarshalText() ([]byte, error) { return xsdDateTime(t).MarshalText() } type ImpliedCurrencyAmountRangeChoice struct { FrAmt AmountRangeBoundary1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FrAmt"` ToAmt AmountRangeBoundary1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ToAmt"` FrToAmt FromToAmountRange `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FrToAmt"` EQAmt float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 EQAmt"` NEQAmt float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 NEQAmt"` } type InterestType1Choice struct { Cd InterestType1Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` Prtry Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` } // May be one of INDY, OVRN type InterestType1Code string // Must be at least 1 items long type Max105Text string // Must be at least 1 items long type Max140Text string // Must match the pattern [0-9]{1,15} type Max15NumericText string // Must match the pattern [+]{0,1}[0-9]{1,15} type Max15PlusSignedNumericText string // Must be at least 1 items long type Max16Text string // Must be at least 1 items long type Max256Text string // Must be at least 1 items long type Max34Text string // Must be at least 1 items long type Max35Text string // Must match the pattern [a-zA-Z0-9]{1,4} type Max4AlphaNumericText string // Must be at least 1 items long type Max500Text string // Must match the pattern [0-9]{1,5} type Max5NumericText string // Must be at least 1 items long type Max70Text string type MessageIdentification2 struct { MsgNmId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 MsgNmId,omitempty"` MsgId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 MsgId,omitempty"` } type NameAndAddress3 struct { Nm Max70Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Nm"` Adr PostalAddress1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Adr"` } type NameAndAddress7 struct { Nm Max70Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Nm"` PstlAdr PostalAddress1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PstlAdr"` } type NumberAndSumOfTransactions1 struct { NbOfNtries Max15NumericText `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 NbOfNtries,omitempty"` Sum float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Sum,omitempty"` } type NumberAndSumOfTransactions2 struct { NbOfNtries Max15NumericText `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 NbOfNtries,omitempty"` Sum float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Sum,omitempty"` TtlNetNtryAmt float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TtlNetNtryAmt,omitempty"` CdtDbtInd CreditDebitCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtDbtInd,omitempty"` } type NumberAndSumOfTransactionsPerBankTransactionCode1 struct { NbOfNtries Max15NumericText `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 NbOfNtries,omitempty"` Sum float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Sum,omitempty"` TtlNetNtryAmt float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TtlNetNtryAmt,omitempty"` CdtDbtInd CreditDebitCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtDbtInd,omitempty"` BkTxCd BankTransactionCodeStructure1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BkTxCd"` Avlbty []CashBalanceAvailability1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Avlbty,omitempty"` } type OrganisationIdentification2 struct { BIC BICIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BIC,omitempty"` IBEI IBEIIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 IBEI,omitempty"` BEI BEIIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BEI,omitempty"` EANGLN EANGLNIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 EANGLN,omitempty"` USCHU CHIPSUniversalIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 USCHU,omitempty"` DUNS DunsIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DUNS,omitempty"` BkPtyId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BkPtyId,omitempty"` TaxIdNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TaxIdNb,omitempty"` PrtryId GenericIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PrtryId,omitempty"` } type Pagination struct { PgNb Max5NumericText `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PgNb"` LastPgInd bool `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 LastPgInd"` } type Party2Choice struct { OrgId OrganisationIdentification2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 OrgId"` PrvtId []PersonIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PrvtId"` } type PartyIdentification8 struct { Nm Max70Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Nm,omitempty"` PstlAdr PostalAddress1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PstlAdr,omitempty"` Id Party2Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id,omitempty"` CtryOfRes CountryCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CtryOfRes,omitempty"` } type PersonIdentification3 struct { DrvrsLicNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DrvrsLicNb"` CstmrNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CstmrNb"` SclSctyNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 SclSctyNb"` AlnRegnNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AlnRegnNb"` PsptNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PsptNb"` TaxIdNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TaxIdNb"` IdntyCardNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 IdntyCardNb"` MplyrIdNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 MplyrIdNb"` DtAndPlcOfBirth DateAndPlaceOfBirth `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DtAndPlcOfBirth"` OthrId GenericIdentification4 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 OthrId"` Issr Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Issr,omitempty"` } type PostalAddress1 struct { AdrTp AddressType2Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AdrTp,omitempty"` AdrLine []Max70Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AdrLine,omitempty"` StrtNm Max70Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 StrtNm,omitempty"` BldgNb Max16Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BldgNb,omitempty"` PstCd Max16Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PstCd,omitempty"` TwnNm Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TwnNm,omitempty"` CtrySubDvsn Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CtrySubDvsn,omitempty"` Ctry CountryCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Ctry"` } type ProprietaryAgent1 struct { Tp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp"` Agt BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Agt"` } type ProprietaryBankTransactionCodeStructure1 struct { Cd Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` Issr Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Issr,omitempty"` } type ProprietaryDate1 struct { Tp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp"` Dt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Dt"` DtTm ISODateTime `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DtTm"` } type ProprietaryParty1 struct { Tp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp"` Pty PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Pty"` } type ProprietaryPrice1 struct { Tp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp"` Pric CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Pric"` } type ProprietaryQuantity1 struct { Tp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp"` Qty Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Qty"` } type ProprietaryReference1 struct { Tp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp"` Ref Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Ref"` } type Purpose1Choice struct { Cd ExternalPurposeCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` Prtry Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` } type Rate1 struct { Rate RateTypeChoice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Rate"` VldtyRg CurrencyAndAmountRange `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 VldtyRg,omitempty"` } type RateTypeChoice struct { PctgRate float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 PctgRate"` TxtlRate Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TxtlRate"` } type ReferredDocumentAmount1Choice struct { DuePyblAmt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DuePyblAmt"` DscntApldAmt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DscntApldAmt"` RmtdAmt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RmtdAmt"` CdtNoteAmt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtNoteAmt"` TaxAmt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TaxAmt"` } type ReferredDocumentInformation1 struct { RfrdDocTp ReferredDocumentType1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RfrdDocTp,omitempty"` RfrdDocNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RfrdDocNb,omitempty"` } type ReferredDocumentType1 struct { Cd DocumentType2Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` Prtry Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` Issr Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Issr,omitempty"` } type RemittanceInformation1 struct { Ustrd []Max140Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Ustrd,omitempty"` Strd []StructuredRemittanceInformation6 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Strd,omitempty"` } type RemittanceLocation1 struct { RmtId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RmtId,omitempty"` RmtLctnMtd RemittanceLocationMethod1Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RmtLctnMtd,omitempty"` RmtLctnElctrncAdr Max256Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RmtLctnElctrncAdr,omitempty"` RmtLctnPstlAdr NameAndAddress3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RmtLctnPstlAdr,omitempty"` } // May be one of FAXI, EDIC, URID, EMAL, POST type RemittanceLocationMethod1Code string type ReturnReason1Choice struct { Cd TransactionRejectReason2Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cd"` Prtry Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` } type ReturnReasonInformation5 struct { OrgnlBkTxCd BankTransactionCodeStructure1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 OrgnlBkTxCd,omitempty"` RtrOrgtr PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RtrOrgtr,omitempty"` RtrRsn ReturnReason1Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RtrRsn,omitempty"` AddtlRtrRsnInf []Max105Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AddtlRtrRsnInf,omitempty"` } type SecurityIdentification4Choice struct { ISIN ISINIdentifier `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ISIN"` Prtry AlternateSecurityIdentification2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` } type SimpleIdentificationInformation2 struct { Id Max34Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id"` } type StatementEntry1 struct { Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt"` CdtDbtInd CreditDebitCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtDbtInd"` RvslInd bool `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RvslInd,omitempty"` Sts EntryStatus3Code `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Sts"` BookgDt DateAndDateTimeChoice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BookgDt,omitempty"` ValDt DateAndDateTimeChoice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ValDt,omitempty"` AcctSvcrRef Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AcctSvcrRef,omitempty"` Avlbty []CashBalanceAvailability1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Avlbty,omitempty"` BkTxCd BankTransactionCodeStructure1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 BkTxCd"` ComssnWvrInd bool `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ComssnWvrInd,omitempty"` AddtlInfInd MessageIdentification2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AddtlInfInd,omitempty"` Btch []BatchInformation1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Btch,omitempty"` AmtDtls AmountAndCurrencyExchange2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AmtDtls,omitempty"` Chrgs []ChargesInformation3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Chrgs,omitempty"` Intrst []TransactionInterest1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Intrst,omitempty"` TxDtls []EntryTransaction1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TxDtls,omitempty"` AddtlNtryInf Max500Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AddtlNtryInf,omitempty"` } type StructuredRemittanceInformation6 struct { RfrdDocInf ReferredDocumentInformation1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RfrdDocInf,omitempty"` RfrdDocRltdDt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RfrdDocRltdDt,omitempty"` RfrdDocAmt []ReferredDocumentAmount1Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RfrdDocAmt,omitempty"` CdtrRefInf CreditorReferenceInformation1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtrRefInf,omitempty"` Invcr PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Invcr,omitempty"` Invcee PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Invcee,omitempty"` AddtlRmtInf Max140Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AddtlRmtInf,omitempty"` } type TaxCharges1 struct { Id Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Id,omitempty"` Rate float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Rate,omitempty"` Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt,omitempty"` } type TaxDetails struct { CertId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CertId,omitempty"` TaxTp TaxType `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TaxTp,omitempty"` } type TaxInformation2 struct { CdtrTaxId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtrTaxId,omitempty"` CdtrTaxTp Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtrTaxTp,omitempty"` DbtrTaxId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DbtrTaxId,omitempty"` TaxRefNb Max140Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TaxRefNb,omitempty"` TtlTaxblBaseAmt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TtlTaxblBaseAmt,omitempty"` TtlTaxAmt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TtlTaxAmt,omitempty"` TaxDt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TaxDt,omitempty"` TaxTpInf []TaxDetails `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TaxTpInf,omitempty"` } type TaxType struct { CtgyDesc Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CtgyDesc,omitempty"` Rate float64 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Rate,omitempty"` TaxblBaseAmt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TaxblBaseAmt,omitempty"` Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt,omitempty"` } type TotalTransactions1 struct { TtlNtries NumberAndSumOfTransactions2 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TtlNtries,omitempty"` TtlCdtNtries NumberAndSumOfTransactions1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TtlCdtNtries,omitempty"` TtlDbtNtries NumberAndSumOfTransactions1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TtlDbtNtries,omitempty"` TtlNtriesPerBkTxCd []NumberAndSumOfTransactionsPerBankTransactionCode1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TtlNtriesPerBkTxCd,omitempty"` } type TransactionAgents1 struct { DbtrAgt BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DbtrAgt,omitempty"` CdtrAgt BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtrAgt,omitempty"` IntrmyAgt1 BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 IntrmyAgt1,omitempty"` IntrmyAgt2 BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 IntrmyAgt2,omitempty"` IntrmyAgt3 BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 IntrmyAgt3,omitempty"` RcvgAgt BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 RcvgAgt,omitempty"` DlvrgAgt BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DlvrgAgt,omitempty"` IssgAgt BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 IssgAgt,omitempty"` SttlmPlc BranchAndFinancialInstitutionIdentification3 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 SttlmPlc,omitempty"` Prtry []ProprietaryAgent1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry,omitempty"` } type TransactionDates1 struct { AccptncDtTm ISODateTime `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AccptncDtTm,omitempty"` TradDt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TradDt,omitempty"` IntrBkSttlmDt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 IntrBkSttlmDt,omitempty"` StartDt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 StartDt,omitempty"` EndDt ISODate `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 EndDt,omitempty"` TxDtTm ISODateTime `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TxDtTm,omitempty"` Prtry []ProprietaryDate1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry,omitempty"` } type TransactionInterest1 struct { Amt CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Amt"` CdtDbtInd CreditDebitCode `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtDbtInd"` Tp InterestType1Choice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Tp,omitempty"` Rate []Rate1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Rate,omitempty"` FrToDt DateTimePeriodDetails `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 FrToDt,omitempty"` Rsn Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Rsn,omitempty"` } type TransactionParty1 struct { InitgPty PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 InitgPty,omitempty"` Dbtr PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Dbtr,omitempty"` DbtrAcct CashAccount7 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DbtrAcct,omitempty"` UltmtDbtr PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 UltmtDbtr,omitempty"` Cdtr PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Cdtr,omitempty"` CdtrAcct CashAccount7 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 CdtrAcct,omitempty"` UltmtCdtr PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 UltmtCdtr,omitempty"` TradgPty PartyIdentification8 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TradgPty,omitempty"` Prtry []ProprietaryParty1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry,omitempty"` } type TransactionPrice1Choice struct { DealPric CurrencyAndAmount `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 DealPric"` Prtry []ProprietaryPrice1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` } type TransactionQuantities1Choice struct { Qty FinancialInstrumentQuantityChoice `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Qty"` Prtry ProprietaryQuantity1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry"` } type TransactionReferences1 struct { MsgId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 MsgId,omitempty"` AcctSvcrRef Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 AcctSvcrRef,omitempty"` InstrId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 InstrId,omitempty"` EndToEndId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 EndToEndId,omitempty"` TxId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 TxId,omitempty"` MndtId Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 MndtId,omitempty"` ChqNb Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ChqNb,omitempty"` ClrSysRef Max35Text `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 ClrSysRef,omitempty"` Prtry ProprietaryReference1 `xml:"urn:iso:std:iso:20022:tech:xsd:camt.053.001.01 Prtry,omitempty"` } // May be one of AC01, AC04, AC06, AM01, AM02, AM03, AM04, AM05, AM06, AM07, BE01, BE04, BE05, AG01, AG02, DT01, RF01, RC01, TM01, ED01, ED03, MS03, MS02, BE06, BE07, AM09, AM10, MD01, MD02, MD03, MD04, MD06, MD07, ED05, NARR type TransactionRejectReason2Code string // Must match the pattern [0-9]{8,17} type UPICIdentifier string type xsdDate time.Time func (t *xsdDate) UnmarshalText(text []byte) error { return _unmarshalTime(text, (*time.Time)(t), "2006-01-02") } func (t xsdDate) MarshalText() ([]byte, error) { return _marshalTime((time.Time)(t), "2006-01-02") } func (t xsdDate) MarshalXML(e *xml.Encoder, start xml.StartElement) error { if (time.Time)(t).IsZero() { return nil } m, err := t.MarshalText() if err != nil { return err } return e.EncodeElement(m, start) } func (t xsdDate) MarshalXMLAttr(name xml.Name) (xml.Attr, error) { if (time.Time)(t).IsZero() { return xml.Attr{}, nil } m, err := t.MarshalText() return xml.Attr{Name: name, Value: string(m)}, err } func
(text []byte, t *time.Time, format string) (err error) { s := string(bytes.TrimSpace(text)) *t, err = time.Parse(format, s) if _, ok := err.(*time.ParseError); ok { *t, err = time.Parse(format+"Z07:00", s) } return err } func _marshalTime(t time.Time, format string) ([]byte, error) { return []byte(t.Format(format + "Z07:00")), nil } type xsdDateTime time.Time func (t *xsdDateTime) UnmarshalText(text []byte) error { return _unmarshalTime(text, (*time.Time)(t), "2006-01-02T15:04:05.999999999") } func (t xsdDateTime) MarshalText() ([]byte, error) { return _marshalTime((time.Time)(t), "2006-01-02T15:04:05.999999999") } func (t xsdDateTime) MarshalXML(e *xml.Encoder, start xml.StartElement) error { if (time.Time)(t).IsZero() { return nil } m, err := t.MarshalText() if err != nil { return err } return e.EncodeElement(m, start) } func (t xsdDateTime) MarshalXMLAttr(name xml.Name) (xml.Attr, error) { if (time.Time)(t).IsZero() { return xml.Attr{}, nil } m, err := t.MarshalText() return xml.Attr{Name: name, Value: string(m)}, err }
_unmarshalTime
lib.rs
#![allow(clippy::type_complexity)] #![cfg_attr(feature = "no_std", no_std)] #[cfg(feature = "no_std")] extern crate alloc; pub mod iter; pub mod iter_set; pub mod mapref; mod read_only; #[cfg(feature = "serde")] mod serde; mod set; pub mod setref; mod t; pub mod try_result; mod util; #[cfg(feature = "rayon")] pub mod rayon { pub mod map; pub mod set; } use alloc::boxed::Box; use alloc::vec::Vec; use cfg_if::cfg_if; use core::borrow::Borrow; use core::fmt; use core::hash::{BuildHasher, Hash, Hasher}; use core::iter::FromIterator; use core::ops::{BitAnd, BitOr, Shl, Shr, Sub}; use iter::{Iter, IterMut, OwningIter}; use mapref::entry::{Entry, OccupiedEntry, VacantEntry}; use mapref::multiple::RefMulti; use mapref::one::{Ref, RefMut}; use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard}; pub use read_only::ReadOnlyView; pub use set::DashSet; #[cfg(feature = "no_std")] use ahash::RandomState; #[cfg(not(feature = "no_std"))] use std::collections::hash_map::RandomState; pub use t::Map; use try_result::TryResult; cfg_if! { if #[cfg(feature = "raw-api")] { pub use util::SharedValue; } else { use util::SharedValue; } } #[cfg(not(feature = "no_std"))] pub(crate) type HashMap<K, V, S> = std::collections::HashMap<K, SharedValue<V>, S>; #[cfg(feature = "no_std")] pub(crate) type HashMap<K, V, S> = hashbrown::HashMap<K, SharedValue<V>, S>; fn shard_amount() -> usize { (num_cpus::get() * 4).next_power_of_two() } fn ncb(shard_amount: usize) -> usize { shard_amount.trailing_zeros() as usize } /// DashMap is an implementation of a concurrent associative array/hashmap in Rust. /// /// DashMap tries to implement an easy to use API similar to `std::collections::HashMap` /// with some slight changes to handle concurrency. /// /// DashMap tries to be very simple to use and to be a direct replacement for `RwLock<HashMap<K, V, S>>`. /// To accomplish these all methods take `&self` instead modifying methods taking `&mut self`. /// This allows you to put a DashMap in an `Arc<T>` and share it between threads while being able to modify it. /// /// Documentation mentioning locking behaviour acts in the reference frame of the calling thread. /// This means that it is safe to ignore it across multiple threads. pub struct DashMap<K, V, S = RandomState> { shift: usize, shards: Box<[RwLock<HashMap<K, V, S>>]>, hasher: S, } impl<K: Eq + Hash + Clone, V: Clone, S: Clone> Clone for DashMap<K, V, S> { fn clone(&self) -> Self { let mut inner_shards = Vec::new(); for shard in self.shards.iter() { let shard = shard.read(); inner_shards.push(RwLock::new((*shard).clone())); } Self { shift: self.shift, shards: inner_shards.into_boxed_slice(), hasher: self.hasher.clone(), } } } impl<K, V, S> Default for DashMap<K, V, S> where K: Eq + Hash, S: Default + BuildHasher + Clone, { fn default() -> Self { Self::with_hasher(Default::default()) } } impl<'a, K: 'a + Eq + Hash, V: 'a> DashMap<K, V, RandomState> { /// Creates a new DashMap with a capacity of 0. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let reviews = DashMap::new(); /// reviews.insert("Veloren", "What a fantastic game!"); /// ``` pub fn new() -> Self { DashMap::with_hasher(RandomState::default()) } /// Creates a new DashMap with a specified starting capacity. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let mappings = DashMap::with_capacity(2); /// mappings.insert(2, 4); /// mappings.insert(8, 16); /// ``` pub fn with_capacity(capacity: usize) -> Self { DashMap::with_capacity_and_hasher(capacity, RandomState::default()) } } impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone> DashMap<K, V, S> { /// Wraps this `DashMap` into a read-only view. This view allows to obtain raw references to the stored values. pub fn into_read_only(self) -> ReadOnlyView<K, V, S> { ReadOnlyView::new(self) } /// Creates a new DashMap with a capacity of 0 and the provided hasher. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// use std::collections::hash_map::RandomState; /// /// let s = RandomState::new(); /// let reviews = DashMap::with_hasher(s); /// reviews.insert("Veloren", "What a fantastic game!"); /// ``` pub fn with_hasher(hasher: S) -> Self { Self::with_capacity_and_hasher(0, hasher) } /// Creates a new DashMap with a specified starting capacity and hasher. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// use std::collections::hash_map::RandomState; /// /// let s = RandomState::new(); /// let mappings = DashMap::with_capacity_and_hasher(2, s); /// mappings.insert(2, 4); /// mappings.insert(8, 16); /// ``` pub fn with_capacity_and_hasher(mut capacity: usize, hasher: S) -> Self { let shard_amount = shard_amount(); let shift = util::ptr_size_bits() - ncb(shard_amount); if capacity != 0 { capacity = (capacity + (shard_amount - 1)) & !(shard_amount - 1); } let cps = capacity / shard_amount; let shards = (0..shard_amount) .map(|_| RwLock::new(HashMap::with_capacity_and_hasher(cps, hasher.clone()))) .collect(); Self { shift, shards, hasher, } } /// Hash a given item to produce a usize. /// Uses the provided or default HashBuilder. pub fn hash_usize<T: Hash>(&self, item: &T) -> usize { let mut hasher = self.hasher.build_hasher(); item.hash(&mut hasher); hasher.finish() as usize } cfg_if! { if #[cfg(feature = "raw-api")] { /// Allows you to peek at the inner shards that store your data. /// You should probably not use this unless you know what you are doing. /// /// Requires the `raw-api` feature to be enabled. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let map = DashMap::<(), ()>::new(); /// println!("Amount of shards: {}", map.shards().len()); /// ``` pub fn shards(&self) -> &[RwLock<HashMap<K, V, S>>] { &self.shards } } else { #[allow(dead_code)] pub(crate) fn shards(&self) -> &[RwLock<HashMap<K, V, S>>] { &self.shards } } } cfg_if! { if #[cfg(feature = "raw-api")] { /// Finds which shard a certain key is stored in. /// You should probably not use this unless you know what you are doing. /// Note that shard selection is dependent on the default or provided HashBuilder. /// /// Requires the `raw-api` feature to be enabled. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let map = DashMap::new(); /// map.insert("coca-cola", 1.4); /// println!("coca-cola is stored in shard: {}", map.determine_map("coca-cola")); /// ``` pub fn determine_map<Q>(&self, key: &Q) -> usize where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { let hash = self.hash_usize(&key); self.determine_shard(hash) } } } cfg_if! { if #[cfg(feature = "raw-api")] { /// Finds which shard a certain hash is stored in. /// /// Requires the `raw-api` feature to be enabled. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let map: DashMap<i32, i32> = DashMap::new(); /// let key = "key"; /// let hash = map.hash_usize(&key); /// println!("hash is stored in shard: {}", map.determine_shard(hash)); /// ``` pub fn determine_shard(&self, hash: usize) -> usize { // Leave the high 7 bits for the HashBrown SIMD tag. (hash << 7) >> self.shift } } else { pub(crate) fn determine_shard(&self, hash: usize) -> usize { // Leave the high 7 bits for the HashBrown SIMD tag. (hash << 7) >> self.shift } } } /// Returns a reference to the map's [`BuildHasher`]. /// /// # Examples /// /// ```rust /// use dashmap::DashMap; /// use std::collections::hash_map::RandomState; /// /// let hasher = RandomState::new(); /// let map: DashMap<i32, i32> = DashMap::new(); /// let hasher: &RandomState = map.hasher(); /// ``` /// /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html pub fn hasher(&self) -> &S { &self.hasher } /// Inserts a key and a value into the map. Returns the old value associated with the key if there was one. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let map = DashMap::new(); /// map.insert("I am the key!", "And I am the value!"); /// ``` pub fn insert(&self, key: K, value: V) -> Option<V> { self._insert(key, value) } /// Removes an entry from the map, returning the key and value if they existed in the map. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let soccer_team = DashMap::new(); /// soccer_team.insert("Jack", "Goalie"); /// assert_eq!(soccer_team.remove("Jack").unwrap().1, "Goalie"); /// ``` pub fn remove<Q>(&self, key: &Q) -> Option<(K, V)> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._remove(key) } /// Removes an entry from the map, returning the key and value /// if the entry existed and the provided conditional function returned true. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// ``` /// use dashmap::DashMap; /// /// let soccer_team = DashMap::new(); /// soccer_team.insert("Sam", "Forward"); /// soccer_team.remove_if("Sam", |_, position| position == &"Goalie"); /// assert!(soccer_team.contains_key("Sam")); /// ``` /// ``` /// use dashmap::DashMap; /// /// let soccer_team = DashMap::new(); /// soccer_team.insert("Sam", "Forward"); /// soccer_team.remove_if("Sam", |_, position| position == &"Forward"); /// assert!(!soccer_team.contains_key("Sam")); /// ``` pub fn remove_if<Q>(&self, key: &Q, f: impl FnOnce(&K, &V) -> bool) -> Option<(K, V)> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._remove_if(key, f) } pub fn remove_if_mut<Q>(&self, key: &Q, f: impl FnOnce(&K, &mut V) -> bool) -> Option<(K, V)> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._remove_if_mut(key, f) } /// Creates an iterator over a DashMap yielding immutable references. /// /// **Locking behaviour:** May deadlock if called when holding a mutable reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let words = DashMap::new(); /// words.insert("hello", "world"); /// assert_eq!(words.iter().count(), 1); /// ``` pub fn iter(&'a self) -> Iter<'a, K, V, S, DashMap<K, V, S>> { self._iter() } /// Iterator over a DashMap yielding mutable references. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let map = DashMap::new(); /// map.insert("Johnny", 21); /// map.iter_mut().for_each(|mut r| *r += 1); /// assert_eq!(*map.get("Johnny").unwrap(), 22); /// ``` pub fn iter_mut(&'a self) -> IterMut<'a, K, V, S, DashMap<K, V, S>> { self._iter_mut() } /// Get a immutable reference to an entry in the map /// /// **Locking behaviour:** May deadlock if called when holding a mutable reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let youtubers = DashMap::new(); /// youtubers.insert("Bosnian Bill", 457000); /// assert_eq!(*youtubers.get("Bosnian Bill").unwrap(), 457000); /// ``` pub fn get<Q>(&'a self, key: &Q) -> Option<Ref<'a, K, V, S>> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._get(key) } /// Get a mutable reference to an entry in the map /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let class = DashMap::new(); /// class.insert("Albin", 15); /// *class.get_mut("Albin").unwrap() -= 1; /// assert_eq!(*class.get("Albin").unwrap(), 14); /// ``` pub fn get_mut<Q>(&'a self, key: &Q) -> Option<RefMut<'a, K, V, S>> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._get_mut(key) } /// Get an immutable reference to an entry in the map, if the shard is not locked. /// If the shard is locked, the function will return [TryResult::Locked]. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// use dashmap::try_result::TryResult; /// /// let map = DashMap::new(); /// map.insert("Johnny", 21); /// /// assert_eq!(*map.try_get("Johnny").unwrap(), 21); /// /// let _result1_locking = map.get_mut("Johnny"); /// /// let result2 = map.try_get("Johnny"); /// assert!(result2.is_locked()); /// ``` pub fn try_get<Q>(&'a self, key: &Q) -> TryResult<Ref<'a, K, V, S>> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._try_get(key) } /// Get a mutable reference to an entry in the map, if the shard is not locked. /// If the shard is locked, the function will return [TryResult::Locked]. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// use dashmap::try_result::TryResult; /// /// let map = DashMap::new(); /// map.insert("Johnny", 21); /// /// *map.try_get_mut("Johnny").unwrap() += 1; /// assert_eq!(*map.get("Johnny").unwrap(), 22); /// /// let _result1_locking = map.get("Johnny"); /// /// let result2 = map.try_get_mut("Johnny"); /// assert!(result2.is_locked()); /// ``` pub fn try_get_mut<Q>(&'a self, key: &Q) -> TryResult<RefMut<'a, K, V, S>> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._try_get_mut(key) } /// Remove excess capacity to reduce memory usage. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. pub fn shrink_to_fit(&self) { self._shrink_to_fit(); } /// Retain elements that whose predicates return true /// and discard elements whose predicates return false. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let people = DashMap::new(); /// people.insert("Albin", 15); /// people.insert("Jones", 22); /// people.insert("Charlie", 27); /// people.retain(|_, v| *v > 20); /// assert_eq!(people.len(), 2); /// ``` pub fn retain(&self, f: impl FnMut(&K, &mut V) -> bool) { self._retain(f); } /// Fetches the total number of key-value pairs stored in the map. /// /// **Locking behaviour:** May deadlock if called when holding a mutable reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let people = DashMap::new(); /// people.insert("Albin", 15); /// people.insert("Jones", 22); /// people.insert("Charlie", 27); /// assert_eq!(people.len(), 3); /// ``` pub fn len(&self) -> usize { self._len() } /// Checks if the map is empty or not. /// /// **Locking behaviour:** May deadlock if called when holding a mutable reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let map = DashMap::<(), ()>::new(); /// assert!(map.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self._is_empty() } /// Removes all key-value pairs in the map. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let stats = DashMap::new(); /// stats.insert("Goals", 4); /// assert!(!stats.is_empty()); /// stats.clear(); /// assert!(stats.is_empty()); /// ``` pub fn clear(&self) { self._clear(); } /// Returns how many key-value pairs the map can store without reallocating. /// /// **Locking behaviour:** May deadlock if called when holding a mutable reference into the map. pub fn capacity(&self) -> usize { self._capacity() } /// Modify a specific value according to a function. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let stats = DashMap::new(); /// stats.insert("Goals", 4); /// stats.alter("Goals", |_, v| v * 2); /// assert_eq!(*stats.get("Goals").unwrap(), 8); /// ``` /// /// # Panics /// /// If the given closure panics, then `alter` will abort the process pub fn alter<Q>(&self, key: &Q, f: impl FnOnce(&K, V) -> V) where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._alter(key, f); } /// Modify every value in the map according to a function. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let stats = DashMap::new(); /// stats.insert("Wins", 4); /// stats.insert("Losses", 2); /// stats.alter_all(|_, v| v + 1); /// assert_eq!(*stats.get("Wins").unwrap(), 5); /// assert_eq!(*stats.get("Losses").unwrap(), 3); /// ``` /// /// # Panics /// /// If the given closure panics, then `alter_all` will abort the process pub fn alter_all(&self, f: impl FnMut(&K, V) -> V) { self._alter_all(f); } /// Scoped access into an item of the map according to a function. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let warehouse = DashMap::new(); /// warehouse.insert(4267, ("Banana", 100)); /// warehouse.insert(2359, ("Pear", 120)); /// let fruit = warehouse.view(&4267, |_k, v| *v); /// assert_eq!(fruit, Some(("Banana", 100))); /// ``` /// /// # Panics /// /// If the given closure panics, then `view` will abort the process pub fn view<Q, R>(&self, key: &Q, f: impl FnOnce(&K, &V) -> R) -> Option<R> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._view(key, f) } /// Checks if the map contains a specific key. /// /// **Locking behaviour:** May deadlock if called when holding a mutable reference into the map. /// /// # Examples /// /// ``` /// use dashmap::DashMap; /// /// let team_sizes = DashMap::new(); /// team_sizes.insert("Dakota Cherries", 23); /// assert!(team_sizes.contains_key("Dakota Cherries")); /// ``` pub fn contains_key<Q>(&self, key: &Q) -> bool where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self._contains_key(key) } /// Advanced entry API that tries to mimic `std::collections::HashMap`. /// See the documentation on `dashmap::mapref::entry` for more details. /// /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. pub fn entry(&'a self, key: K) -> Entry<'a, K, V, S> { self._entry(key) } /// Advanced entry API that tries to mimic `std::collections::HashMap`. /// See the documentation on `dashmap::mapref::entry` for more details. /// /// Returns None if the shard is currently locked. pub fn try_entry(&'a self, key: K) -> Option<Entry<'a, K, V, S>> { self._try_entry(key) } } impl<'a, K: 'a + Eq + Hash, V: 'a, S: 'a + BuildHasher + Clone> Map<'a, K, V, S> for DashMap<K, V, S> { fn _shard_count(&self) -> usize { self.shards.len() } unsafe fn _get_read_shard(&'a self, i: usize) -> &'a HashMap<K, V, S> { debug_assert!(i < self.shards.len()); &*self.shards.get_unchecked(i).data_ptr() } unsafe fn _yield_read_shard(&'a self, i: usize) -> RwLockReadGuard<'a, HashMap<K, V, S>> { debug_assert!(i < self.shards.len()); self.shards.get_unchecked(i).read() } unsafe fn _yield_write_shard(&'a self, i: usize) -> RwLockWriteGuard<'a, HashMap<K, V, S>> { debug_assert!(i < self.shards.len()); self.shards.get_unchecked(i).write() } unsafe fn _try_yield_read_shard( &'a self, i: usize, ) -> Option<RwLockReadGuard<'a, HashMap<K, V, S>>> { debug_assert!(i < self.shards.len()); self.shards.get_unchecked(i).try_read() } unsafe fn _try_yield_write_shard( &'a self, i: usize, ) -> Option<RwLockWriteGuard<'a, HashMap<K, V, S>>> { debug_assert!(i < self.shards.len()); self.shards.get_unchecked(i).try_write() } fn _insert(&self, key: K, value: V) -> Option<V> { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let mut shard = unsafe { self._yield_write_shard(idx) }; shard .insert(key, SharedValue::new(value)) .map(|v| v.into_inner()) } fn _remove<Q>(&self, key: &Q) -> Option<(K, V)> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let mut shard = unsafe { self._yield_write_shard(idx) }; shard.remove_entry(key).map(|(k, v)| (k, v.into_inner())) } fn _remove_if<Q>(&self, key: &Q, f: impl FnOnce(&K, &V) -> bool) -> Option<(K, V)> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let mut shard = unsafe { self._yield_write_shard(idx) }; if let Some((k, v)) = shard.get_key_value(key) { if f(k, v.get()) { shard.remove_entry(key).map(|(k, v)| (k, v.into_inner())) } else { None } } else { None } } fn _remove_if_mut<Q>(&self, key: &Q, f: impl FnOnce(&K, &mut V) -> bool) -> Option<(K, V)> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let mut shard = unsafe { self._yield_write_shard(idx) }; if let Some((kptr, vptr)) = shard.get_key_value(&key) { unsafe { let kptr: *const K = kptr; let vptr: *mut V = vptr.as_ptr(); if f(&*kptr, &mut *vptr) { shard.remove_entry(key).map(|(k, v)| (k, v.into_inner())) } else { None } } } else { None } } fn _iter(&'a self) -> Iter<'a, K, V, S, DashMap<K, V, S>> { Iter::new(self) } fn _iter_mut(&'a self) -> IterMut<'a, K, V, S, DashMap<K, V, S>> { IterMut::new(self) } fn _get<Q>(&'a self, key: &Q) -> Option<Ref<'a, K, V, S>> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let shard = unsafe { self._yield_read_shard(idx) }; if let Some((kptr, vptr)) = shard.get_key_value(key) { unsafe { let kptr: *const K = kptr; let vptr: *const V = vptr.get(); Some(Ref::new(shard, kptr, vptr)) } } else { None } } fn _get_mut<Q>(&'a self, key: &Q) -> Option<RefMut<'a, K, V, S>> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let shard = unsafe { self._yield_write_shard(idx) }; if let Some((kptr, vptr)) = shard.get_key_value(key) { unsafe { let kptr: *const K = kptr; let vptr: *mut V = vptr.as_ptr(); Some(RefMut::new(shard, kptr, vptr)) } } else { None } } fn _try_get<Q>(&'a self, key: &Q) -> TryResult<Ref<'a, K, V, S>> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let shard = match unsafe { self._try_yield_read_shard(idx) } { Some(shard) => shard, None => return TryResult::Locked, }; if let Some((kptr, vptr)) = shard.get_key_value(key) { unsafe { let kptr: *const K = kptr; let vptr: *const V = vptr.get(); TryResult::Present(Ref::new(shard, kptr, vptr)) } } else { TryResult::Absent } } fn _try_get_mut<Q>(&'a self, key: &Q) -> TryResult<RefMut<'a, K, V, S>> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let shard = match unsafe { self._try_yield_write_shard(idx) } { Some(shard) => shard, None => return TryResult::Locked, }; if let Some((kptr, vptr)) = shard.get_key_value(key) { unsafe { let kptr: *const K = kptr; let vptr: *mut V = vptr.as_ptr(); TryResult::Present(RefMut::new(shard, kptr, vptr)) } } else { TryResult::Absent } } fn _shrink_to_fit(&self) { self.shards.iter().for_each(|s| s.write().shrink_to_fit()); } fn _retain(&self, mut f: impl FnMut(&K, &mut V) -> bool) { self.shards .iter() .for_each(|s| s.write().retain(|k, v| f(k, v.get_mut()))); } fn _len(&self) -> usize { self.shards.iter().map(|s| s.read().len()).sum() } fn _capacity(&self) -> usize { self.shards.iter().map(|s| s.read().capacity()).sum() } fn _alter<Q>(&self, key: &Q, f: impl FnOnce(&K, V) -> V) where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { if let Some(mut r) = self.get_mut(key) { util::map_in_place_2(r.pair_mut(), f); } } fn _alter_all(&self, mut f: impl FnMut(&K, V) -> V) { self.shards.iter().for_each(|s| { s.write() .iter_mut() .for_each(|(k, v)| util::map_in_place_2((k, v.get_mut()), &mut f)); }); } fn _view<Q, R>(&self, key: &Q, f: impl FnOnce(&K, &V) -> R) -> Option<R> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self.get(key).map(|r| { let (k, v) = r.pair(); f(k, v) }) } fn _entry(&'a self, key: K) -> Entry<'a, K, V, S> { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let shard = unsafe { self._yield_write_shard(idx) }; if let Some((kptr, vptr)) = shard.get_key_value(&key) { unsafe { let kptr: *const K = kptr; let vptr: *mut V = vptr.as_ptr(); Entry::Occupied(OccupiedEntry::new(shard, key, (kptr, vptr))) } } else { unsafe { Entry::Vacant(VacantEntry::new(shard, key)) } } } fn _try_entry(&'a self, key: K) -> Option<Entry<'a, K, V, S>> { let hash = self.hash_usize(&key); let idx = self.determine_shard(hash); let shard = match unsafe { self._try_yield_write_shard(idx) } { Some(shard) => shard, None => return None, }; if let Some((kptr, vptr)) = shard.get_key_value(&key) { unsafe { let kptr: *const K = kptr; let vptr: *mut V = vptr.as_ptr(); Some(Entry::Occupied(OccupiedEntry::new( shard, key, (kptr, vptr), ))) } } else { unsafe { Some(Entry::Vacant(VacantEntry::new(shard, key))) } } } fn _hasher(&self) -> S { self.hasher.clone() } } impl<K: Eq + Hash + fmt::Debug, V: fmt::Debug, S: BuildHasher + Clone> fmt::Debug for DashMap<K, V, S> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut pmap = f.debug_map(); for r in self { let (k, v) = r.pair(); pmap.entry(k, v); } pmap.finish() } } impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone> Shl<(K, V)> for &'a DashMap<K, V, S> { type Output = Option<V>; fn shl(self, pair: (K, V)) -> Self::Output { self.insert(pair.0, pair.1) } } impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone, Q> Shr<&Q> for &'a DashMap<K, V, S> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { type Output = Ref<'a, K, V, S>; fn shr(self, key: &Q) -> Self::Output { self.get(key).unwrap() } } impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone, Q> BitOr<&Q> for &'a DashMap<K, V, S> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { type Output = RefMut<'a, K, V, S>; fn bitor(self, key: &Q) -> Self::Output { self.get_mut(key).unwrap() } } impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone, Q> Sub<&Q> for &'a DashMap<K, V, S> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { type Output = Option<(K, V)>; fn sub(self, key: &Q) -> Self::Output { self.remove(key) } } impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone, Q> BitAnd<&Q> for &'a DashMap<K, V, S> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { type Output = bool; fn bitand(self, key: &Q) -> Self::Output { self.contains_key(key) } } impl<'a, K: Eq + Hash, V, S: BuildHasher + Clone> IntoIterator for DashMap<K, V, S> { type Item = (K, V); type IntoIter = OwningIter<K, V, S>; fn into_iter(self) -> Self::IntoIter { OwningIter::new(self) } } impl<'a, K: Eq + Hash, V, S: BuildHasher + Clone> IntoIterator for &'a DashMap<K, V, S> { type Item = RefMulti<'a, K, V, S>; type IntoIter = Iter<'a, K, V, S, DashMap<K, V, S>>; fn
(self) -> Self::IntoIter { self.iter() } } impl<K: Eq + Hash, V, S: BuildHasher + Clone> Extend<(K, V)> for DashMap<K, V, S> { fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, intoiter: I) { for pair in intoiter.into_iter() { self.insert(pair.0, pair.1); } } } impl<K: Eq + Hash, V, S: BuildHasher + Clone + Default> FromIterator<(K, V)> for DashMap<K, V, S> { fn from_iter<I: IntoIterator<Item = (K, V)>>(intoiter: I) -> Self { let mut map = DashMap::default(); map.extend(intoiter); map } } #[cfg(test)] mod tests { use crate::DashMap; use std::collections::hash_map::RandomState; #[test] fn test_basic() { let dm = DashMap::new(); dm.insert(0, 0); assert_eq!(dm.get(&0).unwrap().value(), &0); } #[test] fn test_default() { let dm: DashMap<u32, u32> = DashMap::default(); dm.insert(0, 0); assert_eq!(dm.get(&0).unwrap().value(), &0); } #[test] fn test_multiple_hashes() { let dm: DashMap<u32, u32> = DashMap::default(); for i in 0..100 { dm.insert(0, i); dm.insert(i, i); } for i in 1..100 { let r = dm.get(&i).unwrap(); assert_eq!(i, *r.value()); assert_eq!(i, *r.key()); } let r = dm.get(&0).unwrap(); assert_eq!(99, *r.value()); } #[test] fn test_more_complex_values() { #[derive(Hash, PartialEq, Debug, Clone)] struct T0 { s: String, u: u8, } let dm = DashMap::new(); let range = 0..10; for i in range { let t = T0 { s: i.to_string(), u: i as u8, }; dm.insert(i, t.clone()); assert_eq!(&t, dm.get(&i).unwrap().value()); } } #[test] fn test_different_hashers_randomstate() { let dm_hm_default: DashMap<u32, u32, RandomState> = DashMap::with_hasher(RandomState::new()); for i in 0..10 { dm_hm_default.insert(i, i); assert_eq!(i, *dm_hm_default.get(&i).unwrap().value()); } } #[test] fn test_map_view() { let dm = DashMap::new(); let vegetables: [String; 4] = [ "Salad".to_string(), "Beans".to_string(), "Potato".to_string(), "Tomato".to_string(), ]; // Give it some values dm.insert(0, "Banana".to_string()); dm.insert(4, "Pear".to_string()); dm.insert(9, "Potato".to_string()); dm.insert(12, "Chicken".to_string()); let potato_vegetableness = dm.view(&9, |_, v| vegetables.contains(v)); assert_eq!(potato_vegetableness, Some(true)); let chicken_vegetableness = dm.view(&12, |_, v| vegetables.contains(v)); assert_eq!(chicken_vegetableness, Some(false)); let not_in_map = dm.view(&30, |_k, _v| false); assert_eq!(not_in_map, None); } #[test] fn test_try_get() { { let map = DashMap::new(); map.insert("Johnny", 21); assert_eq!(*map.try_get("Johnny").unwrap(), 21); let _result1_locking = map.get_mut("Johnny"); let result2 = map.try_get("Johnny"); assert!(result2.is_locked()); } { let map = DashMap::new(); map.insert("Johnny", 21); *map.try_get_mut("Johnny").unwrap() += 1; assert_eq!(*map.get("Johnny").unwrap(), 22); let _result1_locking = map.get("Johnny"); let result2 = map.try_get_mut("Johnny"); assert!(result2.is_locked()); } } }
into_iter
drink-card.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/modules/app/services/auth.service'; @Component({ selector: 'app-drink-card', templateUrl: './drink-card.component.html', styleUrls: ['./drink-card.component.scss'], providers: [MdbModalService] }) export class DrinkCardComponent implements OnInit { drinks : Item[] = []; modalRef: MdbModalRef<DrinkEditModalComponent> searchTerm: string; term: string; currentRole : any = ""; constructor(private managerService : ManagerService, private modalService: MdbModalService, private authService : AuthService) { } ngOnInit(): void { this.currentRole = this.authService.getCurrentUser()?.dtype; this.managerService.getAllDrinkCardItems().subscribe( (response) => { this.drinks = response; }); } openModal(drink: Item) { this.modalRef = this.modalService.open(DrinkEditModalComponent, { data: { drink : drink } }); } order(item: Item) { this.managerService.orderDrink(item); } }
import { Item } from 'src/modules/app/models/Item'; import { ManagerService } from '../../services/manager.service'; import { DrinkEditModalComponent } from '../../modals/drink-edit-modal/drink-edit-modal.component'; import { MdbModalRef, MdbModalService } from 'mdb-angular-ui-kit/modal';
test_dataset.py
import unittest from unittest.mock import MagicMock import pandas as pd from pandas.testing import assert_frame_equal from data_export.pipeline.dataset import Dataset class TestDataset(unittest.TestCase): def setUp(self):
def test_to_dataframe(self): dataset = Dataset(self.examples, self.labels) df = dataset.to_dataframe() expected = pd.DataFrame([{"data": "example", "labels": ["label"]}]) assert_frame_equal(df, expected)
example = MagicMock() example.to_dict.return_value = {"data": "example"} self.examples = MagicMock() self.examples.__iter__.return_value = [example] label = MagicMock() label.find_by.return_value = {"labels": ["label"]} self.labels = MagicMock() self.labels.__iter__.return_value = [label]
text_processor.go
package plugins import ( "bytes" "errors" "fmt" "os" "os/exec" "strconv" "strings" "github.com/sirupsen/logrus" ) const ( DEFAULT_GET_TEXT_CONTEXT_LINE_OFFSET = 10 ) var TextProcessorPluginActions = make(map[string]Action) func init() { TextProcessorPluginActions["search"] = new(SearchTextAction) TextProcessorPluginActions["getContext"] = new(GetContextAction) } type TextProcessorPlugin struct { } func (plugin *TextProcessorPlugin) GetActionByName(actionName string) (Action, error) { action, found := TextProcessorPluginActions[actionName] if !found { return nil, fmt.Errorf("TextProcessor plugin,action = %s not found", actionName) } return action, nil } type SearchTextInputs struct { Inputs []SearchTextInput `json:"inputs,omitempty"` } type SearchTextInput struct { CallBackParameter Guid string `json:"guid,omitempty"` Target string `json:"target,omitempty"` EndPoint string `json:"endpoint,omitempty"` SearchPattern string `json:"pattern,omitempty"` // AccessKey string `json:"accessKey,omitempty"` // SecretKey string `json:"secretKey,omitempty"` } type SearchTextOutputs struct { Outputs []SearchTextOutput `json:"outputs"` } type SearchResult struct { LineNum int `json:"lineNum"` LineText string `json:"lineText"` } type SearchTextOutput struct { CallBackParameter Result Guid string `json:"guid,omitempty"` Host string `json:"host,omitempty"` Results []SearchResult `json:"result,omitempty"` } type SearchTextAction struct { } func (action *SearchTextAction) ReadParam(param interface{}) (interface{}, error) { var inputs SearchTextInputs if err := UnmarshalJson(param, &inputs); err != nil { return nil, err } return inputs, nil } func (action *SearchTextAction) CheckParam(input SearchTextInput) error { if input.EndPoint == "" { return errors.New("endpoint is empty") } if input.Target == "" { return errors.New("target is empty") } if input.EndPoint == "" { return errors.New("endpoint is empty") } // if input.AccessKey == "" { // return errors.New("accessKey is empty") // } // if input.SecretKey == "" { // return errors.New("secretKey is empty") // } if input.SearchPattern == "" { return errors.New("search pattern is empty") } return nil } func runCmd(shellCommand string) (string, error) { var stderr, stdout bytes.Buffer cmd := exec.Command("/bin/sh", "-c", shellCommand) cmd.Stderr = &stderr cmd.Stdout = &stdout if err := cmd.Run(); err != nil { logrus.Errorf("runCmd (%s) meet err=%v,stderr=%v", shellCommand, err, stderr.String()) return stderr.String(), nil } return stdout.String(), nil } func searchText(fileName string, pattern string) ([]SearchResult, error) { results := []SearchResult{} shellCmd := "grep -n " + "\"" + pattern + "\" " + fileName stdout, err := runCmd(shellCmd) if err != nil { return results, err } lines := strings.Split(stdout, "\n") for _, line := range lines { index := strings.IndexAny(line, ":") if index == -1 { continue } lineNum, err := strconv.Atoi(line[0:index]) if err != nil { logrus.Errorf("searchText get lineNum meet error,lineNum=%s", line[0:index]) continue } result := SearchResult{ LineNum: lineNum, LineText: line[index+1:], } results = append(results, result) } return results, nil } func (action *SearchTextAction) searchText(input *SearchTextInput) (output SearchTextOutput, err error) { defer func() { output.Guid = input.Guid output.Host = input.Target output.CallBackParameter.Parameter = input.CallBackParameter.Parameter if err == nil { output.Result.Code = RESULT_CODE_SUCCESS } else { output.Result.Code = RESULT_CODE_ERROR output.Result.Message = err.Error() } }() err = action.CheckParam(*input) if err != nil { return output, err } // fileName, err := downloadS3File(input.EndPoint, input.AccessKey, input.SecretKey) fileName, err := downloadS3File(input.EndPoint, "access_key", "secret_key") if err != nil { return output, err } results, err := searchText(fileName, input.SearchPattern) os.Remove(fileName) if err != nil { return output, err } output.Results = results return output, err } func (action *SearchTextAction) Do(input interface{}) (interface{}, error) { inputs, _ := input.(SearchTextInputs) outputs := SearchTextOutputs{} var finalErr error for _, input := range inputs.Inputs { output, err := action.searchText(&input) if err != nil { finalErr = err } outputs.Outputs = append(outputs.Outputs, output) } return &outputs, finalErr } //get context type GetContextInputs struct { Inputs []GetContextInput `json:"inputs,omitempty"` } type GetContextInput struct { CallBackParameter Guid string `json:"guid,omitempty"` EndPoint string `json:"endpoint,omitempty"` LineNum int `json:"lineNum,omitempty"` Offset int `json:"offset,omitempty"` // AccessKey string `json:"accessKey,omitempty"` // SecretKey string `json:"secretKey,omitempty"` } type GetContextOutputs struct { Outputs []GetContextOutput `json:"outputs"` } type GetContextOutput struct { CallBackParameter Result Guid string `json:"guid,omitempty"` ContextText string `json:"context"` } type GetContextAction struct { } func (action *GetContextAction) ReadParam(param interface{}) (interface{}, error) { var inputs GetContextInputs if err := UnmarshalJson(param, &inputs); err != nil { return nil, err } return inputs, nil } func (action *GetContextAction) CheckParam(input GetContextInput) error { if input.EndPoint == "" { return errors.New("endpoint is empty") } // if input.AccessKey == "" { // return errors.New("accessKey is empty") // } // if input.SecretKey == "" { // return errors.New("secretKey is empty") // } if input.LineNum <= 0 { return errors.New("invalid lineNum") } return nil } // sed -n '1,3p' filename func getTextContext(fileName string, lineNum int, offset int) (string, error) { if offset <= 0 { offset = DEFAULT_GET_TEXT_CONTEXT_LINE_OFFSET } startLine := lineNum - offset if startLine <= 0 { startLine = 1 }
shellCmd := fmt.Sprintf("cat -n %s |sed -n \"%d,%dp\" ", fileName, startLine, lineNum+offset) //shellCmd:=fmt.Sprintf("sed -n \"%d,%dp\" %s",startLine,lineNum+offset,fileName) return runCmd(shellCmd) } func (action *GetContextAction) getContext(input *GetContextInput) (output GetContextOutput, err error) { defer func() { output.Guid = input.Guid output.CallBackParameter.Parameter = input.CallBackParameter.Parameter if err == nil { output.Result.Code = RESULT_CODE_SUCCESS } else { output.Result.Code = RESULT_CODE_ERROR output.Result.Message = err.Error() } }() err = action.CheckParam(*input) if err != nil { return output, err } // fileName, err := downloadS3File(input.EndPoint, input.AccessKey, input.SecretKey) fileName, err := downloadS3File(input.EndPoint, "access_key", "secret_key") if err != nil { return output, err } contextText, err := getTextContext(fileName, input.LineNum, input.Offset) os.Remove(fileName) if err != nil { return output, err } output.ContextText = contextText return output, err } func (action *GetContextAction) Do(input interface{}) (interface{}, error) { inputs, _ := input.(GetContextInputs) outputs := GetContextOutputs{} var finalErr error for _, input := range inputs.Inputs { output, err := action.getContext(&input) if err != nil { finalErr = err } outputs.Outputs = append(outputs.Outputs, output) } return &outputs, finalErr }
xeger_test.go
package xeger import ( "math/rand" "regexp" "regexp/syntax" "testing" ) func TestXegerBasic(t *testing.T) { pattern := "abc[abc][abc]{3}" xeg, err := NewXeger(pattern) if err != nil { t.Errorf("Failed on valid pattern %s: %s\n", pattern, err.Error()) } result := xeg.Generate() //compiledPattern, _ := regexp.Compile(pattern) if res, _ := regexp.MatchString(pattern, result); !res { t.Errorf("Result %s doesn't match the pattern %s\n", result, pattern) } } func TestXegerInvalidPattern(t *testing.T) { pattern := "abc[abc](" _, err := NewXeger(pattern) if err == nil { t.Errorf("Not failed on invalid pattern %s: %s\n", pattern, err.Error()) } } func TestXegerMinMax(t *testing.T)
func TestXegerRanges(t *testing.T) { pattern := "abc[a-ce-gy-z]{5}" xeg, err := NewXeger(pattern) if err != nil { t.Errorf("Failed on valid pattern %s: %s\n", pattern, err.Error()) } result := xeg.Generate() //compiledPattern, _ := regexp.Compile(pattern) if res, _ := regexp.MatchString(pattern, result); !res { t.Errorf("Result %s doesn't match the pattern %s\n", result, pattern) } } func TestGenerate(t *testing.T) { pattern := "abc[abc][abc]{3}" result, err := Generate(pattern) if err != nil { t.Errorf("Generate failed with %s\n", err.Error()) } if res, _ := regexp.MatchString(pattern, result); !res { t.Errorf("Result %s doesn't match the pattern %s\n", result, pattern) } } func TestNewXegerWithSeed(t *testing.T) { pattern := "abc[a-ce-gy-z]{5}" xeg, err := NewXegerWithSeed(pattern, 123456) if err != nil { t.Errorf("Failed on valid pattern %s: %s\n", pattern, err.Error()) } if result := xeg.Generate(); result != "abczzyfz" { t.Errorf("Result with set seed doesn't meet prediction: %s is not abczzyfz", result) } } func TestImplicitXeger(t *testing.T) { myRegex, _ := syntax.Parse("[0-9]+", syntax.Perl) // handle this error in the real code myXeger := &Xeger{ myRegex, rand.NewSource(1234567), 15, } if res := myXeger.Generate(); res != "9712160" { // since it's set seed, I know the result t.Errorf("Result is wrong when creating Xeger implicitly: %s\n", res) } } func TestDefaultXeger(t *testing.T) { myXeger := &Xeger{} if res := myXeger.Generate(); res != "" { t.Errorf("Result of empty Xeger.Generate() is not empty: %s\n", res) } }
{ pattern := "abc[abc]{15,}" xeg, err := NewXeger(pattern) if err != nil { t.Errorf("Failed on valid pattern %s: %s\n", pattern, err.Error()) } result := xeg.Generate() //compiledPattern, _ := regexp.Compile(pattern) if res, _ := regexp.MatchString(pattern, result); !res { t.Errorf("Result %s doesn't match the pattern %s\n", result, pattern) } if len(result) != 18 { t.Errorf("Result %s doesn't match the expected length", result) } }
GuiTabDetectLeads.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import yaml from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QGroupBox, QVBoxLayout, QHBoxLayout, QMessageBox, \ QFileDialog, QPushButton, QListWidget, QAbstractItemView import utils.HelperFunctions as HF from GUI.GuiTwoLists_generic import TwoListGUI from utils.settingsLeadDetection import GuiLeadDetection import utils.preprocLeadCT as LeadDetectionRoutines import tests.elecModel_manualcorrection as plotElecModel import private.allToolTips as setToolTips from dependencies import ROOTDIR class GuiTabDetectLeads(QWidget): """Tab with options for detecting leads within the (pre-processed and registered) CT imaging""" def __init__(self, parent=None, ROOTDIR=''):
# ------------------------- Start with the functions for lists and buttons in this tab ------------------------- # def change_wdir(self): """A new window appears in which the working directory for NIFTI-files can be set; if set, this is stored in the configuration file, so that upon the next start there is the same folder selected automatically""" self.niftidir = QFileDialog.getExistingDirectory(self, 'Please select the directory of nii-files') if not self.niftidir == "": self.lblWdirTab.setText('wDIR: {}'.format(self.niftidir)) self.cfg["folders"]["nifti"] = self.niftidir with open(os.path.join(ROOTDIR, 'config_imagingTB.yaml'), 'wb') as settings_mod: yaml.safe_dump(self.cfg, settings_mod, default_flow_style=False, explicit_start=True, allow_unicode=True, encoding='utf-8') # saves new folder to yaml-file self.availableNiftiTab.clear() itemsChanged = HF.list_folders(self.cfg["folders"]["nifti"], self.cfg["folders"]["prefix"]) self.add_available_items(self.availableNiftiTab, itemsChanged) else: self.niftidir = self.cfg["folders"]["nifti"] def change_list_item(self): """function intended to provide the item which is selected. As different tabs have a similar functioning, it is coded in a way that the sender is identified""" if self.sender() == self.availableNiftiTab: items = self.availableNiftiTab.selectedItems() self.selected_subj_ANT = [] for i in range(len(items)): self.selected_subj_ANT.append(str(self.availableNiftiTab.selectedItems()[i].text())) # print(self.selected_subj_Gen) def add_available_items(self, sending_list, items, msg='yes'): """adds the available subjects in the working directory into the items list; an error message is dropped if none available""" if len(items) == 0 and msg == 'yes': buttonReply = QMessageBox.question(self, 'No files in dir', 'There are no subjects available ' 'in the current working directory ({}). Do you want to ' ' change to a different one?'.format(self.niftidir), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if buttonReply == QMessageBox.Yes: self.change_wdir() else: items = list(items) items.sort(key=lambda fname: int(fname.split(self.cfg["folders"]["prefix"])[1])) sending_list.addItems(items) def run_reload_files(self): """Reloads files, e.g. after renaming them""" self.cfg = HF.LittleHelpers.load_config(self.cfg["folders"]["rootdir"]) self.availableNiftiTab.clear() itemsChanged = HF.list_folders(self.cfg["folders"]["nifti"], prefix=self.cfg["folders"]["prefix"]) self.add_available_items(self.availableNiftiTab, itemsChanged) # Separate functions/GUIs that may be initialised here def run_LeadDetectionPaCER(self): """wrapper to start lead detection with PaCER routines translated to python; original data can be found at: https://github.com/adhusch/PaCER/""" if len(self.selected_subj_ANT) > 1: HF.msg_box(text="Please select only one subject, as multiprocessing for lead detection is not intended", title="Too many subjects selected") return else: msg = "Are you sure you want to process the following subject:\n\n" \ "{}".format(''.join(' -> {}\n'.format(c) for c in self.selected_subj_ANT)) ret = QMessageBox.question(self, 'MessageBox', msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if ret == QMessageBox.Yes: LeadDetectionRoutines.PaCER_script(subjects=self.selected_subj_ANT) def run_ManualCorrection(self): """wrapper which starts the plotting routine for the detected lead which enables manual corrections""" if len(self.selected_subj_ANT) != 1: HF.msg_box(text="Please select one and only one subject", title="Subjects selected") return else: msg = "Are you sure you want to process the following subject:\n\n" \ "{}".format(''.join(' -> {}\n'.format(c) for c in self.selected_subj_ANT)) ret = QMessageBox.question(self, 'MessageBox', msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if ret == QMessageBox.Yes: plotElecModel.PlotRoutines(subject=self.selected_subj_ANT[0], inputfolder=os.path.join(self.niftidir, self.selected_subj_ANT[0])) def run_PreferencesLeadDetection(self): """change settings for the Lead detection routines, that is settings for PaCER """ self.ANTsSettings = GuiLeadDetection() self.ANTsSettings.show() def VisualiseLeadDetection(self): """wrapper to start comparisons between pre- and post-processed images after N4BiasCorrection""" if not self.selected_subj_ANT: HF.msg_box(text="No folder selected. To proceed, please select at least one.", title="No subject selected") return elif len(self.selected_subj_ANT) > 1: HF.msg_box(text="Please select only one subj.", title="Too many subjects selected") return else: image_folder = os.path.join(self.cfg["folders"]["nifti"], self.selected_subj_ANT[0]) # Is the index necessary self.SelectFiles = TwoListGUI(working_directory=image_folder, option_gui="displayNiftiFiles") self.SelectFiles.show() if __name__ == '__main__': import sys app = QApplication(sys.argv) w = GuiTabDetectLeads() w.show() sys.exit(app.exec_())
super(GuiTabDetectLeads, self).__init__(parent) self.selected_subj_ANT = '' # General settings/variables/helper files needed needed at some point if not ROOTDIR: from dependencies import ROOTDIR self.cfg = HF.LittleHelpers.load_config(ROOTDIR) # load configuration file/options from file if os.path.isdir(self.cfg["folders"]["nifti"]): self.niftidir = self.cfg["folders"]["nifti"] else: self.niftidir = os.getcwd() self.cfg["folders"]["rootdir"] = ROOTDIR HF.LittleHelpers.save_config(ROOTDIR, self.cfg) self.lay = QHBoxLayout(self) self.tab = QWidget() # Customize tab # ============================== Tab 3 - Lead detection routines ============================== self.tab.layout = QHBoxLayout() self.tab.setLayout(self.tab.layout) # ------------------------- Upper left part (Folder) ------------------------- # self.FolderboxTab = QGroupBox("Directory (Bugra-Files)") self.HBoxUpperLeftTab = QVBoxLayout(self.FolderboxTab) self.lblWdirTab = QLabel('wDIR: {}'.format(self.niftidir)) self.HBoxUpperLeftTab.addWidget(self.lblWdirTab) #TODO: is it possible to summarize the working directoy ? If the path is too long the list of available subjects gets too small self.btnChangeWdir = QPushButton('Change working directory') self.btnChangeWdir.clicked.connect(self.change_wdir) #if changing folder is canceled, the whole script shuts down (macOS Catalina) self.btnReloadFilesTab = QPushButton('Reload files') self.btnReloadFilesTab.clicked.connect(self.run_reload_files) self.HBoxUpperLeftTab.addWidget(self.btnChangeWdir) self.HBoxUpperLeftTab.addWidget(self.btnReloadFilesTab) # ------------------------- Middle left part (Settings) ------------------------- # self.SettingsTabLeadDetect = QGroupBox("Preferences") self.HBoxMiddleLeftTabExt = QVBoxLayout(self.SettingsTabLeadDetect) self.btn_LeadDetectSettings = QPushButton('Settings \nLead detection') self.btn_LeadDetectSettings.clicked.connect(self.run_PreferencesLeadDetection) self.btn_LeadDetectSettings.setToolTip(setToolTips.ANTsSettings()) self.HBoxMiddleLeftTabExt.addWidget(self.btn_LeadDetectSettings) # ------------------------- Middle left part (Processing) ------------------------- # self.ActionsTabANTs = QGroupBox("Lead detection routines") self.HBoxMiddleLeftTab = QVBoxLayout(self.ActionsTabANTs) self.btn_LeadDetectPacer = QPushButton('PaCER algorithm') self.btn_LeadDetectPacer.clicked.connect(self.run_LeadDetectionPaCER) self.btn_RefineDetectedLeads = QPushButton('Refine detected leads') self.btn_RefineDetectedLeads.clicked.connect(self.run_ManualCorrection) self.HBoxMiddleLeftTab.addWidget(self.btn_LeadDetectPacer) self.HBoxMiddleLeftTab.addWidget(self.btn_RefineDetectedLeads) # ------------------------- Lower left part (Processing) ------------------------- # self.QualityTabLeadDetect = QGroupBox("Quality checks for Lead detection") self.HBoxLowerLeftTab = QVBoxLayout(self.QualityTabLeadDetect) self.btn_QC_LeadDetect = QPushButton('Check lead detection \nin viewer') self.btn_QC_LeadDetect.setToolTip(setToolTips.compareNIFTIfiles()) self.btn_QC_LeadDetect.clicked.connect(self.VisualiseLeadDetection) self.HBoxLowerLeftTab.addWidget(self.btn_QC_LeadDetect) # self.HBoxLowerLeftTab.addWidget(self.btn_RegQC) #TODO: whatsoever (?); accurate #TODO: view available (...); in tooltips correction instaed of correcion #TODO: additionally.view available in General -> tooltips: subject instead of just subj # -------------------- Right part (Subject list) ----------------------- # self.listbox = QGroupBox('Available subjects') self.HBoxUpperRightTab = QVBoxLayout(self.listbox) self.availableNiftiTab = QListWidget() self.availableNiftiTab.setSelectionMode(QAbstractItemView.ExtendedSelection) itemsTab = HF.list_folders(self.niftidir, prefix=self.cfg["folders"]["prefix"]) self.add_available_items(self.availableNiftiTab, itemsTab, msg='no') self.availableNiftiTab.itemSelectionChanged.connect(self.change_list_item) self.HBoxUpperRightTab.addWidget(self.availableNiftiTab) # Combine all Boxes for Tab 2 Layout self.LeftboxTabANTs = QGroupBox() self.HBoxTabLeadDetectLeft = QVBoxLayout(self.LeftboxTabANTs) self.HBoxTabLeadDetectLeft.addWidget(self.FolderboxTab) self.HBoxTabLeadDetectLeft.addStretch(1) self.HBoxTabLeadDetectLeft.addWidget(self.SettingsTabLeadDetect) self.HBoxTabLeadDetectLeft.addWidget(self.ActionsTabANTs) self.HBoxTabLeadDetectLeft.addWidget(self.QualityTabLeadDetect) self.tab.layout.addWidget(self.LeftboxTabANTs) self.tab.layout.addWidget(self.listbox) self.lay.addWidget(self.tab)
mainThreadEditorsTracker.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import EditorCommon = require('vs/editor/common/editorCommon'); import Event, { Emitter } from 'vs/base/common/event'; import { IEditor } from 'vs/platform/editor/common/editor'; import { ICodeEditorService } from 'vs/editor/common/services/codeEditorService'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IdGenerator } from 'vs/base/common/idGenerator'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { EndOfLine, TextEditorLineNumbersStyle } from 'vs/workbench/api/node/extHostTypes'; export interface ITextEditorConfigurationUpdate { tabSize?: number | 'auto'; insertSpaces?: boolean | 'auto'; cursorStyle?: EditorCommon.TextEditorCursorStyle; lineNumbers?: TextEditorLineNumbersStyle; } export interface IResolvedTextEditorConfiguration { tabSize: number; insertSpaces: boolean; cursorStyle: EditorCommon.TextEditorCursorStyle; lineNumbers: TextEditorLineNumbersStyle; } function configurationsEqual(a: IResolvedTextEditorConfiguration, b: IResolvedTextEditorConfiguration) { if (a && !b || !a && b) { return false; } if (!a && !b) { return true; } return ( a.tabSize === b.tabSize && a.insertSpaces === b.insertSpaces ); } export interface ISelectionChangeEvent { selections: Selection[]; source?: string; } export interface IFocusTracker { onGainedFocus(): void; onLostFocus(): void; } export enum TextEditorRevealType { Default = 0, InCenter = 1, InCenterIfOutsideViewport = 2 } export interface IApplyEditsOptions { undoStopBefore: boolean; undoStopAfter: boolean; setEndOfLine: EndOfLine; } /** * Text Editor that is permanently bound to the same model. * It can be bound or not to a CodeEditor. */ export class MainThreadTextEditor { private _id: string; private _model: EditorCommon.IModel; private _modelService: IModelService; private _modelListeners: IDisposable[]; private _codeEditor: EditorCommon.ICommonCodeEditor; private _focusTracker: IFocusTracker; private _codeEditorListeners: IDisposable[]; private _lastSelection: Selection[]; private _configuration: IResolvedTextEditorConfiguration; private _onSelectionChanged: Emitter<ISelectionChangeEvent>; private _onConfigurationChanged: Emitter<IResolvedTextEditorConfiguration>; constructor( id: string, model: EditorCommon.IModel, codeEditor: EditorCommon.ICommonCodeEditor, focusTracker: IFocusTracker, modelService: IModelService ) { this._id = id; this._model = model; this._codeEditor = null; this._focusTracker = focusTracker; this._modelService = modelService; this._codeEditorListeners = []; this._onSelectionChanged = new Emitter<ISelectionChangeEvent>(); this._onConfigurationChanged = new Emitter<IResolvedTextEditorConfiguration>(); this._lastSelection = [new Selection(1, 1, 1, 1)]; this._modelListeners = []; this._modelListeners.push(this._model.onDidChangeOptions((e) => { this._setConfiguration(this._readConfiguration(this._model, this._codeEditor)); })); this.setCodeEditor(codeEditor); this._setConfiguration(this._readConfiguration(this._model, this._codeEditor)); } public dispose(): void { this._model = null; this._modelListeners = dispose(this._modelListeners); this._codeEditor = null; this._codeEditorListeners = dispose(this._codeEditorListeners); } public getId(): string { return this._id; } public getModel(): EditorCommon.IModel { return this._model; } public hasCodeEditor(codeEditor: EditorCommon.ICommonCodeEditor): boolean { return (this._codeEditor === codeEditor); } public setCodeEditor(codeEditor: EditorCommon.ICommonCodeEditor): void {
if (this.hasCodeEditor(codeEditor)) { // Nothing to do... return; } this._codeEditorListeners = dispose(this._codeEditorListeners); this._codeEditor = codeEditor; if (this._codeEditor) { // Catch early the case that this code editor gets a different model set and disassociate from this model this._codeEditorListeners.push(this._codeEditor.onDidChangeModel(() => { this.setCodeEditor(null); })); let forwardSelection = (event?: EditorCommon.ICursorSelectionChangedEvent) => { this._lastSelection = this._codeEditor.getSelections(); this._onSelectionChanged.fire({ selections: this._lastSelection, source: event && event.source }); }; this._codeEditorListeners.push(this._codeEditor.onDidChangeCursorSelection(forwardSelection)); if (!Selection.selectionsArrEqual(this._lastSelection, this._codeEditor.getSelections())) { forwardSelection(); } this._codeEditorListeners.push(this._codeEditor.onDidFocusEditor(() => { this._focusTracker.onGainedFocus(); })); this._codeEditorListeners.push(this._codeEditor.onDidBlurEditor(() => { this._focusTracker.onLostFocus(); })); this._codeEditorListeners.push(this._codeEditor.onDidChangeConfiguration(() => { this._setConfiguration(this._readConfiguration(this._model, this._codeEditor)); })); this._setConfiguration(this._readConfiguration(this._model, this._codeEditor)); } } public isVisible(): boolean { return !!this._codeEditor; } public get onSelectionChanged(): Event<ISelectionChangeEvent> { return this._onSelectionChanged.event; } public get onConfigurationChanged(): Event<IResolvedTextEditorConfiguration> { return this._onConfigurationChanged.event; } public getSelections(): Selection[] { if (this._codeEditor) { return this._codeEditor.getSelections(); } return this._lastSelection; } public setSelections(selections: EditorCommon.ISelection[]): void { if (this._codeEditor) { this._codeEditor.setSelections(selections); return; } this._lastSelection = selections.map(Selection.liftSelection); console.warn('setSelections on invisble editor'); } public getConfiguration(): IResolvedTextEditorConfiguration { return this._configuration; } private _setIndentConfiguration(newConfiguration: ITextEditorConfigurationUpdate): void { if (newConfiguration.tabSize === 'auto' || newConfiguration.insertSpaces === 'auto') { // one of the options was set to 'auto' => detect indentation let creationOpts = this._modelService.getCreationOptions(); let insertSpaces = creationOpts.insertSpaces; let tabSize = creationOpts.tabSize; if (newConfiguration.insertSpaces !== 'auto' && typeof newConfiguration.insertSpaces !== 'undefined') { insertSpaces = newConfiguration.insertSpaces; } if (newConfiguration.tabSize !== 'auto' && typeof newConfiguration.tabSize !== 'undefined') { tabSize = newConfiguration.tabSize; } this._model.detectIndentation(insertSpaces, tabSize); return; } let newOpts: EditorCommon.ITextModelUpdateOptions = {}; if (typeof newConfiguration.insertSpaces !== 'undefined') { newOpts.insertSpaces = newConfiguration.insertSpaces; } if (typeof newConfiguration.tabSize !== 'undefined') { newOpts.tabSize = newConfiguration.tabSize; } this._model.updateOptions(newOpts); } public setConfiguration(newConfiguration: ITextEditorConfigurationUpdate): void { this._setIndentConfiguration(newConfiguration); if (newConfiguration.cursorStyle) { let newCursorStyle = EditorCommon.cursorStyleToString(newConfiguration.cursorStyle); if (!this._codeEditor) { console.warn('setConfiguration on invisible editor'); return; } this._codeEditor.updateOptions({ cursorStyle: newCursorStyle }); } if (typeof newConfiguration.lineNumbers !== 'undefined') { if (!this._codeEditor) { console.warn('setConfiguration on invisible editor'); return; } let lineNumbers: 'on' | 'off' | 'relative'; switch (newConfiguration.lineNumbers) { case TextEditorLineNumbersStyle.On: lineNumbers = 'on'; break; case TextEditorLineNumbersStyle.Relative: lineNumbers = 'relative'; break; default: lineNumbers = 'off'; } this._codeEditor.updateOptions({ lineNumbers: lineNumbers }); } } public setDecorations(key: string, ranges: EditorCommon.IDecorationOptions[]): void { if (!this._codeEditor) { console.warn('setDecorations on invisible editor'); return; } this._codeEditor.setDecorations(key, ranges); } public revealRange(range: EditorCommon.IRange, revealType: TextEditorRevealType): void { if (!this._codeEditor) { console.warn('revealRange on invisible editor'); return; } if (revealType === TextEditorRevealType.Default) { this._codeEditor.revealRange(range); } else if (revealType === TextEditorRevealType.InCenter) { this._codeEditor.revealRangeInCenter(range); } else if (revealType === TextEditorRevealType.InCenterIfOutsideViewport) { this._codeEditor.revealRangeInCenterIfOutsideViewport(range); } else { console.warn('Unknown revealType'); } } private _readConfiguration(model: EditorCommon.IModel, codeEditor: EditorCommon.ICommonCodeEditor): IResolvedTextEditorConfiguration { if (model.isDisposed()) { // shutdown time return this._configuration; } let cursorStyle = this._configuration ? this._configuration.cursorStyle : EditorCommon.TextEditorCursorStyle.Line; let lineNumbers: TextEditorLineNumbersStyle = this._configuration ? this._configuration.lineNumbers : TextEditorLineNumbersStyle.On; if (codeEditor) { let codeEditorOpts = codeEditor.getConfiguration(); cursorStyle = codeEditorOpts.viewInfo.cursorStyle; if (codeEditorOpts.viewInfo.renderRelativeLineNumbers) { lineNumbers = TextEditorLineNumbersStyle.Relative; } else if (codeEditorOpts.viewInfo.renderLineNumbers) { lineNumbers = TextEditorLineNumbersStyle.On; } else { lineNumbers = TextEditorLineNumbersStyle.Off; } } let indent = model.getOptions(); return { insertSpaces: indent.insertSpaces, tabSize: indent.tabSize, cursorStyle: cursorStyle, lineNumbers: lineNumbers }; } private _setConfiguration(newConfiguration: IResolvedTextEditorConfiguration): void { if (configurationsEqual(this._configuration, newConfiguration)) { return; } this._configuration = newConfiguration; this._onConfigurationChanged.fire(this._configuration); } public isFocused(): boolean { if (this._codeEditor) { return this._codeEditor.isFocused(); } return false; } public matches(editor: IEditor): boolean { if (!editor) { return false; } return editor.getControl() === this._codeEditor; } public applyEdits(versionIdCheck: number, edits: EditorCommon.ISingleEditOperation[], opts: IApplyEditsOptions): boolean { if (this._model.getVersionId() !== versionIdCheck) { console.warn('Model has changed in the meantime!'); // throw new Error('Model has changed in the meantime!'); // model changed in the meantime return false; } if (this._codeEditor) { if (opts.setEndOfLine === EndOfLine.CRLF) { this._model.setEOL(EditorCommon.EndOfLineSequence.CRLF); } else if (opts.setEndOfLine === EndOfLine.LF) { this._model.setEOL(EditorCommon.EndOfLineSequence.LF); } let transformedEdits = edits.map((edit): EditorCommon.IIdentifiedSingleEditOperation => { return { identifier: null, range: Range.lift(edit.range), text: edit.text, forceMoveMarkers: edit.forceMoveMarkers }; }); if (opts.undoStopBefore) { this._codeEditor.pushUndoStop(); } this._codeEditor.executeEdits('MainThreadTextEditor', transformedEdits); if (opts.undoStopAfter) { this._codeEditor.pushUndoStop(); } return true; } console.warn('applyEdits on invisible editor'); return false; } } /** * Keeps track of what goes on in the main thread and maps models => text editors */ export class MainThreadEditorsTracker { private static _Ids = new IdGenerator(''); private _toDispose: IDisposable[]; private _codeEditorService: ICodeEditorService; private _modelService: IModelService; private _updateMapping: RunOnceScheduler; private _editorModelChangeListeners: { [editorId: string]: IDisposable; }; private _model2TextEditors: { [modelUri: string]: MainThreadTextEditor[]; }; private _focusedTextEditorId: string; private _visibleTextEditorIds: string[]; private _onTextEditorAdd: Emitter<MainThreadTextEditor>; private _onTextEditorRemove: Emitter<MainThreadTextEditor>; private _onDidChangeFocusedTextEditor: Emitter<string>; private _onDidUpdateTextEditors: Emitter<void>; private _focusTracker: IFocusTracker; constructor( editorService: ICodeEditorService, modelService: IModelService ) { this._codeEditorService = editorService; this._modelService = modelService; this._toDispose = []; this._focusedTextEditorId = null; this._visibleTextEditorIds = []; this._editorModelChangeListeners = Object.create(null); this._model2TextEditors = Object.create(null); this._onTextEditorAdd = new Emitter<MainThreadTextEditor>(); this._onTextEditorRemove = new Emitter<MainThreadTextEditor>(); this._onDidUpdateTextEditors = new Emitter<void>(); this._onDidChangeFocusedTextEditor = new Emitter<string>(); this._focusTracker = { onGainedFocus: () => this._updateFocusedTextEditor(), onLostFocus: () => this._updateFocusedTextEditor() }; this._modelService.onModelAdded(this._onModelAdded, this, this._toDispose); this._modelService.onModelRemoved(this._onModelRemoved, this, this._toDispose); this._codeEditorService.onCodeEditorAdd(this._onCodeEditorAdd, this, this._toDispose); this._codeEditorService.onCodeEditorRemove(this._onCodeEditorRemove, this, this._toDispose); this._updateMapping = new RunOnceScheduler(() => this._doUpdateMapping(), 0); this._toDispose.push(this._updateMapping); } public dispose(): void { this._toDispose = dispose(this._toDispose); } private _onModelAdded(model: EditorCommon.IModel): void { this._updateMapping.schedule(); } private _onModelRemoved(model: EditorCommon.IModel): void { this._updateMapping.schedule(); } private _onCodeEditorAdd(codeEditor: EditorCommon.ICommonCodeEditor): void { this._editorModelChangeListeners[codeEditor.getId()] = codeEditor.onDidChangeModel(_ => this._updateMapping.schedule()); this._updateMapping.schedule(); } private _onCodeEditorRemove(codeEditor: EditorCommon.ICommonCodeEditor): void { this._editorModelChangeListeners[codeEditor.getId()].dispose(); delete this._editorModelChangeListeners[codeEditor.getId()]; this._updateMapping.schedule(); } private _doUpdateMapping(): void { let allModels = this._modelService.getModels(); // Same filter as in extHostDocuments allModels = allModels.filter((model) => !model.isTooLargeForHavingARichMode()); let allModelsMap: { [modelUri: string]: EditorCommon.IModel; } = Object.create(null); allModels.forEach((model) => { allModelsMap[model.uri.toString()] = model; }); // Remove text editors for models that no longer exist Object.keys(this._model2TextEditors).forEach((modelUri) => { if (allModelsMap[modelUri]) { // model still exists, will be updated below return; } let textEditorsToRemove = this._model2TextEditors[modelUri]; delete this._model2TextEditors[modelUri]; for (let i = 0; i < textEditorsToRemove.length; i++) { this._onTextEditorRemove.fire(textEditorsToRemove[i]); textEditorsToRemove[i].dispose(); } }); // Handle all visible models let visibleModels = this._getVisibleModels(); Object.keys(visibleModels).forEach((modelUri) => { let model = visibleModels[modelUri].model; let codeEditors = visibleModels[modelUri].codeEditors; if (!this._model2TextEditors[modelUri]) { this._model2TextEditors[modelUri] = []; } let existingTextEditors = this._model2TextEditors[modelUri]; // Remove text editors if more exist while (existingTextEditors.length > codeEditors.length) { let removedTextEditor = existingTextEditors.pop(); this._onTextEditorRemove.fire(removedTextEditor); removedTextEditor.dispose(); } // Adjust remaining text editors for (let i = 0; i < existingTextEditors.length; i++) { existingTextEditors[i].setCodeEditor(codeEditors[i]); } // Create new editors as needed for (let i = existingTextEditors.length; i < codeEditors.length; i++) { let newTextEditor = new MainThreadTextEditor(MainThreadEditorsTracker._Ids.nextId(), model, codeEditors[i], this._focusTracker, this._modelService); existingTextEditors.push(newTextEditor); this._onTextEditorAdd.fire(newTextEditor); } }); // Handle all not visible models allModels.forEach((model) => { let modelUri = model.uri.toString(); if (visibleModels[modelUri]) { // model is visible, already handled above return; } if (!this._model2TextEditors[modelUri]) { this._model2TextEditors[modelUri] = []; } let existingTextEditors = this._model2TextEditors[modelUri]; // Remove extra text editors while (existingTextEditors.length > 1) { let removedTextEditor = existingTextEditors.pop(); this._onTextEditorRemove.fire(removedTextEditor); removedTextEditor.dispose(); } // Create new editor if needed or adjust it if (existingTextEditors.length === 0) { let newTextEditor = new MainThreadTextEditor(MainThreadEditorsTracker._Ids.nextId(), model, null, this._focusTracker, this._modelService); existingTextEditors.push(newTextEditor); this._onTextEditorAdd.fire(newTextEditor); } else { existingTextEditors[0].setCodeEditor(null); } }); this._printState(); this._visibleTextEditorIds = this._findVisibleTextEditorIds(); this._updateFocusedTextEditor(); // this is a sync event this._onDidUpdateTextEditors.fire(undefined); } private _updateFocusedTextEditor(): void { this._setFocusedTextEditorId(this._findFocusedTextEditorId()); } private _findFocusedTextEditorId(): string { let modelUris = Object.keys(this._model2TextEditors); for (let i = 0, len = modelUris.length; i < len; i++) { let editors = this._model2TextEditors[modelUris[i]]; for (let j = 0, lenJ = editors.length; j < lenJ; j++) { if (editors[j].isFocused()) { return editors[j].getId(); } } } return null; } private _findVisibleTextEditorIds(): string[] { let result: string[] = []; let modelUris = Object.keys(this._model2TextEditors); for (let i = 0, len = modelUris.length; i < len; i++) { let editors = this._model2TextEditors[modelUris[i]]; for (let j = 0, lenJ = editors.length; j < lenJ; j++) { if (editors[j].isVisible()) { result.push(editors[j].getId()); } } } result.sort(); return result; } private _setFocusedTextEditorId(focusedTextEditorId: string): void { if (this._focusedTextEditorId === focusedTextEditorId) { // no change return; } this._focusedTextEditorId = focusedTextEditorId; this._printState(); this._onDidChangeFocusedTextEditor.fire(this._focusedTextEditorId); } private _printState(): void { // console.log('----------------------'); // Object.keys(this._model2TextEditors).forEach((modelUri) => { // let editors = this._model2TextEditors[modelUri]; // console.log(editors.map((e) => { // return e.getId() + " (" + (e.getId() === this._focusedTextEditorId ? 'FOCUSED, ': '') + modelUri + ")"; // }).join('\n')); // }); } private _getVisibleModels(): IVisibleModels { let r: IVisibleModels = {}; let allCodeEditors = this._codeEditorService.listCodeEditors(); // Maintain a certain sorting such that the mapping doesn't change too much all the time allCodeEditors.sort((a, b) => strcmp(a.getId(), b.getId())); allCodeEditors.forEach((codeEditor) => { let model = codeEditor.getModel(); if (!model || model.isTooLargeForHavingARichMode() || !this._modelService.getModel(model.uri)) { return; } let modelUri = model.uri.toString(); r[modelUri] = r[modelUri] || { model: model, codeEditors: [] }; r[modelUri].codeEditors.push(codeEditor); }); return r; } public getFocusedTextEditorId(): string { return this._focusedTextEditorId; } public getVisibleTextEditorIds(): string[] { return this._visibleTextEditorIds; } public get onTextEditorAdd(): Event<MainThreadTextEditor> { return this._onTextEditorAdd.event; } public get onTextEditorRemove(): Event<MainThreadTextEditor> { return this._onTextEditorRemove.event; } public get onDidUpdateTextEditors(): Event<void> { return this._onDidUpdateTextEditors.event; } public get onChangedFocusedTextEditor(): Event<string> { return this._onDidChangeFocusedTextEditor.event; } public findTextEditorIdFor(codeEditor: EditorCommon.ICommonCodeEditor): string { let modelUris = Object.keys(this._model2TextEditors); for (let i = 0, len = modelUris.length; i < len; i++) { let editors = this._model2TextEditors[modelUris[i]]; for (let j = 0, lenJ = editors.length; j < lenJ; j++) { if (editors[j].hasCodeEditor(codeEditor)) { return editors[j].getId(); } } } return null; } public registerTextEditorDecorationType(key: string, options: EditorCommon.IDecorationRenderOptions): void { this._codeEditorService.registerDecorationType(key, options); } public removeTextEditorDecorationType(key: string): void { this._codeEditorService.removeDecorationType(key); } } interface IVisibleModels { [modelUri: string]: { model: EditorCommon.IModel; codeEditors: EditorCommon.ICommonCodeEditor[]; }; } function strcmp(a: string, b: string): number { if (a < b) { return -1; } if (a > b) { return 1; } return 0; }
unary.rs
pub use crate::generic::server::unary::Once; use crate::codec::{Decoder, Encode, Encoder}; use crate::generic::server::{unary, UnaryService}; use crate::generic::Streaming; use crate::Body; use futures::{try_ready, Future, Poll}; use std::fmt; pub struct ResponseFuture<T, B, R> where T: UnaryService<R>, R: prost::Message + Default, T::Response: prost::Message, B: Body, { inner: Inner<T, T::Response, R, B>, } type Inner<T, U, V, B> = unary::ResponseFuture<T, Encoder<U>, Streaming<Decoder<V>, B>>; impl<T, B, R> ResponseFuture<T, B, R> where T: UnaryService<R>, R: prost::Message + Default, T::Response: prost::Message, B: Body, { pub(crate) fn
(inner: Inner<T, T::Response, R, B>) -> Self { ResponseFuture { inner } } } impl<T, B, R> Future for ResponseFuture<T, B, R> where T: UnaryService<R>, R: prost::Message + Default, T::Response: prost::Message, B: Body, { type Item = http::Response<Encode<Once<T::Response>>>; type Error = crate::error::Never; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let response = try_ready!(self.inner.poll()); let response = response.map(Encode::new); Ok(response.into()) } } impl<T, B, R> fmt::Debug for ResponseFuture<T, B, R> where T: UnaryService<R> + fmt::Debug, R: prost::Message + Default + fmt::Debug, T::Response: prost::Message + fmt::Debug, T::Future: fmt::Debug, B: Body + fmt::Debug, B::Data: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("unary::ResponseFuture") .field("inner", &self.inner) .finish() } }
new
utils_test.go
package ezsqlx import ( "testing" "github.com/stretchr/testify/assert" ) func
(t *testing.T) { assert.Equal(t, "foo_bar", snakeCase("FooBar")) assert.Equal(t, "foo_bar", snakeCase("fooBar")) } func TestRemove(t *testing.T) { x := []string{"a", "b", "c", "d", "e"} x = remove(x, "b") assert.Equal(t, []string{"a", "c", "d", "e"}, x) x = remove(x, "e") assert.Equal(t, []string{"a", "c", "d"}, x) x = remove(x, "a") assert.Equal(t, []string{"c", "d"}, x) }
TestSnakeCase
networks.js
'use strict'; var _ = require('lodash'); var BufferUtil = require('./util/buffer'); var JSUtil = require('./util/js'); var networks = []; var networkMaps = {}; /** * A network is merely a map containing values that correspond to version * numbers for each bitcoin network. Currently only supporting "livenet" * (a.k.a. "mainnet") and "testnet". * @constructor */ function Network() {} Network.prototype.toString = function toString() { return this.name; }; /** * @function * @member Networks#get * Retrieves the network associated with a magic number or string. * @param {string|number|Network} arg * @param {string|Array} keys - if set, only check if the magic number associated with this name matches * @return Network */ function get(arg, keys) { if (~networks.indexOf(arg)) { return arg; } if (keys) { if (!_.isArray(keys)) { keys = [keys]; } var containsArg = function(key) { return networks[index][key] === arg; }; for (var index in networks) { if (_.any(keys, containsArg)) { return networks[index]; } } return undefined; } return networkMaps[arg]; } /** * @function * @member Networks#add * Will add a custom Network * @param {Object} data * @param {string} data.name - The name of the network * @param {string} data.alias - The aliased name of the network * @param {Number} data.pubkeyhash - The publickey hash prefix * @param {Number} data.privatekey - The privatekey prefix * @param {Number} data.scripthash - The scripthash prefix * @param {Number} data.xpubkey - The extended public key magic * @param {Number} data.xprivkey - The extended private key magic * @param {Number} data.zaddr - The LitecoinZ payment address prefix * @param {Number} data.zkey - The LitecoinZ spending key prefix * @param {Number} data.networkMagic - The network magic number * @param {Number} data.port - The network port * @param {Array} data.dnsSeeds - An array of dns seeds * @return Network */ function addNetwork(data) { var network = new Network(); JSUtil.defineImmutable(network, { name: data.name, alias: data.alias, pubkeyhash: data.pubkeyhash, privatekey: data.privatekey, scripthash: data.scripthash, xpubkey: data.xpubkey, xprivkey: data.xprivkey, zaddr: data.zaddr, zkey: data.zkey }); if (data.networkMagic) { JSUtil.defineImmutable(network, { networkMagic: BufferUtil.integerAsBuffer(data.networkMagic) }); } if (data.port) { JSUtil.defineImmutable(network, { port: data.port }); } if (data.dnsSeeds) { JSUtil.defineImmutable(network, { dnsSeeds: data.dnsSeeds }); } _.each(network, function(value) { if (!_.isUndefined(value) && !_.isObject(value)) { networkMaps[value] = network; } }); networks.push(network); return network; } /** * @function * @member Networks#remove * Will remove a custom network * @param {Network} network */ function removeNetwork(network) { for (var i = 0; i < networks.length; i++) { if (networks[i] === network) { networks.splice(i, 1); } } for (var key in networkMaps) { if (networkMaps[key] === network) { delete networkMaps[key]; } } } addNetwork({ name: 'livenet', alias: 'mainnet', pubkeyhash: 0x0ab3, privatekey: 0x80, scripthash: 0x0ab8, xpubkey: 0x0488b21e, xprivkey: 0x0488ade3, zaddr: 0x16aa, zkey: 0x8964, networkMagic: 0xd8cfcd93, port: 29333, dnsSeeds: [ 'dnsseed.litecoinz.org' ] }); /** * @instance * @member Networks#livenet */ var livenet = get('livenet'); addNetwork({ name: 'testnet', alias: 'regtest', pubkeyhash: 0x0ea4, privatekey: 0xef, scripthash: 0x0ea9, xpubkey: 0x043587cf, xprivkey: 0x04358394, zaddr: 0x16b6, zkey: 0xb1f8, }); /** * @instance * @member Networks#testnet */ var testnet = get('testnet'); // Add configurable values for testnet/regtest var TESTNET = { PORT: 39333, NETWORK_MAGIC: BufferUtil.integerAsBuffer(0xfa1af9bf), DNS_SEEDS: [ 'testnet-dnsseed.litecoinz.org', ] }; for (var key in TESTNET) { if (!_.isObject(TESTNET[key])) { networkMaps[TESTNET[key]] = testnet; } } var REGTEST = { PORT: 49444, NETWORK_MAGIC: BufferUtil.integerAsBuffer(0xaae83f5f), DNS_SEEDS: [] }; for (var key in REGTEST) { if (!_.isObject(REGTEST[key])) { networkMaps[REGTEST[key]] = testnet; } } Object.defineProperty(testnet, 'port', { enumerable: true, configurable: false, get: function() { if (this.regtestEnabled) { return REGTEST.PORT; } else { return TESTNET.PORT; } } }); Object.defineProperty(testnet, 'networkMagic', { enumerable: true, configurable: false, get: function() { if (this.regtestEnabled) { return REGTEST.NETWORK_MAGIC; } else { return TESTNET.NETWORK_MAGIC; } } }); Object.defineProperty(testnet, 'dnsSeeds', { enumerable: true, configurable: false, get: function() { if (this.regtestEnabled) { return REGTEST.DNS_SEEDS; } else { return TESTNET.DNS_SEEDS; } } }); /** * @function * @member Networks#enableRegtest * Will enable regtest features for testnet */ function enableRegtest() { testnet.regtestEnabled = true; } /** * @function * @member Networks#disableRegtest * Will disable regtest features for testnet */ function disableRegtest() { testnet.regtestEnabled = false; } /** * @namespace Networks */ module.exports = { add: addNetwork, remove: removeNetwork, defaultNetwork: livenet, livenet: livenet, mainnet: livenet, testnet: testnet, get: get, enableRegtest: enableRegtest,
disableRegtest: disableRegtest };
ssh.go
package main import ( "encoding/binary" "fmt" "os" "os/exec" gopty "github.com/creack/pty" "github.com/hugefiver/qush/ssh" "github.com/rs/zerolog/log" ) func handleSSHChannel(c ssh.NewChannel, user string) { channel, reqs, err := c.Accept() if err != nil { log.Debug().Err(err).Msg("cannot accept channel") return } pty, tty, err := gopty.Open() if err != nil { log.Debug().Err(err).Msg("cannot open pty") } shell := programConfig.Shell if shell == "" { shell = os.Getenv("SHELL") log.Debug().Msgf("show env: SHELL=%s", shell) if shell == ""
} running := false for req := range reqs { log.Debug().Msgf("Type: %v; Payload: %v", req.Type, req.Payload) ok := false home := os.Getenv("HOME") path := os.Getenv("PATH") envs := []string{ "TERM=xterm", fmt.Sprintf("HOME=%s", home), fmt.Sprintf("PWD=%s", home), fmt.Sprintf("PATH=%s", path), fmt.Sprintf("USER=%s", user), fmt.Sprintf("SHELL=%s", shell), } switch req.Type { case "exec": if running { req.Reply(false, nil) log.Debug().Msg("ignore duplicate execute request") continue } running = true ok = true length := req.Payload[3] command := string(req.Payload[4 : length+4]) cmd := exec.Command(shell, []string{"-c", command}...) cmd.Dir = home cmd.Env = envs //e := func(e, v string) string { // return fmt.Sprintf("%s=%s", strings.ToUpper(e), v) //} //envs := []string{ // e("USER", os.Getenv("USER")), // e("HOME", os.Getenv("HOME")), // e("PATH", os.Getenv("PATH")), // e("PWD", os.Getenv("HOME")), //} // //cmd.Env = envs err := PtyRun(cmd, tty) if err != nil { log.Printf("could not start command (%s)", err) continue } // set pipe of ssh channel and pty PipeChannels(channel, pty) // teardown session go func() { _, err := cmd.Process.Wait() if err != nil { log.Printf("failed to exit command: (%s)", err) } channel.Close() log.Printf("session closed") }() case "shell": if running { req.Reply(false, nil) log.Debug().Msg("ignore duplicate execute request") continue } running = true ok = true cmd := exec.Command(shell) cmd.Dir = home cmd.Env = []string{ "TERM=xterm", fmt.Sprintf("HOME=%s", home), fmt.Sprintf("PWD=%s", home), fmt.Sprintf("PATH=%s", path), } err := PtyRun(cmd, tty) if err != nil { log.Printf("%s", err) } PipeChannels(channel, pty) go func() { _, err := cmd.Process.Wait() if err != nil { log.Printf("failed to exit shell (%s)", err) } channel.Close() log.Printf("session closed") }() ok = true case "pty-req": // Responding 'ok' here will let the client // know we have a pty ready for input ok = true // Parse body... termLen := req.Payload[3] termEnv := string(req.Payload[4 : termLen+4]) w, h := parseDims(req.Payload[termLen+4:]) SetWinSize(pty.Fd(), w, h) log.Printf("pty-req '%s'", termEnv) case "window-change": w, h := parseDims(req.Payload) SetWinSize(pty.Fd(), w, h) continue //no response } if !ok { log.Printf("declining %s request", req.Type) } if req.WantReply { _ = req.Reply(ok, nil) } } } // parseDims extracts two uint32s from the provided buffer. func parseDims(b []byte) (uint32, uint32) { w := binary.BigEndian.Uint32(b) h := binary.BigEndian.Uint32(b[4:]) return w, h } // WinSize stores the Height and Width of a terminal. type WinSize struct { Height uint16 Width uint16 x uint16 // unused y uint16 // unused } func logAuthLog(conn ssh.ConnMetadata, method string, err error) { switch method { case "password": if err != nil { log.Info().Err(err). Msgf("Failed to auth user %s login from %v using %s", conn.User(), conn.RemoteAddr(), method) } else { log.Info(). Msgf("Succeed to auth user %s login from %v using %s", conn.User(), conn.RemoteAddr(), method) } default: return } }
{ shell = "sh" log.Debug().Msgf("SHELL is empty, will use `%s` ", shell) }
issue2170exe.rs
// xfail-fast - check-fail fast doesn't under aux-build // aux-build:issue2170lib.rs extern mod issue2170lib; fn main() {
// let _ = issue2170lib::rsrc(2i32); }
client.rs
use crate::{Device, PayloadStruct}; use failure::format_err; use failure::Error; fn check_id(payload: &PayloadStruct, ref_id: u8) -> Result<(), Error> { if payload.id != ref_id { return Err(format_err!( "id should be {}, but it is {}", ref_id, payload.id )); } Ok(()) } pub struct DobotClient<T: Device> { device: T, } impl<T> DobotClient<T> where T: Device, { pub fn new(device: T) -> Self { Self { device } } fn write_params(&mut self, id: u8, params: Vec<u8>) -> Result<(), Error> { let p = PayloadStruct::with_id(id).set_write().set_params(params); let ret = self.device.send(p)?; check_id(&ret, id) } fn write_queued_params(&mut self, id: u8, params: Vec<u8>) -> Result<u64, Error> { let p = PayloadStruct::with_id(id) .set_write() .set_params(params) .set_queued(); let ret = self.device.send(p)?; check_id(&ret, id)?; let mut u = U64Union { val: 0 }; unsafe { u.bytes.copy_from_slice(&ret.params); Ok(u.val) } } fn read_params(&mut self, id: u8) -> Result<Vec<u8>, Error> { let p = PayloadStruct::with_id(id); let ret = self.device.send(p)?; check_id(&ret, id)?; Ok(ret.params) } pub fn get_device_sn(&mut self) -> Result<String, Error> { Ok(String::from_utf8(self.read_params(0)?)?) } pub fn get_alarm_state(&mut self) -> Result<Vec<u8>, Error> { self.read_params(20) } pub fn clear_all_alarm_state(&mut self) -> Result<(), Error> { self.write_params(20, vec![]) } pub fn get_pose(&mut self) -> Result<Pose, Error> { let p = self.read_params(10)?; let mut pose_union = PoseUnion { bytes: [0; 32] }; let pose = unsafe { pose_union.bytes.copy_from_slice(&p); pose_union.poses }; Ok(pose) } pub fn get_jog_joint_params(&mut self) -> Result<JogJointParams, Error> { let p = self.read_params(70)?; let mut params_union = JogJointParamsUnion { bytes: [0; 32] }; let params = unsafe { params_union.bytes.copy_from_slice(&p); params_union.jog_joint_params }; Ok(params) } pub fn set_jog_joint_params(&mut self, params: JogJointParams) -> Result<(), Error> { let params_union = JogJointParamsUnion { jog_joint_params: params, }; self.write_params(70, unsafe { params_union.bytes.to_vec() }) } pub fn get_jog_common_params(&mut self) -> Result<JogCommonParams, Error> { let p = self.read_params(72)?; let mut params_union = JogCommonParamsUnion { bytes: [0; 8] }; let params = unsafe { params_union.bytes.copy_from_slice(&p); params_union.jog_common_params }; Ok(params) } pub fn set_jog_common_params(&mut self, params: JogCommonParams) -> Result<(), Error> { let params_union = JogCommonParamsUnion { jog_common_params: params, }; self.write_params(72, unsafe { params_union.bytes.to_vec() }) } pub fn
(&mut self, mode: JogCommandType, cmd: JogCommand) -> Result<(), Error> { self.write_params(73, vec![mode as u8, cmd as u8]) } pub fn get_ptp_joint_params(&mut self) -> Result<PtpJointParams, Error> { let p = self.read_params(80)?; let mut params_union = PtpJointParamsUnion { bytes: [0; 32] }; let params = unsafe { params_union.bytes.copy_from_slice(&p); params_union.ptp_joint_params }; Ok(params) } pub fn set_ptp_joint_params(&mut self, params: PtpJointParams) -> Result<(), Error> { let params_union = PtpJointParamsUnion { ptp_joint_params: params, }; self.write_params(80, unsafe { params_union.bytes.to_vec() }) } pub fn get_ptp_coordinate_params(&mut self) -> Result<PtpCoordinateParams, Error> { let p = self.read_params(81)?; let mut params_union = PtpCoordinateParamsUnion { bytes: [0; 16] }; let params = unsafe { params_union.bytes.copy_from_slice(&p); params_union.ptp_coordinate_params }; Ok(params) } pub fn set_ptp_coordinate_params(&mut self, params: PtpCoordinateParams) -> Result<(), Error> { let params_union = PtpCoordinateParamsUnion { ptp_coordinate_params: params, }; self.write_params(81, unsafe { params_union.bytes.to_vec() }) } pub fn get_ptp_jump_params(&mut self) -> Result<PtpJumpParams, Error> { let p = self.read_params(82)?; let mut params_union = PtpJumpParamsUnion { bytes: [0; 12] }; let params = unsafe { params_union.bytes.copy_from_slice(&p); params_union.ptp_jump_params }; Ok(params) } pub fn set_ptp_jump_params(&mut self, params: PtpJumpParams) -> Result<(), Error> { let params_union = PtpJumpParamsUnion { ptp_jump_params: params, }; self.write_params(82, unsafe { params_union.bytes.to_vec() }) } pub fn get_ptp_common_params(&mut self) -> Result<PtpCommonParams, Error> { let p = self.read_params(83)?; let mut params_union = PtpCommonParamsUnion { bytes: [0; 8] }; let params = unsafe { params_union.bytes.copy_from_slice(&p); params_union.ptp_common_params }; Ok(params) } pub fn set_ptp_common_params(&mut self, params: PtpCommonParams) -> Result<(), Error> { let params_union = PtpCommonParamsUnion { ptp_common_params: params, }; self.write_params(83, unsafe { params_union.bytes.to_vec() }) } pub fn set_ptp_command(&mut self, command: PtpCommand) -> Result<(), Error> { let command_union = PtpCommandUnion { ptp_command: command, }; self.write_params(84, unsafe { command_union.bytes.to_vec() }) } pub fn set_ptp_command_queued(&mut self, command: PtpCommand) -> Result<u64, Error> { let command_union = PtpCommandUnion { ptp_command: command, }; self.write_queued_params(84, unsafe { command_union.bytes.to_vec() }) } // address = (1 ~ 22), air pump is connected to 18. pub fn set_iodo(&mut self, address: u8, level: IoLevel) -> Result<(), Error> { self.write_params(131, vec![address, level as u8]) } pub fn set_iodo_queued(&mut self, address: u8, level: IoLevel) -> Result<u64, Error> { self.write_queued_params(131, vec![address, level as u8]) } // wait pub fn set_wait_command(&mut self, wait_ms: u32) -> Result<(), Error> { let u = U32Union { val: wait_ms }; self.write_params(110, unsafe { u.bytes.to_vec() }) } pub fn set_wait_command_queued(&mut self, wait_ms: u32) -> Result<u64, Error> { let u = U32Union { val: wait_ms }; self.write_queued_params(110, unsafe { u.bytes.to_vec() }) } pub fn set_arm_orientation(&mut self, l_r: ArmOrientation) -> Result<(), Error> { self.write_params(50, vec![l_r as u8]) } pub fn set_arm_orientation_queued(&mut self, l_r: ArmOrientation) -> Result<u64, Error> { self.write_queued_params(50, vec![l_r as u8]) } pub fn set_queued_command_start_exec(&mut self) -> Result<(), Error> { self.write_params(240, vec![]) } pub fn set_queued_command_stop_exec(&mut self) -> Result<(), Error> { self.write_params(241, vec![]) } pub fn set_queued_command_force_stop_exec(&mut self) -> Result<(), Error> { self.write_params(242, vec![]) } pub fn set_queued_command_clear(&mut self) -> Result<(), Error> { self.write_params(245, vec![]) } pub fn get_queued_command_current_index(&mut self) -> Result<u64, Error> { let params = self.read_params(246)?; let mut u = U64Union { val: 0 }; unsafe { u.bytes.copy_from_slice(&params); Ok(u.val) } } pub fn get_queued_command_left_space(&mut self) -> Result<u32, Error> { let params = self.read_params(247)?; let mut u = U32Union { val: 0 }; unsafe { u.bytes.copy_from_slice(&params); Ok(u.val) } } pub fn get_arm_orientation(&mut self) -> Result<ArmOrientation, Error> { let lr = self.read_params(50)?[0]; Ok(if lr == 0 { ArmOrientation::Lefty } else { ArmOrientation::Righty }) } } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum IoLevel { Low, High, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum ArmOrientation { Lefty, Righty, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum JogCommandType { Cartesian, Joint, } #[repr(u8)] pub enum JogCommand { Idel, ApDown, AnDown, BpDown, BnDown, CpDown, CnDown, DpDown, DnDown, } #[repr(packed)] #[derive(Clone, Copy, Debug)] pub struct Pose { pub x: f32, pub y: f32, pub z: f32, pub r: f32, pub joint_angles: [f32; 4], } //#[repr(C)] union PoseUnion { poses: Pose, bytes: [u8; 32], } //#[repr(C)] union U64Union { val: u64, pub bytes: [u8; 8], } //#[repr(C)] union U32Union { val: u32, pub bytes: [u8; 4], } /// JOG #[repr(packed)] #[derive(Clone, Copy, Debug)] pub struct JogJointParams { pub velocity: [f32; 4], pub acceleration: [f32; 4], } //#[repr(C)] union JogJointParamsUnion { jog_joint_params: JogJointParams, bytes: [u8; 32], } #[repr(packed)] #[derive(Clone, Copy, Debug)] pub struct JogCommonParams { pub velocity_ratio: f32, pub acceleration_ratio: f32, } //#[repr(C)] union JogCommonParamsUnion { jog_common_params: JogCommonParams, bytes: [u8; 8], } /// PTP #[repr(packed)] #[derive(Clone, Copy, Debug)] pub struct PtpJointParams { pub velocity: [f32; 4], pub acceleration: [f32; 4], } #[repr(packed)] union PtpJointParamsUnion { ptp_joint_params: PtpJointParams, bytes: [u8; 32], } //#[repr(C)] #[derive(Clone, Copy, Debug)] pub struct PtpCoordinateParams { pub xyz_velocity: f32, pub r_velocity: f32, pub xyz_acceleration: f32, pub r_acceleration: f32, } //#[repr(C)] union PtpCoordinateParamsUnion { ptp_coordinate_params: PtpCoordinateParams, bytes: [u8; 16], } #[repr(packed)] #[derive(Clone, Copy, Debug)] pub struct PtpJumpParams { pub jump_height: f32, pub z_limit: f32, pub dummy: u32, } #[repr(packed)] union PtpJumpParamsUnion { ptp_jump_params: PtpJumpParams, bytes: [u8; 12], } #[repr(packed)] #[derive(Clone, Copy, Debug)] pub struct PtpCommonParams { pub velocity_ratio: f32, pub acceleration_ratio: f32, } //#[repr(C)] union PtpCommonParamsUnion { ptp_common_params: PtpCommonParams, bytes: [u8; 8], } //#[repr(C)] union PtpCommandUnion { ptp_command: PtpCommand, bytes: [u8; 17], } #[repr(packed)] #[derive(Clone, Copy, Debug)] pub struct PtpCommand { pub ptp_mode: PtpMode, pub x: f32, pub y: f32, pub z: f32, pub r: f32, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum PtpMode { JumpXyz, // JUMP mode, (x,y,z,r) is the target point in Cartesian coordinate system MovjXyz, // MOVJ mode, (x,y,z,r) is the target point in Cartesian coordinate system MovlXyz, // MOVL mode, (x,y,z,r) is the target point in Cartesian coordinate system JumpAngle, // JUMP mode, (x,y,z,r) is the target point in Joint coordinate system MovjAngle, // MOVJ mode, (x,y,z,r) is the target point in Joint coordinate system MovlAngle, // MOVL mode, (x,y,z,r) is the target point in Joint coordinate system MovjInc, // MOVJ mode, (x,y,z,r) is the angle increment in Joint coordinate system MovlInc, // MOVL mode, (x,y,z,r) is the Cartesian coordinate increment in Joint coordinate system MovjXyzInc, // MOVJ mode, (x,y,z,r) is the Cartesian coordinate increment in Cartesian coordinate system JumpMovlXyz, // JUMP mode, (x,y,z,r) is the Cartesian coordinate increment in Cartesian coordinate }
set_jog_command
main.rs
use std::env; use serenity::{ async_trait, model::{ gateway::Ready, id::GuildId, interactions::{ application_command::{ ApplicationCommand, ApplicationCommandInteractionDataOptionValue, ApplicationCommandOptionType, }, Interaction, InteractionResponseType, }, }, prelude::*, }; struct Handler; #[async_trait] impl EventHandler for Handler { async fn interaction_create(&self, ctx: Context, interaction: Interaction) { if let Interaction::ApplicationCommand(command) = interaction { let content = match command.data.name.as_str() { "ping" => "Hey, I'm alive!".to_string(), "id" => { let options = command .data .options .get(0) .expect("Expected user option") .resolved .as_ref() .expect("Expected user object"); if let ApplicationCommandInteractionDataOptionValue::User(user, _member) = options { format!("{}'s id is {}", user.tag(), user.id) } else { "Please provide a valid user".to_string() } }, _ => "not implemented :(".to_string(), }; if let Err(why) = command .create_interaction_response(&ctx.http, |response| { response .kind(InteractionResponseType::ChannelMessageWithSource) .interaction_response_data(|message| message.content(content)) }) .await { println!("Cannot respond to slash command: {}", why); } } } async fn ready(&self, ctx: Context, ready: Ready) { println!("{} is connected!", ready.user.name); let commands = ApplicationCommand::set_global_application_commands(&ctx.http, |commands| { commands .create_application_command(|command| { command.name("ping").description("A ping command") }) .create_application_command(|command| { command.name("id").description("Get a user id").create_option(|option| { option .name("id") .description("The user to lookup") .kind(ApplicationCommandOptionType::User) .required(true) }) }) .create_application_command(|command| { command .name("welcome") .description("Welcome a user") .create_option(|option| { option .name("user") .description("The user to welcome") .kind(ApplicationCommandOptionType::User) .required(true) }) .create_option(|option| { option .name("message") .description("The message to send") .kind(ApplicationCommandOptionType::String) .required(true) .add_string_choice( "Welcome to our cool server! Ask me if you need help", "pizza", ) .add_string_choice("Hey, do you want a coffee?", "coffee") .add_string_choice( "Welcome to the club, you're now a good person. Well, I hope.", "club", ) .add_string_choice( "I hope that you brought a controller to play together!", "game", ) }) }) }) .await; println!("I now have the following global slash commands: {:#?}", commands); let guild_command = GuildId(123456789) .create_application_command(&ctx.http, |command| { command.name("wonderful_command").description("An amazing command") }) .await; println!("I created the following guild command: {:#?}", guild_command); } } #[tokio::main] async fn main()
{ // Configure the client with your Discord bot token in the environment. let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment"); // The Application Id is usually the Bot User Id. let application_id: u64 = env::var("APPLICATION_ID") .expect("Expected an application id in the environment") .parse() .expect("application id is not a valid id"); // Build our client. let mut client = Client::builder(token) .event_handler(Handler) .application_id(application_id) .await .expect("Error creating client"); // Finally, start a single shard, and start listening to events. // // Shards will automatically attempt to reconnect, and will perform // exponential backoff until it reconnects. if let Err(why) = client.start().await { println!("Client error: {:?}", why); } }
ToggleGroup.test.js
const div = document.createElement("div"); document.body.appendChild(div); describe("directive: zen-toggle-group", function() { let element, scope; beforeEach(angular.mock.module("ZenUI")); afterEach(function () { while (div.firstChild) { div.removeChild(div.firstChild); } }); it("should render", function () { inject(function($compile, $rootScope) { scope = $rootScope.$new(); scope.model = null; element = ""+ "<zen-toggle-group>" + "<zen-toggle-radio ng-repeat=\"x in [1,2,3,4]\" zen-model=\"model\" zen-value=\"::x\">{{::x}}</zen-toggle-radio>" + "</zen-toggle-group>";
angular.element(div).append(element); }) expect(div.childNodes).toHaveLength(1); expect(div.firstChild).toMatchSnapshot(); }); it("should render conjoined buttons", function () { inject(function($compile, $rootScope) { scope = $rootScope.$new(); scope.model = null; element = ""+ "<zen-toggle-group zen-conjoined>" + "<zen-toggle-radio ng-repeat=\"x in [1,2,3,4]\" zen-model=\"model\" zen-value=\"::x\">{{::x}}</zen-toggle-radio>" + "</zen-toggle-group>"; element = $compile(element)(scope); scope.$digest(); angular.element(div).append(element); }) expect(div.childNodes).toHaveLength(1); expect(div.firstChild).toMatchSnapshot(); }); });
element = $compile(element)(scope); scope.$digest();
0.19a396a3f2ca5e020fef.hot-update.js
webpackHotUpdate(0,{399:function(module,exports){eval('"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nvar generateMinefield = function generateMinefield(f, x, y, z) {\n return Array.apply(null, Array(x)).map(function () {\n return Array.apply(null, Array(y)).map(function () {\n return Array.apply(null, Array(z)).map(function () {\n return Math.floor(Math.random() * f) % f === 0 ? -1 : 0;\n });\n });\n });\n};\n\nexports.generateMinefield = generateMinefield;\nvar evaluateMinefield = function evaluateMinefield(cube) {\n var getCount = function getCount(arr, x, y, z) {\n var pos = [-1, 0, 1];\n\n return pos.reduce(function (sum, dx) {\n return pos.reduce(function (sum, dy) {\n return pos.reduce(function (sum, dz) {\n var v = arr[x + dx] && arr[x + dx][y + dy] && arr[x + dx][y + dy][z + dz];\n\n if (typeof v !== "undefined") {\n console.log(v, x + dx, y + dy, z + dz);\n }\n\n var i = v === -1 && (dx !== 0 || dy !== 0 || dz !== 0) ? 1 : 0;\n\n return sum + i;\n }, 0);\n });\n });\n };\n\n return cube.map(function (plane, x) {\n return plane.map(function (row, y) {\n return row.map(function (cell, z) {\n return cell === -1 ? -1 : getCount(cube, x, y, z);\n });\n });\n });\n};\nexports.evaluateMinefield = evaluateMinefield;\n\n/*****************\n ** WEBPACK FOOTER\n ** ./app/utils/index.js\n ** module id = 399\n ** module chunks = 0\n **/\n//# sourceURL=webpack:///./app/utils/index.js?')}});
prometheus.go
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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 prometheus import ( "context" "fmt" "math" "time" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-hook-operator/pkg/util/evaluate" metricutil "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-hook-operator/pkg/util/metric" templateutil "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-hook-operator/pkg/util/template" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/kubernetes/common/bcs-hook/apis/tkex/v1alpha1" "github.com/prometheus/client_golang/api" "github.com/prometheus/client_golang/api/prometheus/v1" "github.com/prometheus/common/model" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/klog" ) const ( //ProviderType indicates the provider is prometheus ProviderType = "Prometheus" ) // Provider contains all the required components to run a prometheus query type Provider struct { api v1.API } // Type incidates provider is a prometheus provider func (p *Provider) Type() string { return ProviderType } // Run queries prometheus for the metric func (p *Provider) Run(run *v1alpha1.HookRun, metric v1alpha1.Metric) v1alpha1.Measurement { startTime := metav1.Now() newMeasurement := v1alpha1.Measurement{ StartedAt: &startTime, } //TODO(dthomson) make timeout configuriable ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() query, err := templateutil.ResolveArgs(metric.Provider.Prometheus.Query, run.Spec.Args) if err != nil { return metricutil.MarkMeasurementError(newMeasurement, err) } response, err := p.api.Query(ctx, query, time.Now()) if err != nil { return metricutil.MarkMeasurementError(newMeasurement, err) } newValue, newStatus, err := p.processResponse(metric, response) if err != nil { return metricutil.MarkMeasurementError(newMeasurement, err) } newMeasurement.Value = newValue newMeasurement.Phase = newStatus finishedTime := metav1.Now() newMeasurement.FinishedAt = &finishedTime return newMeasurement } // Resume should not be used the prometheus provider since all the work should occur in the Run method func (p *Provider) Resume(run *v1alpha1.HookRun, metric v1alpha1.Metric, measurement v1alpha1.Measurement) v1alpha1.Measurement { klog.Warningf("HookRun: %s/%s, metric: %s. Prometheus provider should not execute the Resume method", run.Namespace, run.Name, metric.Name) return measurement } // Terminate should not be used the prometheus provider since all the work should occur in the Run method func (p *Provider) Terminate(run *v1alpha1.HookRun, metric v1alpha1.Metric, measurement v1alpha1.Measurement) v1alpha1.Measurement { klog.Warningf("HookRun: %s/%s, metric: %s. Prometheus provider should not execute the Terminate method", run.Namespace, run.Name, metric.Name) return measurement } // GarbageCollect is a no-op for the prometheus provider func (p *Provider) GarbageCollect(run *v1alpha1.HookRun, metric v1alpha1.Metric, limit int) error { return nil } func (p *Provider) evaluateResult(result interface{}, metric v1alpha1.Metric) v1alpha1.HookPhase { successCondition := false failCondition := false var err error if metric.SuccessCondition != "" { successCondition, err = evaluate.EvalCondition(result, metric.SuccessCondition) if err != nil { klog.Warningf(err.Error()) return v1alpha1.HookPhaseError } } if metric.FailureCondition != "" { failCondition, err = evaluate.EvalCondition(result, metric.FailureCondition) if err != nil { return v1alpha1.HookPhaseError } } switch { case metric.SuccessCondition == "" && metric.FailureCondition == "": //Always return success unless there is an error return v1alpha1.HookPhaseSuccessful case metric.SuccessCondition != "" && metric.FailureCondition == "": // Without a failure condition, a measurement is considered a failure if the measurement's success condition is not true failCondition = !successCondition case metric.SuccessCondition == "" && metric.FailureCondition != "": // Without a success condition, a measurement is considered a successful if the measurement's failure condition is not true successCondition = !failCondition } if failCondition { return v1alpha1.HookPhaseFailed } if !failCondition && !successCondition { return v1alpha1.HookPhaseInconclusive } // If we reach this code path, failCondition is false and successCondition is true return v1alpha1.HookPhaseSuccessful } func (p *Provider) processResponse(metric v1alpha1.Metric, response model.Value) (string, v1alpha1.HookPhase, error) { switch value := response.(type) { case *model.Scalar: valueStr := value.Value.String() result := float64(value.Value) if math.IsNaN(result) { return valueStr, v1alpha1.HookPhaseInconclusive, nil } newStatus := p.evaluateResult(result, metric) return valueStr, newStatus, nil case model.Vector: results := make([]float64, 0, len(value)) valueStr := "[" for _, s := range value { if s != nil { valueStr = valueStr + s.Value.String() + "," results = append(results, float64(s.Value)) } } // if we appended to the string, we should remove the last comma on the string if len(valueStr) > 1 { valueStr = valueStr[:len(valueStr)-1] } valueStr = valueStr + "]" for _, result := range results { if math.IsNaN(result) { return valueStr, v1alpha1.HookPhaseInconclusive, nil } } newStatus := p.evaluateResult(results, metric) return valueStr, newStatus, nil default: return "", v1alpha1.HookPhaseError, fmt.Errorf("Prometheus metric type not supported") } } // NewPrometheusProvider Creates a new Prometheus client func NewPrometheusProvider(api v1.API) *Provider { return &Provider{ api: api, } } // NewPrometheusAPI generates a prometheus API from the metric configuration func NewPrometheusAPI(metric v1alpha1.Metric) (v1.API, error)
{ client, err := api.NewClient(api.Config{ Address: metric.Provider.Prometheus.Address, }) if err != nil { return nil, err } return v1.NewAPI(client), nil }
Switches.js
import React, { Component } from 'react'; import { Card, CardBody, CardHeader, Col, Row, Table } from 'reactstrap'; import { AppSwitch } from '../../../core/index' class
extends Component { render() { return ( <div className="animated fadeIn"> <Row> <Col xs="12" md="6"> <Card> <CardHeader> Switch default </CardHeader> <CardBody> <AppSwitch className={'mx-1'} color={'primary'} checked /> <AppSwitch className={'mx-1'} color={'secondary'} checked /> <AppSwitch className={'mx-1'} color={'success'} checked /> <AppSwitch className={'mx-1'} color={'warning'} checked /> <AppSwitch className={'mx-1'} color={'info'} checked /> <AppSwitch className={'mx-1'} color={'danger'} checked /> <AppSwitch className={'mx-1'} color={'light'} checked /> <AppSwitch className={'mx-1'} color={'dark'} checked /> <AppSwitch className={'mx-1'} color={'primary'} disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch pills </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'secondary'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'success'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'warning'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'info'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'danger'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'light'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'dark'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> 3d Switch {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} defaultChecked /> <AppSwitch className={'mx-1'} variant={'3d'} color={'secondary'} defaultChecked /> <AppSwitch className={'mx-1'} variant={'3d'} color={'success'} defaultChecked /> <AppSwitch className={'mx-1'} variant={'3d'} color={'warning'} defaultChecked /> <AppSwitch className={'mx-1'} variant={'3d'} color={'info'} defaultChecked /> <AppSwitch className={'mx-1'} variant={'3d'} color={'danger'} defaultChecked /> <AppSwitch className={'mx-1'} variant={'3d'} color={'light'} defaultChecked /> <AppSwitch className={'mx-1'} variant={'3d'} color={'dark'} defaultChecked /> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> 3d Switch <small><code>disabled</code></small> {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} checked disabled /> <AppSwitch className={'mx-1'} variant={'3d'} color={'secondary'} checked disabled /> <AppSwitch className={'mx-1'} variant={'3d'} color={'success'} checked disabled /> <AppSwitch className={'mx-1'} variant={'3d'} color={'warning'} checked disabled /> <AppSwitch className={'mx-1'} variant={'3d'} color={'info'} checked disabled /> <AppSwitch className={'mx-1'} variant={'3d'} color={'danger'} checked disabled /> <AppSwitch className={'mx-1'} variant={'3d'} color={'light'} checked disabled /> <AppSwitch className={'mx-1'} variant={'3d'} color={'dark'} checked disabled /> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> 3d Switch <small><code>outline="alt"</code></small> {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} checked outline={'alt'} /> <AppSwitch className={'mx-1'} variant={'3d'} color={'secondary'} checked outline={'alt'} /> <AppSwitch className={'mx-1'} variant={'3d'} color={'success'} checked outline={'alt'} /> <AppSwitch className={'mx-1'} variant={'3d'} color={'warning'} checked outline={'alt'} /> <AppSwitch className={'mx-1'} variant={'3d'} color={'info'} checked outline={'alt'} /> <AppSwitch className={'mx-1'} variant={'3d'} color={'danger'} checked outline={'alt'} /> <AppSwitch className={'mx-1'} variant={'3d'} color={'light'} checked outline={'alt'} /> <AppSwitch className={'mx-1'} variant={'3d'} color={'dark'} checked outline={'alt'} /> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} outline={'alt'} disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> 3d Switch <small><code>label</code></small> {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'3d'} color={'secondary'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} color={'success'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} color={'warning'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} color={'info'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} color={'danger'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} color={'light'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} color={'dark'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} label dataOn={'\u2713'} dataOff={'\u2715'}/> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> 3d Switch <small><code>outline="alt" label</code></small> {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'primary'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'secondary'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'success'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'warning'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'info'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'danger'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'light'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'dark'} defaultChecked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'primary'} label dataOn={'\u2713'} dataOff={'\u2715'}/> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> 3d Switch <small><code>outline="alt" label</code></small> {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'primary'} defaultChecked label /> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'secondary'} defaultChecked label /> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'success'} defaultChecked label /> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'warning'} defaultChecked label /> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'info'} defaultChecked label /> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'danger'} defaultChecked label /> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'light'} defaultChecked label /> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'dark'} defaultChecked label /> <AppSwitch className={'mx-1'} variant={'3d'} outline={'alt'} color={'primary'} label /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch outline {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} color={'primary'} outline checked /> <AppSwitch className={'mx-1'} color={'secondary'} outline checked /> <AppSwitch className={'mx-1'} color={'success'} outline checked /> <AppSwitch className={'mx-1'} color={'warning'} outline checked /> <AppSwitch className={'mx-1'} color={'info'} outline checked /> <AppSwitch className={'mx-1'} color={'danger'} outline checked /> <AppSwitch className={'mx-1'} color={'light'} outline checked /> <AppSwitch className={'mx-1'} color={'dark'} outline checked /> <AppSwitch className={'mx-1'} color={'primary'} outline disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch outline pills {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'secondary'} outline checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'success'} outline checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'warning'} outline checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'info'} outline checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'danger'} outline checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'light'} outline checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'dark'} outline checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch outline alternative {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} color={'primary'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} color={'secondary'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} color={'success'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} color={'warning'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} color={'info'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} color={'danger'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} color={'light'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} color={'dark'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} color={'primary'} outline={'alt'} disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch outline alternative - pills {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'secondary'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'success'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'warning'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'info'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'danger'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'light'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'dark'} outline={'alt'} checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline={'alt'} disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} color={'primary'} label checked /> <AppSwitch className={'mx-1'} color={'secondary'} label checked /> <AppSwitch className={'mx-1'} color={'success'} label checked /> <AppSwitch className={'mx-1'} color={'warning'} label checked /> <AppSwitch className={'mx-1'} color={'info'} label checked /> <AppSwitch className={'mx-1'} color={'danger'} label checked /> <AppSwitch className={'mx-1'} color={'light'} label checked /> <AppSwitch className={'mx-1'} color={'dark'} label checked /> <AppSwitch className={'mx-1'} color={'primary'} label disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text pills {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'secondary'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'success'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'warning'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'info'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'danger'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'light'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'dark'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} label disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text outline {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} color={'primary'} outline label checked /> <AppSwitch className={'mx-1'} color={'secondary'} outline label checked /> <AppSwitch className={'mx-1'} color={'success'} outline label checked /> <AppSwitch className={'mx-1'} color={'warning'} outline label checked /> <AppSwitch className={'mx-1'} color={'info'} outline label checked /> <AppSwitch className={'mx-1'} color={'danger'} outline label checked /> <AppSwitch className={'mx-1'} color={'light'} outline label checked /> <AppSwitch className={'mx-1'} color={'dark'} outline label checked /> <AppSwitch className={'mx-1'} color={'primary'} outline label disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text outline pills {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'secondary'} outline label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'success'} outline label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'warning'} outline label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'info'} outline label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'danger'} outline label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'light'} outline label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'dark'} outline label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline label disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text outline alternative pills {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} color={'primary'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} color={'secondary'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} color={'success'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} color={'warning'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} color={'info'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} color={'danger'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} color={'light'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} color={'dark'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} color={'primary'} outline={'alt'} label disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text outline alternative pills {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'secondary'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'success'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'warning'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'info'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'danger'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'light'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'dark'} outline={'alt'} label checked /> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline={'alt'} label disabled /> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text outline alternative {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} color={'primary'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'secondary'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'success'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'warning'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'info'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} color={'danger'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'light'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'dark'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'primary'} outline disabled label dataOn={'\u2713'} dataOff={'\u2715'}/> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text outline alternative pills {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'secondary'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'success'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'warning'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'info'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'danger'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'light'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'dark'} outline checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline disabled label dataOn={'\u2713'} dataOff={'\u2715'}/> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text outline alternative {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} color={'primary'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'secondary'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'success'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'warning'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'info'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} color={'danger'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'light'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'dark'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'}/> <AppSwitch className={'mx-1'} color={'primary'} outline={'alt'} disabled label dataOn={'\u2713'} dataOff={'\u2715'}/> </CardBody> </Card> </Col> <Col xs="12" md="6"> <Card> <CardHeader> Switch with text outline alternative pills {' '}<a href="https://coreui.io/pro/react/" className="badge badge-danger">CoreUI Pro</a> </CardHeader> <CardBody> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'secondary'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'success'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'warning'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'info'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'danger'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'light'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'dark'} outline={'alt'} checked label dataOn={'\u2713'} dataOff={'\u2715'} /> <AppSwitch className={'mx-1'} variant={'pill'} color={'primary'} outline={'alt'} disabled label dataOn={'\u2713'} dataOff={'\u2715'}/> </CardBody> </Card> </Col> <Col xs="12"> <Card> <CardHeader> Sizes </CardHeader> <CardBody className="p-0"> <Table hover striped className="table-align-middle mb-0"> <thead> <tr> <th>Size</th> <th>Example</th> <th>Props</th> </tr> </thead> <tbody> <tr> <td> Large </td> <td> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} checked size={'lg'} /> </td> <td> Add <code>size={'lg'}</code> </td> </tr> <tr> <td> Normal </td> <td> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} checked /> </td> <td> - </td> </tr> <tr> <td> Small </td> <td> <AppSwitch className={'mx-1'} variant={'3d'} color={'primary'} checked size={'sm'} /> </td> <td> Add <code>size={'sm'}</code> </td> </tr> </tbody> </Table> </CardBody> </Card> </Col> </Row> </div> ); } } export default Switches;
Switches
entropic_adaptive.rs
use{ crate::{*, traits::*}, rand::{Rng, seq::*}, std::{ marker::PhantomData, io::Write, iter::*, collections::*, convert::* } }; #[cfg(feature = "serde_support")] use serde::{Serialize, Deserialize}; #[derive(Debug, Clone)] #[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] /// Error states, that entropic sampling, or the creation of `EntropicSamplingAdaptive` /// could encounter pub enum EntropicErrors { /// # source (`WangLandauAdaptive`) was in an invalid state /// * did you forget to use one of the `init*` methods to initialize a valid /// WangLandau state? InvalidWangLandau, /// Still in the process of gathering statistics /// Not enough to make an estimate NotEnoughStatistics, /// Still Gathering Statistics, this is only an estimate! EstimatedStatistic(Vec<f64>), /// Invalid trial step. Is your max_step smaller than your min_step? InvalidMinMaxTrialSteps, /// # Posible reasons /// * `log_density.len()` and `histogram.bin_count()` are not equal /// * not all values of `log_density` are finite InvalidLogDensity, /// You are trying to have a `min_best_of_count` that is /// larger than the total steps you try! InvalidBestof, } /// # Entropic sampling made easy /// > J. Lee, /// > “New Monte Carlo algorithm: Entropic sampling,” /// > Phys. Rev. Lett. 71, 211–214 (1993), /// > DOI: [10.1103/PhysRevLett.71.211](https://doi.org/10.1103/PhysRevLett.71.211) #[derive(Debug, Clone)] #[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] pub struct EntropicSamplingAdaptive<Hist, R, E, S, Res, T> { rng: R, trial_list: Vec<usize>, best_of_steps: Vec<usize>, min_best_of_count: usize, best_of_threshold: f64, ensemble: E, steps: Vec<S>, step_res_marker: PhantomData<Res>, accepted_step_hist: Vec<usize>, rejected_step_hist: Vec<usize>, total_steps_rejected: usize, total_steps_accepted: usize, wl_steps_accepted: usize, wl_steps_rejected: usize, min_step: usize, counter: usize, step_count: usize, step_goal: usize, histogram: Hist, log_density: Vec<f64>, old_energy: T, old_bin: usize, adjust_bestof_every: usize, } impl<Hist, R, E, S, Res, T> TryFrom<WangLandauAdaptive<Hist, R, E, S, Res, T>> for EntropicSamplingAdaptive<Hist, R, E, S, Res, T> where Hist: Histogram, R: Rng { type Error = EntropicErrors; fn try_from(mut wl: WangLandauAdaptive<Hist, R, E, S, Res, T>) -> Result<Self, Self::Error> { if wl.old_bin.is_none() || wl.old_energy.is_none() { return Err(EntropicErrors::InvalidWangLandau); } let wl_steps_rejected = wl.total_steps_rejected(); let wl_steps_accepted = wl.total_steps_accepted(); wl.accepted_step_hist .iter_mut() .for_each(|v| *v = 0); wl.rejected_step_hist .iter_mut() .for_each(|v| *v = 0); wl.best_of_steps.clear(); wl.histogram.reset(); wl.trial_list.shuffle(&mut wl.rng); Ok( Self{ wl_steps_rejected, wl_steps_accepted, counter: 0, steps: wl.steps, step_res_marker: wl.step_res_marker, log_density: wl.log_density, old_energy: wl.old_energy.unwrap(), old_bin: wl.old_bin.unwrap(), accepted_step_hist: wl.accepted_step_hist, rejected_step_hist: wl.rejected_step_hist, total_steps_accepted: 0, total_steps_rejected: 0, min_step: wl.min_step, min_best_of_count: wl.min_best_of_count, best_of_steps: wl.best_of_steps, best_of_threshold: wl.best_of_threshold, rng: wl.rng, trial_list: wl.trial_list, ensemble: wl.ensemble, step_count: 0, step_goal: wl.step_count, histogram: wl.histogram, adjust_bestof_every: 10usize.max(4 * wl.check_refine_every), } ) } } impl<Hist, R, E, S, Res, T> EntropicSamplingAdaptive<Hist, R, E, S, Res, T> { /// # Current state of the Ensemble #[inline] pub fn ensemble(&self) -> &E { &self.ensemble } /// # Energy of ensemble /// * assuming `energy_fn` (see `self.entropic_step` etc.) /// is deterministic and will allways give the same result for the same ensemble, /// this returns the energy of the current ensemble #[inline] pub fn energy(&self) -> &T { &self.old_energy } /// # Number of entropic steps done until now /// * will be reset by [`self.refine_estimate`](#method.refine_estimate) #[inline] pub fn step_count(&self) -> usize { self.step_count } /// # Number of entropic steps to be performed /// * if `self` was created from `WangLandauAdaptive`, /// `step_goal` will be equal to the number of WangLandau steps, that were performed #[inline] pub fn step_goal(&self) -> usize { self.step_goal } /// # Number of entropic steps to be performed /// * set the number of steps to be performed by entropic sampling #[inline] pub fn set_step_goal(&mut self, step_goal: usize){ self.step_goal = step_goal; } /// # Smallest possible markov step (`m_steps` of MarkovChain trait) by entropic step #[inline] pub fn min_step_size(&self) -> usize { self.min_step } /// # Largest possible markov step (`m_steps` of MarkovChain trait) by entropic step #[inline] pub fn max_step_size(&self) -> usize { self.min_step + self.accepted_step_hist.len() - 1 } /// # Currently used best of /// * might have length 0, if statistics are still being gathered /// * otherwise this contains the step sizes, from which the next stepsize /// is drawn uniformly #[inline] pub fn best_of_steps(&self) -> &Vec<usize> { &self.best_of_steps } /// # Fraction of steps accepted since the statistics were reset the last time /// * (steps accepted since last reset) / (steps since last reset) /// * `NaN` if no steps were performed yet pub fn fraction_accepted_current(&self) -> f64 { let accepted: usize = self.accepted_step_hist.iter().sum(); let total = accepted + self.rejected_step_hist.iter().sum::<usize>(); if total == 0 { f64::NAN } else { accepted as f64 / total as f64 } } /// # total number of entropic steps, that were accepted pub fn total_entr_steps_accepted(&self) -> usize { self.total_steps_accepted + self.accepted_step_hist .iter() .sum::<usize>() } /// # total number of entropic steps, that were rejected pub fn total_entr_steps_rejected(&self) -> usize { self.total_steps_rejected + self.rejected_step_hist .iter() .sum::<usize>() } /// # Fraction of steps accepted since the creation of `self` /// * `NaN` if no steps were performed yet pub fn fraction_accepted_total_entropic(&self) -> f64 { let total_acc = self.total_entr_steps_accepted(); let total_steps = total_acc + self.total_entr_steps_rejected(); if total_steps == 0 { f64::NAN } else { total_acc as f64 / total_steps as f64 } } /// * returns the (non normalized) log_density estimate log(P(E)), with which the simulation was started /// * if you created this from a WangLandau simulation, this is the result of the WangLandau Simulation pub fn log_density_estimate(&self) -> &Vec<f64> { &self.log_density } /// # Return current state of histogram pub fn hist(&self) -> &Hist { &self.histogram } } impl<Hist, R, E, S, Res, T> EntropicSamplingAdaptive<Hist, R, E, S, Res, T> where Hist: Histogram, R: Rng { /// # Creates EntropicSamplingAdaptive from a `WangLandauAdaptive` state /// * `WangLandauAdaptive` state needs to be valid, i.e., you must have called one of the `init*` methods /// - this ensures, that the members `old_energy` and `old_bin` are not `None` pub fn from_wl_adaptive(wl: WangLandauAdaptive<Hist, R, E, S, Res, T>) -> Result<Self, EntropicErrors> { wl.try_into() } /// calculates the (non normalized) log_density estimate log(P(E)) according to the [paper](#entropic-sampling-made-easy) pub fn log_density_refined(&self) -> Vec<f64> { let mut log_density = Vec::with_capacity(self.log_density.len()); log_density.extend( self.log_density .iter() .zip(self.histogram.hist().iter()) .map( |(&log_p, &h)| { if h == 0 { log_p } else { log_p + (h as f64).ln() } } ) ); log_density } /// # Calculates `self.log_density_refined` and uses that as estimate for a the entropic sampling simulation /// * returns old estimate /// # prepares `self` for a new entropic simulation /// * sets new estimate for log(P(E)) /// * resets statistic gathering /// * resets step_count pub fn refine_estimate(&mut self) -> Vec<f64> { let mut estimate = self.log_density_refined(); std::mem::swap(&mut estimate, &mut self.log_density); self.counter = 0; self.step_count = 0; self.best_of_steps.clear(); self.histogram.reset(); self.trial_list.shuffle(&mut self.rng); self.total_steps_accepted += self.accepted_step_hist.iter().sum::<usize>(); self.accepted_step_hist .iter_mut() .for_each(|entry| *entry = 0); self.total_steps_rejected += self.rejected_step_hist.iter().sum::<usize>(); self.rejected_step_hist .iter_mut() .for_each(|entry| *entry = 0); estimate } /// # How often to adjust `bestof_steps`? /// * if you try to set a value smaller 10, it will be set to 10 /// * will reevalute the statistics every `adjust_bestof_every` steps, /// - this will not start new statistics gathering but just trigger a reevaluation of /// the gathered statistics (should be O(max_stepsize - min_stepsize)) #[inline] pub fn set_adjust_bestof_every(&mut self, adjust_bestof_every: usize) { self.adjust_bestof_every = adjust_bestof_every.max(10); } /// Is the simulation in the process of rebuilding the statistics, /// i.e., is it currently trying many differnt step sizes? #[inline] pub fn is_rebuilding_statistics(&self) -> bool { self.counter < self.trial_list.len() } fn statistic_bin_not_hit(&self) -> bool { self.accepted_step_hist .iter() .zip(self.rejected_step_hist.iter()) .any(|(a, r )| a + r == 0) } /// # Estimate accept/reject statistics /// * contains list of estimated probabilities for accepting a step of corresponding step size /// * list\[i\] corresponds to step size `i + self.min_step` /// * O(trial_step_max - trial_step_min) pub fn estimate_statistics(&self) -> Result<Vec<f64>, WangLandauErrors> { let calc_estimate = || { let mut estimate = Vec::with_capacity(self.accepted_step_hist.len()); estimate.extend( self.accepted_step_hist .iter() .zip( self.rejected_step_hist.iter() ).map(|(&a, &r)| { a as f64 / (a + r) as f64 } ) ); estimate }; if self.is_rebuilding_statistics() { if self.statistic_bin_not_hit() { Err(WangLandauErrors::NotEnoughStatistics) } else{ Err(WangLandauErrors::EstimatedStatistic(calc_estimate())) } } else { Ok( calc_estimate() ) } } fn generate_bestof(&mut self) { let statistics = self.estimate_statistics().unwrap(); let mut heap = BinaryHeap::with_capacity(statistics.len()); heap.extend(statistics.into_iter() .enumerate() .map(|(index, prob)| { ProbIndex::new(prob, index) } ) ); while let Some(p_i) = heap.pop() { if p_i.is_best_of(self.best_of_threshold) || self.best_of_steps.len() < self.min_best_of_count { let step_size = p_i.index + self.min_step; self.best_of_steps.push(step_size); } else { break; } } } fn adjust_bestof(&mut self){ self.best_of_steps.clear(); self.generate_bestof(); } fn get_stepsize(&mut self) -> usize { match self.trial_list.get(self.counter) { None => { if self.best_of_steps.is_empty(){ self.generate_bestof(); } else if self.counter % self.adjust_bestof_every == 0 { self.adjust_bestof(); } *self.best_of_steps.choose(&mut self.rng).unwrap() }, Some(&step_size) => { step_size }, } } #[inline] fn count_accepted(&mut self, size: usize){ self.accepted_step_hist[size - self.min_step] += 1; self.counter += 1; } #[inline] fn count_rejected(&mut self, size: usize){ self.rejected_step_hist[size - self.min_step] += 1; self.counter += 1; } /// **panics** if index is invalid #[inline(always)] fn metropolis_acception_prob(&self, new_bin: usize) -> f64 { (self.log_density[self.old_bin] - self.log_density[new_bin]) .exp() } } impl<Hist, R, E, S, Res, T> EntropicSamplingAdaptive<Hist, R, E, S, Res, T> where Hist: Histogram + HistogramVal<T>, R: Rng, E: MarkovChain<S, Res>, T: Clone, { /// # Entropic sampling /// * performs `self.entropic_step(energy_fn)` until `condition` is false /// * **Note**: you have access to the current step_count (`self.step_count()`) /// # Parameter /// * `energy_fn` function calculating `Some(energy)` of the system /// or rather the Parameter of which you wish to obtain the probability distribution. /// If there are any states, for which the calculation is invalid, `None` should be returned /// * steps resulting in ensembles for which `energy_fn(&mut ensemble)` is `None` /// will always be rejected /// * **Important** `energy_fn`: should be the same as used for Wang Landau, otherwise the results will be wrong! /// * `print_fn`: see below /// # Correlations /// * if you want to measure correlations between "energy" and other measurable quantities, /// use `print_fn`, which will be called after each step - use this function to write to /// a file or whatever you desire /// * Note: You do not have to recalculate the energy, if you need it in `print_fn`: /// just call `self.energy()` /// * you have access to your ensemble with `self.ensemble()` /// * if you do not need it, you can use `|_|{}` as `print_fn` pub unsafe fn entropic_sampling_while_unsafe<F, G, W>( &mut self, mut energy_fn: F, mut print_fn: G, mut condition: W ) where F: FnMut(&mut E) -> Option<T>, G: FnMut(&Self), W: FnMut(&Self) -> bool { while condition(self) { self.entropic_step_unsafe(&mut energy_fn); print_fn(self); } } /// # Entropic sampling /// * performs `self.entropic_step(energy_fn)` until `condition` is false /// * **Note**: you have access to the current step_count (`self.step_count()`) /// # Parameter /// * `energy_fn` function calculating `Some(energy)` of the system /// or rather the Parameter of which you wish to obtain the probability distribution. /// If there are any states, for which the calculation is invalid, `None` should be returned /// * steps resulting in ensembles for which `energy_fn(&mut ensemble)` is `None` /// will always be rejected /// * **Important** `energy_fn`: should be the same as used for Wang Landau, otherwise the results will be wrong! /// * `print_fn`: see below /// # Correlations /// * if you want to measure correlations between "energy" and other measurable quantities, /// use `print_fn`, which will be called after each step - use this function to write to /// a file or whatever you desire /// * Note: You do not have to recalculate the energy, if you need it in `print_fn`: /// just call `self.energy()` /// * you have access to your ensemble with `self.ensemble()` /// * if you do not need it, you can use `|_|{}` as `print_fn` pub fn entropic_sampling_while<F, G, W>( &mut self, mut energy_fn: F, mut print_fn: G, mut condition: W ) where F: FnMut(&E) -> Option<T>, G: FnMut(&Self), W: FnMut(&Self) -> bool { while condition(self) { self.entropic_step(&mut energy_fn); print_fn(self); } } /// # Entropic sampling using an accumulating markov step /// * performs `self.entropic_step_acc(&mut energy_fn)` until `condition(self) == false` /// # Parameter /// * `energy_fn` function calculating the energy `E` of the system /// (or rather the Parameter of which you wish to obtain the probability distribution) /// during the markov steps, which can be more efficient. /// * **Important** `energy_fn`: should be the same as used for Wang Landau, otherwise the results will be wrong! /// * `print_fn`: see below /// # Correlations /// * if you want to measure correlations between "energy" and other measurable quantities, /// use `print_fn`, which will be called after each step - use this function to write to /// a file or whatever you desire /// * Note: You do not have to recalculate the energy, if you need it in `print_fn`: /// just call `self.energy()` /// * you have access to your ensemble with `self.ensemble()` /// * if you do not need it, you can use `|_|{}` as `print_fn` pub fn entropic_sampling_while_acc<F, G, W>( &mut self, mut energy_fn: F, mut print_fn: G, mut condition: W ) where F: FnMut(&E, &S, &mut T), G: FnMut(&Self), W: FnMut(&Self) -> bool { while condition(self) { self.entropic_step_acc(&mut energy_fn); print_fn(self); } } /// # Entropic sampling /// * if possible, use `self.entropic_sampling()` instead! /// * More powerful version of `self.entropic_sampling()`, since you now have mutable access /// * to access ensemble mutable, use `self.ensemble_mut()` /// * Note: Whatever you do with the ensemble (or self), should not change the result of the energy function, if performed again. /// Otherwise the results will be false! /// * performs `self.entropic_step_unsafe(energy_fn)` until `self.step_count == self.step_goal` /// # Parameter /// * `energy_fn` function calculating `Some(energy)` of the system /// or rather the Parameter of which you wish to obtain the probability distribution. /// If there are any states, for which the calculation is invalid, `None` should be returned /// * steps resulting in ensembles for which `energy_fn(&mut ensemble)` is `None` /// will always be rejected /// * **Important** `energy_fn`: should be the same as used for Wang Landau, otherwise the results will be wrong! /// * `print_fn`: see below /// # Correlations /// * if you want to measure correlations between "energy" and other measurable quantities, /// use `print_fn`, which will be called after each step - use this function to write to /// a file or whatever you desire /// * Note: You do not have to recalculate the energy, if you need it in `print_fn`: /// just call `self.energy()` /// * you have access to your ensemble with `self.ensemble()` /// * if you do not need it, you can use `|_|{}` as `print_fn` pub unsafe fn entropic_sampling_unsafe<F, G>( &mut self, mut energy_fn: F, mut print_fn: G, ) where F: FnMut(&mut E) -> Option<T>, G: FnMut(&mut Self) { while self.step_count < self.step_goal { self.entropic_step_unsafe(&mut energy_fn); print_fn(self); } } /// # Entropic sampling /// * performs `self.entropic_step(energy_fn)` until `self.step_count == self.step_goal` /// # Parameter /// * `energy_fn` function calculating `Some(energy)` of the system /// or rather the Parameter of which you wish to obtain the probability distribution. /// If there are any states, for which the calculation is invalid, `None` should be returned /// * steps resulting in ensembles for which `energy_fn(&mut ensemble)` is `None` /// will always be rejected /// * **Important** `energy_fn`: should be the same as used for Wang Landau, otherwise the results will be wrong! /// * `print_fn`: see below /// # Correlations /// * if you want to measure correlations between "energy" and other measurable quantities, /// use `print_fn`, which will be called after each step - use this function to write to /// a file or whatever you desire /// * Note: You do not have to recalculate the energy, if you need it in `print_fn`: /// just call `self.energy()` /// * you have access to your ensemble with `self.ensemble()` /// * if you do not need it, you can use `|_|{}` as `print_fn` pub fn entropic_sampling<F, G>( &mut self, mut energy_fn: F, mut print_fn: G, ) where F: FnMut(&E) -> Option<T>, G: FnMut(&Self) { while self.step_count < self.step_goal { self.entropic_step(&mut energy_fn); print_fn(self); } } /// # Entropic sampling using an accumulating markov step /// * performs `self.entropic_step_acc(&mut energy_fn)` until `self.step_count == self.step_goal` /// # Parameter /// * `energy_fn` function calculating the energy `E` of the system /// (or rather the Parameter of which you wish to obtain the probability distribution) /// during the markov steps, which can be more efficient. /// * **Important** `energy_fn`: should be the same as used for Wang Landau, otherwise the results will be wrong! /// * `print_fn`: see below /// # Correlations /// * if you want to measure correlations between "energy" and other measurable quantities, /// use `print_fn`, which will be called after each step - use this function to write to /// a file or whatever you desire /// * Note: You do not have to recalculate the energy, if you need it in `print_fn`: /// just call `self.energy()` /// * you have access to your ensemble with `self.ensemble()` /// * if you do not need it, you can use `|_|{}` as `print_fn` pub fn entropic_sampling_acc<F, G>( &mut self, mut energy_fn: F, mut print_fn: G, ) where F: FnMut(&E, &S, &mut T), G: FnMut(&Self) { while self.step_count < self.step_goal { self.entropic_step_acc(&mut energy_fn); print_fn(self); } } /// # Entropic step /// * performs a single step /// # Parameter /// * `energy_fn` function calculating `Some(energy)` of the system /// or rather the Parameter of which you wish to obtain the probability distribution. /// If there are any states, for which the calculation is invalid, `None` should be returned /// * steps resulting in ensembles for which `energy_fn(&mut ensemble)` is `None` /// will always be rejected /// # Important /// * `energy_fn`: should be the same as used for Wang Landau, otherwise the results will be wrong! pub unsafe fn entropic_step_unsafe<F>( &mut self, mut energy_fn: F, )where F: FnMut(&mut E) -> Option<T> { self.step_count += 1; let step_size = self.get_stepsize(); self.ensemble.m_steps(step_size, &mut self.steps); let current_energy = match energy_fn(&mut self.ensemble) { Some(energy) => energy, None => { self.count_rejected(step_size); self.histogram.count_index(self.old_bin).unwrap(); self.ensemble.undo_steps_quiet(&self.steps); return; } }; self.entropic_step_helper(current_energy); } /// # Entropic step /// * performs a single step /// # Parameter /// * `energy_fn` function calculating `Some(energy)` of the system /// or rather the Parameter of which you wish to obtain the probability distribution. /// If there are any states, for which the calculation is invalid, `None` should be returned /// * steps resulting in ensembles for which `energy_fn(&mut ensemble)` is `None` /// will always be rejected /// # Important /// * `energy_fn`: should be the same as used for Wang Landau, otherwise the results will be wrong! pub fn entropic_step<F>( &mut self, mut energy_fn: F, )where F: FnMut(&E) -> Option<T> { unsafe{ self.entropic_step_unsafe(|e| energy_fn(e)) } } /// # Accumulating entropic step /// * performs a single step /// # Parameter /// * `energy_fn` function calculating the energy `E` of the system /// (or rather the Parameter of which you wish to obtain the probability distribution) /// during the markov steps, which can be more efficient. /// # Important /// * `energy_fn`: should be the same as used for Wang Landau, otherwise the results will be wrong! pub fn entropic_step_acc<F>( &mut self, energy_fn: F, ) where F: FnMut(&E, &S, &mut T) { self.step_count += 1; let step_size = self.get_stepsize(); let mut current_energy = self.old_energy.clone(); self.ensemble.m_steps_acc( step_size, &mut self.steps, &mut current_energy, energy_fn ); self.entropic_step_helper(current_energy); } fn entropic_step_helper(&mut self, current_energy: T) { let step_size = self.steps.len(); match self.histogram.get_bin_index(&current_energy) { Ok(current_bin) => {
_ => { // invalid step -> reject self.count_rejected(step_size); self.ensemble.undo_steps_quiet(&self.steps); } }; self.histogram.count_index(self.old_bin).unwrap(); } } impl<Hist, R, E, S, Res, T> Entropic for EntropicSamplingAdaptive<Hist, R, E, S, Res, T> where Hist: Histogram, R: Rng { /// # Number of entropic steps done until now /// * will be reset by [`self.refine_estimate`](#method.refine_estimate) #[inline] fn step_counter(&self) -> usize { self.step_count } fn total_steps_accepted(&self) -> usize { self.total_entr_steps_accepted() + self.wl_steps_accepted } fn total_steps_rejected(&self) -> usize { self.total_entr_steps_rejected() + self.wl_steps_rejected } /// # Number of entropic steps to be performed /// * if `self` was created from `WangLandauAdaptive`, /// `step_goal` will be equal to the number of WangLandau steps, that were performed #[inline] fn step_goal(&self) -> usize { self.step_goal } fn log_density(&self) -> Vec<f64> { self.log_density_refined() } fn write_log<W: Write>(&self, mut w: W) -> Result<(), std::io::Error> { writeln!(w, "#Acceptance prob_total: {}\n#Acceptance prob current: {}\n#total_steps: {}", self.fraction_accepted_total(), self.fraction_accepted_current(), self.step_counter(), )?; writeln!(w, "#min_step_size {}", self.min_step_size())?; writeln!(w, "#max_step_size {}", self.max_step_size())?; write!(w, "#Current acception histogram:")?; for val in self.accepted_step_hist.iter() { write!(w, " {}", val)?; } write!(w, "\n#Current rejection histogram:")?; for val in self.rejected_step_hist.iter() { write!(w, " {}", val)?; } writeln!(w, "\n#bestof threshold: {}", self.best_of_threshold)?; writeln!(w, "#min_bestof_count: {}", self.min_best_of_count)?; write!(w, "\n#Current_Bestof:")?; for val in self.best_of_steps.iter() { write!(w, " {}", val)?; } write!(w, "#current_statistics_estimate:")?; let estimate = self.estimate_statistics(); match estimate { Ok(estimate) => { for val in estimate { write!(w, " {}", val)?; } writeln!(w) }, _ => { writeln!(w, " None") } } } } impl<Hist, R, E, S, Res, Energy> EntropicEnergy<Energy> for EntropicSamplingAdaptive<Hist, R, E, S, Res, Energy> where Hist: Histogram, R: Rng, { /// # Energy of ensemble /// * assuming `energy_fn` (see `self.entropic_step` etc.) /// is deterministic and will allways give the same result for the same ensemble, /// this returns the energy of the current ensemble #[inline] fn energy(&self) -> &Energy { &self.old_energy } } impl<Hist, R, E, S, Res, Energy> EntropicHist<Hist> for EntropicSamplingAdaptive<Hist, R, E, S, Res, Energy> where Hist: Histogram, R: Rng, { #[inline] fn hist(&self) -> &Hist { &self.histogram } } impl<Hist, R, E, S, Res, Energy> EntropicEnsemble<E> for EntropicSamplingAdaptive<Hist, R, E, S, Res, Energy> where Hist: Histogram, R: Rng, { fn ensemble(&self) -> &E { &self.ensemble } unsafe fn ensemble_mut(&mut self) -> &mut E { &mut self.ensemble } } impl<Hist, R, E, S, Res, Energy> HasRng<R> for EntropicSamplingAdaptive<Hist, R, E, S, Res, Energy> where R: Rng, { fn rng(&mut self) -> &mut R { &mut self.rng } fn swap_rng(&mut self, rng: &mut R) { std::mem::swap(&mut self.rng, rng); } }
let accept_prob = self.metropolis_acception_prob(current_bin); if self.rng.gen::<f64>() > accept_prob { // reject step self.count_rejected(step_size); self.ensemble.undo_steps_quiet(&self.steps); } else { // accept step self.count_accepted(step_size); self.old_energy = current_energy; self.old_bin = current_bin; } },
object.rs
use std::fmt; use std::cell::Cell; use crate::JvmValue; use crate::OtField; // If we need this, we'd better impl it manually // #[derive(Debug)] pub enum OtObj { vm_obj { id: usize, mark: u64, klassid: usize, fields: Vec<Cell<JvmValue>>, }, vm_arr_int { id: usize, mark: u64, klassid: usize, length: i32, elements: Vec<i32>, }, vm_arr_long { id: usize, mark: u64, klassid: usize, length: i32, elements: Vec<i64>, }, } impl OtObj { pub fn obj_of(klass_id: usize, obj_id: usize, initial: Vec<JvmValue>) -> OtObj { OtObj::vm_obj { id: obj_id, mark: 0u64, klassid: klass_id, fields: initial.into_iter().map(|s| Cell::new(s)).collect(), } } pub fn int_arr_of(size: i32, obj_id: usize) -> OtObj { let sz = size as usize; let mut elts = Vec::with_capacity(sz); elts.resize(sz, 0); OtObj::vm_arr_int { id: obj_id, mark: 0u64, klassid: 2, // FIXME Need Object in the mix soon... length: size, elements: elts, } } pub fn put_field(&self, offset : usize, val: JvmValue) -> () { let (kid, fields) = match self { OtObj::vm_obj { id: _, mark: _, klassid: id, fields: fs, } => (id, fs), _ => panic!("Not an object"), }; // Get klass dbg!("Made it to object get_field_offset"); // Lookup offset in klass // let offset = REPO.lock().get_field_offset(*kid, f); match self { OtObj::vm_obj { id: _, mark: _, klassid: _, fields: fs, } => { fs[offset].set(val); } _ => panic!("Not an object"), }; } pub fn get_field_value(&self, offset : usize) -> JvmValue { let (kid, fields) = match self { OtObj::vm_obj { id: _, mark: _, klassid: id, fields: fs, } => (id, fs), _ => panic!("Not an object"), }; // Get klass dbg!("Made it to object get_field_offset"); match fields.get(offset) { Some(v) => { // let v = cell.get(); (*v).get() } None => panic!("Fields should hold a value"), } } pub fn get_null() -> OtObj { OtObj::vm_obj { id: 0, mark: 0u64, klassid: 0, // klassid of 0 implies null fields: Vec::new(), } } pub fn is_null(&self) -> bool { if self.get_mark() == 0u64 && self.get_klassid() == 0 { true } else { false } } pub fn get_id(&self) -> usize { match *self { OtObj::vm_obj { id: i, mark: _, klassid: _, fields: _, } => i, OtObj::vm_arr_int { id: i, mark: _, klassid: _, length: _, elements: _, } => i, OtObj::vm_arr_long { id: i, mark: _, klassid: _, length: _, elements: _, } => i, } } pub fn get_mark(&self) -> u64 { match *self { OtObj::vm_obj { id: _, mark: m, klassid: _, fields: _, } => m, OtObj::vm_arr_int { id: _, mark: m, klassid: _, length: _, elements: _, } => m, OtObj::vm_arr_long { id: _, mark: m, klassid: _, length: _, elements: _, } => m, } } pub fn get_klassid(&self) -> usize { match *self { OtObj::vm_obj { id: _, mark: _, klassid: k, fields: _, } => k, OtObj::vm_arr_int { id: _, mark: _, klassid: k, length: _, elements: _, } => k, OtObj::vm_arr_long { id: _, mark: _,
} } pub fn length(&self) -> i32 { match *self { OtObj::vm_obj { id: _, mark: _, klassid: _, fields: _, } => panic!("Attempted to take the length of a normal object!"), OtObj::vm_arr_int { id: _, mark: _, klassid: _, length: l, elements: _, } => l, OtObj::vm_arr_long { id: _, mark: _, klassid: _, length: l, elements: _, } => l, } } } impl fmt::Display for OtObj { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "MarK: {} ; Klass: {}", self.get_mark(), self.get_klassid() ) } }
klassid: k, length: _, elements: _, } => k,
dialog_multithreading_d.rs
/*! An example that shows how multithreading works in NWG. Upon clicking on "Open Dialog" button, the application starts a new GUI thread. Once the user selects a value in the new dialog, the dialog notice the main thread that it should read the data. Requires the following features: `cargo run --example dialog_multithreading_d --features "notice"` */ extern crate native_windows_gui as nwg; extern crate native_windows_derive as nwd; use nwd::NwgUi; use nwg::NativeUi; use std::{thread, cell::RefCell}; /// The dialog UI #[derive(Default, NwgUi)] pub struct YesNoDialog { data: RefCell<Option<String>>, #[nwg_control(size: (300, 115), position: (650, 300), title: "A dialog", flags: "WINDOW|VISIBLE")] #[nwg_events( OnWindowClose: [YesNoDialog::close] )] window: nwg::Window, #[nwg_control(text: "YES", position: (10, 10), size: (130, 95))] #[nwg_events( OnButtonClick: [YesNoDialog::choose(SELF, CTRL)] )] choice_yes: nwg::Button, #[nwg_control(text: "NO", position: (160, 10), size: (130, 95), focus: true)] #[nwg_events( OnButtonClick: [YesNoDialog::choose(SELF, CTRL)] )] choice_no: nwg::Button, } impl YesNoDialog { /// Create the dialog UI on a new thread. The dialog result will be returned by the thread handle. /// To alert the main GUI that the dialog completed, this function takes a notice sender object. fn popup(sender: nwg::NoticeSender) -> thread::JoinHandle<String>
fn close(&self) { nwg::stop_thread_dispatch(); } fn choose(&self, btn: &nwg::Button) { let mut data = self.data.borrow_mut(); if btn == &self.choice_no { *data = Some("No!".to_string()); } else if btn == &self.choice_yes { *data = Some("Yes!".to_string()); } self.window.close(); } } /// The Main UI #[derive(Default, NwgUi)] pub struct ThreadingApp { dialog_data: RefCell<Option<thread::JoinHandle<String>>>, #[nwg_control(size: (300, 115), position: (300, 300), title: "Multithreading example", flags: "WINDOW|VISIBLE")] #[nwg_events( OnWindowClose: [ThreadingApp::exit] )] window: nwg::Window, #[nwg_control] #[nwg_events( OnNotice: [ThreadingApp::read_dialog_output] )] dialog_notice: nwg::Notice, #[nwg_control(size: (280, 25), position: (10, 10), readonly: true)] name_edit: nwg::TextInput, #[nwg_control(text: "Open Dialog", size: (280, 60), position: (10, 40), focus: true)] #[nwg_events( OnButtonClick: [ThreadingApp::open_dialog] )] button: nwg::Button, } impl ThreadingApp { fn exit(&self) { nwg::stop_thread_dispatch(); } fn open_dialog(&self) { // Disable the button to stop the user from spawning multiple dialogs self.button.set_enabled(false); *self.dialog_data.borrow_mut() = Some(YesNoDialog::popup(self.dialog_notice.sender())); } fn read_dialog_output(&self) { self.button.set_enabled(true); let data = self.dialog_data.borrow_mut().take(); match data { Some(handle) => { let dialog_result = handle.join().unwrap(); self.name_edit.set_text(&dialog_result); self.button.set_focus(); }, None => {} } } } fn main() { // nwg::init can be done on any thread. nwg::init().expect("Failed to init Native Windows GUI"); nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font"); let _app = ThreadingApp::build_ui(Default::default()).expect("Failed to build UI"); nwg::dispatch_thread_events(); }
{ thread::spawn(move || { // Create the UI just like in the main function let app = YesNoDialog::build_ui(Default::default()).expect("Failed to build UI"); nwg::dispatch_thread_events(); // Notice the main thread that the dialog completed sender.notice(); // Return the dialog data app.data.take().unwrap_or("Cancelled!".to_owned()) }) }
client_test.go
/* Copyright 2018 Comcast Cable Communications Management, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package vinyldns import ( "fmt" "os" "testing" ) func TestNewClientFromEnv(t *testing.T) { os.Setenv("VINYLDNS_ACCESS_KEY", "accessKey") os.Setenv("VINYLDNS_SECRET_KEY", "secretKey") os.Setenv("VINYLDNS_HOST", "https://vinyldns-api.com") client := NewClientFromEnv() if client.AccessKey != "accessKey" { t.Error("NewClientFromEnv should set an AccessKey from the environment") } if client.SecretKey != "secretKey" { t.Error("NewClientFromEnv should set a SecretKey from the environment") } if client.Host != "https://vinyldns-api.com" { t.Error("NewClientFromEnv should set a Host from the environment") } if client.UserAgent != fmt.Sprintf("go-vinyldns/%s", Version) { t.Error("NewClientFromEnv should set a default UserAgent if one is not present in the environment") } os.Setenv("VINYLDNS_ACCESS_KEY", "") os.Setenv("VINYLDNS_SECRET_KEY", "") os.Setenv("VINYLDNS_HOST", "") } func
(t *testing.T) { os.Setenv("VINYLDNS_USER_AGENT", "foo") client := NewClientFromEnv() if client.UserAgent != "foo" { t.Error("NewClientFromEnv should set a UserAgent from the environment if one is present") } os.Setenv("VINYLDNS_USER_AGENT", "") }
TestNewClientFromEnvWithUserAgent
app.js
var app = null; var eventAggregator = new Vue(); function
(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } addLoadEvent(function (ev) { Vue.use(Toasted); Vue.component('contribute', { props: ["targetCurrency", "active", "perks", "inModal", "displayPerksRanking", "loading"], template: "#contribute-template" }); Vue.component('perks', { props: ["perks", "targetCurrency", "active", "inModal","displayPerksRanking", "loading"], template: "#perks-template" }); Vue.component('perk', { props: ["perk", "targetCurrency", "active", "inModal", "displayPerksRanking", "index", "loading"], template: "#perk-template", data: function () { return { amount: null, expanded: false } }, computed: { canExpand: function(){ return !this.expanded && this.active && (this.perk.price.value || this.perk.custom) } }, methods: { onContributeFormSubmit: function (e) { if (e) { e.preventDefault(); } if(!this.active || this.loading){ return; } eventAggregator.$emit("contribute", {amount: parseFloat(this.amount), choiceKey: this.perk.id}); }, expand: function(){ if(this.canExpand){ this.expanded = true; } }, setAmount: function (amount) { this.amount = (amount || 0).noExponents(); this.expanded = false; } }, mounted: function () { this.setAmount(this.perk.price.value); }, watch: { perk: function (newValue, oldValue) { if (newValue.price.value != oldValue.price.value) { this.setAmount(newValue.price.value); } } } }); app = new Vue({ el: '#app', data: function(){ return { srvModel: window.srvModel, connectionStatus: "", endDate: "", startDate: "", startDateRelativeTime: "", endDateRelativeTime: "", started: false, ended: false, contributeModalOpen: false, endDiff: "", startDiff: "", active: true, animation: true, sound: true, lastUpdated:"", loading: false, timeoutState: 0 } }, computed: { raisedAmount: function(){ return parseFloat(this.srvModel.info.currentAmount + this.srvModel.info.currentPendingAmount ).toFixed(this.srvModel.currencyData.divisibility) ; }, percentageRaisedAmount: function(){ return parseFloat(this.srvModel.info.progressPercentage + this.srvModel.info.pendingProgressPercentage ).toFixed(2); }, targetCurrency: function(){ return this.srvModel.targetCurrency.toUpperCase(); }, paymentStats: function(){ var result= []; var combinedStats = {}; var keys = Object.keys(this.srvModel.info.paymentStats); for (var i = 0; i < keys.length; i++) { if(combinedStats[keys[i]]){ combinedStats[keys[i]] +=this.srvModel.info.paymentStats[keys[i]]; }else{ combinedStats[keys[i]] =this.srvModel.info.paymentStats[keys[i]]; } } keys = Object.keys(this.srvModel.info.pendingPaymentStats); for (var i = 0; i < keys.length; i++) { if(combinedStats[keys[i]]){ combinedStats[keys[i]] +=this.srvModel.info.pendingPaymentStats[keys[i]]; }else{ combinedStats[keys[i]] =this.srvModel.info.pendingPaymentStats[keys[i]]; } } keys = Object.keys(combinedStats); for (var i = 0; i < keys.length; i++) { var newItem = {key:keys[i], value: combinedStats[keys[i]], label: keys[i].replace("_","")}; result.push(newItem); } for (var i = 0; i < result.length; i++) { var current = result[i]; if(current.label.endsWith("LightningLike")){ current.label = current.label.substr(0,current.label.indexOf("LightningLike")); current.lightning = true; } } return result; }, perks: function(){ var result = []; for (var i = 0; i < this.srvModel.perks.length; i++) { var currentPerk = this.srvModel.perks[i]; if(this.srvModel.perkCount.hasOwnProperty(currentPerk.id)){ currentPerk.sold = this.srvModel.perkCount[currentPerk.id]; } result.push(currentPerk); } return result; } }, methods: { updateComputed: function () { if (this.srvModel.endDate) { var endDateM = moment(this.srvModel.endDate); this.endDate = endDateM.format('MMMM Do YYYY'); this.endDateRelativeTime = endDateM.fromNow(); this.ended = endDateM.isBefore(moment()); }else{ this.ended = false; } if (this.srvModel.startDate) { var startDateM = moment(this.srvModel.startDate); this.startDate = startDateM.format('MMMM Do YYYY'); this.startDateRelativeTime = startDateM.fromNow(); this.started = startDateM.isBefore(moment()); }else{ this.started = true; } if(this.started && !this.ended && this.srvModel.endDate){ var mDiffD = moment(this.srvModel.endDate).diff(moment(), "days"); var mDiffH = moment(this.srvModel.endDate).diff(moment(), "hours"); var mDiffM = moment(this.srvModel.endDate).diff(moment(), "minutes"); var mDiffS = moment(this.srvModel.endDate).diff(moment(), "seconds"); this.endDiff = mDiffD > 0? mDiffD + " days" : mDiffH> 0? mDiffH + " hours" : mDiffM> 0? mDiffM+ " minutes" : mDiffS> 0? mDiffS + " seconds": ""; } if(!this.started && this.srvModel.startDate){ var mDiffD = moment(this.srvModel.startDate).diff(moment(), "days"); var mDiffH = moment(this.srvModel.startDate).diff(moment(), "hours"); var mDiffM = moment(this.srvModel.startDate).diff(moment(), "minutes"); var mDiffS = moment(this.srvModel.startDate).diff(moment(), "seconds"); this.startDiff = mDiffD > 0? mDiffD + " days" : mDiffH> 0? mDiffH + " hours" : mDiffM> 0? mDiffM+ " minutes" : mDiffS> 0? mDiffS + " seconds": ""; } this.lastUpdated = moment(this.srvModel.info.lastUpdated).calendar(); this.active = this.started && !this.ended; setTimeout(this.updateComputed, 1000); }, setLoading: function(val){ this.loading = val; if(this.timeoutState){ clearTimeout(this.timeoutState); } } }, mounted: function () { hubListener.connect(); var self = this; this.sound = this.srvModel.soundsEnabled; this.animation = this.srvModel.animationsEnabled; eventAggregator.$on("invoice-created", function (invoiceId) { btcpay.setApiUrlPrefix(window.location.origin); btcpay.showInvoice(invoiceId); btcpay.showFrame(); self.contributeModalOpen = false; self.setLoading(false); }); eventAggregator.$on("contribute", function () { self.setLoading(true); self.timeoutState = setTimeout(function(){ self.setLoading(false); },5000); }); eventAggregator.$on("invoice-error", function(error){ self.setLoading(false); var msg = ""; if(typeof error === "string"){ msg = error; }else if(!error){ msg = "Unknown Error"; }else{ msg = JSON.stringify(error); } Vue.toasted.show("Error creating invoice: " + msg, { iconPack: "fontawesome", icon: "exclamation-triangle", fullWidth: false, theme: "bubble", type: "error", position: "top-center", duration: 10000 } ); }); eventAggregator.$on("payment-received", function (amount, cryptoCode, type) { var onChain = type.toLowerCase() === "btclike"; if(self.sound) { playRandomSound(); } if(self.animation) { fireworks(); } amount = parseFloat(amount).noExponents(); if(onChain){ Vue.toasted.show('New payment of ' + amount+ " "+ cryptoCode + " " + (onChain? "On Chain": "LN "), { iconPack: "fontawesome", icon: "plus", duration: 10000 } ); }else{ Vue.toasted.show('New payment of ' + amount+ " "+ cryptoCode + " " + (onChain? "On Chain": "LN "), { iconPack: "fontawesome", icon: "bolt", duration: 10000 } ); } }); if(srvModel.disqusEnabled){ window.disqus_config = function () { // Replace PAGE_URL with your page's canonical URL variable this.page.url = window.location.href; // Replace PAGE_IDENTIFIER with your page's unique identifier variable this.page.identifier = self.srvModel.appId; }; (function() { // REQUIRED CONFIGURATION VARIABLE: EDIT THE SHORTNAME BELOW var d = document, s = d.createElement('script'); // IMPORTANT: Replace EXAMPLE with your forum shortname! s.src = "https://"+self.srvModel.disqusShortname+".disqus.com/embed.js"; s.async= true; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); var s2 = d.createElement('script'); s2.src="//"+self.srvModel.disqusShortname+".disqus.com/count.js"; s2.async= true; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); } eventAggregator.$on("info-updated", function (model) { console.warn("UPDATED", self.srvModel, arguments); self.srvModel = model; }); eventAggregator.$on("connection-pending", function () { self.connectionStatus = "pending"; }); eventAggregator.$on("connection-failed", function () { self.connectionStatus = "failed"; }); eventAggregator.$on("connection-lost", function () { self.connectionStatus = "connection lost"; }); this.updateComputed(); } }); });
addLoadEvent
coroutine_lowerer.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ocamlrep::OcamlRep; use parser_core_types::{positioned_syntax::PositionedSyntax, source_text::SourceText}; use rust_to_ocaml::{SerializationContext, ToOcaml}; extern "C" { fn ocamlpool_enter(); fn ocamlpool_leave(); } /// `rewrite_coroutines` returns a pair of source text (old, new) pub fn rewrite_coroutines<'a>(
) -> (SourceText<'a>, SourceText<'a>) { let rewrite_coroutines = ocaml::named_value("rewrite_coroutines_for_rust") .expect("rewrite_coroutines not registered"); let ocaml_source_text = source.ocaml_source_text().unwrap().as_usize(); let context = SerializationContext::new(ocaml_source_text); unsafe { ocamlpool_enter(); let ocaml_root = root.to_ocaml(&context); ocamlpool_leave(); let rewritten_ocaml_source = rewrite_coroutines .call_n(&[ ocaml::Value::new(ocaml_source_text), ocaml::Value::new(ocaml_root), ]) .unwrap(); <(SourceText, SourceText)>::from_ocaml(rewritten_ocaml_source.0).unwrap() } }
source: &'a SourceText<'a>, root: &PositionedSyntax,
stake_instruction.rs
use crate::{ config, id, stake_state::{StakeAccount, StakeState}, }; use bincode::deserialize; use log::*; use serde_derive::{Deserialize, Serialize}; use solana_sdk::{ account::KeyedAccount, clock::Slot, instruction::{AccountMeta, Instruction, InstructionError}, pubkey::Pubkey, system_instruction, sysvar, }; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] pub enum StakeInstruction { /// `Lockup` a stake until the specified slot /// /// Expects 1 Account: /// 0 - Uninitialized StakeAccount to be lockup'd /// /// The u64 is the portion of the Stake account balance to be activated, /// must be less than StakeAccount.lamports /// Lockup(Slot), /// `Delegate` a stake to a particular node /// /// Expects 3 Accounts: /// 0 - Lockup'd StakeAccount to be delegated <= must have this signature /// 1 - VoteAccount to which this Stake will be delegated /// 2 - Clock sysvar Account that carries clock bank epoch /// 3 - Config Account that carries stake config /// /// The u64 is the portion of the Stake account balance to be activated, /// must be less than StakeAccount.lamports /// DelegateStake(u64), /// Redeem credits in the stake account /// /// Expects 4 Accounts: /// 0 - Delegate StakeAccount to be updated with rewards /// 1 - VoteAccount to which the Stake is delegated, /// 2 - RewardsPool Stake Account from which to redeem credits /// 3 - Rewards sysvar Account that carries points values /// 4 - StakeHistory sysvar that carries stake warmup/cooldown history RedeemVoteCredits, /// Withdraw unstaked lamports from the stake account /// /// Expects 3 Accounts: /// 0 - Delegate StakeAccount /// 1 - System account to which the lamports will be transferred, /// 2 - Syscall Account that carries epoch /// 3 - StakeHistory sysvar that carries stake warmup/cooldown history /// /// The u64 is the portion of the Stake account balance to be withdrawn, /// must be <= StakeAccount.lamports - staked lamports Withdraw(u64), /// Deactivates the stake in the account /// /// Expects 2 Accounts: /// 0 - Delegate StakeAccount /// 1 - VoteAccount to which the Stake is delegated /// 2 - Syscall Account that carries epoch Deactivate, } pub fn create_stake_account_with_lockup( from_pubkey: &Pubkey, stake_pubkey: &Pubkey, lamports: u64, lockup: Slot, ) -> Vec<Instruction> { vec![ system_instruction::create_account( from_pubkey, stake_pubkey, lamports, std::mem::size_of::<StakeState>() as u64, &id(), ), Instruction::new( id(), &StakeInstruction::Lockup(lockup), vec![AccountMeta::new(*stake_pubkey, false)], ), ] } pub fn create_stake_account( from_pubkey: &Pubkey, stake_pubkey: &Pubkey, lamports: u64, ) -> Vec<Instruction> { create_stake_account_with_lockup(from_pubkey, stake_pubkey, lamports, 0) } pub fn create_stake_account_and_delegate_stake( from_pubkey: &Pubkey, stake_pubkey: &Pubkey, vote_pubkey: &Pubkey, lamports: u64, ) -> Vec<Instruction> { let mut instructions = create_stake_account(from_pubkey, stake_pubkey, lamports); instructions.push(delegate_stake(stake_pubkey, vote_pubkey, lamports)); instructions } pub fn redeem_vote_credits(stake_pubkey: &Pubkey, vote_pubkey: &Pubkey) -> Instruction { let account_metas = vec![ AccountMeta::new(*stake_pubkey, false), AccountMeta::new_credit_only(*vote_pubkey, false), AccountMeta::new(crate::rewards_pools::random_id(), false), AccountMeta::new_credit_only(sysvar::rewards::id(), false), AccountMeta::new_credit_only(sysvar::stake_history::id(), false), ]; Instruction::new(id(), &StakeInstruction::RedeemVoteCredits, account_metas) } pub fn delegate_stake(stake_pubkey: &Pubkey, vote_pubkey: &Pubkey, stake: u64) -> Instruction { let account_metas = vec![ AccountMeta::new(*stake_pubkey, true), AccountMeta::new_credit_only(*vote_pubkey, false), AccountMeta::new_credit_only(sysvar::clock::id(), false), AccountMeta::new_credit_only(crate::config::id(), false), ]; Instruction::new(id(), &StakeInstruction::DelegateStake(stake), account_metas) } pub fn withdraw(stake_pubkey: &Pubkey, to_pubkey: &Pubkey, lamports: u64) -> Instruction { let account_metas = vec![ AccountMeta::new(*stake_pubkey, true), AccountMeta::new_credit_only(*to_pubkey, false), AccountMeta::new_credit_only(sysvar::clock::id(), false), AccountMeta::new_credit_only(sysvar::stake_history::id(), false), ]; Instruction::new(id(), &StakeInstruction::Withdraw(lamports), account_metas) } pub fn deactivate_stake(stake_pubkey: &Pubkey, vote_pubkey: &Pubkey) -> Instruction { let account_metas = vec![ AccountMeta::new(*stake_pubkey, true), AccountMeta::new_credit_only(*vote_pubkey, false), AccountMeta::new_credit_only(sysvar::clock::id(), false), ]; Instruction::new(id(), &StakeInstruction::Deactivate, account_metas) } pub fn process_instruction( _program_id: &Pubkey, keyed_accounts: &mut [KeyedAccount], data: &[u8], ) -> Result<(), InstructionError> { solana_logger::setup(); trace!("process_instruction: {:?}", data); trace!("keyed_accounts: {:?}", keyed_accounts); if keyed_accounts.is_empty() { Err(InstructionError::InvalidInstructionData)?; } let (me, rest) = &mut keyed_accounts.split_at_mut(1); let me = &mut me[0]; // TODO: data-driven unpack and dispatch of KeyedAccounts match deserialize(data).map_err(|_| InstructionError::InvalidInstructionData)? { StakeInstruction::Lockup(slot) => me.lockup(slot), StakeInstruction::DelegateStake(stake) => { if rest.len() != 3 { Err(InstructionError::InvalidInstructionData)?; } let vote = &rest[0]; me.delegate_stake( vote, stake, &sysvar::clock::from_keyed_account(&rest[1])?, &config::from_keyed_account(&rest[2])?, ) } StakeInstruction::RedeemVoteCredits => { if rest.len() != 4 { Err(InstructionError::InvalidInstructionData)?; } let (vote, rest) = rest.split_at_mut(1); let vote = &mut vote[0]; let (rewards_pool, rest) = rest.split_at_mut(1); let rewards_pool = &mut rewards_pool[0]; me.redeem_vote_credits( vote, rewards_pool, &sysvar::rewards::from_keyed_account(&rest[0])?, &sysvar::stake_history::from_keyed_account(&rest[1])?, ) } StakeInstruction::Withdraw(lamports) => { if rest.len() != 3 { Err(InstructionError::InvalidInstructionData)?; } let (to, sysvar) = &mut rest.split_at_mut(1); let mut to = &mut to[0]; me.withdraw( lamports, &mut to, &sysvar::clock::from_keyed_account(&sysvar[0])?, &sysvar::stake_history::from_keyed_account(&sysvar[1])?, ) } StakeInstruction::Deactivate => { if rest.len() != 2 { Err(InstructionError::InvalidInstructionData)?; } let (vote, rest) = rest.split_at_mut(1); let vote = &mut vote[0]; let clock = &rest[0]; me.deactivate_stake(vote, &sysvar::clock::from_keyed_account(&clock)?) } } } #[cfg(test)] mod tests { use super::*; use bincode::serialize; use solana_sdk::{account::Account, sysvar::stake_history::StakeHistory}; fn process_instruction(instruction: &Instruction) -> Result<(), InstructionError> { let mut accounts: Vec<_> = instruction .accounts .iter() .map(|meta| { if sysvar::clock::check_id(&meta.pubkey)
else if sysvar::rewards::check_id(&meta.pubkey) { sysvar::rewards::create_account(1, 0.0, 0.0) } else if sysvar::stake_history::check_id(&meta.pubkey) { sysvar::stake_history::create_account(1, &StakeHistory::default()) } else if config::check_id(&meta.pubkey) { config::create_account(1, &config::Config::default()) } else { Account::default() } }) .collect(); { let mut keyed_accounts: Vec<_> = instruction .accounts .iter() .zip(accounts.iter_mut()) .map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account)) .collect(); super::process_instruction(&Pubkey::default(), &mut keyed_accounts, &instruction.data) } } #[test] fn test_stake_process_instruction() { assert_eq!( process_instruction(&redeem_vote_credits(&Pubkey::default(), &Pubkey::default())), Err(InstructionError::InvalidAccountData), ); assert_eq!( process_instruction(&delegate_stake(&Pubkey::default(), &Pubkey::default(), 0)), Err(InstructionError::InvalidAccountData), ); assert_eq!( process_instruction(&withdraw(&Pubkey::default(), &Pubkey::new_rand(), 100)), Err(InstructionError::InvalidAccountData), ); assert_eq!( process_instruction(&deactivate_stake(&Pubkey::default(), &Pubkey::default())), Err(InstructionError::InvalidAccountData), ); } #[test] fn test_stake_process_instruction_decode_bail() { // these will not call stake_state, have bogus contents // gets the first check assert_eq!( super::process_instruction( &Pubkey::default(), &mut [KeyedAccount::new( &Pubkey::default(), false, &mut Account::default(), )], &serialize(&StakeInstruction::DelegateStake(0)).unwrap(), ), Err(InstructionError::InvalidInstructionData), ); // gets the sub-check for number of args assert_eq!( super::process_instruction( &Pubkey::default(), &mut [KeyedAccount::new( &Pubkey::default(), false, &mut Account::default() ),], &serialize(&StakeInstruction::DelegateStake(0)).unwrap(), ), Err(InstructionError::InvalidInstructionData), ); assert_eq!( super::process_instruction( &Pubkey::default(), &mut [ KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), ], &serialize(&StakeInstruction::RedeemVoteCredits).unwrap(), ), Err(InstructionError::InvalidInstructionData), ); // gets the check non-deserialize-able account in delegate_stake assert_eq!( super::process_instruction( &Pubkey::default(), &mut [ KeyedAccount::new(&Pubkey::default(), true, &mut Account::default()), KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new( &sysvar::clock::id(), false, &mut sysvar::clock::create_account(1, 0, 0, 0, 0) ), KeyedAccount::new( &config::id(), false, &mut config::create_account(1, &config::Config::default()) ), ], &serialize(&StakeInstruction::DelegateStake(0)).unwrap(), ), Err(InstructionError::InvalidAccountData), ); // gets the deserialization checks in redeem_vote_credits assert_eq!( super::process_instruction( &Pubkey::default(), &mut [ KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new( &sysvar::rewards::id(), false, &mut sysvar::rewards::create_account(1, 0.0, 0.0) ), KeyedAccount::new( &sysvar::stake_history::id(), false, &mut sysvar::stake_history::create_account(1, &StakeHistory::default()) ), ], &serialize(&StakeInstruction::RedeemVoteCredits).unwrap(), ), Err(InstructionError::InvalidAccountData), ); // Tests 3rd keyed account is of correct type (Clock instead of rewards) in withdraw assert_eq!( super::process_instruction( &Pubkey::default(), &mut [ KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new( &sysvar::rewards::id(), false, &mut sysvar::rewards::create_account(1, 0.0, 0.0) ), KeyedAccount::new( &sysvar::stake_history::id(), false, &mut sysvar::stake_history::create_account(1, &StakeHistory::default()) ), ], &serialize(&StakeInstruction::Withdraw(42)).unwrap(), ), Err(InstructionError::InvalidArgument), ); // Tests correct number of accounts are provided in withdraw assert_eq!( super::process_instruction( &Pubkey::default(), &mut [ KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new( &sysvar::clock::id(), false, &mut sysvar::rewards::create_account(1, 0.0, 0.0) ), KeyedAccount::new( &sysvar::stake_history::id(), false, &mut sysvar::stake_history::create_account(1, &StakeHistory::default()) ), ], &serialize(&StakeInstruction::Withdraw(42)).unwrap(), ), Err(InstructionError::InvalidInstructionData), ); // Tests 2nd keyed account is of correct type (Clock instead of rewards) in deactivate assert_eq!( super::process_instruction( &Pubkey::default(), &mut [ KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new( &sysvar::rewards::id(), false, &mut sysvar::rewards::create_account(1, 0.0, 0.0) ), ], &serialize(&StakeInstruction::Deactivate).unwrap(), ), Err(InstructionError::InvalidArgument), ); // Tests correct number of accounts are provided in deactivate assert_eq!( super::process_instruction( &Pubkey::default(), &mut [ KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()), KeyedAccount::new( &sysvar::clock::id(), false, &mut sysvar::rewards::create_account(1, 0.0, 0.0) ), ], &serialize(&StakeInstruction::Deactivate).unwrap(), ), Err(InstructionError::InvalidInstructionData), ); } }
{ sysvar::clock::create_account(1, 0, 0, 0, 0) }
matrix.rs
//! Collection of matrix implementations. use crate::util; use std; use std::fmt::Debug; use std::str::FromStr; type AdjacencyMap<T> = util::HashMap<String, Option<T>>; type AdjacencyMatrix<T> = util::HashMap<String, AdjacencyMap<T>>; /// Adjacency matrix struct. pub struct Adjacency<M: Clone> { edges: AdjacencyMatrix<M>, } impl<M: Clone + Debug> Default for Adjacency<M> { fn default() -> Adjacency<M> { Adjacency { edges: Default::default(), } } } /// Poor man's adjacency matrix biased towards incident edge queries. /// /// Edges are not symmetric. Two values are symmetrically adjacent when /// edges originate from each value to the other value. impl<M: Clone + Debug> Adjacency<M> { /// Construct a new adjacency matrix. pub fn new() -> Self { Adjacency { edges: Default::default(), } } /// Adds an outbound edge from a node to another. pub fn add_asymmetric_edge( &mut self, from_str: &str, to_str: &str, metadata: Option<M>, ) { let to = String::from_str(to_str).unwrap(); let from = String::from_str(from_str).unwrap(); let vec = self.edges.entry(from).or_insert_with(Default::default); vec.insert(to, metadata); } /// Adds symmetric edges between the given node and a set of other nodes. pub fn add_edges( &mut self, from_str: &str, to_strs: Vec<String>, metadata: Option<M>, ) { for to_str in to_strs { self.add_asymmetric_edge(from_str, &to_str, metadata.clone()); self.add_asymmetric_edge(&to_str, from_str, metadata.clone()) } drop(metadata); } /// Returns the number of incident edges to the given node. pub fn num_edges(&mut self, id: &str) -> usize { match self.edges.get(id) { Some(value) => value.keys().len(), None => 0, } } /// Returns true iff relations exist for the given node id. pub fn contains_node(&self, id: &str) -> bool { self.edges.contains_key(id) } /// Filters and returns edges satisfying the given constraint. pub fn filter_nodes<F>(&self, id: &str, f: F) -> Vec<String> where for<'r> F: FnMut(&'r (&String, &Option<M>)) -> bool, { self.edges[id] .iter() .filter(f) .map(|(k, _v)| k.clone()) .collect() } /// Iterates over edge relations in the matrix. pub fn iter(&self) -> std::collections::hash_map::Iter<String, AdjacencyMap<M>> { self.edges.iter() } /// Pops adjacency metadata for the given node. pub fn pop(&mut self, id: &str) -> Option<AdjacencyMap<M>>
/// As pop, but returns a vec of node identifiers connected to the given /// node. pub fn pop_nodes(&mut self, id: &str) -> Vec<String> { match self.pop(id) { Some(map) => map.into_iter().map(|(k, _v)| k).collect(), None => Vec::new(), } } /// As pop, but returns a vec of edge metadata. /// Option values will be unwrapped and None values filtered. pub fn pop_metadata(&mut self, id: &str) -> Vec<M> { match self.pop(id) { Some(map) => map .into_iter() .filter(|&(ref _k, ref option_v)| option_v.is_some()) .map(|(_, some_v)| some_v.unwrap()) .collect(), None => Vec::new(), } } }
{ self.edges.remove(id) }
oneclickwatch_mv_tv.py
# -*- coding: utf-8 -*- ''' Specto Add-on Copyright (C) 2015 lambda This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urlparse,time, urllib from resources.lib.libraries import client from resources.lib.libraries import client2 from resources.lib.libraries import cleantitle from resources.lib.libraries import workers from resources.lib.libraries import control from resources.lib.resolvers import cloudzilla from resources.lib.resolvers import openload from resources.lib.resolvers import uptobox from resources.lib.resolvers import zstream from resources.lib.resolvers import videomega from resources.lib import resolvers class source: def __init__(self): self.base_link = 'http://oneclickwatch.ws' self.search_link = '/search/%s' self.title = '' def get_movie(self, imdb, title, year): try: query = self.search_link % urllib.quote_plus(title +' '+year) query = urlparse.urljoin(self.base_link, query) result = client2.http_get(query) years = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1)] result = client.parseDOM(result, 'h2', attrs={'class': 'title'}) result = [(client.parseDOM(i, 'a', ret='href')[0], client.parseDOM(i, 'a')[0]) for i in result] print('R',result) result = [i for i in result if cleantitle.movie(title.lower()) in cleantitle.movie(i[1]).lower()] print('R',result) result = [i for i in result if any(x in i[1] for x in years)] print('R',result) result2 = [i for i in result if '1080' in i[1]] print('R',result) result3 = [i for i in result if '720' in i[1].lower()] print('R',result) if len(result3) > 0: result = result3 if len(result2) > 0: result = result2 url = result[0][0] return url except: return def get_show(self, imdb, tvdb, tvshowtitle, year): try: url = tvshowtitle url = client.cleanHTMLCodes(url) url = url.encode('utf-8') return url except: return def get_episode(self, url, imdb, tvdb, title, date, season, episode): try: if url == None: return mytitile = url.lower() url = '%s S%02dE%02d' % (url, int(season), int(episode)) url = client.replaceHTMLCodes(url) url = url.encode('utf-8') url = self.search_link % urllib.quote_plus(url) query = urlparse.urljoin(self.base_link, url) result = client2.http_get(query) result = client.parseDOM(result, 'h2', attrs={'class': 'title'}) result = [(client.parseDOM(i, 'a', ret='href')[0], client.parseDOM(i, 'a')[0]) for i in result] result = [i for i in result if mytitile in i[1].lower()] result2 = [i for i in result if '1080' in i[1].lower()] result3 = [i for i in result if '720' in i[1].lower()] if len(result3) > 0: result = result3 if len(result2) > 0: result = result2 url=result[0][0] return url except: return def
(self, url, hosthdDict, hostDict, locDict): try: self.sources =[] mylinks = [] result = client2.http_get(url) mytitle = re.compile('<title>(.*?)</title>', re.DOTALL).findall(result)[0] if any(word in mytitle.lower() for word in ['camrip', 'tsrip', 'hdcam', 'hdts', 'dvdcam', 'dvdts', 'cam', 'ts']): quality = 'CAM' elif '1080p' in mytitle: quality = '1080p' elif '720p' in mytitle: quality = 'HD' else: quality = 'MQ' links = client.parseDOM(result, 'a', attrs={'rel': 'nofollow'}) links = [i for i in links if i.startswith('http')] for a in links: mylinks.append([a,quality]) threads = [] for i in mylinks: threads.append(workers.Thread(self.check, i)) [i.start() for i in threads] for i in range(0, 10 * 2): is_alive = [x.is_alive() for x in threads] if all(x == False for x in is_alive): break time.sleep(1) return self.sources except: return self.sources def check(self, i): try: url = client.replaceHTMLCodes(i[0]) url = url.encode('utf-8') host = urlparse.urlparse(url).netloc host = host.replace('www.', '').replace('embed.', '') host = host.rsplit('.', 1)[0] host = host.lower() host = client.replaceHTMLCodes(host) host = host.encode('utf-8') control.log("##OneClickWatch %s - url %s" % (host, i[0])) #if host in i[2]: check = url = resolvers.request(url) if host == 'openload': check = openload.check(url) elif host == 'uptobox': check = uptobox.check(url) elif host == 'cloudzilla': check = cloudzilla.check(url) elif host == 'zstream': check = zstream.check(url) elif host == 'videomega': check = videomega.check(url) else: raise Exception() if check == None or check == False: raise Exception() self.sources.append({'source': host, 'quality': i[1], 'provider': 'Oneclickwatch', 'url': url}) except: pass def resolve(self, url): try: url = resolvers.request(url) return url except: return
get_sources
hmongo.py
#!/usr/bin/env python # # Copyright (c) 2013 In-Q-Tel, Inc/Lab41, All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from hemlock_debugger import Hemlock_Debugger from pymongo import MongoClient import sys class HMongo: def __init__(self):
# connect to the mongo server # required fields in the client creds file are as follows: # MONGO_SERVER # MONGO_PORT # MONGO_DB # MONGO_COLLECTION c_server = "" # DEBUG try: c_server = MongoClient(client_dict['MONGO_SERVER'], int(client_dict['MONGO_PORT'])) c_database = c_server[client_dict['MONGO_DB']] c_collection = c_database[client_dict['MONGO_COLLECTION']] except: # pragma: no cover print "Failure connecting to the client server" sys.exit(0) return c_collection def get_data(self, debug, client_dict, c_server, h_server, client_uuid, no_couchbase): data_list = [[]] desc_list = [] # DEBUG i = 0 for record in c_server.find(): data_list[0].append([]) desc_list.append([]) for key in record: data_list[0][i].append(str(record[key])) desc_list[i].append([str(key)]) i += 1 return data_list, desc_list
self.log = Hemlock_Debugger() def connect_client(self, debug, client_dict):
helper.module.ts
/** * Helper module. * @file Helper 全局模块 * @module processor/helper/module */ import { Global, HttpModule, Module } from '@nestjs/common'; import { IpService } from './helper.service.ip'; // const services = [AkismetService, BaiduSeoService, EmailService, IpService]; @Global() @Module({ imports: [HttpModule], providers: [IpService], exports: [IpService], }) export class HelperMo
dule {}
register_domain_test.go
package namesilo import ( "fmt" "net/http" "net/http/httptest" "strconv" "testing" ) func TestRegisterDomain(t *testing.T)
{ domain := "foo.com" years := 3 code := 300 charge := "6.42" extraParams := make(map[string]string) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { v := r.URL.Query() i, _ := strconv.Atoi(v.Get("years")) if i != years { t.Error("RegisterDomain should send 'years' key.") } if domain != v.Get("domain") { t.Error("RegisterDomain should send 'domain' key.") } for k, kv := range extraParams { if v.Get(k) != kv { t.Error("RegisterDomain should send any extra key-value pairs in the query string.") } } w.WriteHeader(200) fmt.Fprintln(w, `<namesilo> <request> <operation>registerDomain</operation> <ip>55.555.55.55</ip> </request> <reply> <code>`+strconv.Itoa(code)+`</code> <detail>success</detail> <message>Your domain registration was successfully processed.</message> <domain>namesilo.com</domain> <order_amount>`+charge+`</order_amount> </reply> </namesilo>`) })) defer ts.Close() c := NewClient("myapikey") c.server = ts.URL // test without extra params rcode, rcharge, err := c.RegisterDomain(domain, years) if err != nil { t.Error("RegisterDomain should not return error on success. Error: " + err.Error()) } if rcode != code { t.Error("RegisterDomain should return the status code in the XML.") } if rcharge != charge { t.Error("RegisterDomain should return the order_amount in the XML.") } // test with extra params extraParams["extraKey"] = "extraValue" c.RegisterDomain(domain, years, "extraKey=extraValue") }
leaderboards.min.js
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; var domready = require('domready'); domready(function() { //document.addEventListener('DOMContentLoaded', function() //{ console.log('client DOM Loaded...'); //* // amazon sdk globals AWS.config.region = "us-east-1"; AWS.config.apiVersions = { dynamodb: '2012-08-10', // other service API versions }; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'us-east-1:b5e61654-606a-4082-adab-382e69a24413', Logins: { // optional tokens, used for authenticated login // 'graph.facebook.com': 'FBTOKEN', // 'www.amazon.com': 'AMAZONTOKEN', // 'accounts.google.com': 'GOOGLETOKEN' } }); AWS.config.credentials.get(function(err) { if (err) console.log(err); // else console.log(AWS.config.credentials); }) // amazon sdk // dynamodb // var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); // docClient abstracts away the 'type-casting' requirement of the above dynamoDB var docClient = new AWS.DynamoDB.DocumentClient(); var listData = []; var boardIndex = 0; var scoreButton = document.getElementById('scoreButton'); var killsButton = document.getElementById('killsButton'); var wavesButton = document.getElementById('wavesButton'); function clearTable() { var tb = document.getElementById('table'); while (tb.rows.length > 1) { tb.deleteRow(1); } } scoreButton.addEventListener('click', function() { clearTable(); getTop10(0); }); killsButton.addEventListener('click', function() { clearTable(); getTop10(1); }); wavesButton.addEventListener('click', function() { clearTable(); getTop10(2); }); function getTop10(index, range) { if (!range) { range = 1; // 1 = all time, 2 = month, 3 = week, 4 = today } var d = new Date(); switch (range) { case 1: // all time break; case 2: // month d.setDate(d.getMonth() - 7); break; case 3: // this week (from last week) d.setDate(d.getDate() - 7); break; case 4: // today (from yesterday) d.setDate(d.getDate() - 1); break; } // convert date to epoch d.getTime() - d.getMilliseconds() / 1000; var dateFrom = parseFloat((Date.parse(d) / 1000).toFixed(3)); console.log("* dateFrom", dateFrom, typeof(dateFrom)); boardIndex = index; var gIndicies = ["TopScoreIndex", "TopKillsIndex", "TopWavesIndex"]; var params = { // Key: // { // "Userid": 1, // Requried: Primary partition key // "Date": 1498568140 // Requried: Primary sort key // }, TableName: "Session", IndexName: gIndicies[index], //"TopScoresIndex", ScanIndexForward: false, KeyConditionExpression: 'GameId = :gameid', // and CreatedAt > :rkey', ExpressionAttributeValues: { ':gameid': 1, // ':rkey': dateFrom }, Limit: 20 //10 }; // console.log(docClient); docClient.query(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else { console.log("* got AWS item:", data); // successful response listData = data; buildList(); } }); function buildList() { var table = document.getElementById('table'); var valueText = document.getElementById('valueText'); var label; switch (boardIndex) { case 0: label = "Score"; break; case 1: label = "Kills"; break; case 2:
label = "Waves"; break; } valueText.innerHTML = label; var row, cellRank, cellValue, cellPlayer; var nsPre = "<span style='font-size:15px;text-align:left;display:block'>" var nsPost = "</span>" var vsPre = "<span style='font-size:15px;text-align:right;display:block'>" var vsPost = "</span>" for (var i = 0; i < listData.Count; i++) { console.log(listData.Items[i]); row = table.insertRow(); cellRank = row.insertCell(0); cellPlayer = row.insertCell(1); cellValue = row.insertCell(2); if (i === 0) { // nsPre = "<span style='color:gold;font-size:19px;text-align:left;display:block'>"; // vsPre = "<span style='color:gold;font-size:19px;text-align:right;display:block'>"; nsPre = "<span style='background-color:gold;color:#8b5a00;font-size:19px;text-align:left;display:block'>"; vsPre = "<span style='background-color:gold;color:#8b5a00;font-size:19px;text-align:right;display:block'>"; } else if (i < 5) { nsPre = "<span style='color:orange;font-size:17px;text-align:left;display:block'>"; vsPre = "<span style='color:orange;font-size:17px;text-align:right;display:block'>"; } else if (i < 10) { nsPre = "<span style='color:#cd8500;font-size:15px;text-align:left;display:block'>"; vsPre = "<span style='color:#cd8500;font-size:15px;text-align:right;display:block'>"; } else if (i < 15) { nsPre = "<span style='color:#8b5a00;font-size:13px;text-align:left;display:block'>"; vsPre = "<span style='color:#8b5a00;font-size:13px;text-align:right;display:block'>"; } else { nsPre = "<span style='color:#8b5a2b;font-size:11px;text-align:left;display:block'>"; vsPre = "<span style='color:#8b5a2b;font-size:11px;text-align:right;display:block'>"; } cellRank.innerHTML = nsPre + (i + 1) + vsPost; switch (boardIndex) { case 0: // score cellValue.innerHTML = vsPre + listData.Items[i].Score.toLocaleString() + vsPost; break; case 1: // kills cellValue.innerHTML = vsPre + listData.Items[i].Kills.toLocaleString() + vsPost; break; case 2: // waves cellValue.innerHTML = vsPre + listData.Items[i].Waves.toLocaleString() + vsPost; break; } if (listData.Items[i].Player) cellPlayer.innerHTML = nsPre + listData.Items[i].Player + nsPost; else cellPlayer.innerHTML = nsPre + "Guest_" + (Math.floor(Math.random() * 999) + 1) + nsPost; } } } // 0 = score, 1 = kills, 2 = waves if (listData.length === 0) getTop10(0); }); },{"domready":2}],2:[function(require,module,exports){ /*! * domready (c) Dustin Diaz 2014 - License MIT */ !function (name, definition) { if (typeof module != 'undefined') module.exports = definition() else if (typeof define == 'function' && typeof define.amd == 'object') define(definition) else this[name] = definition() }('domready', function () { var fns = [], listener , doc = document , hack = doc.documentElement.doScroll , domContentLoaded = 'DOMContentLoaded' , loaded = (hack ? /^loaded|^c/ : /^loaded|^i|^c/).test(doc.readyState) if (!loaded) doc.addEventListener(domContentLoaded, listener = function () { doc.removeEventListener(domContentLoaded, listener) loaded = 1 while (listener = fns.shift()) listener() }) return function (fn) { loaded ? setTimeout(fn, 0) : fns.push(fn) } }); },{}]},{},[1]);
mod.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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. use rustc::dep_graph::{DepGraphQuery, DepNode, DepKind}; use rustc::ich::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::graph::{Graph, NodeIndex}; use super::hash::*; mod compress; /// A data-structure that makes it easy to enumerate the hashable /// predecessors of any given dep-node. pub struct Predecessors<'query> { // A reduced version of the input graph that contains fewer nodes. // This is intended to keep all of the base inputs (i.e., HIR // nodes) and all of the "work-products" we may care about // later. Other nodes may be retained if it keeps the overall size // of the graph down. pub reduced_graph: Graph<&'query DepNode, ()>, // These are output nodes that have no incoming edges. We have to // track these specially because, when we load the data back up // again, we want to make sure and recreate these nodes (we want // to recreate the nodes where all incoming edges are clean; but // since we ordinarily just serialize edges, we wind up just // forgetting that bootstrap outputs even exist in that case.) pub bootstrap_outputs: Vec<&'query DepNode>, // For the inputs (hir/foreign-metadata), we include hashes. pub hashes: FxHashMap<&'query DepNode, Fingerprint>, } impl<'q> Predecessors<'q> { pub fn new(query: &'q DepGraphQuery, hcx: &mut HashContext) -> Self
}
{ let tcx = hcx.tcx; // Find the set of "start nodes". These are nodes that we will // possibly query later. let is_output = |node: &DepNode| -> bool { match node.kind { DepKind::WorkProduct => true, DepKind::MetaData => { // We do *not* create dep-nodes for the current crate's // metadata anymore, just for metadata that we import/read // from other crates. debug_assert!(!node.extract_def_id(tcx).unwrap().is_local()); false } // if -Z query-dep-graph is passed, save more extended data // to enable better unit testing DepKind::TypeckTables => tcx.sess.opts.debugging_opts.query_dep_graph, _ => false, } }; // Reduce the graph to the most important nodes. let compress::Reduction { graph, input_nodes } = compress::reduce_graph(&query.graph, |n| HashContext::is_hashable(tcx, n), |n| is_output(n)); let mut hashes = FxHashMap(); for input_index in input_nodes { let input = *graph.node_data(input_index); debug!("computing hash for input node `{:?}`", input); hashes.entry(input) .or_insert_with(|| hcx.hash(input).unwrap()); } if tcx.sess.opts.debugging_opts.query_dep_graph { // Not all inputs might have been reachable from an output node, // but we still want their hash for our unit tests. let hir_nodes = query.graph.all_nodes().iter().filter_map(|node| { match node.data.kind { DepKind::Hir => Some(&node.data), _ => None, } }); for node in hir_nodes { hashes.entry(node) .or_insert_with(|| hcx.hash(node).unwrap()); } } let bootstrap_outputs: Vec<&'q DepNode> = (0 .. graph.len_nodes()) .map(NodeIndex) .filter(|&n| graph.incoming_edges(n).next().is_none()) .map(|n| *graph.node_data(n)) .filter(|n| is_output(n)) .collect(); Predecessors { reduced_graph: graph, bootstrap_outputs: bootstrap_outputs, hashes: hashes, } }
domrec.js
/* Copyright Pernosco 2020. See LICENSE. */ const DOMREC_ADD = "a"; const DOMREC_CANVAS_DATA = "c"; const DOMREC_DELAY = "d"; const DOMREC_FRAME = "e"; const DOMREC_FORCE_STYLE_FLUSH = "f"; const DOMREC_INPUT = "i"; const DOMREC_LABEL = "l"; const DOMREC_MOUSE_MOVE = "m"; const DOMREC_MOUSE_DOWN = "n"; const DOMREC_ATTR = "r"; const DOMREC_TEXT = "t"; const DOMREC_MOUSE_UP = "u"; const DOMREC_REMOVE = "v"; const DOMREC_SCROLL = "s"; // If an element has the "hidden" class and its ID is in this list, // assume it won't be needed for the replay and just ignore the node // completely. window.DOMREC_SKIP_HIDDEN_IDS = ['toolbox']; // XXX Currently we assume all scrollable elements are one of PRE/DIV/INPUT/TEXTAREA // XXX we don't support :hover at all. function DOMRecFrame(win, node, rec, iframeElement) { this.win = win; this.node = node; this.rec = rec; this.iframeElement = iframeElement; node.ownerDocument.DOMRecInner = this; let prepEvent = (function(event) { this.flushObserver(); if ("DOMRecID" in event.target) { return event.target.DOMRecID; } return 0; }).bind(this); if (!this.iframeElement) { this.node.classList.add("domrecRoot"); } this.inputListener = (function(event) { if (!this.node.contains(event.target)) { return; } let id = prepEvent(event); if (id) { let a = {}; let value = null; // For contenteditable elements, the DOM changes will just // be recorded and we don't have to do anything here except // record an input event so the caret can be updated. if ("value" in event.target) { value = event.target.value; } a[DOMREC_INPUT] = [id, event.target.value]; this.rec.actions.push(a); } }).bind(this); this.mouseListener = (function(event) { let x = event.clientX; let y = event.clientY; let frameElem = this.iframeElement; let target = event.target; let node = this.node; // Translate to root document coordinates. while (frameElem) { let frameRect = frameElem.getBoundingClientRect(); // XXX assumes no border/padding on the IFRAME. handling that is a pain. x += frameRect.left; y += frameRect.top; target = frameElem; let nextInner = frameElem.ownerDocument.DOMRecInner; node = nextInner.node; frameElem = nextInner.iframeElement; } if (!node.contains(target)) { return; } this.flushObserver(); let nodeRect = node.getBoundingClientRect(); x -= nodeRect.left; y -= nodeRect.top; let key; switch (event.type) { case "mousemove": key = DOMREC_MOUSE_MOVE; break; case "mouseup": key = DOMREC_MOUSE_UP; break; case "mousedown": key = DOMREC_MOUSE_DOWN; break; default: throw "Unknown event type: " + event.type; } let a = {}; a[key] = [Math.round(x), Math.round(y)]; this.rec.actions.push(a); }).bind(this); this.flushListener = (function(event) { if (!this.node.contains(event.target)) { return; } let id = prepEvent(event); if (id) { let a = {}; a[DOMREC_FORCE_STYLE_FLUSH] = id; this.rec.actions.push(a); } }).bind(this); this.canvasListener = (function(event) { if (!this.node.contains(event.target)) { return; } let id = prepEvent(event); if (id) { let a = {}; a[DOMREC_CANVAS_DATA] = [id, event.target.toDataURL(), "didDraw"]; this.rec.actions.push(a); } }).bind(this); this.focusListener = (function(event) { rec.evaluateFocus(); }).bind(this); this.scrollListener = (function(event) { if (!this.node.contains(event.target)) { return; } let id = prepEvent(event); if (id) { this.rec.pushScrollAction(id, event.target); } }).bind(this); let actions = []; let serializedNode = rec.serializeNode(node, actions); if (!serializedNode) { throw "Can't record element " + node.tagName; } this.initialState = [serializedNode, actions]; this.observer = new MutationObserver(rec.observerCallback); this.observer.observe(node, {attributes:true, characterData:true, childList:true, subtree:true}); win.addEventListener("input", this.inputListener, {capture:true, passive:true}); win.addEventListener("mousemove", this.mouseListener, {capture:true, passive:true}); win.addEventListener("mousedown", this.mouseListener, {capture:true, passive:true}); win.addEventListener("mouseup", this.mouseListener, {capture:true, passive:true}); // Dispatch this event on an element when you want to flush styles on it and its descendants. win.addEventListener("forceStyleFlush", this.flushListener, {capture:true, passive:true}); // Dispatch this event on a canvas element when you've drawn into it. win.addEventListener("didDrawCanvas", this.canvasListener, {capture:true, passive:true}); win.addEventListener("focus", this.focusListener, {capture:true, passive:true}); } DOMRecFrame.prototype.flushObserver = function() { this.rec.observerCallback(this.observer.takeRecords()); } DOMRecFrame.prototype.stop = function() { this.flushObserver(); this.observer.disconnect(); this.win.removeEventListener("input", this.inputListener, {capture:true, passive:true}); this.win.removeEventListener("mousemove", this.mouseListener, {capture:true, passive:true}); this.win.removeEventListener("mousedown", this.mouseListener, {capture:true, passive:true}); this.win.removeEventListener("mouseup", this.mouseListener, {capture:true, passive:true}); this.win.removeEventListener("forceStyleFlush", this.flushListener, {capture:true, passive:true}); this.win.removeEventListener("didDrawCanvas", this.canvasListener, {capture:true, passive:true}); this.win.removeEventListener("focus", this.focusListener, {capture:true, passive:true}); this.rec.deleteAllDOMRecIDs(this.node); if (!this.iframeElement) { this.node.classList.remove("domrecRoot"); } } function DOMRec(node) { this.nextID = 1; this.actions = []; this.lastActionTime = Date.now(); this.nestedObserverCallbacks = 0; this.observerCallback = this.callback.bind(this); this.iframeLoadedListener = (function(event) { this.iframeLoaded(event.target, this.actions); }).bind(this); this.rootFrame = new DOMRecFrame(window, node, this, null); this.focusedElement = null; this.evaluateFocus(); this.rootFrame.initialState[1] = this.rootFrame.initialState[1].concat(this.actions); this.actions = []; } DOMRec.prototype.clearFakeFocus = function() { if (!this.focusedElement) { return; } this.focusedElement.removeAttribute("fakeFocus"); let ancestor = this.focusedElement; while (ancestor) { ancestor.removeAttribute("fakeFocusWithin"); let nextAncestor = ancestor.parentElement; if (!nextAncestor) { ancestor = ancestor.ownerDocument.DOMRecInner.iframeElement; } else { ancestor = nextAncestor; } } } DOMRec.prototype.evaluateFocus = function() { let frame = this.rootFrame; let e; while (true) { e = frame.win.document.activeElement; if (!frame.node.contains(e)) { e = null; break; } if (e.tagName == "IFRAME") { frame = e.contentDocument.DOMRecInner; } else { break; } } if (e == this.focusedElement) { return; } this.clearFakeFocus(); e.setAttribute("fakeFocus", ""); let ancestor = e; while (ancestor) { ancestor.setAttribute("fakeFocusWithin", ""); let nextAncestor = ancestor.parentElement; if (!nextAncestor) { ancestor.ownerDocument.DOMRecInner.flushObserver(); ancestor = ancestor.ownerDocument.DOMRecInner.iframeElement; } else { ancestor = nextAncestor; } } // Flush observer so that during startup we have the right set of actions this.rootFrame.flushObserver(); this.focusedElement = e; } DOMRec.prototype.stop = function() { let width = this.rootFrame.node.getBoundingClientRect().width; let height = this.rootFrame.node.getBoundingClientRect().height; let ret = {initialState: this.rootFrame.initialState, actions: this.actions, width: width, height: height}; this.rootFrame.stop(); this.clearFakeFocus(); this.rootFrame = null; return ret; } DOMRec.prototype.allowAttribute = function(e, name) { switch (name) { case "src": case "srcdoc": if (e.tagName == "IFRAME") { return false; } break; case "title": return false; } return true; } DOMRec.prototype.pushScrollAction = function(id, element, actionsList) { let actions = actionsList ? actionsList : this.actions; let scrolledIntoView = element.elementScrolledIntoView; if (scrolledIntoView) { let a = {}; if (scrolledIntoView.DOMRecID) { let scrolledIntoViewOffset = "elementScrolledIntoViewOffset" in element ? element.elementScrolledIntoViewOffset : null; a[DOMREC_SCROLL] = [id, scrolledIntoView.DOMRecID, scrolledIntoViewOffset]; } else { if (scrolledIntoView != "bottom") { throw "Unknown scrolledIntoView: " + scrolledIntoView; } a[DOMREC_SCROLL] = [id, scrolledIntoView]; } actions.push(a); } else { console.log("Warning: unknown scroll operation ignored"); } } DOMRec.prototype.serializeNode = function(node, actions) { if ("DOMRecID" in node) { throw "Already serialized " + node.DOMRecID; } let id = this.nextID++; let obj = {id:id}; node.DOMRecID = id; switch (node.nodeType) { case Node.ELEMENT_NODE: { let tag = node.tagName; switch (tag) { case "INPUT": case "TEXTAREA": { let a = {}; a[DOMREC_INPUT] = [id, node.value]; actions.push(a); let listener = node.ownerDocument.DOMRecInner.scrollListener; node.addEventListener("scroll", listener, {passive:true}); break; } case "PRE": case "DIV": { if (node.classList.contains("hidden") && DOMREC_SKIP_HIDDEN_IDS.indexOf(node.id) >= 0) { delete node.DOMRecID; return null; } let listener = node.ownerDocument.DOMRecInner.scrollListener; node.addEventListener("scroll", listener, {passive:true}); break; } case "SCRIPT": case "LINK": delete node.DOMRecID; return null; case "CANVAS": { let a = {}; a[DOMREC_CANVAS_DATA] = [id, node.toDataURL()]; actions.push(a); break; } case "IFRAME": this.attachToIFrame(node, actions); break; } obj[""] = tag; let attrs = {}; let hasAttr = false; for (let a of node.attributes) { let name = a.name; if (this.allowAttribute(node, name)) { attrs[name] = a.value; hasAttr = true; } } if (hasAttr) { obj.a = attrs; } let children = []; for (let c of node.childNodes) { let serialized = this.serializeNode(c, actions); if (serialized) { children.push(serialized); } } if (children.length > 0) { obj.c = children; } if (node.scrollLeft || node.scrollTop) { this.pushScrollAction(id, node, actions); } break; } case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: { let data = node.data; if (data.length > 0) { obj.d = data; } break; } case Node.PROCESSING_INSTRUCTION_NODE: case Node.COMMENT_NODE: break; default: delete node.DOMRecID; throw "Bad node " + node; } return obj; } DOMRec.prototype.attachToIFrame = function(e, actions) { e.addEventListener("load", this.iframeLoadedListener); if (e.contentDocument && e.contentDocument.readyState == "complete") { this.iframeLoaded(e, actions); } } DOMRec.prototype.iframeLoaded = function(e, actions) { e.DOMRecInner = new DOMRecFrame(e.contentWindow, e.contentDocument.body, this, e); let bodyElement = e.DOMRecInner.initialState[0]; if (!bodyElement.c) { bodyElement.c = []; } for (let c = e.contentDocument.head.firstElementChild; c; c = c.nextElementSibling) { if (c.tagName == "STYLE") { bodyElement.c.push(this.serializeNode(c, e.DOMRecInner.initialState[1])); this.deleteAllDOMRecIDs(c); } else if (c.tagName == "LINK" && c.getAttribute("rel") == "stylesheet") { let href = c.getAttribute("href"); let lastSlash = href.lastIndexOf("/"); if (lastSlash >= 0) { href = href.substring(lastSlash + 1); } let style = { "": "STYLE", a: { "cached": href }, id: this.nextID++ }; bodyElement.c.push(style); } } let styles = { "": "STYLE", c: [{d:".scrollbar { opacity: 0 ! important }", id:this.nextID++}], id: this.nextID++ }; bodyElement.c.push(styles); let a = {}; a[DOMREC_FRAME] = [e.DOMRecID, bodyElement]; actions.push(a); for (let aa of e.DOMRecInner.initialState[1]) { actions.push(aa); } delete e.DOMRecInner.initialState; } DOMRec.prototype.detachFromIFrame = function(e) { // XXX not sure how this can be null if (e.DOMRecInner) { e.DOMRecInner.stop(); } e.removeEventListener("load", this.iframeLoadedListener); } DOMRec.prototype.label = function(name) { this.callback(this.observer.takeRecords()); let a = {}; a[DOMREC_LABEL] = name; this.actions.push(a); } DOMRec.prototype.delay = function(seconds) { this.lastActionTime -= seconds*1000; } DOMRec.prototype.deleteAllDOMRecIDs = function(e) { delete e.DOMRecID; let listener = e.ownerDocument.DOMRecInner.scrollListener; e.removeEventListener("scroll", listener, {passive:true}); for (let c = e.firstChild; c; c = c.nextSibling) { if (c.DOMRecID) { this.deleteAllDOMRecIDs(c); } } if (e.tagName == "IFRAME") { this.detachFromIFrame(e); } } DOMRec.prototype.callback = function(records, observer) { // Observer callbacks can nest when we flush while detaching from an IFRAME if (this.nestedObserverCallbacks == 0) { let now = Date.now(); if (now > this.lastActionTime) { let a = {}; a[DOMREC_DELAY] = now - this.lastActionTime; this.actions.push(a); } } ++this.nestedObserverCallbacks; try { // A node has a DOMRecID if and only if it was in the non-excluded DOM at the start of the records // batch. // If a node has a DOMRecID and is not our root, then its parent must also // have a DOMRecID. for (let r of records) { if (r.target.DOMRecID && r.type == "childList") { for (let child of r.removedNodes) { let childID = child.DOMRecID; if (!childID) { continue; } let a = {}; a[DOMREC_REMOVE] = childID; this.actions.push(a); this.deleteAllDOMRecIDs(child); } } } // A node has a DOMRecID if and only if it was in the non-excluded DOM at the start of the records // batch, and was not ever removed during this records batch. // If a node has a DOMRecID and is not our root, then its parent must also // have a DOMRecID. let nodesWithAddedChildren = []; for (let r of records) { let target = r.target; let id = target.DOMRecID; if (!id) { // Node not in non-excluded DOM at the start of the records batch. continue; } switch (r.type) { case "attributes": { let attributeName = r.attributeName; if (this.allowAttribute(target, attributeName)) { let a = {}; a[DOMREC_ATTR] = [id, attributeName, target.getAttribute(attributeName)]; this.actions.push(a); } break; } case "characterData": { let a = {}; a[DOMREC_TEXT] = [id, target.data]; this.actions.push(a); break; } case "childList": { if (r.addedNodes.length > 0 && !target.DOMRecNodesAdded) { target.DOMRecNodesAdded = true; nodesWithAddedChildren.push(target); } } } } for (let node of nodesWithAddedChildren) { delete node.DOMRecNodesAdded; for (let c = node.lastChild; c; c = c.previousSibling) { if (c.DOMRecID) { continue; } let a = {}; let actions = []; let serializedNode = this.serializeNode(c, actions); if (!serializedNode) { continue; } let nextSibling = c.nextSibling; a[DOMREC_ADD] = [node.DOMRecID, nextSibling ? nextSibling.DOMRecID : null, serializedNode, actions]; this.actions.push(a); } } } catch (ex) { --this.nestedObserverCallbacks; console.log("MutationObserver exception: ", ex); throw ex; } --this.nestedObserverCallbacks; if (this.nestedObserverCallbacks == 0) { // Ignore time spent doing DOMRec recording. // Note that during this processing, the browser might be downloading stuff or // doing other off-main-thread work, so this could give an optimistic picture // of actual performance. Doesn't really matter. this.lastActionTime = Date.now(); } } function DOMReplay(hostElem) { let state = window[hostElem.id]; this.initialState = state.initialState; this.actions = state.actions; this.width = state.width; this.height = state.height; this.hostElem = hostElem; hostFrame = hostElem.lastChild; this.hostDoc = hostFrame.contentDocument; this.host = this.hostDoc.body; this.index = 0; this.scaleX = 1; this.scaleY = 1; this.nodes = {}; this.cursor = this.hostDoc.createElement("div"); let cursorImage = this.hostDoc.createElementNS("http://www.w3.org/2000/svg", "svg"); cursorImage.setAttribute("viewBox", "0 0 320 512"); cursorImage.innerHTML = '<path d="M302.189 329.126H196.105l55.831 135.993c3.889 9.428-.555 19.999-9.444 23.999l-49.165 21.427c-9.165 4-19.443-.571-23.332-9.714l-53.053-129.136-86.664 89.138C18.729 472.71 0 463.554 0 447.977V18.299C0 1.899 19.921-6.096 30.277 5.443l284.412 292.542c11.472 11.179 3.007 31.141-12.5 31.141z"/>'; this.cursor.setAttribute("class", "mouseCursor"); this.cursor.appendChild(cursorImage); this.reset(); this.pendingTimeout = null; this.caretElement = null; this.maybeFocusedElement = null; this.maybeFocusedElementChanged = false; let resize = (function() { const margin = 2; this.scaleX = (this.hostDoc.defaultView.innerWidth - 2*margin)/state.width; this.scaleY = (this.hostDoc.defaultView.innerHeight - 2*margin)/state.height; this.hostDoc.body.style.transform = "translate(2px, 2px) scale(" + this.scaleX + "," + this.scaleY + ")"; }).bind(this); resize(); hostFrame.contentWindow.addEventListener("resize", resize); } DOMReplay.prototype.reset = function() { this.index = 0; this.nodes = {}; this.host.textContent = ""; let child = this.deserialize(this.initialState[0]); child.style.width = this.width + "px"; child.style.height = this.height + "px"; this.host.appendChild(child); for (let a of this.initialState[1]) { this.doAction(a); } this.notifyPossibleFocusChange(); } let DOMRecStylesheetCache = {}; DOMReplay.prototype.deserialize = function(obj) { let node; if ("" in obj) { node = this.hostDoc.createElement(obj[""]); if ("a" in obj) { for (let a in obj.a) { if (a == "cached" && obj[""] == "STYLE") { let cached = DOMRecStylesheetCache[obj.a[a]]; if (cached) { node.textContent = cached; } continue; } if (a == "fakefocus") { this.maybeFocusedElement = node; this.maybeFocusedElementChanged = true; } node.setAttribute(a, obj.a[a]); } } if ("c" in obj) { for (let c of obj.c) { node.appendChild(this.deserialize(c)); } } } else if ("d" in obj) { node = this.hostDoc.createTextNode(obj.d); } else { node = this.hostDoc.createTextNode(""); } this.nodes[obj.id] = node; return node; } DOMReplay.prototype.node = function(id) { if (id == null) { return null; } if (id in this.nodes) { return this.nodes[id]; } throw "Unknown ID " + id; } DOMReplay.prototype.setCursorPos = function(x, y) { this.cursor.style.left = x + "px"; this.cursor.style.top = y + "px"; if (!this.cursor.parentNode) { this.host.appendChild(this.cursor); } } DOMReplay.prototype.step = function() { let action = this.actions[this.index++]; this.doAction(action); this.notifyPossibleFocusChange(); return action; } DOMReplay.prototype.setupFrame = function(frame) { frame.contentDocument.body.remove(); frame.contentDocument.documentElement.appendChild(frame.DOMRecBody); this.notifyPossibleFocusChange(); } DOMReplay.prototype.notifyPossibleFocusChange = function() { if (!this.maybeFocusedElementChanged) { return; } this.maybeFocusedElementChanged = false; if (this.caretElement) { this.caretElement.remove(); this.caretElement = null; } if (this.maybeFocusedElement && this.maybeFocusedElement.hasAttribute("fakeFocus") && this.maybeFocusedElement.ownerDocument.documentElement.contains(this.maybeFocusedElement)) { this.setCaret(this.maybeFocusedElement); } } DOMReplay.prototype.doAction = function(action) { if (DOMREC_MOUSE_MOVE in action) { let a = action[DOMREC_MOUSE_MOVE]; this.setCursorPos(a[0], a[1]); } else if (DOMREC_DELAY in action || DOMREC_LABEL in action) { // do nothing } else if (DOMREC_ATTR in action) { let a = action[DOMREC_ATTR]; let attr = a[1]; let node = this.node(a[0]); if (typeof a[2] == "string") { node.setAttribute(attr, a[2]); if (attr == "fakefocus") { this.maybeFocusedElement = node; this.maybeFocusedElementChanged = true; } } else { node.removeAttribute(attr); } } else if (DOMREC_TEXT in action) { let a = action[DOMREC_TEXT]; this.node(a[0]).data = a[1]; } else if (DOMREC_ADD in action) { let a = action[DOMREC_ADD]; this.node(a[0]).insertBefore(this.deserialize(a[2]), this.node(a[1])); for (let action of a[3]) { this.doAction(action); } } else if (DOMREC_REMOVE in action) { let n = action[DOMREC_REMOVE]; let node = this.node(n); // XXX delete descendant nodes from our map too? delete this.nodes[n]; node.remove(); } else if (DOMREC_INPUT in action) { let a = action[DOMREC_INPUT]; let n = this.node(a[0]); let v = a[1]; if (v) { n.value = v; } this.maybeFocusedElementChanged = true; } else if (DOMREC_MOUSE_DOWN in action) { let a = action[DOMREC_MOUSE_DOWN]; this.setCursorPos(a[0], a[1]); this.cursor.classList.add("down"); } else if (DOMREC_MOUSE_UP in action) { let a = action[DOMREC_MOUSE_UP]; this.setCursorPos(a[0], a[1]); this.cursor.classList.remove("down"); } else if (DOMREC_FORCE_STYLE_FLUSH in action) { let n = action[DOMREC_FORCE_STYLE_FLUSH]; this.node(n).getBoundingClientRect(); } else if (DOMREC_SCROLL in action) { let a = action[DOMREC_SCROLL]; let container = this.node(a[0]); if (container.getClientRects().length > 0) { let s = a[1]; if (s == "bottom") { container.scrollTop = 1000000; } else { let element = this.node(s); let o = element; let offsetY = 0; do { offsetY += o.offsetTop; o = o.offsetParent; } while (o != container); let offsetHeight = element.offsetHeight; if (offsetY < o.scrollTop || offsetY + offsetHeight > o.scrollTop + o.clientHeight) { let y; if (a.length >= 3) { y = offsetY - a[2]; } else { y = offsetY - (o.clientHeight - offsetHeight) / 2; } container.scrollTo(0, y); } } } } else if (DOMREC_FRAME in action) { let a = action[DOMREC_FRAME]; let frame = this.node(a[0]); frame.DOMRecBody = this.deserialize(a[1]); if (frame.contentDocument.readyState == "complete") { this.setupFrame(frame); } else { frame.addEventListener("load", (function(event) { // Firefox might have destroyed our document due to loading "about:blank". // Restore it. this.setupFrame(frame); }).bind(this)); } } else if (DOMREC_CANVAS_DATA in action) { let a = action[DOMREC_CANVAS_DATA]; let n = this.node(a[0]); var img = new window.Image(); n.loadingImage = img; function onload(event) { // Check that the right image is drawing. If images decode out of // order we could have a problem. if (n.loadingImage == event.target) { n.getContext("2d").drawImage(img, 0, 0); n.loadingImage = null; } img.removeEventListener("load", onload); } img.addEventListener("load", onload); img.setAttribute("src", a[1]); } else { throw "Unknown action"; } } DOMReplay.prototype.setCaret = function(element) { // Create a fake caret for the text. We need to measure its position using hacks. // Currently we assume 'element' is a display:inline <input> or <textarea>. if (!(element.tagName == "INPUT" || element.tagName == "TEXTAREA" || element.hasAttribute("contenteditable"))) { return; } let e = document.createElement("DIV"); e.classList.add("fakeInput"); e.style.left = element.offsetLeft + "px"; e.style.top = element.offsetTop + "px"; e.style.width = element.offsetWidth + "px"; function pixels(v) { if (v.endsWith("px")) { return parseInt(v.substring(0, v.length - 2)); } return 0; } let cs = window.getComputedStyle(element); function fixPadding(direction) { e.style["padding" + direction] = pixels(cs["border" + direction + "Width"]) + pixels(cs["padding" + direction]) + "px"; } fixPadding("Left"); fixPadding("Top"); fixPadding("Right"); fixPadding("Bottom"); for (let p of ["fontFamily", "fontSize", "verticalAlign", "wordWrap", "whiteSpace"]) { e.style[p] = cs[p]; } if (cs.display == "inline-block" || cs.display == "inline") { let baselineMeasurer = document.createElement("DIV"); baselineMeasurer.classList.add("baselineMeasurer"); element.parentNode.insertBefore(baselineMeasurer, element); let baselineRect = baselineMeasurer.getBoundingClientRect(); let elementRect = element.getBoundingClientRect(); baselineMeasurer.remove(); // Create an empty span to push the text baseline down to where it needs to be let span = document.createElement("span"); span.style.height = (baselineRect.bottom - elementRect.top)/this.scaleY + "px"; e.appendChild(span); } let value = "value" in element ? element.value : element.textContent; let textIndex = value.length; // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=839987. // If the value is entirely whitespace then we might need more workarounds but // that doesn't happen currently. if (value == "") { value = "|"; } e.appendChild(document.createTextNode(value)); let parent = element.offsetParent ? element.offsetParent : element.ownerDocument.documentElement; parent.appendChild(e); let r = new Range(); r.setStart(e.lastChild, textIndex); r.collapse(true); let rangeRect = r.getClientRects()[0]; let parentRect = parent.getBoundingClientRect(); let caret = document.createElement("DIV"); caret.classList.add("fakeCaret"); caret.style.left = (rangeRect.left - parentRect.left)/this.scaleX + "px"; caret.style.top = (rangeRect.top - parentRect.top)/this.scaleY + "px"; caret.style.height = rangeRect.height/this.scaleY + "px"; caret.inputElement = element; e.remove(); parent.appendChild(caret); this.caretElement = caret; } DOMReplay.prototype.labelIndex = function(name, def) { if (typeof name == "undefined") { return def; } for (let i = 0; i < this.actions.length; ++i) { if (this.actions[i][DOMREC_LABEL] == name) { return i; } } throw "Unknown label " + name; } DOMReplay.prototype.stop = function() { if (this.pendingTimeout != null) { clearTimeout(this.pendingTimeout); this.pendingTimeout = null; } this.hostElem.classList.remove("playing"); setTitle(this.hostElem); } DOMReplay.prototype.stopped = function() { return this.pendingTimeout == null; } DOMReplay.prototype.seekInternal = function(index) { if (this.index > index) { this.reset(); } while (this.index < index) { this.step(); } } DOMReplay.prototype.seek = function(name) { let index = this.labelIndex(name, 0); this.stop(); this.seekInternal(index); } function setTitle(d) { if (d.hasAttribute("popOut")) { if (d.classList.contains("poppedOut")) { d.title = "Click outside to shrink"; } else { d.title = "Click to enlarge"; } } else if (d.classList.contains("DOMRecMovie")) { if (d.classList.contains("playing")) { d.title = "Click to pause"; } else { d.title = "Click to resume"; } } else { d.title = ""; } } DOMReplay.prototype.play = function(options) { this.stop(); let stopAtIndex = this.actions.length; if (options && ("end" in options)) { stopAtIndex = this.labelIndex(options.end); } let loop = !!(options && options.loop); let loopToIndex = 0; let timeScale = 1.0; if (options && ("timeScale" in options)) { timeScale = options.timeScale; } let playStart = Date.now(); let playTime = 0; let oneLoopTime = 0; if (loop) { for (let i = loopToIndex; i < stopAtIndex; ++i) { let action = this.actions[i]; if (DOMREC_DELAY in action) { oneLoopTime += action[DOMREC_DELAY]; } } if (oneLoopTime <= 0) { loop = false; } } let doPlay = (function() { this.pendingTimeout = null; while (true) { if (this.index >= stopAtIndex) { if (loop) { let delay = Date.now() - playStart; while (delay > timeScale*(playTime + oneLoopTime)) { // Fake playing some loops without doing the work to catch up to real time playTime += oneLoopTime; } this.hostElem.classList.add("looping"); setTimeout((function() { this.hostElem.classList.remove("looping"); }).bind(this), 500); this.seekInternal(loopToIndex); } else { break; } } let action = this.step(); if (DOMREC_DELAY in action) { playTime += action[DOMREC_DELAY]; let delay = Date.now() - playStart; if (delay < timeScale*playTime) { this.pendingTimeout = setTimeout(doPlay, timeScale*playTime - delay); break; } } } }).bind(this); this.hostElem.classList.add("playing"); setTitle(this.hostElem); doPlay(); } // For subframe external stylesheets, replay loads the stylesheet text and inject the // text directly into the subframe. // The key here is the stylesheet URL in the recorded document's LINK // element, the value is the URL from which we should fetch its text during replay. const DOMREC_REPLAY_FRAME_STYLESHEETS = { }; // These stylesheets will be loaded in the main replay frame. We don't try to load // the original stylesheets from the recording at all; instead list their replay-time // URLs here. // XXX this assumes a fixed list of stylesheets will do for all the replays that // use this script! const DOMREC_REPLAY_STYLESHEETS = [ "domrec-replay.css", ]; // Full URL of the current script let DOMRecScriptURL = document.currentScript ? document.currentScript.src : null; // This function gets called to rewrite all the stylesheet URLs during replay. // This can apply dynamic changes e.g. using DOMRecScriptURL. function rewriteResourceURL(url) { return url; } function DOMSetupReplay(element) { let data = window[element.id]; if (!("initialState" in data)) { return false; } element.textContent = ''; let frame = document.createElement("iframe"); let srcdoc = '<html class="replay"><head>'; for (let sheet of DOMREC_REPLAY_STYLESHEETS) { sheet = rewriteResourceURL(sheet); srcdoc += '<link rel="stylesheet" href="' + sheet + '">'; } frame.srcdoc = srcdoc; // Crazy hack to get the correct size for the IFRAME. We insert an SVG element // with the correct aspect ratio and let its intrinsic height be the height of our // DIV, then make the IFRAME use that height. Too bad there's no way to tell an IFRAME // to use a specific intrinsic ratio. let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); if (window.origin == "http://127.0.0.1:3000" && (element.style.width != data.width + "px" || element.style.height != data.height + "px")) { alert("Invalid dimensions for " + element.id + ": expected " + data.width + "px x " + data.height + "px, got " + element.style.width + " x " + element.style.height); } svg.setAttribute("viewBox", "0 0 " + data.width + " " + data.height); element.appendChild(svg); element.appendChild(frame); // IFRAME navigation to the srcdoc document will have started but for now // we will have a blank document. Make sure this doesn't confuse us. frame.contentDocument.initialDoc = true; element.frame = frame; if (!element.hasAttribute("fixedWidth")) { element.style.maxWidth = data.width + "px"; element.style.width = ''; } element.style.height = ''; return true; } let DOMResolveSetupReplay; DOMSetupReplayPromise = new Promise(function(resolve, reject) { DOMResolveSetupReplay = resolve; }); function DOMSetupReplayAll() { for (let d of document.querySelectorAll(".DOMRecScreenshot")) { if (!DOMSetupReplay(d)) { return false; } } for (let d of document.querySelectorAll(".DOMRecMovie:not(.demo)")) { if (!DOMSetupReplay(d)) { return false; } } DOMResolveSetupReplay(); return true; } if (document.readyState == "loading") { document.addEventListener("DOMContentLoaded", function() { if (!DOMSetupReplayAll()) { throw "Data missing"; } }); } else { if (!DOMSetupReplayAll()) { // The script with the DOMRec data hasn't loaded yet. let s = document.currentScript.previousElementSibling; if (s.tagName != "SCRIPT") { throw "Expected DOMRec data script!"; } s.addEventListener("load", function() { if (!DOMSetupReplayAll()) { throw "Data missing"; } }); } } function DOMReplayStylesheetCacheLoaded() { function onloaded(element, callback) { if (!element.frame) { return; } function
() { element.frame.contentDocument.fonts.ready.then(callback); } let doc = element.frame.contentDocument; if (doc.readyState == "complete" && !doc.initialDoc) { waitForFonts(); } else { element.frame.addEventListener("load", waitForFonts); } } function createFullscreenButton(d) { if (!document.fullscreenEnabled) { return; } let fullscreen = document.createElement("button"); fullscreen.className = "fullscreen"; fullscreen.title = "Click to enter/exit fullscreen"; fullscreen.addEventListener("click", function(event) { event.stopPropagation(); if (document.fullscreenElement == d) { document.exitFullscreen(); } else { function resize() { let cw = d.clientWidth; let ch = d.clientHeight; let data = window[d.id]; if (data.width*ch < data.height*cw) { d.frame.style.top = "0"; d.frame.style.height = "100%"; let w = data.width*(ch/data.height); d.frame.style.width = w + "px"; d.frame.style.left = "calc(50% - " + w/2 + "px)"; } else { d.frame.style.left = "0"; d.frame.style.width = "100%"; let h = data.height*(cw/data.width); d.frame.style.height = h + "px"; d.frame.style.top = "calc(50% - " + h/2 + "px)"; } } let addedResizeListener = false; d.requestFullscreen().then(function() { resize(); if (!addedResizeListener) { addedResizeListener = true; window.addEventListener("resize", resize); } }); } }); d.appendChild(fullscreen); } function tryPopOut(d, event) { if (!d.hasAttribute("popOut") || d.classList.contains("poppedOut") || document.fullscreenElement == d) { return false; } event.stopPropagation(); let container = d.parentNode; let dRect = d.getBoundingClientRect(); container.scrollIntoView({behavior: 'smooth', block: 'start'}); if (window.getComputedStyle(d).position == 'absolute') { let savedMinHeight = container.style.minHeight; container.style.minHeight = "0"; let containerRect = container.getBoundingClientRect(); let newDWidth = 220 + containerRect.width; let newDHeight = newDWidth*dRect.height/dRect.width; container.style.height = containerRect.height + "px"; container.getBoundingClientRect(); d.classList.add("poppedOut"); container.style.height = (containerRect.height + newDHeight + 20) + "px"; d.style.width = newDWidth + "px"; d.style.top = (containerRect.height + 10) + "px"; d.escapeHandler = function(event) { if (!d.contains(event.target)) { document.removeEventListener("click", d.escapeHandler, true); d.classList.remove("poppedOut"); container.style.height = ''; container.style.minHeight = savedMinHeight; d.style.width = ''; d.style.top = ''; setTitle(d); // Don't stop propagation; allow the click to function normally } }; } else { let containerRect = container.getBoundingClientRect(); let newDWidth = containerRect.width; d.classList.add("poppedOut"); d.style.left = "0"; d.style.width = newDWidth + "px"; d.escapeHandler = function(event) { if (!d.contains(event.target)) { document.removeEventListener("click", d.escapeHandler, true); d.classList.remove("poppedOut"); d.style.left = ''; d.style.width = ''; setTitle(d); // Don't stop propagation; allow the click to function normally } }; } document.addEventListener("click", d.escapeHandler, true); setTitle(d); return true; } function setupScreenshotReplay(d) { d.player = new DOMReplay(d); createFullscreenButton(d); d.addEventListener("click", function(event) { if (tryPopOut(d, event)) { return; } if (document.fullscreenElement == d) { document.exitFullscreen(); event.stopPropagation(); } }); setTitle(d); } for (let d of document.querySelectorAll(".DOMRecScreenshot")) { onloaded(d, function() { setupScreenshotReplay(d); }); } function setupMovieReplay(d) { d.player = new DOMReplay(d); let replayIndicator = document.createElement("div"); d.appendChild(replayIndicator); let play = document.createElement("button"); play.className = "play"; d.appendChild(play); createFullscreenButton(d); d.addEventListener("click", function(event) { if (tryPopOut(d, event)) { return; } event.stopPropagation(); if (d.player.stopped()) { d.player.play({loop:true}); } else { d.player.stop(); } }); setTitle(d); } for (let d of document.querySelectorAll(".DOMRecMovie:not(.demo)")) { onloaded(d, function() { setupMovieReplay(d); }); } window.addEventListener("click", function(event) { if (event.target.classList.contains("DOMRecShowDemo")) { let demo = event.target.nextSibling; demo.classList.toggle("show"); if (demo.player) { if (demo.classList.contains("show")) { demo.player.play({loop:true}); } else { demo.player.stop(); } } else { DOMSetupReplay(demo); onloaded(demo, function() { setupMovieReplay(demo); demo.player.play({loop:true}); }); } event.preventDefault(); event.stopPropagation(); } }); } function DOMReplayLoadStylesheets() { if (!DOMRecScriptURL) { // We were injected, not loaded, so just bail out. return; } // The ?1 suffix distinguishes this resource from non-CORS direct loads, to // ensure the results are cached separately. Cloudfront/S3 doesn't set CORS // headers on non-CORS loads. let promises = [DOMSetupReplayPromise]; for (let s in DOMREC_REPLAY_FRAME_STYLESHEETS) { let cached = s; let url = rewriteResourceURL(DOMREC_REPLAY_FRAME_STYLESHEETS[s]); promises.push(window.fetch(url).then(function(response) { if (!response.ok) { throw "Failed to load " + url + ": " + response.statusText; } return response.text(); }).then(function(text) { if (typeof text != "string") { throw "Unexpected source text: " + text; } DOMRecStylesheetCache[cached] = text; })); } Promise.all(promises).then(DOMReplayStylesheetCacheLoaded); } DOMReplayLoadStylesheets(); window.addEventListener("load", function() { document.body.classList.add("loaded"); });
waitForFonts
location-map.js
import Ember from 'ember'; export default Ember.Component.extend({ maps: Ember.inject.service(), didInsertElement() { this._super(...arguments);
} });
let location = this.get('location'); let mapElement = this.get('maps').getMapElement(location); this.$('map-container').append(mapElement);
lib.rs
use itertools::Itertools; use std::collections::{HashSet, VecDeque}; type Point = (usize, usize); fn get_neighbors(pos: &Point, n: usize, m: usize) -> Vec<Point> { let x = pos.0 as i32; let y = pos.1 as i32; let neighbors = vec![ ((x - 1) as usize, y as usize), ((x + 1) as usize, y as usize), (x as usize, (y - 1) as usize), (x as usize, (y + 1) as usize), ((x + 1) as usize, (y - 1) as usize), ((x - 1) as usize, (y + 1) as usize), ((x + 1) as usize, (y + 1) as usize), ((x - 1) as usize, (y - 1) as usize), ]; neighbors .into_iter() .filter(|&(x, y)| x < n && y < m) .collect() } /// 1. Each octopus energy increases by 1. /// 1. Each octopus energy greater than 9 flashes. /// 1. All adjacent octopus get 1 energy from flashing /// 1. Octupus can flash at most once /// 1. Octupus that flash return to 0 fn octopus_flashes(octopus_energies: &mut Vec<Vec<u32>>) -> u32 { let mut flashed: HashSet<Point> = HashSet::new(); let mut flashes = VecDeque::new(); let mut flash_count = 0; for x in 0..octopus_energies.len() { for y in 0..octopus_energies[x].len() { octopus_energies[x][y] += 1; } } for x in 0..octopus_energies.len() { for y in 0..octopus_energies[x].len() { flashes.push_back((x, y)); while !flashes.is_empty() { if let Some((i, j)) = flashes.pop_front() { let octopus = octopus_energies[i][j]; if octopus > 9 && !flashed.contains(&(i, j)) { flashed.insert((i, j)); flash_count += 1; for neighbor in get_neighbors( &(i, j), octopus_energies.len(), octopus_energies[x].len(), ) { octopus_energies[neighbor.0][neighbor.1] += 1; flashes.push_back(neighbor); } } } } } } for flash in flashed { octopus_energies[flash.0][flash.1] = 0; } flash_count } fn all_octopus_flashed(octopus_energies: &mut Vec<Vec<u32>>) -> bool { let mut flashed: HashSet<Point> = HashSet::new(); let mut flashes = VecDeque::new(); let mut flash_count = 0; for x in 0..octopus_energies.len() { for y in 0..octopus_energies[x].len() { octopus_energies[x][y] += 1; } } for x in 0..octopus_energies.len() { for y in 0..octopus_energies[x].len() { flashes.push_back((x, y)); while !flashes.is_empty() { if let Some((i, j)) = flashes.pop_front() { let octopus = octopus_energies[i][j]; if octopus > 9 && !flashed.contains(&(i, j)) { flashed.insert((i, j)); flash_count += 1; for neighbor in get_neighbors( &(i, j), octopus_energies.len(), octopus_energies[x].len(), ) { octopus_energies[neighbor.0][neighbor.1] += 1; flashes.push_back(neighbor); } } } } } } for flash in &flashed { octopus_energies[flash.0][flash.1] = 0; } flashed.len() == octopus_energies.len() * octopus_energies[0].len() } #[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::prelude::*; const EXAMPLE_INPUT: &str = "example_input.txt"; const PUZZLE_INPUT: &str = "puzzle_input.txt"; #[test] fn
() { let mut octopy = vec![ vec![5, 4, 8, 3, 1, 4, 3, 2, 2, 3], vec![2, 7, 4, 5, 8, 5, 4, 7, 1, 1], vec![5, 2, 6, 4, 5, 5, 6, 1, 7, 3], vec![6, 1, 4, 1, 3, 3, 6, 1, 4, 6], vec![6, 3, 5, 7, 3, 8, 5, 4, 7, 8], vec![4, 1, 6, 7, 5, 2, 4, 6, 4, 5], vec![2, 1, 7, 6, 8, 4, 1, 7, 2, 1], vec![6, 8, 8, 2, 8, 8, 1, 1, 3, 4], vec![4, 8, 4, 6, 8, 4, 8, 5, 5, 4], vec![5, 2, 8, 3, 7, 5, 1, 5, 2, 6], ]; let mut flashes = 0; for i in 0..10 { flashes += octopus_flashes(&mut octopy); } assert_eq!(204, flashes); for _ in 0..90 { flashes += octopus_flashes(&mut octopy); } assert_eq!(1656, flashes); } #[test] fn example_all_octupus_flashed() { let mut octopy = vec![ vec![5, 4, 8, 3, 1, 4, 3, 2, 2, 3], vec![2, 7, 4, 5, 8, 5, 4, 7, 1, 1], vec![5, 2, 6, 4, 5, 5, 6, 1, 7, 3], vec![6, 1, 4, 1, 3, 3, 6, 1, 4, 6], vec![6, 3, 5, 7, 3, 8, 5, 4, 7, 8], vec![4, 1, 6, 7, 5, 2, 4, 6, 4, 5], vec![2, 1, 7, 6, 8, 4, 1, 7, 2, 1], vec![6, 8, 8, 2, 8, 8, 1, 1, 3, 4], vec![4, 8, 4, 6, 8, 4, 8, 5, 5, 4], vec![5, 2, 8, 3, 7, 5, 1, 5, 2, 6], ]; for _ in 0..194 { all_octopus_flashed(&mut octopy); } assert_eq!(true, all_octopus_flashed(&mut octopy)); } #[test] fn octopus_flash() { let mut octopy = vec![ vec![5, 6, 5, 1, 3, 4, 1, 4, 5, 2], vec![1, 3, 8, 1, 5, 4, 1, 2, 5, 2], vec![1, 8, 7, 8, 4, 3, 5, 2, 2, 4], vec![6, 8, 1, 4, 8, 3, 1, 5, 3, 5], vec![3, 8, 8, 3, 5, 4, 7, 3, 8, 3], vec![6, 4, 7, 3, 5, 4, 8, 4, 6, 4], vec![1, 8, 8, 5, 8, 3, 3, 6, 5, 8], vec![3, 7, 3, 2, 5, 8, 4, 7, 5, 2], vec![1, 8, 8, 1, 5, 4, 6, 1, 2, 8], vec![5, 1, 2, 1, 7, 1, 7, 7, 7, 6], ]; let mut flashes = 0; for _ in 0..100 { flashes += octopus_flashes(&mut octopy); } assert_eq!(1625, flashes); } #[test] fn all_octopus_flash() { let mut octopy = vec![ vec![5, 6, 5, 1, 3, 4, 1, 4, 5, 2], vec![1, 3, 8, 1, 5, 4, 1, 2, 5, 2], vec![1, 8, 7, 8, 4, 3, 5, 2, 2, 4], vec![6, 8, 1, 4, 8, 3, 1, 5, 3, 5], vec![3, 8, 8, 3, 5, 4, 7, 3, 8, 3], vec![6, 4, 7, 3, 5, 4, 8, 4, 6, 4], vec![1, 8, 8, 5, 8, 3, 3, 6, 5, 8], vec![3, 7, 3, 2, 5, 8, 4, 7, 5, 2], vec![1, 8, 8, 1, 5, 4, 6, 1, 2, 8], vec![5, 1, 2, 1, 7, 1, 7, 7, 7, 6], ]; let mut count = 0; loop { count += 1; if all_octopus_flashed(&mut octopy) { break; } } assert_eq!(244, count); } }
example_octupus_flashes
api.rs
// example API function #[get("/test")] pub fn test_func() { println!("Successful request to /api/test")
}
bridge.py
import rospy import tf from geometry_msgs.msg import PoseStamped, Quaternion, TwistStamped from dbw_mkz_msgs.msg import SteeringReport, ThrottleCmd, BrakeCmd, SteeringCmd from std_msgs.msg import Float32 as Float from std_msgs.msg import Bool from sensor_msgs.msg import PointCloud2 from sensor_msgs.msg import Image import sensor_msgs.point_cloud2 as pcl2 from std_msgs.msg import Header from cv_bridge import CvBridge, CvBridgeError from styx_msgs.msg import TrafficLight, TrafficLightArray, Lane import numpy as np from PIL import Image as PIL_Image from io import BytesIO import base64 import math TYPE = { 'bool': Bool, 'float': Float, 'pose': PoseStamped, 'pcl': PointCloud2, 'twist': TwistStamped, 'steer': SteeringReport, 'trafficlights': TrafficLightArray, 'steer_cmd': SteeringCmd, 'brake_cmd': BrakeCmd, 'throttle_cmd': ThrottleCmd, 'path_draw': Lane, 'image':Image } NUM_IMAGES_TO_SKIP = 2 class Bridge(object): def __init__(self, conf, server): rospy.init_node('styx_server') self.server = server self.vel = 0. self.yaw = None self.angular_vel = 0. self.bridge = CvBridge() self.img_count = 0 self.callbacks = { '/vehicle/steering_cmd': self.callback_steering, '/vehicle/throttle_cmd': self.callback_throttle, '/vehicle/brake_cmd': self.callback_brake, '/final_waypoints': self.callback_path } self.subscribers = [rospy.Subscriber(e.topic, TYPE[e.type], self.callbacks[e.topic]) for e in conf.subscribers] self.publishers = {e.name: rospy.Publisher(e.topic, TYPE[e.type], queue_size=1) for e in conf.publishers} def create_light(self, x, y, z, yaw, state): light = TrafficLight() light.header = Header() light.header.stamp = rospy.Time.now() light.header.frame_id = '/world' light.pose = self.create_pose(x, y, z, yaw) light.state = state return light def create_pose(self, x, y, z, yaw=0.): pose = PoseStamped() pose.header = Header() pose.header.stamp = rospy.Time.now() pose.header.frame_id = '/world' pose.pose.position.x = x pose.pose.position.y = y pose.pose.position.z = z q = tf.transformations.quaternion_from_euler(0., 0., math.pi * yaw/180.) pose.pose.orientation = Quaternion(*q) return pose def create_float(self, val):
return fl def create_twist(self, velocity, angular): tw = TwistStamped() tw.twist.linear.x = velocity tw.twist.angular.z = angular return tw def create_steer(self, val): st = SteeringReport() st.steering_wheel_angle_cmd = val * math.pi/180. st.enabled = True st.speed = self.vel return st def calc_angular(self, yaw): angular_vel = 0. if self.yaw is not None: angular_vel = (yaw - self.yaw)/(rospy.get_time() - self.prev_time) self.yaw = yaw self.prev_time = rospy.get_time() return angular_vel def create_point_cloud_message(self, pts): header = Header() header.stamp = rospy.Time.now() header.frame_id = '/world' cloud_message = pcl2.create_cloud_xyz32(header, pts) return cloud_message def broadcast_transform(self, name, position, orientation): br = tf.TransformBroadcaster() br.sendTransform(position, orientation, rospy.Time.now(), name, "world") def publish_odometry(self, data): pose = self.create_pose(data['x'], data['y'], data['z'], data['yaw']) position = (data['x'], data['y'], data['z']) orientation = tf.transformations.quaternion_from_euler(0, 0, math.pi * data['yaw']/180.) self.broadcast_transform("base_link", position, orientation) self.publishers['current_pose'].publish(pose) self.vel = data['velocity']* 0.44704 self.angular = self.calc_angular(data['yaw'] * math.pi/180.) self.publishers['current_velocity'].publish(self.create_twist(self.vel, self.angular)) def publish_controls(self, data): steering, throttle, brake = data['steering_angle'], data['throttle'], data['brake'] self.publishers['steering_report'].publish(self.create_steer(steering)) self.publishers['throttle_report'].publish(self.create_float(throttle)) self.publishers['brake_report'].publish(self.create_float(brake)) def publish_obstacles(self, data): for obs in data['obstacles']: pose = self.create_pose(obs[0], obs[1], obs[2]) self.publishers['obstacle'].publish(pose) header = Header() header.stamp = rospy.Time.now() header.frame_id = '/world' cloud = pcl2.create_cloud_xyz32(header, data['obstacles']) self.publishers['obstacle_points'].publish(cloud) def publish_lidar(self, data): self.publishers['lidar'].publish(self.create_point_cloud_message(zip(data['lidar_x'], data['lidar_y'], data['lidar_z']))) def publish_traffic(self, data): x, y, z = data['light_pos_x'], data['light_pos_y'], data['light_pos_z'], yaw = [math.atan2(dy, dx) for dx, dy in zip(data['light_pos_dx'], data['light_pos_dy'])] status = data['light_state'] lights = TrafficLightArray() header = Header() header.stamp = rospy.Time.now() header.frame_id = '/world' lights.lights = [self.create_light(*e) for e in zip(x, y, z, yaw, status)] self.publishers['trafficlights'].publish(lights) def publish_dbw_status(self, data): self.publishers['dbw_status'].publish(Bool(data)) def publish_camera(self, data): self.img_count += 1 if self.img_count >= NUM_IMAGES_TO_SKIP: # rospy.logwarn("Publish camera data") imgString = data["image"] image = PIL_Image.open(BytesIO(base64.b64decode(imgString))) image_array = np.asarray(image) image_message = self.bridge.cv2_to_imgmsg(image_array, encoding="rgb8") self.publishers['image'].publish(image_message) self.img_count = 0 def callback_steering(self, data): self.server('steer', data={'steering_angle': str(data.steering_wheel_angle_cmd)}) def callback_throttle(self, data): self.server('throttle', data={'throttle': str(data.pedal_cmd)}) def callback_brake(self, data): self.server('brake', data={'brake': str(data.pedal_cmd)}) def callback_path(self, data): x_values = [] y_values = [] z_values = [] for waypoint in data.waypoints: x = waypoint.pose.pose.position.x y = waypoint.pose.pose.position.y z = waypoint.pose.pose.position.z+0.5 x_values.append(x) y_values.append(y) z_values.append(z) self.server('drawline', data={'next_x': x_values, 'next_y': y_values, 'next_z': z_values})
fl = Float() fl.data = val
config_test.go
package main import ( "testing" ) func
(t *testing.T) { var tests = []struct { input string proto string addr string }{ { input: "localhost", proto: "", addr: "localhost", }, { input: "tls://my.local.domain", proto: "tls", addr: "my.local.domain", }, { input: "starttls://my.local.domain", proto: "starttls", addr: "my.local.domain", }, } for i, test := range tests { testName := test.input t.Run(testName, func(t *testing.T) { pa := splitProto(test.input) if pa.protocol != test.proto { t.Errorf("Testcase %d: Incorrect proto: expected %v, got %v", i, test.proto, pa.protocol) } if pa.address != test.addr { t.Errorf("Testcase %d: Incorrect addr: expected %v, got %v", i, test.addr, pa.address) } }) } }
TestSplitProto
tsne_p.py
# Generated with SMOP 0.41 from libsmop import * # tsne_p.m @function def tsne_p(P=None,labels=None,no_dims=None,*args,**kwargs): varargin = tsne_p.varargin nargin = tsne_p.nargin #TSNE_P Performs symmetric t-SNE on affinity matrix P # mappedX = tsne_p(P, labels, no_dims) # The function performs symmetric t-SNE on pairwise similarity matrix P # to create a low-dimensional map of no_dims dimensions (default = 2). # The matrix P is assumed to be symmetric, sum up to 1, and have zeros # on the diagonal. # The labels of the data are not used by t-SNE itself, however, they # are used to color intermediate plots. Please provide an empty labels # matrix [] if you don't want to plot results during the optimization. # The low-dimensional data representation is returned in mappedX. # (C) Laurens van der Maaten, 2010 # University of California, San Diego if logical_not(exist('labels','var')): labels=[] # tsne_p.m:21 if logical_not(exist('no_dims','var')) or isempty(no_dims): no_dims=2 # tsne_p.m:24 # First check whether we already have an initial solution if numel(no_dims) > 1: initial_solution=copy(true) # tsne_p.m:29 ydata=copy(no_dims) # tsne_p.m:30 no_dims=size(ydata,2) # tsne_p.m:31 else: initial_solution=copy(false) # tsne_p.m:33 # Initialize some variables n=size(P,1) # tsne_p.m:37 momentum=0.5 # tsne_p.m:38 final_momentum=0.8
# tsne_p.m:39 mom_switch_iter=250 # tsne_p.m:40 stop_lying_iter=100 # tsne_p.m:41 max_iter=1000 # tsne_p.m:42 epsilon=500 # tsne_p.m:43 min_gain=0.01 # tsne_p.m:44 # Make sure P-vals are set properly P[arange(1,end(),n + 1)]=0 # tsne_p.m:47 P=dot(0.5,(P + P.T)) # tsne_p.m:48 P=max(P / sum(ravel(P)),realmin) # tsne_p.m:49 const=sum(multiply(ravel(P),log(ravel(P)))) # tsne_p.m:50 if logical_not(initial_solution): P=dot(P,4) # tsne_p.m:52 # Initialize the solution if logical_not(initial_solution): ydata=dot(0.0001,randn(n,no_dims)) # tsne_p.m:57 y_incs=zeros(size(ydata)) # tsne_p.m:59 gains=ones(size(ydata)) # tsne_p.m:60 for iter in arange(1,max_iter).reshape(-1): # Compute joint probability that point i and j are neighbors sum_ydata=sum(ydata ** 2,2) # tsne_p.m:66 num=1 / (1 + bsxfun(plus,sum_ydata,bsxfun(plus,sum_ydata.T,dot(- 2,(dot(ydata,ydata.T)))))) # tsne_p.m:67 num[arange(1,end(),n + 1)]=0 # tsne_p.m:68 Q=max(num / sum(ravel(num)),realmin) # tsne_p.m:69 # Compute the gradients (faster implementation) L=multiply((P - Q),num) # tsne_p.m:72 y_grads=dot(dot(4,(diag(sum(L,1)) - L)),ydata) # tsne_p.m:73 gains=multiply((gains + 0.2),(sign(y_grads) != sign(y_incs))) + multiply((dot(gains,0.8)),(sign(y_grads) == sign(y_incs))) # tsne_p.m:76 gains[gains < min_gain]=min_gain # tsne_p.m:78 y_incs=dot(momentum,y_incs) - dot(epsilon,(multiply(gains,y_grads))) # tsne_p.m:79 ydata=ydata + y_incs # tsne_p.m:80 ydata=bsxfun(minus,ydata,mean(ydata,1)) # tsne_p.m:81 if iter == mom_switch_iter: momentum=copy(final_momentum) # tsne_p.m:85 if iter == stop_lying_iter and logical_not(initial_solution): P=P / 4 # tsne_p.m:88 # Print out progress if logical_not(rem(iter,10)): cost=const - sum(multiply(ravel(P),log(ravel(Q)))) # tsne_p.m:93 disp(concat(['Iteration ',num2str(iter),': error is ',num2str(cost)])) # Display scatter plot (maximally first three dimensions) if logical_not(rem(iter,10)) and logical_not(isempty(labels)): if no_dims == 1: scatter(ydata,ydata,9,labels,'filled') else: if no_dims == 2: scatter(ydata(arange(),1),ydata(arange(),2),9,labels,'filled') else: scatter3(ydata(arange(),1),ydata(arange(),2),ydata(arange(),3),40,labels,'filled') axis('tight') axis('off') drawnow
lib.rs
//! `bellperson` is a crate for building zk-SNARK circuits. It provides circuit //! traits and and primitive structures, as well as basic gadget implementations //! such as booleans and number abstractions. //! //! # Example circuit //! //! Say we want to write a circuit that proves we know the preimage to some hash //! computed using SHA-256d (calling SHA-256 twice). The preimage must have a //! fixed length known in advance (because the circuit parameters will depend on //! it), but can otherwise have any value. We take the following strategy: //! //! - Witness each bit of the preimage. //! - Compute `hash = SHA-256d(preimage)` inside the circuit. //! - Expose `hash` as a public input using multiscalar packing. //! //! ``` //! use bellperson::{ //! gadgets::{ //! boolean::{AllocatedBit, Boolean}, //! multipack, //! sha256::sha256, //! }, //! groth16, Circuit, ConstraintSystem, SynthesisError, //! }; //! use paired::{bls12_381::Bls12, Engine}; //! use rand::rngs::OsRng; //! use sha2::{Digest, Sha256}; //! //! /// Our own SHA-256d gadget. Input and output are in little-endian bit order. //! fn sha256d<E: Engine, CS: ConstraintSystem<E>>( //! mut cs: CS, //! data: &[Boolean], //! ) -> Result<Vec<Boolean>, SynthesisError> { //! // Flip endianness of each input byte //! let input: Vec<_> = data //! .chunks(8) //! .map(|c| c.iter().rev()) //! .flatten() //! .cloned() //! .collect(); //! //! let mid = sha256(cs.namespace(|| "SHA-256(input)"), &input)?; //! let res = sha256(cs.namespace(|| "SHA-256(mid)"), &mid)?; //! //! // Flip endianness of each output byte //! Ok(res //! .chunks(8) //! .map(|c| c.iter().rev()) //! .flatten() //! .cloned() //! .collect()) //! } //! //! struct MyCircuit { //! /// The input to SHA-256d we are proving that we know. Set to `None` when we //! /// are verifying a proof (and do not have the witness data). //! preimage: Option<[u8; 80]>, //! } //! //! impl<E: Engine> Circuit<E> for MyCircuit { //! fn synthesize<CS: ConstraintSystem<E>>(self, cs: &mut CS) -> Result<(), SynthesisError> { //! // Compute the values for the bits of the preimage. If we are verifying a proof, //! // we still need to create the same constraints, so we return an equivalent-size //! // Vec of None (indicating that the value of each bit is unknown). //! let bit_values = if let Some(preimage) = self.preimage { //! preimage //! .into_iter() //! .map(|byte| (0..8).map(move |i| (byte >> i) & 1u8 == 1u8)) //! .flatten() //! .map(|b| Some(b)) //! .collect() //! } else { //! vec![None; 80 * 8] //! }; //! assert_eq!(bit_values.len(), 80 * 8); //! //! // Witness the bits of the preimage. //! let preimage_bits = bit_values //! .into_iter() //! .enumerate() //! // Allocate each bit. //! .map(|(i, b)| { //! AllocatedBit::alloc(cs.namespace(|| format!("preimage bit {}", i)), b) //! }) //! // Convert the AllocatedBits into Booleans (required for the sha256 gadget). //! .map(|b| b.map(Boolean::from)) //! .collect::<Result<Vec<_>, _>>()?; //! //! // Compute hash = SHA-256d(preimage). //! let hash = sha256d(cs.namespace(|| "SHA-256d(preimage)"), &preimage_bits)?; //! //! // Expose the vector of 32 boolean variables as compact public inputs. //! multipack::pack_into_inputs(cs.namespace(|| "pack hash"), &hash) //! } //! } //! //! // Create parameters for our circuit. In a production deployment these would //! // be generated securely using a multiparty computation. //! let params = { //! let c = MyCircuit { preimage: None }; //! groth16::generate_random_parameters::<Bls12, _, _>(c, &mut OsRng).unwrap() //! }; //! //! // Prepare the verification key (for proof verification). //! let pvk = groth16::prepare_verifying_key(&params.vk); //! //! // Pick a preimage and compute its hash. //! let preimage = [42; 80]; //! let hash = Sha256::digest(&Sha256::digest(&preimage)); //! //! // Create an instance of our circuit (with the preimage as a witness). //! let c = MyCircuit { //! preimage: Some(preimage), //! }; //! //! // Create a Groth16 proof with our parameters. //! let proof = groth16::create_random_proof(c, &params, &mut OsRng).unwrap(); //! //! // Pack the hash as inputs for proof verification. //! let hash_bits = multipack::bytes_to_bits_le(&hash); //! let inputs = multipack::compute_multipacking::<Bls12>(&hash_bits); //! //! // Check the proof! //! assert!(groth16::verify_proof(&pvk, &proof, &inputs).unwrap()); //! ``` //! //! # Roadmap //! //! `bellperson` is being refactored into a generic proving library. Currently it //! is pairing-specific, and different types of proving systems need to be //! implemented as sub-modules. After the refactor, `bellperson` will be generic //! using the [`ff`] and [`group`] crates, while specific proving systems will //! be separate crates that pull in the dependencies they require. // Catch documentation errors caused by code changes. #![deny(intra_doc_link_resolution_failure)] #[cfg(test)] #[macro_use] extern crate hex_literal; pub mod domain; pub mod gadgets; mod gpu; #[cfg(feature = "groth16")] pub mod groth16; pub mod multicore; pub mod multiexp; #[cfg(feature = "gpu")] pub use gpu::GPU_NVIDIA_DEVICES; use ff::{Field, ScalarEngine}; use std::error::Error; use std::fmt; use std::io; use std::marker::PhantomData; use std::ops::{Add, Sub}; /// Computations are expressed in terms of arithmetic circuits, in particular /// rank-1 quadratic constraint systems. The `Circuit` trait represents a /// circuit that can be synthesized. The `synthesize` method is called during /// CRS generation and during proving. pub trait Circuit<E: ScalarEngine> { /// Synthesize the circuit into a rank-1 quadratic constraint system fn synthesize<CS: ConstraintSystem<E>>(self, cs: &mut CS) -> Result<(), SynthesisError>; } /// Represents a variable in our constraint system. #[derive(Copy, Clone, Debug)] pub struct Variable(Index); impl Variable { /// This constructs a variable with an arbitrary index. /// Circuit implementations are not recommended to use this. pub fn new_unchecked(idx: Index) -> Variable { Variable(idx) } /// This returns the index underlying the variable. /// Circuit implementations are not recommended to use this. pub fn get_unchecked(&self) -> Index { self.0 } } /// Represents the index of either an input variable or /// auxiliary variable. #[derive(Copy, Clone, PartialEq, Debug)] pub enum Index { Input(usize), Aux(usize), } /// This represents a linear combination of some variables, with coefficients /// in the scalar field of a pairing-friendly elliptic curve group. #[derive(Clone)] pub struct LinearCombination<E: ScalarEngine>(Vec<(Variable, E::Fr)>); impl<E: ScalarEngine> AsRef<[(Variable, E::Fr)]> for LinearCombination<E> { fn as_ref(&self) -> &[(Variable, E::Fr)] { &self.0 } } impl<E: ScalarEngine> LinearCombination<E> { pub fn zero() -> LinearCombination<E> { LinearCombination(vec![]) } } impl<E: ScalarEngine> Add<(E::Fr, Variable)> for LinearCombination<E> { type Output = LinearCombination<E>; fn add(mut self, (coeff, var): (E::Fr, Variable)) -> LinearCombination<E> { self.0.push((var, coeff)); self } } impl<E: ScalarEngine> Sub<(E::Fr, Variable)> for LinearCombination<E> { type Output = LinearCombination<E>; #[allow(clippy::suspicious_arithmetic_impl)] fn sub(self, (mut coeff, var): (E::Fr, Variable)) -> LinearCombination<E> { coeff.negate(); self + (coeff, var) } } impl<E: ScalarEngine> Add<Variable> for LinearCombination<E> { type Output = LinearCombination<E>; fn add(self, other: Variable) -> LinearCombination<E> { self + (E::Fr::one(), other) } } impl<E: ScalarEngine> Sub<Variable> for LinearCombination<E> { type Output = LinearCombination<E>; fn sub(self, other: Variable) -> LinearCombination<E> { self - (E::Fr::one(), other) } } impl<'a, E: ScalarEngine> Add<&'a LinearCombination<E>> for LinearCombination<E> { type Output = LinearCombination<E>; fn add(mut self, other: &'a LinearCombination<E>) -> LinearCombination<E> { for s in &other.0 { self = self + (s.1, s.0); } self } } impl<'a, E: ScalarEngine> Sub<&'a LinearCombination<E>> for LinearCombination<E> { type Output = LinearCombination<E>; fn sub(mut self, other: &'a LinearCombination<E>) -> LinearCombination<E> { for s in &other.0 { self = self - (s.1, s.0); } self } } impl<'a, E: ScalarEngine> Add<(E::Fr, &'a LinearCombination<E>)> for LinearCombination<E> { type Output = LinearCombination<E>; fn add(mut self, (coeff, other): (E::Fr, &'a LinearCombination<E>)) -> LinearCombination<E> { for s in &other.0 { let mut tmp = s.1; tmp.mul_assign(&coeff); self = self + (tmp, s.0); } self } } impl<'a, E: ScalarEngine> Sub<(E::Fr, &'a LinearCombination<E>)> for LinearCombination<E> { type Output = LinearCombination<E>; fn sub(mut self, (coeff, other): (E::Fr, &'a LinearCombination<E>)) -> LinearCombination<E> { for s in &other.0 { let mut tmp = s.1; tmp.mul_assign(&coeff); self = self - (tmp, s.0); } self } } /// This is an error that could occur during circuit synthesis contexts, /// such as CRS generation, proving or verification. #[derive(Debug)] pub enum SynthesisError { /// During synthesis, we lacked knowledge of a variable assignment. AssignmentMissing, /// During synthesis, we divided by zero. DivisionByZero, /// During synthesis, we constructed an unsatisfiable constraint system. Unsatisfiable, /// During synthesis, our polynomials ended up being too high of degree PolynomialDegreeTooLarge, /// During proof generation, we encountered an identity in the CRS UnexpectedIdentity, /// During proof generation, we encountered an I/O error with the CRS IoError(io::Error), /// During verification, our verifying key was malformed. MalformedVerifyingKey, /// During CRS generation, we observed an unconstrained auxiliary variable UnconstrainedVariable, } impl From<io::Error> for SynthesisError { fn from(e: io::Error) -> SynthesisError
} impl Error for SynthesisError { fn description(&self) -> &str { match *self { SynthesisError::AssignmentMissing => { "an assignment for a variable could not be computed" } SynthesisError::DivisionByZero => "division by zero", SynthesisError::Unsatisfiable => "unsatisfiable constraint system", SynthesisError::PolynomialDegreeTooLarge => "polynomial degree is too large", SynthesisError::UnexpectedIdentity => "encountered an identity element in the CRS", SynthesisError::IoError(_) => "encountered an I/O error", SynthesisError::MalformedVerifyingKey => "malformed verifying key", SynthesisError::UnconstrainedVariable => "auxiliary variable was unconstrained", } } } impl fmt::Display for SynthesisError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { if let SynthesisError::IoError(ref e) = *self { write!(f, "I/O error: ")?; e.fmt(f) } else { write!(f, "{}", self.description()) } } } /// Represents a constraint system which can have new variables /// allocated and constrains between them formed. pub trait ConstraintSystem<E: ScalarEngine>: Sized { /// Represents the type of the "root" of this constraint system /// so that nested namespaces can minimize indirection. type Root: ConstraintSystem<E>; /// Return the "one" input variable fn one() -> Variable { Variable::new_unchecked(Index::Input(0)) } /// Allocate a private variable in the constraint system. The provided function is used to /// determine the assignment of the variable. The given `annotation` function is invoked /// in testing contexts in order to derive a unique name for this variable in the current /// namespace. fn alloc<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError> where F: FnOnce() -> Result<E::Fr, SynthesisError>, A: FnOnce() -> AR, AR: Into<String>; /// Allocate a public variable in the constraint system. The provided function is used to /// determine the assignment of the variable. fn alloc_input<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError> where F: FnOnce() -> Result<E::Fr, SynthesisError>, A: FnOnce() -> AR, AR: Into<String>; /// Enforce that `A` * `B` = `C`. The `annotation` function is invoked in testing contexts /// in order to derive a unique name for the constraint in the current namespace. fn enforce<A, AR, LA, LB, LC>(&mut self, annotation: A, a: LA, b: LB, c: LC) where A: FnOnce() -> AR, AR: Into<String>, LA: FnOnce(LinearCombination<E>) -> LinearCombination<E>, LB: FnOnce(LinearCombination<E>) -> LinearCombination<E>, LC: FnOnce(LinearCombination<E>) -> LinearCombination<E>; /// Create a new (sub)namespace and enter into it. Not intended /// for downstream use; use `namespace` instead. fn push_namespace<NR, N>(&mut self, name_fn: N) where NR: Into<String>, N: FnOnce() -> NR; /// Exit out of the existing namespace. Not intended for /// downstream use; use `namespace` instead. fn pop_namespace(&mut self); /// Gets the "root" constraint system, bypassing the namespacing. /// Not intended for downstream use; use `namespace` instead. fn get_root(&mut self) -> &mut Self::Root; /// Begin a namespace for this constraint system. fn namespace<NR, N>(&mut self, name_fn: N) -> Namespace<'_, E, Self::Root> where NR: Into<String>, N: FnOnce() -> NR, { self.get_root().push_namespace(name_fn); Namespace(self.get_root(), PhantomData) } } /// This is a "namespaced" constraint system which borrows a constraint system (pushing /// a namespace context) and, when dropped, pops out of the namespace context. pub struct Namespace<'a, E: ScalarEngine, CS: ConstraintSystem<E>>(&'a mut CS, PhantomData<E>); impl<'cs, E: ScalarEngine, CS: ConstraintSystem<E>> ConstraintSystem<E> for Namespace<'cs, E, CS> { type Root = CS::Root; fn one() -> Variable { CS::one() } fn alloc<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError> where F: FnOnce() -> Result<E::Fr, SynthesisError>, A: FnOnce() -> AR, AR: Into<String>, { self.0.alloc(annotation, f) } fn alloc_input<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError> where F: FnOnce() -> Result<E::Fr, SynthesisError>, A: FnOnce() -> AR, AR: Into<String>, { self.0.alloc_input(annotation, f) } fn enforce<A, AR, LA, LB, LC>(&mut self, annotation: A, a: LA, b: LB, c: LC) where A: FnOnce() -> AR, AR: Into<String>, LA: FnOnce(LinearCombination<E>) -> LinearCombination<E>, LB: FnOnce(LinearCombination<E>) -> LinearCombination<E>, LC: FnOnce(LinearCombination<E>) -> LinearCombination<E>, { self.0.enforce(annotation, a, b, c) } // Downstream users who use `namespace` will never interact with these // functions and they will never be invoked because the namespace is // never a root constraint system. fn push_namespace<NR, N>(&mut self, _: N) where NR: Into<String>, N: FnOnce() -> NR, { panic!("only the root's push_namespace should be called"); } fn pop_namespace(&mut self) { panic!("only the root's pop_namespace should be called"); } fn get_root(&mut self) -> &mut Self::Root { self.0.get_root() } } impl<'a, E: ScalarEngine, CS: ConstraintSystem<E>> Drop for Namespace<'a, E, CS> { fn drop(&mut self) { self.get_root().pop_namespace() } } /// Convenience implementation of ConstraintSystem<E> for mutable references to /// constraint systems. impl<'cs, E: ScalarEngine, CS: ConstraintSystem<E>> ConstraintSystem<E> for &'cs mut CS { type Root = CS::Root; fn one() -> Variable { CS::one() } fn alloc<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError> where F: FnOnce() -> Result<E::Fr, SynthesisError>, A: FnOnce() -> AR, AR: Into<String>, { (**self).alloc(annotation, f) } fn alloc_input<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError> where F: FnOnce() -> Result<E::Fr, SynthesisError>, A: FnOnce() -> AR, AR: Into<String>, { (**self).alloc_input(annotation, f) } fn enforce<A, AR, LA, LB, LC>(&mut self, annotation: A, a: LA, b: LB, c: LC) where A: FnOnce() -> AR, AR: Into<String>, LA: FnOnce(LinearCombination<E>) -> LinearCombination<E>, LB: FnOnce(LinearCombination<E>) -> LinearCombination<E>, LC: FnOnce(LinearCombination<E>) -> LinearCombination<E>, { (**self).enforce(annotation, a, b, c) } fn push_namespace<NR, N>(&mut self, name_fn: N) where NR: Into<String>, N: FnOnce() -> NR, { (**self).push_namespace(name_fn) } fn pop_namespace(&mut self) { (**self).pop_namespace() } fn get_root(&mut self) -> &mut Self::Root { (**self).get_root() } }
{ SynthesisError::IoError(e) }
ChannelDetailsVideos.tsx
import { IPanelProps } from '@blueprintjs/core' import _ from 'lodash' import pluralize from 'pluralize' import * as React from 'react' import { ChannelDetailsProps } from 'components/ChannelDetails' import { ChannelDetailsType } from 'components/ChannelDetailsOverview' import ChannelDetailsPanel from 'components/ChannelDetailsPanel' import ExternalResource, { Resource, ResourceType } from 'components/ExternalResource' import NonIdealState from 'components/NonIdealState' import Spinner from 'components/Spinner' import Twitch, { ClipPeriod } from 'libs/Twitch' import styled, { theme } from 'styled' /** * ChannelDetailsVideo component. */ const ChannelDetailsVideo = styled(ExternalResource)` &:hover { background-color: ${theme('channel.background')}; } ` /** * React State. */ const initialState = { didFail: false, videos: undefined as Optional<Resource[]> } type State = Readonly<typeof initialState> /** * ChannelDetailsVideos Component. */ export default class ChannelDetailsVideos extends React.Component<IPanelProps & ChannelDetailsProps & Props, State> { public state: State = initialState /** * Lifecycle: componentDidMount. */ public async componentDidMount() { const { id, name, type } = this.props try { if (type === ChannelDetailsType.LastVods) { const { videos } = await Twitch.fetchChannelVideos(id, 10) const parsedVideos = _.map(videos, (video) => ({ id: video._id, meta: `${new Date(video.created_at).toLocaleDateString()} - ${video.views.toLocaleString()} ${pluralize( 'views', video.views )}`, text: video.title, thumbnail: video.preview.small, type: ResourceType.Vod, url: video.url, })) this.setState(() => ({ didFail: false, videos: parsedVideos })) } else if (type === ChannelDetailsType.TopClips || type === ChannelDetailsType.RecentClips) { const period = type === ChannelDetailsType.TopClips ? ClipPeriod.All : ClipPeriod.Week const { clips } = await Twitch.fetchTopClips(name, period) const parsedVideos = _.map(clips, (clip) => ({ id: clip.slug, meta: `${new Date(clip.created_at).toLocaleDateString()} - ${clip.views.toLocaleString()} ${pluralize( 'views', clip.views )} - ${clip.curator.display_name}`, text: clip.title,
url: clip.url, })) this.setState(() => ({ didFail: false, videos: parsedVideos })) } else { this.setState(() => ({ didFail: true })) } } catch { this.setState(() => ({ didFail: true })) } } /** * Renders the component. * @return Element to render. */ public render() { const { didFail, videos } = this.state if (didFail) { return <NonIdealState small retry /> } if (_.isUndefined(videos)) { return <Spinner /> } if (_.isNil(videos) || _.size(videos) === 0) { return <NonIdealState small title="Nothing yet!" retry /> } return ( <ChannelDetailsPanel minimal> {_.map(videos, (video) => ( <ChannelDetailsVideo key={video.id} resource={video} /> ))} </ChannelDetailsPanel> ) } } /** * React Props. */ interface Props { type: VideoType } /** * Channel video type. */ type VideoType = ChannelDetailsType.LastVods | ChannelDetailsType.RecentClips | ChannelDetailsType.TopClips /** * Channel details video. */ export type Video = { id: string meta: string thumbnail: string title: string type: VideoType url: string }
thumbnail: clip.thumbnails.small, type: ResourceType.Clip,
__init__.py
#!/usr/bin/env python """Generic parsers (for GRR server and client code).""" from typing import Iterator from typing import Text from typing import Type from typing import TypeVar from grr_response_core.lib import factory from grr_response_core.lib import rdfvalue from grr_response_core.lib.parsers import abstract from grr_response_core.lib.util import collection from grr_response_core.lib.util import precondition ParseError = abstract.ParseError Parser = abstract.Parser SingleResponseParser = abstract.SingleResponseParser SingleFileParser = abstract.SingleFileParser MultiResponseParser = abstract.MultiResponseParser MultiFileParser = abstract.MultiFileParser _Factory = factory.Factory _RDFValue = rdfvalue.RDFValue SINGLE_RESPONSE_PARSER_FACTORY: _Factory[SingleResponseParser[_RDFValue]] = ( _Factory(SingleResponseParser[_RDFValue])) MULTI_RESPONSE_PARSER_FACTORY: _Factory[MultiResponseParser[_RDFValue]] = ( _Factory(MultiResponseParser[_RDFValue])) SINGLE_FILE_PARSER_FACTORY: _Factory[SingleFileParser[_RDFValue]] = ( _Factory(SingleFileParser[_RDFValue])) MULTI_FILE_PARSER_FACTORY: _Factory[MultiFileParser[_RDFValue]] = ( _Factory(MultiFileParser[_RDFValue])) _P = TypeVar("_P", bound=Parser) class ArtifactParserFactory(object): """A factory wrapper class that yields parsers for specific artifact.""" def __init__(self, artifact_name: Text) -> None: """Initializes the artifact parser factory. Args: artifact_name: A name of the artifact this factory is supposed to provide parser instances for. """ precondition.AssertType(artifact_name, Text) self._artifact_name = artifact_name def HasParsers(self) -> bool: return (self.HasSingleResponseParsers() or self.HasMultiResponseParsers() or self.HasSingleFileParsers() or self.HasMultiFileParsers()) def HasSingleResponseParsers(self) -> bool: return any(self.SingleResponseParserTypes()) def SingleResponseParsers(self) -> Iterator[SingleResponseParser[_RDFValue]]: return self._CreateSupportedParsers(SINGLE_RESPONSE_PARSER_FACTORY) def SingleResponseParserTypes( self) -> Iterator[Type[SingleResponseParser[_RDFValue]]]: return self._SupportedTypes(SINGLE_RESPONSE_PARSER_FACTORY) def HasMultiResponseParsers(self) -> bool: return any(self.MultiResponseParserTypes()) def MultiResponseParsers(self) -> Iterator[MultiResponseParser[_RDFValue]]: return self._CreateSupportedParsers(MULTI_RESPONSE_PARSER_FACTORY) def MultiResponseParserTypes( self) -> Iterator[Type[MultiResponseParser[_RDFValue]]]: return self._SupportedTypes(MULTI_RESPONSE_PARSER_FACTORY) def HasSingleFileParsers(self) -> bool: return any(self.SingleFileParserTypes()) def SingleFileParsers(self) -> Iterator[SingleFileParser[_RDFValue]]: return self._CreateSupportedParsers(SINGLE_FILE_PARSER_FACTORY) def SingleFileParserTypes( self) -> Iterator[Type[SingleFileParser[_RDFValue]]]: return self._SupportedTypes(SINGLE_FILE_PARSER_FACTORY) def HasMultiFileParsers(self) -> bool: return any(self.MultiFileParserTypes()) def MultiFileParsers(self) -> Iterator[MultiFileParser[_RDFValue]]: return self._CreateSupportedParsers(MULTI_FILE_PARSER_FACTORY)
def AllParserTypes(self) -> Iterator[Type[Parser[_RDFValue]]]: """Returns all known parser types applicable for the artifact.""" return collection.Flatten([ self.SingleResponseParserTypes(), self.MultiResponseParserTypes(), self.SingleFileParserTypes(), self.MultiFileParserTypes(), ]) def _CreateSupportedParsers(self, fac: _Factory[_P]) -> Iterator[_P]: for name in fac.Names(): cls = fac.GetType(name) if self._artifact_name in cls.supported_artifacts: yield fac.Create(name) def _SupportedTypes(self, fac: _Factory[_P]) -> Iterator[Type[_P]]: for name in fac.Names(): cls = fac.GetType(name) if self._artifact_name in cls.supported_artifacts: yield cls
def MultiFileParserTypes(self) -> Iterator[Type[MultiFileParser[_RDFValue]]]: return self._SupportedTypes(MULTI_FILE_PARSER_FACTORY)
cyclomatic_complexity.rs
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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. //! calculate cyclomatic complexity and warn about overly complex functions use crate::rustc::cfg::CFG; use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, LintContext}; use crate::rustc::{declare_tool_lint, lint_array}; use crate::rustc::hir::*; use crate::rustc::ty; use crate::rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor}; use crate::syntax::ast::{Attribute, NodeId}; use crate::syntax::source_map::Span; use crate::utils::{in_macro, is_allowed, match_type, paths, span_help_and_lint, LimitStack}; /// **What it does:** Checks for methods with high cyclomatic complexity. /// /// **Why is this bad?** Methods of high cyclomatic complexity tend to be badly /// readable. Also LLVM will usually optimize small methods better. /// /// **Known problems:** Sometimes it's hard to find a way to reduce the /// complexity. /// /// **Example:** No. You'll see it when you get the warning. declare_clippy_lint! { pub CYCLOMATIC_COMPLEXITY, complexity, "functions that should be split up into multiple functions" } pub struct CyclomaticComplexity { limit: LimitStack, } impl CyclomaticComplexity { pub fn new(limit: u64) -> Self { Self { limit: LimitStack::new(limit), } } } impl LintPass for CyclomaticComplexity { fn get_lints(&self) -> LintArray { lint_array!(CYCLOMATIC_COMPLEXITY) } } impl CyclomaticComplexity { fn check<'a, 'tcx: 'a>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) { if in_macro(span) { return; } let cfg = CFG::new(cx.tcx, body); let expr = &body.value; let n = cfg.graph.len_nodes() as u64; let e = cfg.graph.len_edges() as u64; if e + 2 < n { // the function has unreachable code, other lints should catch this return; } let cc = e + 2 - n; let mut helper = CCHelper { match_arms: 0, divergence: 0, short_circuits: 0, returns: 0, cx, }; helper.visit_expr(expr); let CCHelper { match_arms, divergence, short_circuits, returns, .. } = helper; let ret_ty = cx.tables.node_id_to_type(expr.hir_id); let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) { returns } else { returns / 2 }; if cc + divergence < match_arms + short_circuits { report_cc_bug( cx, cc, match_arms, divergence, short_circuits, ret_adjust, span, body.id().node_id, ); } else { let mut rust_cc = cc + divergence - match_arms - short_circuits; // prevent degenerate cases where unreachable code contains `return` statements if rust_cc >= ret_adjust { rust_cc -= ret_adjust;
CYCLOMATIC_COMPLEXITY, span, &format!("the function has a cyclomatic complexity of {}", rust_cc), "you could split it up into multiple smaller functions", ); } } } } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CyclomaticComplexity { fn check_fn( &mut self, cx: &LateContext<'a, 'tcx>, _: intravisit::FnKind<'tcx>, _: &'tcx FnDecl, body: &'tcx Body, span: Span, node_id: NodeId, ) { let def_id = cx.tcx.hir.local_def_id(node_id); if !cx.tcx.has_attr(def_id, "test") { self.check(cx, body, span); } } fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) { self.limit .push_attrs(cx.sess(), attrs, "cyclomatic_complexity"); } fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) { self.limit .pop_attrs(cx.sess(), attrs, "cyclomatic_complexity"); } } struct CCHelper<'a, 'tcx: 'a> { match_arms: u64, divergence: u64, returns: u64, short_circuits: u64, // && and || cx: &'a LateContext<'a, 'tcx>, } impl<'a, 'tcx> Visitor<'tcx> for CCHelper<'a, 'tcx> { fn visit_expr(&mut self, e: &'tcx Expr) { match e.node { ExprKind::Match(_, ref arms, _) => { walk_expr(self, e); let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum(); if arms_n > 1 { self.match_arms += arms_n - 2; } }, ExprKind::Call(ref callee, _) => { walk_expr(self, e); let ty = self.cx.tables.node_id_to_type(callee.hir_id); match ty.sty { ty::FnDef(..) | ty::FnPtr(_) => { let sig = ty.fn_sig(self.cx.tcx); if sig.skip_binder().output().sty == ty::Never { self.divergence += 1; } }, _ => (), } }, ExprKind::Closure(.., _) => (), ExprKind::Binary(op, _, _) => { walk_expr(self, e); match op.node { BinOpKind::And | BinOpKind::Or => self.short_circuits += 1, _ => (), } }, ExprKind::Ret(_) => self.returns += 1, _ => walk_expr(self, e), } } fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> { NestedVisitorMap::None } } #[cfg(feature = "debugging")] #[allow(clippy::too_many_arguments)] fn report_cc_bug(_: &LateContext<'_, '_>, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span, _: NodeId) { span_bug!( span, "Clippy encountered a bug calculating cyclomatic complexity: cc = {}, arms = {}, \ div = {}, shorts = {}, returns = {}. Please file a bug report.", cc, narms, div, shorts, returns ); } #[cfg(not(feature = "debugging"))] #[allow(clippy::too_many_arguments)] fn report_cc_bug(cx: &LateContext<'_, '_>, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span, id: NodeId) { if !is_allowed(cx, CYCLOMATIC_COMPLEXITY, id) { cx.sess().span_note_without_error( span, &format!( "Clippy encountered a bug calculating cyclomatic complexity \ (hide this message with `#[allow(cyclomatic_complexity)]`): \ cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \ Please file a bug report.", cc, narms, div, shorts, returns ), ); } }
} if rust_cc > self.limit.limit() { span_help_and_lint( cx,
g1.rs
// The following code is from (scipr-lab's zexe)[https://github.com/scipr-lab/zexe] and thanks for their work use crate::{ bytes::ToBytes, curves::{ mnt6::MNT6Parameters, short_weierstrass_jacobian::{GroupAffine, GroupProjective}, AffineCurve, }, io::{Result as IoResult, Write}, Fp3, }; pub type G1Affine<P> = GroupAffine<<P as MNT6Parameters>::G1Parameters>; pub type G1Projective<P> = GroupProjective<<P as MNT6Parameters>::G1Parameters>; #[derive(Derivative)] #[derivative( Clone(bound = "P: MNT6Parameters"), Debug(bound = "P: MNT6Parameters"), PartialEq(bound = "P: MNT6Parameters"), Eq(bound = "P: MNT6Parameters") )] pub struct G1Prepared<P: MNT6Parameters> { pub x: P::Fp, pub y: P::Fp, pub x_twist: Fp3<P::Fp3Params>, pub y_twist: Fp3<P::Fp3Params>, } impl<P: MNT6Parameters> From<G1Affine<P>> for G1Prepared<P> { fn from(g1: G1Affine<P>) -> Self { let mut x_twist = P::TWIST.clone(); x_twist.mul_assign_by_fp(&g1.x); let mut y_twist = P::TWIST.clone(); y_twist.mul_assign_by_fp(&g1.y); Self {
} } } impl<P: MNT6Parameters> Default for G1Prepared<P> { fn default() -> Self { Self::from(G1Affine::<P>::prime_subgroup_generator()) } } impl<P: MNT6Parameters> ToBytes for G1Prepared<P> { fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { self.x.write(&mut writer)?; self.y.write(&mut writer)?; self.x_twist.write(&mut writer)?; self.y_twist.write(&mut writer) } }
x: g1.x, y: g1.y, x_twist, y_twist,
bitvecfunc.py
from typing import Optional, Union, cast, Callable import z3 from mythril.laser.smt.bitvec import BitVec, Bool, And, Annotations from mythril.laser.smt.bool import Or import operator def _arithmetic_helper( a: "BitVecFunc", b: Union[BitVec, int], operation: Callable ) -> "BitVecFunc": """ Helper function for arithmetic operations on BitVecFuncs. :param a: The BitVecFunc to perform the operation on. :param b: A BitVec or int to perform the operation on. :param operation: The arithmetic operation to perform. :return: The resulting BitVecFunc """ if isinstance(b, int): b = BitVec(z3.BitVecVal(b, a.size())) raw = operation(a.raw, b.raw) union = a.annotations + b.annotations if isinstance(b, BitVecFunc): # TODO: Find better value to set input and name to in this case? return BitVecFunc(raw=raw, func_name=None, input_=None, annotations=union) return BitVecFunc( raw=raw, func_name=a.func_name, input_=a.input_, annotations=union ) def _comparison_helper( a: "BitVecFunc", b: Union[BitVec, int], operation: Callable, default_value: bool, inputs_equal: bool, ) -> Bool: """ Helper function for comparison operations with BitVecFuncs. :param a: The BitVecFunc to compare. :param b: A BitVec or int to compare to. :param operation: The comparison operation to perform. :return: The resulting Bool """ # Is there some hack for gt/lt comparisons? if isinstance(b, int): b = BitVec(z3.BitVecVal(b, a.size())) union = a.annotations + b.annotations if not a.symbolic and not b.symbolic: return Bool(z3.BoolVal(operation(a.value, b.value)), annotations=union) if ( not isinstance(b, BitVecFunc) or not a.func_name or not a.input_ or not a.func_name == b.func_name ): return Bool(z3.BoolVal(default_value), annotations=union) return And( Bool(cast(z3.BoolRef, operation(a.raw, b.raw)), annotations=union), a.input_ == b.input_ if inputs_equal else a.input_ != b.input_, ) class BitVecFunc(BitVec): """A bit vector function symbol. Used in place of functions like sha3.""" def __init__( self, raw: z3.BitVecRef, func_name: Optional[str], input_: Union[int, "BitVec"] = None, annotations: Optional[Annotations] = None, ): """ :param raw: The raw bit vector symbol :param func_name: The function name. e.g. sha3 :param input: The input to the functions :param annotations: The annotations the BitVecFunc should start with """ self.func_name = func_name self.input_ = input_ super().__init__(raw, annotations) def __add__(self, other: Union[int, "BitVec"]) -> "BitVecFunc": """Create an addition expression. :param other: The int or BitVec to add to this BitVecFunc :return: The resulting BitVecFunc """ return _arithmetic_helper(self, other, operator.add) def __sub__(self, other: Union[int, "BitVec"]) -> "BitVecFunc": """Create a subtraction expression. :param other: The int or BitVec to subtract from this BitVecFunc :return: The resulting BitVecFunc """ return _arithmetic_helper(self, other, operator.sub) def __mul__(self, other: "BitVec") -> "BitVecFunc": """Create a multiplication expression. :param other: The int or BitVec to multiply to this BitVecFunc :return: The resulting BitVecFunc """ return _arithmetic_helper(self, other, operator.mul) def __truediv__(self, other: "BitVec") -> "BitVecFunc": """Create a signed division expression. :param other: The int or BitVec to divide this BitVecFunc by :return: The resulting BitVecFunc """ return _arithmetic_helper(self, other, operator.truediv) def __and__(self, other: Union[int, "BitVec"]) -> "BitVecFunc": """Create an and expression. :param other: The int or BitVec to and with this BitVecFunc :return: The resulting BitVecFunc """ return _arithmetic_helper(self, other, operator.and_) def __or__(self, other: "BitVec") -> "BitVecFunc": """Create an or expression. :param other: The int or BitVec to or with this BitVecFunc :return: The resulting BitVecFunc """ return _arithmetic_helper(self, other, operator.or_) def __xor__(self, other: "BitVec") -> "BitVecFunc": """Create a xor expression. :param other: The int or BitVec to xor with this BitVecFunc :return: The resulting BitVecFunc """ return _arithmetic_helper(self, other, operator.xor) def __lt__(self, other: "BitVec") -> Bool: """Create a signed less than expression. :param other: The int or BitVec to compare to this BitVecFunc
:return: The resulting Bool """ return _comparison_helper( self, other, operator.lt, default_value=False, inputs_equal=False ) def __gt__(self, other: "BitVec") -> Bool: """Create a signed greater than expression. :param other: The int or BitVec to compare to this BitVecFunc :return: The resulting Bool """ return _comparison_helper( self, other, operator.gt, default_value=False, inputs_equal=False ) def __le__(self, other: "BitVec") -> Bool: """Create a signed less than or equal to expression. :param other: The int or BitVec to compare to this BitVecFunc :return: The resulting Bool """ return Or(self < other, self == other) def __ge__(self, other: "BitVec") -> Bool: """Create a signed greater than or equal to expression. :param other: The int or BitVec to compare to this BitVecFunc :return: The resulting Bool """ return Or(self > other, self == other) # MYPY: fix complains about overriding __eq__ def __eq__(self, other: Union[int, "BitVec"]) -> Bool: # type: ignore """Create an equality expression. :param other: The int or BitVec to compare to this BitVecFunc :return: The resulting Bool """ return _comparison_helper( self, other, operator.eq, default_value=False, inputs_equal=True ) # MYPY: fix complains about overriding __ne__ def __ne__(self, other: Union[int, "BitVec"]) -> Bool: # type: ignore """Create an inequality expression. :param other: The int or BitVec to compare to this BitVecFunc :return: The resulting Bool """ return _comparison_helper( self, other, operator.eq, default_value=True, inputs_equal=False ) def __lshift__(self, other: Union[int, "BitVec"]) -> "BitVec": """ Left shift operation :param other: The int or BitVec to shift on :return The resulting left shifted output """ return _arithmetic_helper(self, other, operator.lshift) def __rshift__(self, other: Union[int, "BitVec"]) -> "BitVec": """ Right shift operation :param other: The int or BitVec to shift on :return The resulting right shifted output: """ return _arithmetic_helper(self, other, operator.rshift)
producer_nf.go
package producer import ( "bytes" "encoding/binary" "errors" "fmt" "net" "sync" "time" "github.com/netsampler/goflow2/decoders/netflow" flowmessage "github.com/netsampler/goflow2/pb" ) type SamplingRateSystem interface { GetSamplingRate(version uint16, obsDomainId uint32) (uint32, error) AddSamplingRate(version uint16, obsDomainId uint32, samplingRate uint32) } type basicSamplingRateSystem struct { sampling map[uint16]map[uint32]uint32 samplinglock *sync.RWMutex } func CreateSamplingSystem() SamplingRateSystem { ts := &basicSamplingRateSystem{ sampling: make(map[uint16]map[uint32]uint32), samplinglock: &sync.RWMutex{}, } return ts } func (s *basicSamplingRateSystem) AddSamplingRate(version uint16, obsDomainId uint32, samplingRate uint32) { s.samplinglock.Lock() defer s.samplinglock.Unlock() _, exists := s.sampling[version] if exists != true { s.sampling[version] = make(map[uint32]uint32) } s.sampling[version][obsDomainId] = samplingRate } func (s *basicSamplingRateSystem) GetSamplingRate(version uint16, obsDomainId uint32) (uint32, error) { s.samplinglock.RLock() defer s.samplinglock.RUnlock() samplingVersion, okver := s.sampling[version] if okver { samplingRate, okid := samplingVersion[obsDomainId] if okid { return samplingRate, nil } return 0, errors.New("") // TBC } return 0, errors.New("") // TBC } type SingleSamplingRateSystem struct { Sampling uint32 } func (s *SingleSamplingRateSystem) AddSamplingRate(version uint16, obsDomainId uint32, samplingRate uint32) { } func (s *SingleSamplingRateSystem) GetSamplingRate(version uint16, obsDomainId uint32) (uint32, error) { return s.Sampling, nil } func NetFlowLookFor(dataFields []netflow.DataField, typeId uint16) (bool, interface{}) { for _, dataField := range dataFields { if dataField.Type == typeId { return true, dataField.Value } } return false, nil } func NetFlowPopulate(dataFields []netflow.DataField, typeId uint16, addr interface{}) bool { exists, value := NetFlowLookFor(dataFields, typeId) if exists && value != nil { valueBytes, ok := value.([]byte) valueReader := bytes.NewReader(valueBytes) if ok { switch addrt := addr.(type) { case *(net.IP): *addrt = valueBytes case *(time.Time): t := uint64(0) binary.Read(valueReader, binary.BigEndian, &t) t64 := int64(t / 1000) *addrt = time.Unix(t64, 0) default: binary.Read(valueReader, binary.BigEndian, addr) } } } return exists } func DecodeUNumber(b []byte, out interface{}) error { var o uint64 l := len(b) switch l { case 1: o = uint64(b[0]) case 2: o = uint64(binary.BigEndian.Uint16(b)) case 4: o = uint64(binary.BigEndian.Uint32(b)) case 8: o = binary.BigEndian.Uint64(b) default: if l < 8 { var iter uint for i := range b { o |= uint64(b[i]) << uint(8*(uint(l)-iter-1)) iter++ } } else { return errors.New(fmt.Sprintf("Non-regular number of bytes for a number: %v", l)) } } switch t := out.(type) { case *byte: *t = byte(o) case *uint16: *t = uint16(o) case *uint32: *t = uint32(o) case *uint64: *t = o default: return errors.New("The parameter is not a pointer to a byte/uint16/uint32/uint64 structure") } return nil } func DecodeNumber(b []byte, out interface{}) error { var o int64 l := len(b) switch l { case 1: o = int64(int8(b[0])) case 2: o = int64(int16(binary.BigEndian.Uint16(b))) case 4: o = int64(int32(binary.BigEndian.Uint32(b))) case 8: o = int64(binary.BigEndian.Uint64(b)) default: if l < 8 { var iter int for i := range b { o |= int64(b[i]) << int(8*(int(l)-iter-1)) iter++ } } else { return errors.New(fmt.Sprintf("Non-regular number of bytes for a number: %v", l)) } } switch t := out.(type) { case *int8: *t = int8(o) case *int16: *t = int16(o) case *int32: *t = int32(o) case *int64: *t = o default: return errors.New("The parameter is not a pointer to a int8/int16/int32/int64 structure") } return nil } func ConvertNetFlowDataSet(version uint16, baseTime uint32, uptime uint32, record []netflow.DataField, mapperNetFlow *NetFlowMapper, mapperSFlow *SFlowMapper) *flowmessage.FlowMessage { flowMessage := &flowmessage.FlowMessage{} var time uint64 if version == 9 { flowMessage.Type = flowmessage.FlowMessage_NETFLOW_V9 } else if version == 10 { flowMessage.Type = flowmessage.FlowMessage_IPFIX } for i := range record { df := record[i] v, ok := df.Value.([]byte) if !ok { continue } MapCustomNetFlow(flowMessage, df, mapperNetFlow) if df.PenProvided { continue } switch df.Type { // Statistics case netflow.NFV9_FIELD_IN_BYTES: DecodeUNumber(v, &(flowMessage.Bytes)) case netflow.NFV9_FIELD_IN_PKTS: DecodeUNumber(v, &(flowMessage.Packets)) case netflow.NFV9_FIELD_OUT_BYTES: DecodeUNumber(v, &(flowMessage.Bytes)) case netflow.NFV9_FIELD_OUT_PKTS: DecodeUNumber(v, &(flowMessage.Packets)) // L4 case netflow.NFV9_FIELD_L4_SRC_PORT: DecodeUNumber(v, &(flowMessage.SrcPort)) case netflow.NFV9_FIELD_L4_DST_PORT: DecodeUNumber(v, &(flowMessage.DstPort)) case netflow.NFV9_FIELD_PROTOCOL: DecodeUNumber(v, &(flowMessage.Proto)) // Network case netflow.NFV9_FIELD_SRC_AS: DecodeUNumber(v, &(flowMessage.SrcAS)) case netflow.NFV9_FIELD_DST_AS: DecodeUNumber(v, &(flowMessage.DstAS)) // Interfaces case netflow.NFV9_FIELD_INPUT_SNMP: DecodeUNumber(v, &(flowMessage.InIf)) case netflow.NFV9_FIELD_OUTPUT_SNMP: DecodeUNumber(v, &(flowMessage.OutIf)) case netflow.NFV9_FIELD_FORWARDING_STATUS: DecodeUNumber(v, &(flowMessage.ForwardingStatus)) case netflow.NFV9_FIELD_SRC_TOS: DecodeUNumber(v, &(flowMessage.IPTos)) case netflow.NFV9_FIELD_TCP_FLAGS: DecodeUNumber(v, &(flowMessage.TCPFlags)) case netflow.NFV9_FIELD_MIN_TTL: DecodeUNumber(v, &(flowMessage.IPTTL)) // IP case netflow.NFV9_FIELD_IPV4_SRC_ADDR: flowMessage.SrcAddr = v flowMessage.Etype = 0x800 case netflow.NFV9_FIELD_IPV4_DST_ADDR: flowMessage.DstAddr = v flowMessage.Etype = 0x800 case netflow.NFV9_FIELD_SRC_MASK: DecodeUNumber(v, &(flowMessage.SrcNet)) case netflow.NFV9_FIELD_DST_MASK: DecodeUNumber(v, &(flowMessage.DstNet)) case netflow.NFV9_FIELD_IPV6_SRC_ADDR: flowMessage.SrcAddr = v flowMessage.Etype = 0x86dd case netflow.NFV9_FIELD_IPV6_DST_ADDR: flowMessage.DstAddr = v flowMessage.Etype = 0x86dd case netflow.NFV9_FIELD_IPV6_SRC_MASK: DecodeUNumber(v, &(flowMessage.SrcNet)) case netflow.NFV9_FIELD_IPV6_DST_MASK: DecodeUNumber(v, &(flowMessage.DstNet)) case netflow.NFV9_FIELD_IPV4_NEXT_HOP: flowMessage.NextHop = v case netflow.NFV9_FIELD_BGP_IPV4_NEXT_HOP: flowMessage.NextHop = v case netflow.NFV9_FIELD_IPV6_NEXT_HOP: flowMessage.NextHop = v case netflow.NFV9_FIELD_BGP_IPV6_NEXT_HOP: flowMessage.NextHop = v // ICMP case netflow.NFV9_FIELD_ICMP_TYPE: var icmpTypeCode uint16 DecodeUNumber(v, &icmpTypeCode) flowMessage.IcmpType = uint32(icmpTypeCode >> 8) flowMessage.IcmpCode = uint32(icmpTypeCode & 0xff) case netflow.IPFIX_FIELD_icmpTypeCodeIPv6: var icmpTypeCode uint16 DecodeUNumber(v, &icmpTypeCode) flowMessage.IcmpType = uint32(icmpTypeCode >> 8) flowMessage.IcmpCode = uint32(icmpTypeCode & 0xff) case netflow.IPFIX_FIELD_icmpTypeIPv4: DecodeUNumber(v, &(flowMessage.IcmpType)) case netflow.IPFIX_FIELD_icmpTypeIPv6: DecodeUNumber(v, &(flowMessage.IcmpType)) case netflow.IPFIX_FIELD_icmpCodeIPv4: DecodeUNumber(v, &(flowMessage.IcmpCode)) case netflow.IPFIX_FIELD_icmpCodeIPv6: DecodeUNumber(v, &(flowMessage.IcmpCode)) // Mac case netflow.NFV9_FIELD_IN_SRC_MAC: DecodeUNumber(v, &(flowMessage.SrcMac)) case netflow.NFV9_FIELD_IN_DST_MAC: DecodeUNumber(v, &(flowMessage.DstMac)) case netflow.NFV9_FIELD_OUT_SRC_MAC: DecodeUNumber(v, &(flowMessage.SrcMac)) case netflow.NFV9_FIELD_OUT_DST_MAC: DecodeUNumber(v, &(flowMessage.DstMac)) case netflow.NFV9_FIELD_SRC_VLAN: DecodeUNumber(v, &(flowMessage.VlanId)) DecodeUNumber(v, &(flowMessage.SrcVlan)) case netflow.NFV9_FIELD_DST_VLAN: DecodeUNumber(v, &(flowMessage.DstVlan)) case netflow.IPFIX_FIELD_ingressVRFID: DecodeUNumber(v, &(flowMessage.IngressVrfID)) case netflow.IPFIX_FIELD_egressVRFID: DecodeUNumber(v, &(flowMessage.EgressVrfID)) case netflow.NFV9_FIELD_IPV4_IDENT: DecodeUNumber(v, &(flowMessage.FragmentId)) case netflow.NFV9_FIELD_FRAGMENT_OFFSET: var fragOffset uint32 DecodeUNumber(v, &fragOffset) flowMessage.FragmentOffset |= fragOffset case netflow.IPFIX_FIELD_fragmentFlags: var ipFlags uint32 DecodeUNumber(v, &ipFlags) flowMessage.FragmentOffset |= ipFlags case netflow.NFV9_FIELD_IPV6_FLOW_LABEL: DecodeUNumber(v, &(flowMessage.IPv6FlowLabel)) case netflow.IPFIX_FIELD_biflowDirection: DecodeUNumber(v, &(flowMessage.BiFlowDirection)) case netflow.IPFIX_FIELD_natEvent: DecodeUNumber(v, &(flowMessage.NatEvent)) case netflow.NFV9_FIELD_DIRECTION: DecodeUNumber(v, &(flowMessage.FlowDirection)) default: if version == 9 { // NetFlow v9 time works with a differential based on router's uptime switch df.Type { case netflow.NFV9_FIELD_FIRST_SWITCHED: var timeFirstSwitched uint32 DecodeUNumber(v, &timeFirstSwitched) timeDiff := (uptime - timeFirstSwitched) / 1000 flowMessage.TimeFlowStart = uint64(baseTime - timeDiff) case netflow.NFV9_FIELD_LAST_SWITCHED: var timeLastSwitched uint32 DecodeUNumber(v, &timeLastSwitched) timeDiff := (uptime - timeLastSwitched) / 1000 flowMessage.TimeFlowEnd = uint64(baseTime - timeDiff) } } else if version == 10 { switch df.Type { case netflow.IPFIX_FIELD_flowStartSeconds: DecodeUNumber(v, &time)
case netflow.IPFIX_FIELD_flowStartMicroseconds: DecodeUNumber(v, &time) flowMessage.TimeFlowStart = time / 1000000 case netflow.IPFIX_FIELD_flowStartNanoseconds: DecodeUNumber(v, &time) flowMessage.TimeFlowStart = time / 1000000000 case netflow.IPFIX_FIELD_flowEndSeconds: DecodeUNumber(v, &time) flowMessage.TimeFlowEnd = time case netflow.IPFIX_FIELD_flowEndMilliseconds: DecodeUNumber(v, &time) flowMessage.TimeFlowEnd = time / 1000 case netflow.IPFIX_FIELD_flowEndMicroseconds: DecodeUNumber(v, &time) flowMessage.TimeFlowEnd = time / 1000000 case netflow.IPFIX_FIELD_flowEndNanoseconds: DecodeUNumber(v, &time) flowMessage.TimeFlowEnd = time / 1000000000 case netflow.IPFIX_FIELD_flowStartDeltaMicroseconds: DecodeUNumber(v, &time) flowMessage.TimeFlowStart = uint64(baseTime) - time/1000000 case netflow.IPFIX_FIELD_flowEndDeltaMicroseconds: DecodeUNumber(v, &time) flowMessage.TimeFlowEnd = uint64(baseTime) - time/1000000 // RFC7133 case netflow.IPFIX_FIELD_dataLinkFrameSize: DecodeUNumber(v, &(flowMessage.Bytes)) flowMessage.Packets = 1 case netflow.IPFIX_FIELD_dataLinkFrameSection: ParseEthernetHeader(flowMessage, v, mapperSFlow) flowMessage.Packets = 1 if flowMessage.Bytes == 0 { flowMessage.Bytes = uint64(len(v)) } } } } } return flowMessage } func SearchNetFlowDataSetsRecords(version uint16, baseTime uint32, uptime uint32, dataRecords []netflow.DataRecord, mapperNetFlow *NetFlowMapper, mapperSFlow *SFlowMapper) []*flowmessage.FlowMessage { flowMessageSet := make([]*flowmessage.FlowMessage, 0) for _, record := range dataRecords { fmsg := ConvertNetFlowDataSet(version, baseTime, uptime, record.Values, mapperNetFlow, mapperSFlow) if fmsg != nil { flowMessageSet = append(flowMessageSet, fmsg) } } return flowMessageSet } func SearchNetFlowDataSets(version uint16, baseTime uint32, uptime uint32, dataFlowSet []netflow.DataFlowSet, mapperNetFlow *NetFlowMapper, mapperSFlow *SFlowMapper) []*flowmessage.FlowMessage { flowMessageSet := make([]*flowmessage.FlowMessage, 0) for _, dataFlowSetItem := range dataFlowSet { fmsg := SearchNetFlowDataSetsRecords(version, baseTime, uptime, dataFlowSetItem.Records, mapperNetFlow, mapperSFlow) if fmsg != nil { flowMessageSet = append(flowMessageSet, fmsg...) } } return flowMessageSet } func SearchNetFlowOptionDataSets(dataFlowSet []netflow.OptionsDataFlowSet) (uint32, bool) { var samplingRate uint32 var found bool for _, dataFlowSetItem := range dataFlowSet { for _, record := range dataFlowSetItem.Records { b := NetFlowPopulate(record.OptionsValues, 305, &samplingRate) if b { return samplingRate, b } b = NetFlowPopulate(record.OptionsValues, 50, &samplingRate) if b { return samplingRate, b } b = NetFlowPopulate(record.OptionsValues, 34, &samplingRate) if b { return samplingRate, b } } } return samplingRate, found } func SplitNetFlowSets(packetNFv9 netflow.NFv9Packet) ([]netflow.DataFlowSet, []netflow.TemplateFlowSet, []netflow.NFv9OptionsTemplateFlowSet, []netflow.OptionsDataFlowSet) { dataFlowSet := make([]netflow.DataFlowSet, 0) templatesFlowSet := make([]netflow.TemplateFlowSet, 0) optionsTemplatesFlowSet := make([]netflow.NFv9OptionsTemplateFlowSet, 0) optionsDataFlowSet := make([]netflow.OptionsDataFlowSet, 0) for _, flowSet := range packetNFv9.FlowSets { switch flowSet.(type) { case netflow.TemplateFlowSet: templatesFlowSet = append(templatesFlowSet, flowSet.(netflow.TemplateFlowSet)) case netflow.NFv9OptionsTemplateFlowSet: optionsTemplatesFlowSet = append(optionsTemplatesFlowSet, flowSet.(netflow.NFv9OptionsTemplateFlowSet)) case netflow.DataFlowSet: dataFlowSet = append(dataFlowSet, flowSet.(netflow.DataFlowSet)) case netflow.OptionsDataFlowSet: optionsDataFlowSet = append(optionsDataFlowSet, flowSet.(netflow.OptionsDataFlowSet)) } } return dataFlowSet, templatesFlowSet, optionsTemplatesFlowSet, optionsDataFlowSet } func SplitIPFIXSets(packetIPFIX netflow.IPFIXPacket) ([]netflow.DataFlowSet, []netflow.TemplateFlowSet, []netflow.IPFIXOptionsTemplateFlowSet, []netflow.OptionsDataFlowSet) { dataFlowSet := make([]netflow.DataFlowSet, 0) templatesFlowSet := make([]netflow.TemplateFlowSet, 0) optionsTemplatesFlowSet := make([]netflow.IPFIXOptionsTemplateFlowSet, 0) optionsDataFlowSet := make([]netflow.OptionsDataFlowSet, 0) for _, flowSet := range packetIPFIX.FlowSets { switch flowSet.(type) { case netflow.TemplateFlowSet: templatesFlowSet = append(templatesFlowSet, flowSet.(netflow.TemplateFlowSet)) case netflow.IPFIXOptionsTemplateFlowSet: optionsTemplatesFlowSet = append(optionsTemplatesFlowSet, flowSet.(netflow.IPFIXOptionsTemplateFlowSet)) case netflow.DataFlowSet: dataFlowSet = append(dataFlowSet, flowSet.(netflow.DataFlowSet)) case netflow.OptionsDataFlowSet: optionsDataFlowSet = append(optionsDataFlowSet, flowSet.(netflow.OptionsDataFlowSet)) } } return dataFlowSet, templatesFlowSet, optionsTemplatesFlowSet, optionsDataFlowSet } func ProcessMessageNetFlow(msgDec interface{}, samplingRateSys SamplingRateSystem) ([]*flowmessage.FlowMessage, error) { return ProcessMessageNetFlowConfig(msgDec, samplingRateSys, nil) } // Convert a NetFlow datastructure to a FlowMessage protobuf // Does not put sampling rate func ProcessMessageNetFlowConfig(msgDec interface{}, samplingRateSys SamplingRateSystem, config *ProducerConfigMapped) ([]*flowmessage.FlowMessage, error) { seqnum := uint32(0) var baseTime uint32 var uptime uint32 flowMessageSet := make([]*flowmessage.FlowMessage, 0) switch msgDecConv := msgDec.(type) { case netflow.NFv9Packet: dataFlowSet, _, _, optionDataFlowSet := SplitNetFlowSets(msgDecConv) seqnum = msgDecConv.SequenceNumber baseTime = msgDecConv.UnixSeconds uptime = msgDecConv.SystemUptime obsDomainId := msgDecConv.SourceId var cfg *NetFlowMapper if config != nil { cfg = config.NetFlowV9 } flowMessageSet = SearchNetFlowDataSets(9, baseTime, uptime, dataFlowSet, cfg, nil) samplingRate, found := SearchNetFlowOptionDataSets(optionDataFlowSet) if samplingRateSys != nil { if found { samplingRateSys.AddSamplingRate(9, obsDomainId, samplingRate) } else { samplingRate, _ = samplingRateSys.GetSamplingRate(9, obsDomainId) } } for _, fmsg := range flowMessageSet { fmsg.SequenceNum = seqnum fmsg.SamplingRate = uint64(samplingRate) } case netflow.IPFIXPacket: dataFlowSet, _, _, optionDataFlowSet := SplitIPFIXSets(msgDecConv) seqnum = msgDecConv.SequenceNumber baseTime = msgDecConv.ExportTime obsDomainId := msgDecConv.ObservationDomainId var cfgIpfix *NetFlowMapper var cfgSflow *SFlowMapper if config != nil { cfgIpfix = config.IPFIX cfgSflow = config.SFlow } flowMessageSet = SearchNetFlowDataSets(10, baseTime, uptime, dataFlowSet, cfgIpfix, cfgSflow) samplingRate, found := SearchNetFlowOptionDataSets(optionDataFlowSet) if samplingRateSys != nil { if found { samplingRateSys.AddSamplingRate(10, obsDomainId, samplingRate) } else { samplingRate, _ = samplingRateSys.GetSamplingRate(10, obsDomainId) } } for _, fmsg := range flowMessageSet { fmsg.SequenceNum = seqnum fmsg.SamplingRate = uint64(samplingRate) } default: return flowMessageSet, errors.New("Bad NetFlow/IPFIX version") } return flowMessageSet, nil }
flowMessage.TimeFlowStart = time case netflow.IPFIX_FIELD_flowStartMilliseconds: DecodeUNumber(v, &time) flowMessage.TimeFlowStart = time / 1000
getLighthouseScoreColor.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; // https://developers.google.com/web/tools/lighthouse/v3/scoring var _default = score => { if (typeof score !== 'number') { return '#e0e0e0'; } let scoreColor = '#0cce6b'; // medium range if (score < 75) { scoreColor = '#ffa400'; } // bad
} return scoreColor; }; exports.default = _default;
if (score < 45) { scoreColor = '#f74531';
conanfile.py
import os from conans import ConanFile, tools required_conan_version = ">=1.33.0" class VisitStructConan(ConanFile): name = "visit_struct" description = "A miniature library for struct-field reflection in C++" topics = ("reflection", "introspection", "visitor", "struct-field-visitor",) homepage = "https://github.com/garbageslam/visit_struct" url = "https://github.com/conan-io/conan-center-index" license = "BSL-1.0" settings = "os", "arch", "compiler", "build_type", options = { "with_boost_fusion": [True, False], "with_boost_hana": [True, False], } default_options = { "with_boost_fusion": False, "with_boost_hana": False, } no_copy_source = True @property def _source_subfolder(self):
def requirements(self): if self.options.with_boost_fusion or self.options.with_boost_hana: self.requires("boost/1.78.0") def package_id(self): self.info.header_only() def validate(self): if self.settings.compiler.get_safe("cppstd"): tools.check_min_cppstd(self, "11") def source(self): tools.get(**self.conan_data["sources"][self.version], strip_root=True, destination=self._source_subfolder) def package(self): self.copy(pattern="LICENSE", src=self._source_subfolder, dst="licenses") self.copy(pattern="*visit_struct.hpp", src=os.path.join(self._source_subfolder, "include"), dst="include") self.copy(pattern="*visit_struct_intrusive.hpp", src=os.path.join(self._source_subfolder, "include"), dst="include") if self.options.with_boost_fusion: self.copy(pattern="*visit_struct_boost_fusion.hpp", src=os.path.join(self._source_subfolder, "include"), dst="include") if self.options.with_boost_hana: self.copy(pattern="*visit_struct_boost_hana.hpp", src=os.path.join(self._source_subfolder, "include"), dst="include")
return "source_subfolder"
iconInlineStyling.component.tsx
/** * Visit react-native-svg documentation for more details on styling * https://github.com/react-native-community/react-native-svg#common-props */ import React from 'react'; import { Icon } from '@ui-kitten/components';
width={32} height={32} fill='#FF7E6D' /> );
export const IconInlineStylingShowcase = () => ( <Icon name='github'
models.py
from django.db import models # Create your models here. class TimeStampMixin(models.Model):
""" An abstract base class model that provides self-updating ``created_at`` and ``updated_at`` fields. """ created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True
collision_checker.rs
use crate::tetronimoe::{Figure, Direction}; use crate::game_state::{FIELD_WIDTH, FIELD_HEIGHT}; pub fn direction_is_clear(figure: &Figure, direction: Direction, field: &Vec<bool>) -> bool { let points = figure.tiles.clone(); for point in points { match direction { Direction::Left => { if point.x == 0 { return false; } if field[(point.y * FIELD_WIDTH as isize + point.x - 1) as usize] { return false; } }, Direction::Right => { if point.x == (FIELD_WIDTH - 1) as isize { return false; } if field[(point.y * FIELD_WIDTH as isize + point.x + 1) as usize] { return false; } }, Direction::Down => { if point.y == (FIELD_HEIGHT - 1) as isize { return false; } if field[((point.y + 1) * FIELD_WIDTH as isize + point.x) as usize] { return false; } }, _ => unreachable!(), } } return true; } pub fn position_is_clear(figure: &Figure, field: &Vec<bool>) -> bool
{ for point in figure.tiles.clone() { if field[(point.y * FIELD_WIDTH as isize + point.x) as usize] { return false; } } true }
catch_message.py
#!/usr/bin/env python3 """ 1. 实现微信消息的抓取 :author Wang Weiwei <email>[email protected] / [email protected]</email> :sine 2017/8/11 :version 1.0 """ import itchat,time import queue import _thread XIAOBING_ID = 'xiaoice-ms' msgQueue = queue.Queue(maxsize=100) @itchat.msg_register(itchat.content.TEXT, isMpChat=True) def print_content(msg): if msg["FromUserName"] == XIAOBING_ID: msgQueue.put(msg["
, msg["Text"]) @itchat.msg_register(itchat.content.TEXT, isFriendChat=True) def print_contents(msg): print(msg) itchat.send_msg(msg["Text"], toUserName="@3c0f48b3cec6e9d90fe03a8a0edb78eb") return msgQueue.get() itchat.auto_login(hotReload=True) itchat.start_receiving() # mps = itchat.get_mps() # # a = itchat.send_msg("你是谁", toUserName="@3c0f48b3cec6e9d90fe03a8a0edb78eb") # # message = itchat.get_msg() # print("回复信息: ", message) _thread.start_new_thread(itchat.run, ())
Text"]) print("公众号消息"
multiple_dispatch_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for multiple_dispatch.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.autograph.utils import multiple_dispatch from tensorflow.python.client.session import Session from tensorflow.python.framework.constant_op import constant from tensorflow.python.platform import test class MultipleDispatchTest(test.TestCase): def test_dynamic_is_python(self): a = np.eye(3) also_a = a not_actually_a = np.eye(3) should_be_true1 = multiple_dispatch.dynamic_is(a, also_a) should_be_false1 = multiple_dispatch.dynamic_is_not(a, also_a) should_be_true2 = multiple_dispatch.dynamic_is_not(a, not_actually_a) should_be_false2 = multiple_dispatch.dynamic_is(a, not_actually_a) self.assertTrue(should_be_true1)
self.assertTrue(should_be_true2) self.assertFalse(should_be_false1) self.assertFalse(should_be_false2) def test_dynamic_is_tf(self): with Session().as_default(): a = constant([2.0]) also_a = a not_actually_a = constant([2.0]) should_be_true1 = multiple_dispatch.dynamic_is(a, also_a) should_be_false1 = multiple_dispatch.dynamic_is_not(a, also_a) should_be_true2 = multiple_dispatch.dynamic_is_not(a, not_actually_a) should_be_false2 = multiple_dispatch.dynamic_is(a, not_actually_a) self.assertTrue(should_be_true1) self.assertTrue(should_be_true2) self.assertFalse(should_be_false1) self.assertFalse(should_be_false2) def test_run_cond_python(self): true_fn = lambda: (2,) false_fn = lambda: (3,) self.assertEqual(multiple_dispatch.run_cond(True, true_fn, false_fn), 2) self.assertEqual(multiple_dispatch.run_cond(False, true_fn, false_fn), 3) def test_run_cond_tf(self): true_fn = lambda: (constant(2),) false_fn = lambda: (constant(3),) with Session() as sess: out = multiple_dispatch.run_cond(constant(True), true_fn, false_fn) self.assertEqual(sess.run(out), 2) out = multiple_dispatch.run_cond(constant(False), true_fn, false_fn) self.assertEqual(sess.run(out), 3) if __name__ == '__main__': test.main()
string.go
package utils import "strings" // IsStringArrContainsStr 判断[]string中是否包含某个字符串 func IsStringArrContainsStr(stringArr []string, str string) bool { flag := false for _, strVal := range stringArr { flag = strings.Contains(strVal, str) if flag {
break } } return flag }
app.js
(self.webpackChunk=self.webpackChunk||[]).push([[773],{54227:(e,s,t)=>{"use strict";var a=t(70538),n=t(78345);const r=[{path:"*",component:function(){return Promise.all([t.e(898),t.e(336)]).then(t.bind(t,19336))},name:"home"}];function
(e,s){(null==s||s>e.length)&&(s=e.length);for(var t=0,a=new Array(s);t<s;t++)a[t]=e[t];return a}a.default.use(n.Z);const l=new n.Z({mode:"history",scrollBehavior:function(e,s,t){return{y:0}},routes:(o=r,function(e){if(Array.isArray(e))return j(e)}(o)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(o)||function(e,s){if(e){if("string"==typeof e)return j(e,s);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?j(e,s):void 0}}(o)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())});var o,i=t(72737),u=t(67166),c=t.n(u),m=t(14765),d=t.n(m),h=t(67540),f=t(17152);const p=JSON.parse('{"en":{"zone":"Waste Zone","group":"Waste Group","mone":"Mone","select_all":"Select All","delta":"Delta","percent":"Percent","minimum":"Minimum","maximum":"Maximum","x_axis":"X-Axis","sum":"Sum","graph_type":"Graph Type","graph_data":"Graph Data","show":"Show","stacked":"Stacked","select_zones_placeholder":"Select Zones","select_groups_placeholder":"Select Groups","select_mones_placeholder":"Select Mones","date":"Date","daily":"Daily","weekly":"Weekly","monthly":"Monthly","yearly":"Yearly","line":"Line","bar":"Bar","area":"Area","qty":"QTY","real_qty":"Real QTY","water_difference_analytics":"Water Difference Analytics","show_sidebar":"Show Sidebar"},"he":{"zone":"אזור פחת","group":"קבוצת פחת","mone":"מונה","select_all":"בחר הכל","delta":"הפרש מדידה","percent":"אחוז","minimum":"מינימום","maximum":"מקסימום","x_axis":"X-ציר","sum":"סכום","graph_type":"סוג גרף","graph_data":"נתוני הגרף","show":"הצג","stacked":"צבור","select_zones_placeholder":"\'בחר אזור","select_groups_placeholder":"בחר קבוצה","select_mones_placeholder":"בחר מונים","date":"תאריך","daily":"יומי","weekly":"שבועי","monthly":"חודשי","yearly":"שנתי","line":"קו","bar":"עמודות","area":"שטח","qty":"כמות","real_qty":"כמות ממונים","water_difference_analytics":"ניתוח הפרשי מדידה","show_sidebar":"הצג סרגל צד"}}');t(49147),window.Vue=t(70538),window.router=l,window.Fire=new a.default,a.default.use(i.ZP),a.default.use(c()),a.default.use(d()),a.default.use(h.Z),a.default.use(f.Z);var y=new f.Z({locale:"he",fallbackLocale:"en",messages:p});a.default.component("apexchart",c()),a.default.component("datepicker",h.Z);new a.default({el:"#app",router:l,i18n:y}).$mount("#app")},49147:(e,s,t)=>{window._=t(96486),window.axios=t(9669),window.axios.defaults.headers.common["X-Requested-With"]="XMLHttpRequest",window.axios.defaults.baseURL=window.baseURI},75067:()=>{},46700:(e,s,t)=>{var a={"./af":42786,"./af.js":42786,"./ar":30867,"./ar-dz":14130,"./ar-dz.js":14130,"./ar-kw":96135,"./ar-kw.js":96135,"./ar-ly":56440,"./ar-ly.js":56440,"./ar-ma":47702,"./ar-ma.js":47702,"./ar-sa":16040,"./ar-sa.js":16040,"./ar-tn":37100,"./ar-tn.js":37100,"./ar.js":30867,"./az":31083,"./az.js":31083,"./be":9808,"./be.js":9808,"./bg":68338,"./bg.js":68338,"./bm":67438,"./bm.js":67438,"./bn":8905,"./bn-bd":76225,"./bn-bd.js":76225,"./bn.js":8905,"./bo":11560,"./bo.js":11560,"./br":1278,"./br.js":1278,"./bs":80622,"./bs.js":80622,"./ca":2468,"./ca.js":2468,"./cs":5822,"./cs.js":5822,"./cv":50877,"./cv.js":50877,"./cy":47373,"./cy.js":47373,"./da":24780,"./da.js":24780,"./de":59740,"./de-at":60217,"./de-at.js":60217,"./de-ch":60894,"./de-ch.js":60894,"./de.js":59740,"./dv":5300,"./dv.js":5300,"./el":50837,"./el.js":50837,"./en-au":78348,"./en-au.js":78348,"./en-ca":77925,"./en-ca.js":77925,"./en-gb":22243,"./en-gb.js":22243,"./en-ie":46436,"./en-ie.js":46436,"./en-il":47207,"./en-il.js":47207,"./en-in":44175,"./en-in.js":44175,"./en-nz":76319,"./en-nz.js":76319,"./en-sg":31662,"./en-sg.js":31662,"./eo":92915,"./eo.js":92915,"./es":55655,"./es-do":55251,"./es-do.js":55251,"./es-mx":96112,"./es-mx.js":96112,"./es-us":71146,"./es-us.js":71146,"./es.js":55655,"./et":5603,"./et.js":5603,"./eu":77763,"./eu.js":77763,"./fa":76959,"./fa.js":76959,"./fi":11897,"./fi.js":11897,"./fil":42549,"./fil.js":42549,"./fo":94694,"./fo.js":94694,"./fr":94470,"./fr-ca":63049,"./fr-ca.js":63049,"./fr-ch":52330,"./fr-ch.js":52330,"./fr.js":94470,"./fy":5044,"./fy.js":5044,"./ga":29295,"./ga.js":29295,"./gd":2101,"./gd.js":2101,"./gl":38794,"./gl.js":38794,"./gom-deva":27884,"./gom-deva.js":27884,"./gom-latn":23168,"./gom-latn.js":23168,"./gu":95349,"./gu.js":95349,"./he":24206,"./he.js":24206,"./hi":30094,"./hi.js":30094,"./hr":30316,"./hr.js":30316,"./hu":22138,"./hu.js":22138,"./hy-am":11423,"./hy-am.js":11423,"./id":29218,"./id.js":29218,"./is":90135,"./is.js":90135,"./it":90626,"./it-ch":10150,"./it-ch.js":10150,"./it.js":90626,"./ja":39183,"./ja.js":39183,"./jv":24286,"./jv.js":24286,"./ka":12105,"./ka.js":12105,"./kk":47772,"./kk.js":47772,"./km":18758,"./km.js":18758,"./kn":79282,"./kn.js":79282,"./ko":33730,"./ko.js":33730,"./ku":1408,"./ku.js":1408,"./ky":33291,"./ky.js":33291,"./lb":36841,"./lb.js":36841,"./lo":55466,"./lo.js":55466,"./lt":57010,"./lt.js":57010,"./lv":37595,"./lv.js":37595,"./me":39861,"./me.js":39861,"./mi":35493,"./mi.js":35493,"./mk":95966,"./mk.js":95966,"./ml":87341,"./ml.js":87341,"./mn":5115,"./mn.js":5115,"./mr":10370,"./mr.js":10370,"./ms":9847,"./ms-my":41237,"./ms-my.js":41237,"./ms.js":9847,"./mt":72126,"./mt.js":72126,"./my":56165,"./my.js":56165,"./nb":64924,"./nb.js":64924,"./ne":16744,"./ne.js":16744,"./nl":93901,"./nl-be":59814,"./nl-be.js":59814,"./nl.js":93901,"./nn":83877,"./nn.js":83877,"./oc-lnc":92135,"./oc-lnc.js":92135,"./pa-in":15858,"./pa-in.js":15858,"./pl":64495,"./pl.js":64495,"./pt":89520,"./pt-br":57971,"./pt-br.js":57971,"./pt.js":89520,"./ro":96459,"./ro.js":96459,"./ru":21793,"./ru.js":21793,"./sd":40950,"./sd.js":40950,"./se":10490,"./se.js":10490,"./si":90124,"./si.js":90124,"./sk":64249,"./sk.js":64249,"./sl":14985,"./sl.js":14985,"./sq":51104,"./sq.js":51104,"./sr":49131,"./sr-cyrl":79915,"./sr-cyrl.js":79915,"./sr.js":49131,"./ss":85893,"./ss.js":85893,"./sv":98760,"./sv.js":98760,"./sw":91172,"./sw.js":91172,"./ta":27333,"./ta.js":27333,"./te":23110,"./te.js":23110,"./tet":52095,"./tet.js":52095,"./tg":27321,"./tg.js":27321,"./th":9041,"./th.js":9041,"./tk":19005,"./tk.js":19005,"./tl-ph":75768,"./tl-ph.js":75768,"./tlh":89444,"./tlh.js":89444,"./tr":72397,"./tr.js":72397,"./tzl":28254,"./tzl.js":28254,"./tzm":51106,"./tzm-latn":30699,"./tzm-latn.js":30699,"./tzm.js":51106,"./ug-cn":9288,"./ug-cn.js":9288,"./uk":67691,"./uk.js":67691,"./ur":13795,"./ur.js":13795,"./uz":6791,"./uz-latn":60588,"./uz-latn.js":60588,"./uz.js":6791,"./vi":65666,"./vi.js":65666,"./x-pseudo":14378,"./x-pseudo.js":14378,"./yo":75805,"./yo.js":75805,"./zh-cn":83839,"./zh-cn.js":83839,"./zh-hk":55726,"./zh-hk.js":55726,"./zh-mo":99807,"./zh-mo.js":99807,"./zh-tw":74152,"./zh-tw.js":74152};function n(e){var s=r(e);return t(s)}function r(e){if(!t.o(a,e)){var s=new Error("Cannot find module '"+e+"'");throw s.code="MODULE_NOT_FOUND",s}return a[e]}n.keys=function(){return Object.keys(a)},n.resolve=r,e.exports=n,n.id=46700}},e=>{var s=s=>e(e.s=s);e.O(0,[170,898],(()=>(s(54227),s(75067))));e.O()}]);
j
lib.rs
#[allow(dead_code)] fn day_4_part_1(start: i32, end: i32) -> usize { check_passwords_between(start, end, true) } #[allow(dead_code)] fn day_4_part_2(start: i32, end: i32) -> usize { check_passwords_between(start, end, false) } fn check_passwords_between(start: i32, end: i32, allow_larger_groups_of_adjacent_digits: bool) -> usize { (start..=end).filter(|i| { i.to_string().chars() .fold(PasswordMatchStatus::new(allow_larger_groups_of_adjacent_digits), |status, c| status.next(c)) .is_valid() }).count() } #[derive(Debug)] struct PasswordMatchStatus { two_adjacent_digits: bool, never_decreased: bool, previous_digit: Option<char>, previous_adjacent_digits: i32, allow_larger_groups_of_adjacent_digits: bool } impl PasswordMatchStatus { fn new(allow_larger_groups_of_adjacent_digits: bool) -> Self { PasswordMatchStatus { two_adjacent_digits: false, never_decreased: true, previous_digit: None, previous_adjacent_digits: 0, allow_larger_groups_of_adjacent_digits } } fn next(self, digit: char) -> Self { let (never_decreased, two_adjacent_digits, previous_adjacent_digits) = match self.previous_digit { Some(prev_digit) => { let never_decreased = prev_digit <= digit; let two_adjacent_digits = prev_digit != digit && if self.allow_larger_groups_of_adjacent_digits { self.previous_adjacent_digits >= 2 } else { self.previous_adjacent_digits == 2 }; let previous_adjacent_digits = if prev_digit == digit { self.previous_adjacent_digits + 1 } else { 1 }; (never_decreased, two_adjacent_digits, previous_adjacent_digits) }, None => (true, false, 1) }; PasswordMatchStatus { two_adjacent_digits: self.two_adjacent_digits || two_adjacent_digits, never_decreased: self.never_decreased && never_decreased, previous_digit: Some(digit), previous_adjacent_digits: previous_adjacent_digits, allow_larger_groups_of_adjacent_digits: self.allow_larger_groups_of_adjacent_digits } } fn is_valid(&self) -> bool { let adjacent_digits = if self.allow_larger_groups_of_adjacent_digits { self.two_adjacent_digits || self.previous_adjacent_digits >= 2 } else { self.two_adjacent_digits || self.previous_adjacent_digits == 2 }; self.never_decreased && adjacent_digits } } #[cfg(test)] mod tests { use super::day_4_part_1; use super::day_4_part_2; #[test] fn day_4_part_1_examples() { assert_eq!(day_4_part_1(111111, 111111), 1); assert_eq!(day_4_part_1(223450, 223450), 0); assert_eq!(day_4_part_1(123789, 123789), 0); } #[test] fn day_4_part_1_test_input()
#[test] fn day_4_part_2_examples() { assert_eq!(day_4_part_2(112233, 112233), 1); assert_eq!(day_4_part_2(123444, 123444), 0); assert_eq!(day_4_part_2(111122, 111122), 1); assert_eq!(day_4_part_2(444444, 444444), 0); assert_eq!(day_4_part_2(444445, 444445), 0); } #[test] fn day_4_part_2_test_input() { assert_eq!(day_4_part_2(172851, 675869), 1135); } }
{ assert_eq!(day_4_part_1(172851, 675869), 1660); }
itasa.py
# -*- coding: utf-8 -*- # Copyright 2012 Mr_Orange <[email protected]> # # This file is part of subliminal. # # subliminal 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. # # subliminal 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 subliminal. If not, see <http://www.gnu.org/licenses/>. from . import ServiceBase from ..exceptions import DownloadFailedError, ServiceError from ..cache import cachedmethod from ..language import language_set, Language from ..subtitles import get_subtitle_path, ResultSubtitle, EXTENSIONS from ..utils import get_keywords from ..videos import Episode from bs4 import BeautifulSoup import logging import re import os import requests import zipfile import StringIO import guessit from sickbeard.common import Quality logger = logging.getLogger("subliminal") class Itasa(ServiceBase): server_url = 'http://www.italiansubs.net/' site_url = 'http://www.italiansubs.net/' api_based = False languages = language_set(['it']) videos = [Episode] require_video = False required_features = ['permissive'] quality_dict = {Quality.SDTV : '', Quality.SDDVD : 'dvdrip', Quality.RAWHDTV : '1080i', Quality.HDTV : '720p', Quality.FULLHDTV : ('1080p','720p'), Quality.HDWEBDL : 'web-dl', Quality.FULLHDWEBDL : 'web-dl', Quality.HDBLURAY : ('bdrip', 'bluray'), Quality.FULLHDBLURAY : ('bdrip', 'bluray'), Quality.UNKNOWN : 'unknown' #Any subtitle will be downloaded } def init(self): super(Itasa, self).init() login_pattern = '<input type="hidden" name="return" value="([^\n\r\t ]+?)" /><input type="hidden" name="([^\n\r\t ]+?)" value="([^\n\r\t ]+?)" />' response = requests.get(self.server_url + 'index.php') if response.status_code != 200: raise ServiceError('Initiate failed') match = re.search(login_pattern, response.content, re.IGNORECASE | re.DOTALL) if not match: raise ServiceError('Can not find unique id parameter on page') login_parameter = {'username': 'sickbeard', 'passwd': 'subliminal', 'remember': 'yes', 'Submit': 'Login', 'remember': 'yes', 'option': 'com_user', 'task': 'login', 'silent': 'true', 'return': match.group(1), match.group(2): match.group(3) } self.session = requests.session() r = self.session.post(self.server_url + 'index.php', data=login_parameter) if not re.search('logouticon.png', r.content, re.IGNORECASE | re.DOTALL): raise ServiceError('Itasa Login Failed') @cachedmethod def get_series_id(self, name): """Get the show page and cache every show found in it""" r = self.session.get(self.server_url + 'index.php?option=com_remository&Itemid=9') soup = BeautifulSoup(r.content, self.required_features) all_series = soup.find('div', attrs = {'id' : 'remositorycontainerlist'}) for tv_series in all_series.find_all(href=re.compile('func=select')): series_name = tv_series.text.lower().strip().replace(':','') match = re.search('&id=([0-9]+)', tv_series['href']) if match is None: continue series_id = int(match.group(1)) self.cache_for(self.get_series_id, args=(series_name,), result=series_id) return self.cached_value(self.get_series_id, args=(name,)) def
(self, series, series_id, season, episode, quality): """Get the id subtitle for episode with the given quality""" season_link = None quality_link = None episode_id = None r = self.session.get(self.server_url + 'index.php?option=com_remository&Itemid=6&func=select&id=' + str(series_id)) soup = BeautifulSoup(r.content, self.required_features) all_seasons = soup.find('div', attrs = {'id' : 'remositorycontainerlist'}) for seasons in all_seasons.find_all(href=re.compile('func=select')): if seasons.text.lower().strip() == 'stagione %s' % str(season): season_link = seasons['href'] break if not season_link: logger.debug(u'Could not find season %s for series %s' % (series, str(season))) return None r = self.session.get(season_link) soup = BeautifulSoup(r.content, self.required_features) all_qualities = soup.find('div', attrs = {'id' : 'remositorycontainerlist'}) for qualities in all_qualities.find_all(href=re.compile('func=select')): if qualities.text.lower().strip() in self.quality_dict[quality]: quality_link = qualities['href'] r = self.session.get(qualities['href']) soup = BeautifulSoup(r.content, self.required_features) break #If we want SDTV we are just on the right page so quality link will be None if not quality == Quality.SDTV and not quality_link: logger.debug(u'Could not find a subtitle with required quality for series %s season %s' % (series, str(season))) return None all_episodes = soup.find('div', attrs = {'id' : 'remositoryfilelisting'}) for episodes in all_episodes.find_all(href=re.compile('func=fileinfo')): ep_string = "%(seasonnumber)dx%(episodenumber)02d" % {'seasonnumber': season, 'episodenumber': episode} if re.search(ep_string, episodes.text, re.I) or re.search('completa$', episodes.text, re.I): match = re.search('&id=([0-9]+)', episodes['href']) if match: episode_id = match.group(1) return episode_id return episode_id def list_checked(self, video, languages): return self.query(video.path or video.release, languages, get_keywords(video.guess), video.series, video.season, video.episode) def query(self, filepath, languages, keywords, series, season, episode): logger.debug(u'Getting subtitles for %s season %d episode %d with languages %r' % (series, season, episode, languages)) self.init_cache() try: series = series.lower().replace('(','').replace(')','') series_id = self.get_series_id(series) except KeyError: logger.debug(u'Could not find series id for %s' % series) return [] episode_id = self.get_episode_id(series, series_id, season, episode, Quality.nameQuality(filepath)) if not episode_id: logger.debug(u'Could not find subtitle for series %s' % series) return [] r = self.session.get(self.server_url + 'index.php?option=com_remository&Itemid=6&func=fileinfo&id=' + episode_id) soup = BeautifulSoup(r.content) sub_link = soup.find('div', attrs = {'id' : 'remositoryfileinfo'}).find(href=re.compile('func=download'))['href'] sub_language = self.get_language('it') path = get_subtitle_path(filepath, sub_language, self.config.multi) subtitle = ResultSubtitle(path, sub_language, self.__class__.__name__.lower(), sub_link) return [subtitle] def download(self, subtitle): logger.info(u'Downloading %s in %s' % (subtitle.link, subtitle.path)) try: r = self.session.get(subtitle.link, headers={'Referer': self.server_url, 'User-Agent': self.user_agent}) zipcontent = StringIO.StringIO(r.content) zipsub = zipfile.ZipFile(zipcontent) # if not zipsub.is_zipfile(zipcontent): # raise DownloadFailedError('Downloaded file is not a zip file') subfile = '' if len(zipsub.namelist()) == 1: subfile = zipsub.namelist()[0] else: #Season Zip Retrive Season and episode Numbers from path guess = guessit.guess_file_info(subtitle.path, 'episode') ep_string = "s%(seasonnumber)02de%(episodenumber)02d" % {'seasonnumber': guess['season'], 'episodenumber': guess['episodeNumber']} for file in zipsub.namelist(): if re.search(ep_string, file, re.I): subfile = file break if os.path.splitext(subfile)[1] in EXTENSIONS: with open(subtitle.path, 'wb') as f: f.write(zipsub.open(subfile).read()) else: zipsub.close() raise DownloadFailedError('No subtitles found in zip file') zipsub.close() except Exception as e: if os.path.exists(subtitle.path): os.remove(subtitle.path) raise DownloadFailedError(str(e)) logger.debug(u'Download finished') Service = Itasa
get_episode_id
mod.rs
use common::{generate, generate_trimesh_around_origin, unref}; use na::Isometry3; use ncollide3d::bounding_volume::{BoundingVolume, HasBoundingVolume}; use ncollide3d::bounding_volume::{AABB, BoundingSphere}; use ncollide3d::shape::{Ball, Capsule, Cone, ConvexHull, Cuboid, Cylinder, Segment, Triangle, TriMesh}; use rand::IsaacRng; use test; use test::Bencher; #[path = "../common/macros.rs"] #[macro_use] mod macros; /* * Bounding volume methods. */ bench_method!( bench_aabb_intersects_aabb_always_true, intersects, aabb1: AABB<f32>, aabb2: AABB<f32> ); bench_method!( bench_bounding_sphere_intersects_bounding_sphere_always_true, intersects, bs1: BoundingSphere<f32>, bs2: BoundingSphere<f32> ); bench_method!( bench_aabb_contains_aabb, contains, aabb1: AABB<f32>, aabb2: AABB<f32> ); bench_method!( bench_bounding_sphere_contains_bounding_sphere, contains, bs1: BoundingSphere<f32>, bs2: BoundingSphere<f32> ); bench_method!( bench_aabb_merged_aabb, merged, aabb1: AABB<f32>, aabb2: AABB<f32> ); bench_method!( bench_bounding_sphere_merged_bounding_sphere, merged, bs1: BoundingSphere<f32>, bs2: BoundingSphere<f32> ); bench_method!( bench_aabb_loosened_aabb, loosened, aabb1: AABB<f32>, margin: f32 ); bench_method!(
margin: f32 ); /* * Bounding volume construction. */ bench_method!( bench_cuboid_aabb, bounding_volume: AABB<f32>, c: Cuboid<f32>, m: Isometry3<f32> ); bench_method!( bench_cuboid_bounding_sphere, bounding_volume: BoundingSphere<f32>, c: Cuboid<f32>, m: Isometry3<f32> ); bench_method!( bench_ball_aabb, bounding_volume: AABB<f32>, b: Ball<f32>, m: Isometry3<f32> ); bench_method!( bench_ball_bounding_sphere, bounding_volume: BoundingSphere<f32>, b: Ball<f32>, m: Isometry3<f32> ); bench_method!( bench_capsule_aabb, bounding_volume: AABB<f32>, c: Capsule<f32>, m: Isometry3<f32> ); bench_method!( bench_capsule_bounding_sphere, bounding_volume: BoundingSphere<f32>, c: Capsule<f32>, m: Isometry3<f32> ); bench_method!( bench_cone_aabb, bounding_volume: AABB<f32>, c: Cone<f32>, m: Isometry3<f32> ); bench_method!( bench_cone_bounding_sphere, bounding_volume: BoundingSphere<f32>, c: Cone<f32>, m: Isometry3<f32> ); bench_method!( bench_cylinder_aabb, bounding_volume: AABB<f32>, c: Cylinder<f32>, m: Isometry3<f32> ); bench_method!( bench_cylinder_bounding_sphere, bounding_volume: BoundingSphere<f32>, c: Cylinder<f32>, m: Isometry3<f32> ); bench_method!( bench_segment_aabb, bounding_volume: AABB<f32>, c: Segment<f32>, m: Isometry3<f32> ); bench_method!( bench_segment_bounding_sphere, bounding_volume: BoundingSphere<f32>, c: Segment<f32>, m: Isometry3<f32> ); bench_method!( bench_triangle_aabb, bounding_volume: AABB<f32>, c: Triangle<f32>, m: Isometry3<f32> ); bench_method!( bench_triangle_bounding_sphere, bounding_volume: BoundingSphere<f32>, c: Triangle<f32>, m: Isometry3<f32> ); bench_method!( bench_convex_aabb, bounding_volume: AABB<f32>, c: ConvexHull<f32>, m: Isometry3<f32> ); bench_method!( bench_convex_bounding_sphere, bounding_volume: BoundingSphere<f32>, c: ConvexHull<f32>, m: Isometry3<f32> ); bench_method_gen!( bench_mesh_aabb, bounding_volume: AABB<f32>, mesh: TriMesh<f32> = generate_trimesh_around_origin, m: Isometry3<f32> = generate ); bench_method_gen!( bench_mesh_bounding_sphere, bounding_volume: BoundingSphere<f32>, mesh: TriMesh<f32> = generate_trimesh_around_origin, m: Isometry3<f32> = generate );
bench_bounding_sphere_loosened_bounding_sphere, loosened, bs1: BoundingSphere<f32>,
hostspool_mgr_allocation.go
// Copyright 2018 Bull S.A.S. Atos Technologies - Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois, France. // // 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 hostspool import ( "encoding/json" "fmt" "github.com/ystia/yorc/v4/helper/collections" "github.com/ystia/yorc/v4/log" "net/url" "path" "strconv" "strings" "time" "github.com/hashicorp/consul/api" "github.com/pkg/errors" "github.com/ystia/yorc/v4/helper/consulutil" "github.com/ystia/yorc/v4/helper/labelsutil" ) const ( binPackingPlacement = "yorc.policies.hostspool.BinPackingPlacement" weightBalancedPlacement = "yorc.policies.hostspool.WeightBalancedPlacement" placementPolicy = "yorc.policies.hostspool.Placement" ) type hostCandidate struct { name string allocations int } func (cm *consulManager) Allocate(locationName string, allocation *Allocation, filters ...labelsutil.Filter) (string, []labelsutil.Warning, error) { return cm.allocateWait(locationName, maxWaitTimeSeconds*time.Second, allocation, filters...) } func (cm *consulManager) allocateWait(locationName string, maxWaitTime time.Duration, allocation *Allocation, filters ...labelsutil.Filter) (string, []labelsutil.Warning, error) { // Build allocationID if err := allocation.buildID(); err != nil { return "", nil, err } lockCh, cleanupFn, err := cm.lockKey(locationName, "", "allocation", maxWaitTime) if err != nil { return "", nil, err } defer cleanupFn() hosts, warnings, _, err := cm.List(locationName, filters...) if err != nil { return "", warnings, err } // define host candidates in only free or allocated hosts in case of shareable allocation candidates := make([]hostCandidate, 0) var lastErr error for _, h := range hosts { select { case <-lockCh: return "", warnings, errors.New("admin lock lost on hosts pool during host allocation") default: } err := cm.checkConnection(locationName, h) if err != nil { lastErr = err continue } hs, err := cm.GetHostStatus(locationName, h) if err != nil { lastErr = err } else { if hs == HostStatusFree { candidates = append(candidates, hostCandidate{ name: h, allocations: 0, }) } else if hs == HostStatusAllocated && allocation.Shareable { allocations, err := cm.getAllocations(locationName, h) if err != nil { lastErr = err continue } // Check the host allocation is not shareable if len(allocations) == 1 && !allocations[0].Shareable { continue } candidates = append(candidates, hostCandidate{ name: h, allocations: len(allocations), }) } } } if len(candidates) == 0 { if lastErr != nil { return "", warnings, lastErr } return "", warnings, errors.WithStack(noMatchingHostFoundError{}) } // Apply the policy placement hostname := cm.electHostFromCandidates(locationName, allocation, candidates) select { case <-lockCh: return "", warnings, errors.New("admin lock lost on hosts pool during host allocation") default: } if err := cm.addAllocation(locationName, hostname, allocation); err != nil { return "", warnings, errors.Wrapf(err, "failed to add allocation for hostname:%q", hostname) } return hostname, warnings, cm.setHostStatus(locationName, hostname, HostStatusAllocated) } func (cm *consulManager) electHostFromCandidates(locationName string, allocation *Allocation, candidates []hostCandidate) string { switch allocation.PlacementPolicy { case weightBalancedPlacement: log.Printf("Applying weight-balanced placement policy for location:%s, deployment:%s, node name:%s, instance:%s", locationName, allocation.DeploymentID, allocation.NodeName, allocation.Instance) return weightBalanced(candidates) case binPackingPlacement: log.Printf("Applying bin packing placement policy for location:%s, deployment:%s, node name:%s, instance:%s", locationName, allocation.DeploymentID, allocation.NodeName, allocation.Instance) return binPacking(candidates) default: // default is bin packing placement log.Printf("Applying default bin packing placement policy for location:%s, deployment:%s, node name:%s, instance:%s", locationName, allocation.DeploymentID, allocation.NodeName, allocation.Instance) return binPacking(candidates) } } func weightBalanced(candidates []hostCandidate) string { hostname := candidates[0].name minAllocations := candidates[0].allocations for _, candidate := range candidates { if candidate.allocations < minAllocations { minAllocations = candidate.allocations hostname = candidate.name } } return hostname } func binPacking(candidates []hostCandidate) string { hostname := candidates[0].name maxAllocations := candidates[0].allocations for _, candidate := range candidates { if candidate.allocations > maxAllocations { maxAllocations = candidate.allocations hostname = candidate.name } } return hostname } func (cm *consulManager) Release(locationName, hostname, deploymentID, nodeName, instance string) (*Allocation, error) { return cm.releaseWait(locationName, hostname, deploymentID, nodeName, instance, maxWaitTimeSeconds*time.Second) } func (cm *consulManager) releaseWait(locationName, hostname, deploymentID, nodeName, instance string, maxWaitTime time.Duration) (*Allocation, error) { _, cleanupFn, err := cm.lockKey(locationName, hostname, "release", maxWaitTime) if err != nil { return nil, err } defer cleanupFn() // Need to retrieve complete information about allocation for resources updates allocation, err := cm.getAllocation(locationName, hostname, buildAllocationID(deploymentID, nodeName, instance)) if err != nil { return nil, err } if err := cm.removeAllocation(locationName, hostname, allocation); err != nil { return nil, errors.Wrapf(err, "failed to remove allocation with ID:%q, hostname:%q, location: %q", allocation.ID, hostname, locationName) } host, err := cm.GetHost(locationName, hostname) if err != nil { return nil, err } // Set the host status to free only for host with no allocations if len(host.Allocations) == 0 { if err = cm.setHostStatus(locationName, hostname, HostStatusFree); err != nil { return nil, err } } err = cm.checkConnection(locationName, hostname) if err != nil { cm.backupHostStatus(locationName, hostname) cm.setHostStatusWithMessage(locationName, hostname, HostStatusError, hostConnectionErrorMessage) } return allocation, nil } func getKVTxnOp(verb api.KVOp, key string, value []byte) *api.KVTxnOp { return &api.KVTxnOp{ Verb: verb, Key: key, Value: value, } } func getAddAllocationsOperation(locationName, hostname string, allocations []Allocation) (api.KVTxnOps, error) { allocsOps := api.KVTxnOps{} hostKVPrefix := path.Join(consulutil.HostsPoolPrefix, locationName, hostname) if allocations != nil { for _, alloc := range allocations { allocKVPrefix := path.Join(hostKVPrefix, "allocations", alloc.ID) allocOps := api.KVTxnOps{ getKVTxnOp(api.KVSet, path.Join(allocKVPrefix), []byte(alloc.ID)), getKVTxnOp(api.KVSet, path.Join(allocKVPrefix, "node_name"), []byte(alloc.NodeName)), getKVTxnOp(api.KVSet, path.Join(allocKVPrefix, "instance"), []byte(alloc.Instance)), getKVTxnOp(api.KVSet, path.Join(allocKVPrefix, "deployment_id"), []byte(alloc.DeploymentID)), getKVTxnOp(api.KVSet, path.Join(allocKVPrefix, "shareable"), []byte(strconv.FormatBool(alloc.Shareable))), getKVTxnOp(api.KVSet, path.Join(allocKVPrefix, "placement_policy"), []byte(alloc.PlacementPolicy)), } for k, v := range alloc.Resources { k = url.PathEscape(k) if k == "" { return nil, errors.WithStack(badRequestError{"empty labels are not allowed"}) } allocOps = append(allocOps, getKVTxnOp(api.KVSet, path.Join(allocKVPrefix, "resources", k), []byte(v))) } for _, gResource := range alloc.GenericResources { // save generic resource in JSON data, err := json.Marshal(gResource) if err != nil { return nil, err } allocOps = append(allocOps, getKVTxnOp(api.KVSet, path.Join(allocKVPrefix, "generic_resources", gResource.Name), data)) } allocsOps = append(allocsOps, allocOps...) } } return allocsOps, nil } func (cm *consulManager) addAllocation(locationName, hostname string, allocation *Allocation) error { var allocOps api.KVTxnOps var err error if allocation.GenericResources != nil { if err = cm.allocateGenericResources(locationName, hostname, allocation); err != nil { return err } } if allocOps, err = getAddAllocationsOperation(locationName, hostname, []Allocation{*allocation}); err != nil { return errors.Wrapf(err, "failed to add allocation to host:%q, location: %q", hostname, locationName) } ok, response, _, err := cm.cc.KV().Txn(allocOps, nil) if err != nil { return errors.Wrap(err, consulutil.ConsulGenericErrMsg) } if !ok { // Check the response errs := make([]string, 0) for _, e := range response.Errors { errs = append(errs, e.What) } return errors.Errorf("Failed to add allocation on host %q, location %q: %s", hostname, locationName, strings.Join(errs, ", ")) } return nil } func (cm *consulManager) allocateGenericResources(locationName, hostname string, allocation *Allocation) error { // Retrieve host generic resources labels labels, err := cm.GetHostLabels(locationName, hostname) if err != nil { return err } for i := range allocation.GenericResources { gResource := allocation.GenericResources[i] hostGenResourceStr, ok := labels[gResource.Label] if !ok { return errors.Errorf("failed to retrieve generic resource:%q for location:%q, host:%s", gResource.Name, locationName, hostname) } hostGenResource := toSlice(hostGenResourceStr) // Retrieve no_consume generic resource label if existing noConsumeLabel := fmt.Sprintf("%s.%s", gResource.Label, genericResourceNoConsumeProperty) noConsumeStr, ok := labels[noConsumeLabel] if ok { if noConsumeStr != "" { gResource.NoConsumable, err = strconv.ParseBool(noConsumeStr) if err != nil { return errors.Wrapf(err, "expected boolean value for no_consumable label of generic resource with name:%q", gResource.Name) } } } // check ids for the related instance instance, err := strconv.Atoi(allocation.Instance) if err != nil { return errors.Wrapf(err, "unexpected non integer value for node name:%q, instance:%q", allocation.NodeName, allocation.Instance) } if gResource.ids != nil && len(gResource.ids) > 0 { // Get the ids relative to the instance if exists // Otherwise, use the first occurrence gResourceInstanceIds := gResource.ids[0] if len(gResource.ids) > instance { gResourceInstanceIds = gResource.ids[instance] } // Check list contains ids for _, id := range gResourceInstanceIds { if !collections.ContainsString(hostGenResource, id) { return errors.Errorf("missing expected id:%q for generic resource:%q, location:%q, host:%s, node name:%q, instance:%q", id, gResource.Name, locationName, hostname, allocation.NodeName, allocation.Instance) } } gResource.Value = strings.Join(gResourceInstanceIds, ",") continue } if gResource.nb == 0 { return errors.Errorf("Neither ids nor number is provided for generic resource:%q, location:%q, host:%s, node name:%q, instance:%q", gResource.Name, locationName, hostname, allocation.NodeName, allocation.Instance) } // check nb if len(hostGenResource) < gResource.nb { return errors.Errorf("missing %d expected resource(s) for generic resource:%q, location:%q, host:%s, node name:%q, instance:%q", gResource.nb-len(hostGenResource), gResource.Name, locationName, hostname, allocation.NodeName, allocation.Instance) } gResource.Value = strings.Join(hostGenResource[:gResource.nb], ",") } return nil } func (cm *consulManager) removeAllocation(locationName, hostname string, allocation *Allocation) error { _, err := cm.cc.KV().DeleteTree(path.Join(consulutil.HostsPoolPrefix, locationName, hostname, "allocations", allocation.ID)+"/", nil) if err != nil { return errors.Wrap(err, consulutil.ConsulGenericErrMsg) } _, err = cm.cc.KV().Delete(path.Join(consulutil.HostsPoolPrefix, locationName, hostname, "allocations", allocation.ID), nil) return errors.Wrap(err, consulutil.ConsulGenericErrMsg) } func exist(allocations []Allocation, ID string) bool { for _, alloc := range allocations { if alloc.ID == ID { return true } } return false } func (cm *consulManager) getAllocations(locationName, hostname string) ([]Allocation, error) { allocations := make([]Allocation, 0) keys, _, err := cm.cc.KV().Keys(path.Join(consulutil.HostsPoolPrefix, locationName, hostname, "allocations")+"/", "/", nil) if err != nil
for _, key := range keys { id := path.Base(key) if exist(allocations, id) { continue } alloc, err := cm.getAllocation(locationName, hostname, id) if err != nil { return nil, err } allocations = append(allocations, *alloc) } return allocations, nil } func (cm *consulManager) getAllocation(locationName, hostname, allocationID string) (*Allocation, error) { alloc := &Allocation{ ID: allocationID, } stringFields := []struct { name string attr *string }{ {"node_name", &alloc.NodeName}, {"instance", &alloc.Instance}, {"deployment_id", &alloc.DeploymentID}, {"placement_policy", &alloc.PlacementPolicy}, } key := path.Join(consulutil.HostsPoolPrefix, locationName, hostname, "allocations", allocationID) for _, field := range stringFields { kvp, _, err := cm.cc.KV().Get(path.Join(key, field.name), nil) if err != nil { return nil, errors.Wrap(err, consulutil.ConsulGenericErrMsg) } if kvp != nil && len(kvp.Value) > 0 { *field.attr = string(kvp.Value) } } kvp, _, err := cm.cc.KV().Get(path.Join(key, "shareable"), nil) if err != nil { return nil, errors.Wrap(err, consulutil.ConsulGenericErrMsg) } if kvp != nil && len(kvp.Value) > 0 { alloc.Shareable, err = strconv.ParseBool(string(kvp.Value)) if err != nil { return nil, errors.Wrapf(err, "failed to parse boolean from value:%q", string(kvp.Value)) } } // Retrieve resources alloc.Resources, err = cm.getResourcesForAllocation(locationName, hostname, allocationID) if err != nil { return nil, err } // Retrieve generic resources alloc.GenericResources, err = cm.getGenericResourcesForAllocation(locationName, hostname, allocationID) if err != nil { return nil, err } return alloc, nil } func (cm *consulManager) getResourcesForAllocation(locationName, hostname, allocationID string) (map[string]string, error) { // Appending a final "/" here is not necessary as there is no other keys starting with "resources" prefix key := path.Join(consulutil.HostsPoolPrefix, locationName, hostname, "allocations", allocationID) kvps, _, err := cm.cc.KV().List(path.Join(key, "resources"), nil) if err != nil { return nil, errors.Wrap(err, consulutil.ConsulGenericErrMsg) } resources := make(map[string]string, len(kvps)) for _, kvp := range kvps { resources[path.Base(kvp.Key)] = string(kvp.Value) } return resources, nil } func (cm *consulManager) getGenericResourcesForAllocation(locationName, hostname, allocationID string) ([]*GenericResource, error) { // Appending a final "/" here is not necessary as there is no other keys starting with "resources" prefix key := path.Join(consulutil.HostsPoolPrefix, locationName, hostname, "allocations", allocationID) kvps, _, err := cm.cc.KV().List(path.Join(key, "generic_resources"), nil) if err != nil { return nil, errors.Wrap(err, consulutil.ConsulGenericErrMsg) } gResources := make([]*GenericResource, 0) for _, kvp := range kvps { var gResource GenericResource err = json.Unmarshal(kvp.Value, &gResource) if err != nil { return nil, errors.Wrapf(err, "failed to unmarshal generic resource for key:%q", kvp.Key) } gResources = append(gResources, &gResource) } return gResources, nil } // CheckPlacementPolicy check if placement policy is supported func (cm *consulManager) CheckPlacementPolicy(placementPolicy string) error { if placementPolicy == "" { return nil } switch placementPolicy { case weightBalancedPlacement, binPackingPlacement: return nil default: return errors.Errorf("placement policy:%q is not actually supported", placementPolicy) } }
{ return nil, errors.Wrap(err, consulutil.ConsulGenericErrMsg) }
symbols.rs
use std::borrow::Cow; use std::collections::{BTreeMap, HashSet}; use std::iter::{IntoIterator, Peekable}; use std::slice; use goblin::mach; use regex::Regex; use symbolic_common::{ErrorKind, Name, Result}; use object::{Object, ObjectTarget}; lazy_static! { static ref HIDDEN_SYMBOL_RE: Regex = Regex::new("__?hidden#\\d+_").unwrap(); } /// A single symbol #[derive(Debug)] pub struct Symbol<'data> { name: Cow<'data, str>, addr: u64, len: Option<u64>, } impl<'data> Symbol<'data> { /// Binary string value of the symbol pub fn name(&self) -> &Cow<'data, str>
/// Address of this symbol pub fn addr(&self) -> u64 { self.addr } /// Presumed length of the symbol pub fn len(&self) -> Option<u64> { self.len } /// Returns the string representation of this symbol pub fn as_str(&self) -> &str { self.name().as_ref() } } impl<'data> Into<Name<'data>> for Symbol<'data> { fn into(self) -> Name<'data> { Name::new(self.name) } } impl<'data> Into<Cow<'data, str>> for Symbol<'data> { fn into(self) -> Cow<'data, str> { self.name } } impl<'data> Into<String> for Symbol<'data> { fn into(self) -> String { self.name.into() } } /// Internal wrapper around certain symbol table implementations #[derive(Clone, Copy, Debug)] enum SymbolsInternal<'data> { MachO(&'data mach::symbols::Symbols<'data>), } impl<'data> SymbolsInternal<'data> { /// Returns the symbol at the given index /// /// To compute the presumed length of a symbol, pass the index of the /// logically next symbol (i.e. the one with the next greater address). pub fn get(&self, index: usize, next: Option<usize>) -> Result<Option<Symbol<'data>>> { Ok(Some(match *self { SymbolsInternal::MachO(symbols) => { let (name, nlist) = symbols.get(index)?; let stripped = if name.starts_with("_") { &name[1..] } else { name }; // The length is only calculated if `next` is specified and does // not result in an error. Otherwise, errors here are swallowed. let addr = nlist.n_value; let len = next.and_then(|index| symbols.get(index).ok()) .map(|(_, nlist)| nlist.n_value - addr); Symbol { name: Cow::Borrowed(stripped), addr: addr, len: len, } } })) } } /// Internal type used to map addresses to symbol indices /// /// `mapping.0`: The address of a symbol /// `mapping.1`: The index of a symbol in the symbol list type IndexMapping = (u64, usize); /// An iterator over `Symbol`s in a symbol table /// /// Can be obtained via `SymbolTable::symbols`. This is primarily intended for /// consuming all symbols in an object file. To lookup single symbols, use /// `Symbols::lookup` instead. pub struct SymbolIterator<'data, 'sym> where 'data: 'sym, { symbols: &'sym Symbols<'data>, iter: Peekable<slice::Iter<'sym, IndexMapping>>, } impl<'data, 'sym> Iterator for SymbolIterator<'data, 'sym> { type Item = Result<Symbol<'data>>; fn next(&mut self) -> Option<Self::Item> { let index = match self.iter.next() { Some(map) => map.1, None => return None, }; let next = self.iter.peek().map(|mapping| mapping.1); match self.symbols.internal.get(index, next) { Ok(Some(symbol)) => Some(Ok(symbol)), Ok(None) => None, Err(err) => Some(Err(err)), } } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } fn count(self) -> usize { self.iter.count() } } /// Provides access to `Symbol`s of an `Object` /// /// It allows to either lookup single symbols with `Symbols::lookup` or iterate /// them using `Symbols::into_iter`. Use `SymbolTable::lookup` on an `Object` to /// retrieve the symbols. pub struct Symbols<'data> { internal: SymbolsInternal<'data>, mappings: Vec<IndexMapping>, } impl<'data> Symbols<'data> { /// Creates a `Symbols` wrapper for MachO fn from_macho(macho: &'data mach::MachO) -> Result<Symbols<'data>> { let macho_symbols = match macho.symbols { Some(ref symbols) => symbols, None => return Err(ErrorKind::MissingDebugInfo("symbol table missing").into()), }; let mut sections = HashSet::new(); let mut section_index = 0; // Cache section indices that we are interested in for segment in &macho.segments { for section_rv in segment { let (section, _) = section_rv?; let name = section.name()?; if name == "__stubs" || name == "__text" { sections.insert(section_index); } section_index += 1; } } // Build an ordered map of only symbols we are interested in let mut symbol_map = BTreeMap::new(); for (symbol_index, symbol_result) in macho.symbols().enumerate() { let (_, nlist) = symbol_result?; let in_valid_section = nlist.get_type() == mach::symbols::N_SECT && nlist.n_sect != (mach::symbols::NO_SECT as usize) && sections.contains(&(nlist.n_sect - 1)); if in_valid_section { symbol_map.insert(nlist.n_value, symbol_index); } } Ok(Symbols { internal: SymbolsInternal::MachO(macho_symbols), mappings: symbol_map.into_iter().collect(), }) } /// Searches for a single `Symbol` inside the symbol table pub fn lookup(&self, addr: u64) -> Result<Option<Symbol<'data>>> { let found = match self.mappings.binary_search_by_key(&addr, |&x| x.0) { Ok(idx) => idx, Err(0) => return Ok(None), Err(next_idx) => next_idx - 1, }; let index = self.mappings[found].1; let next = self.mappings.get(found + 1).map(|mapping| mapping.1); self.internal.get(index, next) } /// Checks whether this binary contains hidden symbols /// /// This is an indication that BCSymbolMaps are needed to symbolicate /// symbols correctly. pub fn requires_symbolmap(&self) -> Result<bool> { // Hidden symbols can only ever occur in Apple's dSYM match self.internal { SymbolsInternal::MachO(..) => (), }; for symbol in self.iter() { if HIDDEN_SYMBOL_RE.is_match(symbol?.as_str()) { return Ok(true); } } Ok(false) } pub fn iter<'sym>(&'sym self) -> SymbolIterator<'data, 'sym> { SymbolIterator { symbols: self, iter: self.mappings.iter().peekable(), } } } /// Gives access to the symbol table of an `Object` file pub trait SymbolTable { /// Returns the symbols of this `Object` fn symbols(&self) -> Result<Symbols>; } impl<'data> SymbolTable for Object<'data> { fn symbols(&self) -> Result<Symbols> { match self.target { ObjectTarget::MachOSingle(macho) => Symbols::from_macho(macho), ObjectTarget::MachOFat(_, ref macho) => Symbols::from_macho(macho), _ => Err(ErrorKind::Internal("symbol table not implemented").into()), } } }
{ &self.name }
runAutomaticFix.ts
import chalk from 'chalk'; import ora, {Ora} from 'ora'; import {logger} from '@react-native-community/cli-tools'; import {HEALTHCHECK_TYPES} from './healthchecks'; import {EnvironmentInfo} from '@react-native-community/cli-types'; import {HealthCheckCategoryResult} from './types'; import {logManualInstallation} from './healthchecks/common'; export enum AUTOMATIC_FIX_LEVELS { ALL_ISSUES = 'ALL_ISSUES', ERRORS = 'ERRORS', WARNINGS = 'WARNINGS', } interface RunAutomaticFixArgs { healthchecks: HealthCheckCategoryResult[]; automaticFixLevel: AUTOMATIC_FIX_LEVELS; stats: { errors: number; warnings: number; }; loader: Ora; environmentInfo: EnvironmentInfo; } export default async function ({ healthchecks, automaticFixLevel, stats, environmentInfo, }: RunAutomaticFixArgs) { // Remove the fix options from screen if (process.stdout.isTTY) { // @ts-ignore process.stdout.moveCursor(0, -6);
process.stdout.clearScreenDown(); } const totalIssuesBasedOnFixLevel: {[x in AUTOMATIC_FIX_LEVELS]: number} = { [AUTOMATIC_FIX_LEVELS.ALL_ISSUES]: stats.errors + stats.warnings, [AUTOMATIC_FIX_LEVELS.ERRORS]: stats.errors, [AUTOMATIC_FIX_LEVELS.WARNINGS]: stats.warnings, }; const issuesCount = totalIssuesBasedOnFixLevel[automaticFixLevel]; logger.log( `\nAttempting to fix ${chalk.bold(issuesCount.toString())} issue${ issuesCount > 1 ? 's' : '' }...`, ); for (const category of healthchecks) { const healthchecksToRun = category.healthchecks.filter((healthcheck) => { if (automaticFixLevel === AUTOMATIC_FIX_LEVELS.ALL_ISSUES) { return healthcheck.needsToBeFixed; } if (automaticFixLevel === AUTOMATIC_FIX_LEVELS.ERRORS) { return ( healthcheck.needsToBeFixed && healthcheck.type === HEALTHCHECK_TYPES.ERROR ); } if (automaticFixLevel === AUTOMATIC_FIX_LEVELS.WARNINGS) { return ( healthcheck.needsToBeFixed && healthcheck.type === HEALTHCHECK_TYPES.WARNING ); } return; }); if (!healthchecksToRun.length) { continue; } logger.log(`\n${chalk.dim(category.label)}`); for (const healthcheckToRun of healthchecksToRun) { const spinner = ora({ prefixText: '', text: healthcheckToRun.label, }).start(); try { await healthcheckToRun.runAutomaticFix({ loader: spinner, logManualInstallation, environmentInfo, }); } catch (error) { // TODO: log the error in a meaningful way } } } }
// @ts-ignore
Hash.tsx
/* GENERATED FILE */ import * as React from 'react'; import Svg, { Rect, Line } from 'react-native-svg'; import { IconProps } from '../lib'; function Hash(props: IconProps) { return ( <Svg id="Raw" viewBox="0 0 256 256" width={props.size} height={props.size} {...props} > <Rect width={256} height={256} fill="none" /> <Line x1={43.63636} y1={96} x2={224} y2={96} fill="none" stroke={props.color} strokeLinecap="round" strokeLinejoin="round" strokeWidth={24} /> <Line x1={176}
fill="none" stroke={props.color} strokeLinecap="round" strokeLinejoin="round" strokeWidth={24} /> <Line x1={112} y1={40} x2={80} y2={216} fill="none" stroke={props.color} strokeLinecap="round" strokeLinejoin="round" strokeWidth={24} /> <Line x1={32} y1={160} x2={212.36376} y2={160} fill="none" stroke={props.color} strokeLinecap="round" strokeLinejoin="round" strokeWidth={24} /> </Svg> ); } export default Hash;
y1={40} x2={144} y2={216}
test_commoncrypto.py
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import pytest from cryptography import utils from cryptography.exceptions import InternalError, _Reasons from cryptography.hazmat.backends import _available_backends from cryptography.hazmat.primitives.ciphers import Cipher, CipherAlgorithm from cryptography.hazmat.primitives.ciphers.algorithms import AES from cryptography.hazmat.primitives.ciphers.modes import CBC, GCM from ...utils import raises_unsupported_algorithm @utils.register_interface(CipherAlgorithm) class DummyCipher(object): name = "dummy-cipher" block_size = None key_size = None @pytest.mark.skipif("commoncrypto" not in [i.name for i in _available_backends()], reason="CommonCrypto not available") class TestCommonCrypto(object): def test_supports_cipher(self): from cryptography.hazmat.backends.commoncrypto.backend import backend assert backend.cipher_supported(None, None) is False def test_register_duplicate_cipher_adapter(self): from cryptography.hazmat.backends.commoncrypto.backend import backend with pytest.raises(ValueError): backend._register_cipher_adapter( AES, backend._lib.kCCAlgorithmAES128, CBC, backend._lib.kCCModeCBC ) def test_handle_response(self): from cryptography.hazmat.backends.commoncrypto.backend import backend with pytest.raises(ValueError): backend._check_cipher_response(backend._lib.kCCAlignmentError) with pytest.raises(InternalError): backend._check_cipher_response(backend._lib.kCCMemoryFailure) with pytest.raises(InternalError): backend._check_cipher_response(backend._lib.kCCDecodeError) def test_nonexistent_aead_cipher(self):
from cryptography.hazmat.backends.commoncrypto.backend import Backend b = Backend() cipher = Cipher( DummyCipher(), GCM(b"fake_iv_here"), backend=b, ) with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER): cipher.encryptor()
0003_auto_20180915_2336.py
# Generated by Django 2.1.1 on 2018-09-16 04:36 from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('partners', '0002_auto_20180915_2328'), ] operations = [ migrations.AlterField( model_name='communitypartner', name='college', field=models.CharField(blank=True, max_length=50), ), migrations.AlterField( model_name='communitypartner', name='department', field=models.CharField(blank=True, max_length=30), ), migrations.AlterField( model_name='communitypartner', name='k12_level', field=models.CharField(blank=True, max_length=20), ), ]
template.py
"""A simple Python template renderer, for a nano-subset of Django syntax.""" # Comes from http://aosabook.org/en/500L/a-template-engine.html # By Ned Batchelder (nedbatchelder.com) # Hosted on https://github.com/aosabook/500lines/tree/master/template-engine/code # Coincidentally named the same as http://code.activestate.com/recipes/496702/ # Modified by Pierre-Jean Fichet to suport more tests. # And renamed template, class Template, etc., for convenience. # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import re class TemplateSyntaxError(ValueError): """Raised when a template has a syntax error.""" pass class CodeBuilder(object): """Build source code conveniently.""" def __init__(self, indent=0): self.code = [] self.indent_level = indent def __str__(self): return "".join(str(c) for c in self.code) def add_line(self, line): """Add a line of source to the code. Indentation and newline will be added for you, don't provide them. """ self.code.extend([" " * self.indent_level, line, "\n"]) def add_section(self): """Add a section, a sub-CodeBuilder.""" section = CodeBuilder(self.indent_level) self.code.append(section) return section INDENT_STEP = 4 # PEP8 says so! def indent(self): """Increase the current indent for following lines.""" self.indent_level += self.INDENT_STEP def dedent(self): """Decrease the current indent for following lines.""" self.indent_level -= self.INDENT_STEP def get_globals(self): """Execute the code, and return a dict of globals it defines.""" # A check that the caller really finished all the blocks they started. assert self.indent_level == 0 # Get the Python source as a single string. python_source = str(self) # Execute the source, defining globals, and return them. global_namespace = {} exec(python_source, global_namespace) return global_namespace class Template(object): """A simple template renderer, for a nano-subset of Django syntax. Supported constructs are extended variable access:: {{var.modifer.modifier|filter|filter}} loops:: {% for var in list %}...{% endfor %} and ifs:: {% if var %}...{% endif %} Comments are within curly-hash markers:: {# This will be ignored #} Construct a Template with the template text, then use `render` against a dictionary context to create a finished string:: template = Template(''' <h1>Hello {{name|upper}}!</h1> {% for topic in topics %} <p>You are interested in {{topic}}.</p> {% endif %} ''', {'upper': str.upper}, ) text = template.render({ 'name': "Ned", 'topics': ['Python', 'Geometry', 'Juggling'], }) """ def __init__(self, text, *contexts): """Construct a Template with the given `text`. `contexts` are dictionaries of values to use for future renderings. These are good for filters and global values. """ self.context = {} for context in contexts: self.context.update(context) self.all_vars = set() self.loop_vars = set() # We construct a function in source form, then compile it and hold onto # it, and execute it to render the template. code = CodeBuilder() code.add_line("def render_function(context, do_dots):") code.indent() vars_code = code.add_section() code.add_line("result = []") code.add_line("append_result = result.append") code.add_line("extend_result = result.extend") code.add_line("to_str = str") buffered = [] def flush_output(): """Force `buffered` to the code builder.""" if len(buffered) == 1: code.add_line("append_result(%s)" % buffered[0]) elif len(buffered) > 1: code.add_line("extend_result([%s])" % ", ".join(buffered)) del buffered[:] ops_stack = [] # Split the text to form a list of tokens. tokens = re.split(r"(?s)({{.*?}}|{%.*?%}|{#.*?#})", text) for token in tokens: if token.startswith('{#'): # Comment: ignore it and move on. continue elif token.startswith('{{'): # An expression to evaluate. expr = self._expr_code(token[2:-2].strip()) buffered.append("to_str(%s)" % expr) elif token.startswith('{%'): # Action tag: split into words and parse further. flush_output() words = token[2:-2].strip().split() if words[0] == 'if': # An if statement: evaluate the expression to determine if. if len(words) != 2 and len(words) != 4: self._syntax_error("Don't understand if", token) ops_stack.append('if') code.add_line(self._test_code(words)) code.indent() elif words[0] == 'elif': # An elif statement: evaluate the expression to determine if. if len(words) != 2 and len(words) != 4: self._syntax_error("Don't understand elif", token) code.dedent() code.add_line(self._test_code(words)) code.indent() elif words[0] == 'else': # An else statement: evalute the expression to determine it.
elif words[0] == 'for': # A loop: iterate over expression result. if len(words) != 4 or words[2] != 'in': self._syntax_error("Don't understand for", token) ops_stack.append('for') self._variable(words[1], self.loop_vars) code.add_line( "for c_%s in %s:" % ( words[1], self._expr_code(words[3]) ) ) code.indent() elif words[0].startswith('end'): # Endsomething. Pop the ops stack. if len(words) != 1: self._syntax_error("Don't understand end", token) end_what = words[0][3:] if not ops_stack: self._syntax_error("Too many ends", token) start_what = ops_stack.pop() if start_what != end_what: self._syntax_error("Mismatched end tag", end_what) code.dedent() else: self._syntax_error("Don't understand tag", words[0]) else: # Literal content. If it isn't empty, output it. if token: #spaces = re.compile('\s+') #spaces.sub(' ', token) buffered.append(repr(token)) if ops_stack: self._syntax_error("Unmatched action tag", ops_stack[-1]) flush_output() for var_name in self.all_vars - self.loop_vars: vars_code.add_line("c_%s = context[%r]" % (var_name, var_name)) code.add_line("return ''.join(result)") code.dedent() self._render_function = code.get_globals()['render_function'] def _test_code(self, words): if len(words) == 2: code = "{} {}:".format(words[0], self._expr_code(words[1])) if len(words) == 4: expr1 = words[1] expr2 = words[3] if words[1][0] != '"' and words[1][0] != "'" and not words[1].isdigit(): expr1 = self._expr_code(words[1]) if words[3][0] != '"' and words[3][0] != "'" and not words[3].isdigit(): expr2 = self._expr_code(words[3]) code = "{} {} {} {}:".format(words[0], expr1, words[2], expr2) return code def _expr_code(self, expr): """Generate a Python expression for `expr`.""" if "|" in expr: pipes = expr.split("|") code = self._expr_code(pipes[0]) for func in pipes[1:]: self._variable(func, self.all_vars) code = "c_%s(%s)" % (func, code) elif "." in expr: dots = expr.split(".") code = self._expr_code(dots[0]) args = ", ".join(repr(d) for d in dots[1:]) code = "do_dots(%s, %s)" % (code, args) else: self._variable(expr, self.all_vars) code = "c_%s" % expr return code def _syntax_error(self, msg, thing): """Raise a syntax error using `msg`, and showing `thing`.""" raise TemplateSyntaxError("%s: %r" % (msg, thing)) def _variable(self, name, vars_set): """Track that `name` is used as a variable. Adds the name to `vars_set`, a set of variable names. Raises an syntax error if `name` is not a valid name. """ if not re.match(r"[_a-zA-Z][_a-zA-Z0-9]*$", name): self._syntax_error("Not a valid name", name) vars_set.add(name) def render(self, context=None): """Render this template by applying it to `context`. `context` is a dictionary of values to use in this rendering. """ # Make the complete context we'll use. render_context = dict(self.context) if context: render_context.update(context) return self._render_function(render_context, self._do_dots) def _do_dots(self, value, *dots): """Evaluate dotted expressions at runtime.""" for dot in dots: try: value = getattr(value, dot) except AttributeError: value = value[dot] if callable(value): value = value() return value
if len(words) != 1: self._syntax_error("Don't understand else", token) code.dedent() code.add_line("else:") code.indent()
logcall.py
# logcall.py
from functools import wraps def logged(func): # Idea: Give me a function, I'll put logging # around it print('Adding logging to', func.__name__) @wraps(func) def wrapper(*args, **kwargs): print('You called', func.__name__) return func(*args, **kwargs) return wrapper