file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
ch8_reqsel.rs
#[doc = "Reader of register CH8_REQSEL"] pub type R = crate::R<u32, super::CH8_REQSEL>; #[doc = "Writer for register CH8_REQSEL"] pub type W = crate::W<u32, super::CH8_REQSEL>; #[doc = "Register CH8_REQSEL `reset()`'s with value 0"] impl crate::ResetValue for super::CH8_REQSEL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `SIGSEL`"] pub type SIGSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SIGSEL`"] pub struct SIGSEL_W<'a> { w: &'a mut W, } impl<'a> SIGSEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Source Select\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SOURCESEL_A { #[doc = "0: No source selected"] NONE = 0, #[doc = "1: Peripheral Reflex System"] PRS = 1, #[doc = "8: Analog to Digital Converter 0"] ADC0 = 8, #[doc = "9: Analog to Digital Converter 0"] ADC1 = 9, #[doc = "10: Digital to Analog Converter 0"] VDAC0 = 10, #[doc = "12: Universal Synchronous/Asynchronous Receiver/Transmitter 0"] USART0 = 12, #[doc = "13: Universal Synchronous/Asynchronous Receiver/Transmitter 1"] USART1 = 13, #[doc = "14: Universal Synchronous/Asynchronous Receiver/Transmitter 2"] USART2 = 14, #[doc = "15: Universal Synchronous/Asynchronous Receiver/Transmitter 3"] USART3 = 15, #[doc = "16: Universal Synchronous/Asynchronous Receiver/Transmitter 4"] USART4 = 16, #[doc = "17: Universal Synchronous/Asynchronous Receiver/Transmitter 5"] USART5 = 17, #[doc = "18: Universal Asynchronous Receiver/Transmitter 0"] UART0 = 18, #[doc = "19: Universal Asynchronous Receiver/Transmitter 1"] UART1 = 19, #[doc = "20: Low Energy UART 0"] LEUART0 = 20, #[doc = "21: Low Energy UART 1"] LEUART1 = 21, #[doc = "22: I2C 0"] I2C0 = 22, #[doc = "23: I2C 1"] I2C1 = 23, #[doc = "24: I2C 2"] I2C2 = 24, #[doc = "25: Timer 0"] TIMER0 = 25, #[doc = "26: Timer 1"] TIMER1 = 26, #[doc = "27: Timer 2"] TIMER2 = 27, #[doc = "28: Timer 3"] TIMER3 = 28, #[doc = "29: Timer 4"] TIMER4 = 29, #[doc = "30: Timer 5"] TIMER5 = 30, #[doc = "31: Timer 6"] TIMER6 = 31, #[doc = "32: Wide Timer 0"] WTIMER0 = 32, #[doc = "33: Wide Timer 0"] WTIMER1 = 33, #[doc = "34: Wide Timer 2"] WTIMER2 = 34, #[doc = "35: Wide Timer 3"] WTIMER3 = 35, #[doc = "48: Memory System Controller"] MSC = 48, #[doc = "49: Advanced Encryption Standard Accelerator"] CRYPTO0 = 49, #[doc = "50: External Bus Interface"] EBI = 50, #[doc = "61: Capacitive touch sense module"] CSEN = 61, #[doc = "62: Low Energy Sensor Interface"] LESENSE = 62, } impl From<SOURCESEL_A> for u8 { #[inline(always)] fn from(variant: SOURCESEL_A) -> Self { variant as _ } } #[doc = "Reader of field `SOURCESEL`"] pub type SOURCESEL_R = crate::R<u8, SOURCESEL_A>; impl SOURCESEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, SOURCESEL_A> { use crate::Variant::*; match self.bits { 0 => Val(SOURCESEL_A::NONE), 1 => Val(SOURCESEL_A::PRS), 8 => Val(SOURCESEL_A::ADC0), 9 => Val(SOURCESEL_A::ADC1), 10 => Val(SOURCESEL_A::VDAC0), 12 => Val(SOURCESEL_A::USART0), 13 => Val(SOURCESEL_A::USART1), 14 => Val(SOURCESEL_A::USART2), 15 => Val(SOURCESEL_A::USART3), 16 => Val(SOURCESEL_A::USART4), 17 => Val(SOURCESEL_A::USART5), 18 => Val(SOURCESEL_A::UART0), 19 => Val(SOURCESEL_A::UART1), 20 => Val(SOURCESEL_A::LEUART0), 21 => Val(SOURCESEL_A::LEUART1), 22 => Val(SOURCESEL_A::I2C0), 23 => Val(SOURCESEL_A::I2C1), 24 => Val(SOURCESEL_A::I2C2), 25 => Val(SOURCESEL_A::TIMER0), 26 => Val(SOURCESEL_A::TIMER1), 27 => Val(SOURCESEL_A::TIMER2), 28 => Val(SOURCESEL_A::TIMER3), 29 => Val(SOURCESEL_A::TIMER4), 30 => Val(SOURCESEL_A::TIMER5), 31 => Val(SOURCESEL_A::TIMER6), 32 => Val(SOURCESEL_A::WTIMER0), 33 => Val(SOURCESEL_A::WTIMER1), 34 => Val(SOURCESEL_A::WTIMER2), 35 => Val(SOURCESEL_A::WTIMER3), 48 => Val(SOURCESEL_A::MSC), 49 => Val(SOURCESEL_A::CRYPTO0), 50 => Val(SOURCESEL_A::EBI), 61 => Val(SOURCESEL_A::CSEN), 62 => Val(SOURCESEL_A::LESENSE), i => Res(i), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SOURCESEL_A::NONE } #[doc = "Checks if the value of the field is `PRS`"] #[inline(always)] pub fn is_prs(&self) -> bool { *self == SOURCESEL_A::PRS } #[doc = "Checks if the value of the field is `ADC0`"] #[inline(always)] pub fn is_adc0(&self) -> bool { *self == SOURCESEL_A::ADC0 } #[doc = "Checks if the value of the field is `ADC1`"] #[inline(always)] pub fn is_adc1(&self) -> bool { *self == SOURCESEL_A::ADC1 } #[doc = "Checks if the value of the field is `VDAC0`"] #[inline(always)] pub fn is_vdac0(&self) -> bool { *self == SOURCESEL_A::VDAC0 } #[doc = "Checks if the value of the field is `USART0`"] #[inline(always)] pub fn is_usart0(&self) -> bool { *self == SOURCESEL_A::USART0 } #[doc = "Checks if the value of the field is `USART1`"] #[inline(always)] pub fn is_usart1(&self) -> bool { *self == SOURCESEL_A::USART1 } #[doc = "Checks if the value of the field is `USART2`"] #[inline(always)] pub fn is_usart2(&self) -> bool { *self == SOURCESEL_A::USART2 } #[doc = "Checks if the value of the field is `USART3`"] #[inline(always)] pub fn is_usart3(&self) -> bool { *self == SOURCESEL_A::USART3 } #[doc = "Checks if the value of the field is `USART4`"] #[inline(always)] pub fn is_usart4(&self) -> bool { *self == SOURCESEL_A::USART4 } #[doc = "Checks if the value of the field is `USART5`"] #[inline(always)] pub fn is_usart5(&self) -> bool { *self == SOURCESEL_A::USART5 } #[doc = "Checks if the value of the field is `UART0`"] #[inline(always)] pub fn is_uart0(&self) -> bool { *self == SOURCESEL_A::UART0 } #[doc = "Checks if the value of the field is `UART1`"] #[inline(always)] pub fn is_uart1(&self) -> bool { *self == SOURCESEL_A::UART1 } #[doc = "Checks if the value of the field is `LEUART0`"] #[inline(always)] pub fn is_leuart0(&self) -> bool { *self == SOURCESEL_A::LEUART0 } #[doc = "Checks if the value of the field is `LEUART1`"] #[inline(always)] pub fn is_leuart1(&self) -> bool { *self == SOURCESEL_A::LEUART1 } #[doc = "Checks if the value of the field is `I2C0`"] #[inline(always)] pub fn is_i2c0(&self) -> bool { *self == SOURCESEL_A::I2C0 } #[doc = "Checks if the value of the field is `I2C1`"] #[inline(always)] pub fn is_i2c1(&self) -> bool { *self == SOURCESEL_A::I2C1 } #[doc = "Checks if the value of the field is `I2C2`"] #[inline(always)] pub fn is_i2c2(&self) -> bool { *self == SOURCESEL_A::I2C2 } #[doc = "Checks if the value of the field is `TIMER0`"] #[inline(always)] pub fn is_timer0(&self) -> bool { *self == SOURCESEL_A::TIMER0 } #[doc = "Checks if the value of the field is `TIMER1`"] #[inline(always)] pub fn is_timer1(&self) -> bool { *self == SOURCESEL_A::TIMER1 } #[doc = "Checks if the value of the field is `TIMER2`"] #[inline(always)] pub fn is_timer2(&self) -> bool { *self == SOURCESEL_A::TIMER2 } #[doc = "Checks if the value of the field is `TIMER3`"] #[inline(always)] pub fn is_timer3(&self) -> bool { *self == SOURCESEL_A::TIMER3 } #[doc = "Checks if the value of the field is `TIMER4`"] #[inline(always)] pub fn is_timer4(&self) -> bool { *self == SOURCESEL_A::TIMER4 } #[doc = "Checks if the value of the field is `TIMER5`"] #[inline(always)] pub fn is_timer5(&self) -> bool { *self == SOURCESEL_A::TIMER5 } #[doc = "Checks if the value of the field is `TIMER6`"] #[inline(always)] pub fn is_timer6(&self) -> bool { *self == SOURCESEL_A::TIMER6 } #[doc = "Checks if the value of the field is `WTIMER0`"] #[inline(always)] pub fn is_wtimer0(&self) -> bool { *self == SOURCESEL_A::WTIMER0 } #[doc = "Checks if the value of the field is `WTIMER1`"] #[inline(always)] pub fn is_wtimer1(&self) -> bool { *self == SOURCESEL_A::WTIMER1 } #[doc = "Checks if the value of the field is `WTIMER2`"] #[inline(always)] pub fn is_wtimer2(&self) -> bool { *self == SOURCESEL_A::WTIMER2 } #[doc = "Checks if the value of the field is `WTIMER3`"] #[inline(always)] pub fn is_wtimer3(&self) -> bool { *self == SOURCESEL_A::WTIMER3 } #[doc = "Checks if the value of the field is `MSC`"] #[inline(always)] pub fn is_msc(&self) -> bool { *self == SOURCESEL_A::MSC } #[doc = "Checks if the value of the field is `CRYPTO0`"] #[inline(always)] pub fn is_crypto0(&self) -> bool { *self == SOURCESEL_A::CRYPTO0 } #[doc = "Checks if the value of the field is `EBI`"] #[inline(always)] pub fn is_ebi(&self) -> bool { *self == SOURCESEL_A::EBI } #[doc = "Checks if the value of the field is `CSEN`"] #[inline(always)] pub fn is_csen(&self) -> bool { *self == SOURCESEL_A::CSEN } #[doc = "Checks if the value of the field is `LESENSE`"] #[inline(always)] pub fn is_lesense(&self) -> bool { *self == SOURCESEL_A::LESENSE } } #[doc = "Write proxy for field `SOURCESEL`"] pub struct SOURCESEL_W<'a> { w: &'a mut W, } impl<'a> SOURCESEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SOURCESEL_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "No source selected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SOURCESEL_A::NONE) } #[doc = "Peripheral Reflex System"] #[inline(always)] pub fn prs(self) -> &'a mut W { self.variant(SOURCESEL_A::PRS) } #[doc = "Analog to Digital Converter 0"] #[inline(always)] pub fn adc0(self) -> &'a mut W { self.variant(SOURCESEL_A::ADC0) } #[doc = "Analog to Digital Converter 0"] #[inline(always)] pub fn adc1(self) -> &'a mut W { self.variant(SOURCESEL_A::ADC1) } #[doc = "Digital to Analog Converter 0"] #[inline(always)] pub fn vdac0(self) -> &'a mut W { self.variant(SOURCESEL_A::VDAC0) } #[doc = "Universal Synchronous/Asynchronous Receiver/Transmitter 0"] #[inline(always)] pub fn usart0(self) -> &'a mut W { self.variant(SOURCESEL_A::USART0) } #[doc = "Universal Synchronous/Asynchronous Receiver/Transmitter 1"] #[inline(always)] pub fn usart1(self) -> &'a mut W { self.variant(SOURCESEL_A::USART1) } #[doc = "Universal Synchronous/Asynchronous Receiver/Transmitter 2"] #[inline(always)] pub fn usart2(self) -> &'a mut W { self.variant(SOURCESEL_A::USART2) } #[doc = "Universal Synchronous/Asynchronous Receiver/Transmitter 3"] #[inline(always)] pub fn usart3(self) -> &'a mut W { self.variant(SOURCESEL_A::USART3) } #[doc = "Universal Synchronous/Asynchronous Receiver/Transmitter 4"] #[inline(always)] pub fn usart4(self) -> &'a mut W { self.variant(SOURCESEL_A::USART4) } #[doc = "Universal Synchronous/Asynchronous Receiver/Transmitter 5"] #[inline(always)] pub fn usart5(self) -> &'a mut W { self.variant(SOURCESEL_A::USART5) } #[doc = "Universal Asynchronous Receiver/Transmitter 0"] #[inline(always)] pub fn uart0(self) -> &'a mut W { self.variant(SOURCESEL_A::UART0) } #[doc = "Universal Asynchronous Receiver/Transmitter 1"] #[inline(always)] pub fn uart1(self) -> &'a mut W { self.variant(SOURCESEL_A::UART1) } #[doc = "Low Energy UART 0"] #[inline(always)] pub fn leuart0(self) -> &'a mut W { self.variant(SOURCESEL_A::LEUART0) } #[doc = "Low Energy UART 1"] #[inline(always)] pub fn leuart1(self) -> &'a mut W { self.variant(SOURCESEL_A::LEUART1) } #[doc = "I2C 0"] #[inline(always)] pub fn i2c0(self) -> &'a mut W { self.variant(SOURCESEL_A::I2C0) } #[doc = "I2C 1"] #[inline(always)] pub fn i2c1(self) -> &'a mut W { self.variant(SOURCESEL_A::I2C1) } #[doc = "I2C 2"] #[inline(always)] pub fn i2c2(self) -> &'a mut W { self.variant(SOURCESEL_A::I2C2) } #[doc = "Timer 0"] #[inline(always)] pub fn timer0(self) -> &'a mut W { self.variant(SOURCESEL_A::TIMER0) } #[doc = "Timer 1"] #[inline(always)] pub fn timer1(self) -> &'a mut W { self.variant(SOURCESEL_A::TIMER1) } #[doc = "Timer 2"] #[inline(always)] pub fn timer2(self) -> &'a mut W { self.variant(SOURCESEL_A::TIMER2) } #[doc = "Timer 3"] #[inline(always)] pub fn timer3(self) -> &'a mut W { self.variant(SOURCESEL_A::TIMER3) } #[doc = "Timer 4"] #[inline(always)] pub fn timer4(self) -> &'a mut W { self.variant(SOURCESEL_A::TIMER4) } #[doc = "Timer 5"] #[inline(always)] pub fn timer5(self) -> &'a mut W { self.variant(SOURCESEL_A::TIMER5) } #[doc = "Timer 6"] #[inline(always)] pub fn timer6(self) -> &'a mut W { self.variant(SOURCESEL_A::TIMER6) } #[doc = "Wide Timer 0"] #[inline(always)] pub fn wtimer0(self) -> &'a mut W { self.variant(SOURCESEL_A::WTIMER0) } #[doc = "Wide Timer 0"] #[inline(always)] pub fn wtimer1(self) -> &'a mut W { self.variant(SOURCESEL_A::WTIMER1) } #[doc = "Wide Timer 2"] #[inline(always)] pub fn wtimer2(self) -> &'a mut W { self.variant(SOURCESEL_A::WTIMER2) } #[doc = "Wide Timer 3"] #[inline(always)] pub fn wtimer3(self) -> &'a mut W { self.variant(SOURCESEL_A::WTIMER3) } #[doc = "Memory System Controller"] #[inline(always)] pub fn msc(self) -> &'a mut W { self.variant(SOURCESEL_A::MSC) } #[doc = "Advanced Encryption Standard Accelerator"] #[inline(always)] pub fn crypto0(self) -> &'a mut W { self.variant(SOURCESEL_A::CRYPTO0) } #[doc = "External Bus Interface"] #[inline(always)] pub fn ebi(self) -> &'a mut W { self.variant(SOURCESEL_A::EBI) } #[doc = "Capacitive touch sense module"] #[inline(always)] pub fn csen(self) -> &'a mut W { self.variant(SOURCESEL_A::CSEN) } #[doc = "Low Energy Sensor Interface"] #[inline(always)] pub fn lesense(self) -> &'a mut W
#[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x3f << 16)) | (((value as u32) & 0x3f) << 16); self.w } } impl R { #[doc = "Bits 0:3 - Signal Select"] #[inline(always)] pub fn sigsel(&self) -> SIGSEL_R { SIGSEL_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 16:21 - Source Select"] #[inline(always)] pub fn sourcesel(&self) -> SOURCESEL_R { SOURCESEL_R::new(((self.bits >> 16) & 0x3f) as u8) } } impl W { #[doc = "Bits 0:3 - Signal Select"] #[inline(always)] pub fn sigsel(&mut self) -> SIGSEL_W { SIGSEL_W { w: self } } #[doc = "Bits 16:21 - Source Select"] #[inline(always)] pub fn sourcesel(&mut self) -> SOURCESEL_W { SOURCESEL_W { w: self } } }
{ self.variant(SOURCESEL_A::LESENSE) }
fetch_into_object_pool_test.go
package objectpool import ( "bytes" "encoding/json" "io/ioutil" "os" "path/filepath" "strings" "testing" "time" "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/v14/internal/git" "gitlab.com/gitlab-org/gitaly/v14/internal/git/catfile" "gitlab.com/gitlab-org/gitaly/v14/internal/git/gittest" "gitlab.com/gitlab-org/gitaly/v14/internal/git/hooks" "gitlab.com/gitlab-org/gitaly/v14/internal/git/objectpool" "gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/config" "gitlab.com/gitlab-org/gitaly/v14/internal/testhelper" "gitlab.com/gitlab-org/gitaly/v14/internal/testhelper/testassert" "gitlab.com/gitlab-org/gitaly/v14/internal/testhelper/testcfg" "gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb" "gitlab.com/gitlab-org/labkit/log"
"google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func TestFetchIntoObjectPool_Success(t *testing.T) { cfg, repo, repoPath, locator, client := setup(t) ctx, cancel := testhelper.Context() defer cancel() repoCommit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch(t.Name())) pool, err := objectpool.NewObjectPool(cfg, locator, git.NewExecCommandFactory(cfg), nil, repo.GetStorageName(), gittest.NewObjectPoolName(t)) require.NoError(t, err) defer func() { require.NoError(t, pool.Remove(ctx)) }() req := &gitalypb.FetchIntoObjectPoolRequest{ ObjectPool: pool.ToProto(), Origin: repo, Repack: true, } _, err = client.FetchIntoObjectPool(ctx, req) require.NoError(t, err) require.True(t, pool.IsValid(), "ensure underlying repository is valid") // No problems gittest.Exec(t, cfg, "-C", pool.FullPath(), "fsck") packFiles, err := filepath.Glob(filepath.Join(pool.FullPath(), "objects", "pack", "pack-*.pack")) require.NoError(t, err) require.Len(t, packFiles, 1, "ensure commits got packed") packContents := gittest.Exec(t, cfg, "-C", pool.FullPath(), "verify-pack", "-v", packFiles[0]) require.Contains(t, string(packContents), repoCommit) _, err = client.FetchIntoObjectPool(ctx, req) require.NoError(t, err, "calling FetchIntoObjectPool twice should be OK") require.True(t, pool.IsValid(), "ensure that pool is valid") // Simulate a broken ref poolPath, err := locator.GetRepoPath(pool) require.NoError(t, err) brokenRef := filepath.Join(poolPath, "refs", "heads", "broken") require.NoError(t, os.MkdirAll(filepath.Dir(brokenRef), 0755)) require.NoError(t, ioutil.WriteFile(brokenRef, []byte{}, 0777)) oldTime := time.Now().Add(-25 * time.Hour) require.NoError(t, os.Chtimes(brokenRef, oldTime, oldTime)) _, err = client.FetchIntoObjectPool(ctx, req) require.NoError(t, err) _, err = os.Stat(brokenRef) require.Error(t, err, "Expected refs/heads/broken to be deleted") } func TestFetchIntoObjectPool_hooks(t *testing.T) { cfg, repo, _, locator, client := setup(t) gitCmdFactory := git.NewExecCommandFactory(cfg) ctx, cancel := testhelper.Context() defer cancel() pool, err := objectpool.NewObjectPool(cfg, locator, gitCmdFactory, nil, repo.GetStorageName(), gittest.NewObjectPoolName(t)) require.NoError(t, err) defer func() { require.NoError(t, pool.Remove(ctx)) }() hookDir := testhelper.TempDir(t) defer func(oldValue string) { hooks.Override = oldValue }(hooks.Override) hooks.Override = hookDir // Set up a custom reference-transaction hook which simply exits failure. This asserts that // the RPC doesn't invoke any reference-transaction. require.NoError(t, ioutil.WriteFile(filepath.Join(hookDir, "reference-transaction"), []byte("#!/bin/sh\nexit 1\n"), 0777)) req := &gitalypb.FetchIntoObjectPoolRequest{ ObjectPool: pool.ToProto(), Origin: repo, Repack: true, } _, err = client.FetchIntoObjectPool(ctx, req) testassert.GrpcEqualErr(t, status.Error(codes.Internal, "fetch into object pool: exit status 128, stderr: \"fatal: ref updates aborted by hook\\n\""), err) } func TestFetchIntoObjectPool_CollectLogStatistics(t *testing.T) { cfg, repo, _ := testcfg.BuildWithRepo(t) testhelper.BuildGitalyHooks(t, cfg) locator := config.NewLocator(cfg) logBuffer := &bytes.Buffer{} logger := &logrus.Logger{Out: logBuffer, Formatter: &logrus.JSONFormatter{}, Level: logrus.InfoLevel} serverSocketPath := runObjectPoolServer(t, cfg, locator, logger) conn, err := grpc.Dial(serverSocketPath, grpc.WithInsecure()) require.NoError(t, err) t.Cleanup(func() { testhelper.MustClose(t, conn) }) client := gitalypb.NewObjectPoolServiceClient(conn) ctx, cancel := testhelper.Context() defer cancel() ctx = ctxlogrus.ToContext(ctx, log.WithField("test", "logging")) pool, err := objectpool.NewObjectPool(cfg, locator, git.NewExecCommandFactory(cfg), nil, repo.GetStorageName(), gittest.NewObjectPoolName(t)) require.NoError(t, err) defer func() { require.NoError(t, pool.Remove(ctx)) }() req := &gitalypb.FetchIntoObjectPoolRequest{ ObjectPool: pool.ToProto(), Origin: repo, Repack: true, } _, err = client.FetchIntoObjectPool(ctx, req) require.NoError(t, err) msgs := strings.Split(logBuffer.String(), "\n") const key = "count_objects" for _, msg := range msgs { if strings.Contains(msg, key) { var out map[string]interface{} require.NoError(t, json.NewDecoder(strings.NewReader(msg)).Decode(&out)) require.Contains(t, out, key, "there is no any information about statistics") countObjects := out[key].(map[string]interface{}) assert.Contains(t, countObjects, "count") return } } require.FailNow(t, "no info about statistics") } func TestFetchIntoObjectPool_Failure(t *testing.T) { cfgBuilder := testcfg.NewGitalyCfgBuilder() cfg, repos := cfgBuilder.BuildWithRepoAt(t, t.Name()) locator := config.NewLocator(cfg) gitCmdFactory := git.NewExecCommandFactory(cfg) server := NewServer(cfg, locator, gitCmdFactory, catfile.NewCache(cfg)) ctx, cancel := testhelper.Context() defer cancel() pool, err := objectpool.NewObjectPool(cfg, locator, gitCmdFactory, nil, repos[0].StorageName, gittest.NewObjectPoolName(t)) require.NoError(t, err) defer func() { require.NoError(t, pool.Remove(ctx)) }() poolWithDifferentStorage := pool.ToProto() poolWithDifferentStorage.Repository.StorageName = "some other storage" testCases := []struct { description string request *gitalypb.FetchIntoObjectPoolRequest code codes.Code errMsg string }{ { description: "empty origin", request: &gitalypb.FetchIntoObjectPoolRequest{ ObjectPool: pool.ToProto(), }, code: codes.InvalidArgument, errMsg: "origin is empty", }, { description: "empty pool", request: &gitalypb.FetchIntoObjectPoolRequest{ Origin: repos[0], }, code: codes.InvalidArgument, errMsg: "object pool is empty", }, { description: "origin and pool do not share the same storage", request: &gitalypb.FetchIntoObjectPoolRequest{ Origin: repos[0], ObjectPool: poolWithDifferentStorage, }, code: codes.InvalidArgument, errMsg: "origin has different storage than object pool", }, } for _, tc := range testCases { t.Run(tc.description, func(t *testing.T) { _, err := server.FetchIntoObjectPool(ctx, tc.request) require.Error(t, err) testhelper.RequireGrpcError(t, err, tc.code) assert.Contains(t, err.Error(), tc.errMsg) }) } }
"google.golang.org/grpc"
control.go
// 12 december 2015 package ui import ( "unsafe" ) // #include "pkgui.h" import "C" // no need to lock this; only the GUI thread can access it var controls = make(map[*C.uiControl]Control) // Control represents a GUI control. It provdes methods // common to all Controls. // // The preferred way to create new Controls is to use // ControlBase; see ControlBase below. type Control interface { // LibuiControl returns the uiControl pointer for the Control. // This is intended for use when adding a control to a // container. LibuiControl() uintptr // Destroy destroys the Control. Destroy() // Handle returns the OS-level handle that backs the // Control. On OSs that use reference counting for // controls, Handle does not increment the reference // count; you are sharing package ui's reference. Handle() uintptr // Visible returns whether the Control is visible. Visible() bool // Show shows the Control. Show() // Hide shows the Control. Hidden controls do not participate // in layout (that is, Box, Grid, etc. does not reserve space for // hidden controls). Hide() // Enabled returns whether the Control is enabled. Enabled() bool // Enable enables the Control. Enable() // Disable disables the Control. Disable() } // ControlBase is an implementation of Control that provides // all the methods that Control requires. To use it, embed a // ControlBase (not a *ControlBase) into your structure, then // assign the result of NewControlBase to that field: // // type MyControl struct { // ui.ControlBase // c *C.MyControl // } // // func NewMyControl() *MyControl { // m := &NewMyControl{ // c: C.newMyControl(), // } // m.ControlBase = ui.NewControlBase(m, uintptr(unsafe.Pointer(c))) // return m // } type ControlBase struct { iface Control c *C.uiControl } // NewControlBase creates a new ControlBase. See the // documentation of ControlBase for an example. // NewControl should only be called once per instance of Control. func NewControlBase(iface Control, c uintptr) ControlBase { b := ControlBase{ iface: iface, c: (*C.uiControl)(unsafe.Pointer(c)), } controls[b.c] = b.iface return b } func (c *ControlBase) LibuiControl() uintptr { return uintptr(unsafe.Pointer(c.c)) } func (c *ControlBase) Destroy() { delete(controls, c.c) C.uiControlDestroy(c.c) } func (c *ControlBase) Handle() uintptr { return uintptr(C.uiControlHandle(c.c)) } func (c *ControlBase) Visible() bool { return tobool(C.uiControlVisible(c.c)) } func (c *ControlBase) Show() { C.uiControlShow(c.c) } func (c *ControlBase) Hide() { C.uiControlHide(c.c) } func (c *ControlBase) Enabled() bool { return tobool(C.uiControlEnabled(c.c)) } func (c *ControlBase) Enable() { C.uiControlEnable(c.c) } func (c *ControlBase) Disable() { C.uiControlDisable(c.c) } func (c *ControlBase) SetFocus() { C.uiControlSetFocus(c.c) } // ControlFromLibui returns the Control associated with a libui // uiControl. This is intended for implementing event handlers // on the Go side, to prevent sharing Go pointers with C. // This function only works on Controls that use ControlBase. func ControlFromLibui(c uintptr) Control { // comma-ok form to avoid creating nil entries cc, _ := controls[(*C.uiControl)(unsafe.Pointer(c))] return cc } func touiControl(c uintptr) *C.uiControl { return (*C.uiControl)(unsafe.Pointer(c)) } // LibuiFreeText allows implementations of Control // to call the libui function uiFreeText. func
(c uintptr) { C.uiFreeText((*C.char)(unsafe.Pointer(c))) }
LibuiFreeText
service.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package e2e import ( "bytes" "fmt" "io/ioutil" "math/rand" "net" "net/http" "sort" "strconv" "strings" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/service" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/controller/endpoint" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/intstr" utilnet "k8s.io/kubernetes/pkg/util/net" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" testutils "k8s.io/kubernetes/test/utils" ) const ( // Maximum time a kube-proxy daemon on a node is allowed to not // notice a Service update, such as type=NodePort. // TODO: This timeout should be O(10s), observed values are O(1m), 5m is very // liberal. Fix tracked in #20567. kubeProxyLagTimeout = 5 * time.Minute // Maximum time a load balancer is allowed to not respond after creation. loadBalancerLagTimeoutDefault = 2 * time.Minute // On AWS there is a delay between ELB creation and serving traffic; // a few minutes is typical, so use 10m. loadBalancerLagTimeoutAWS = 10 * time.Minute // How long to wait for a load balancer to be created/modified. //TODO: once support ticket 21807001 is resolved, reduce this timeout back to something reasonable loadBalancerCreateTimeoutDefault = 20 * time.Minute loadBalancerCreateTimeoutLarge = 2 * time.Hour largeClusterMinNodesNumber = 100 // Don't test with more than 3 nodes. // Many tests create an endpoint per node, in large clusters, this is // resource and time intensive. maxNodesForEndpointsTests = 3 // timeout is used for most polling/waiting activities timeout = 60 * time.Second ) // This should match whatever the default/configured range is var ServiceNodePortRange = utilnet.PortRange{Base: 30000, Size: 2768} var _ = framework.KubeDescribe("Services", func() { f := framework.NewDefaultFramework("services") var cs clientset.Interface serviceLBNames := []string{} BeforeEach(func() { cs = f.ClientSet }) AfterEach(func() { if CurrentGinkgoTestDescription().Failed { describeSvc(f.Namespace.Name) } for _, lb := range serviceLBNames { framework.Logf("cleaning gce resource for %s", lb) cleanupServiceGCEResources(lb) } //reset serviceLBNames serviceLBNames = []string{} }) // TODO: We get coverage of TCP/UDP and multi-port services through the DNS test. We should have a simpler test for multi-port TCP here. It("should provide secure master service [Conformance]", func() { _, err := cs.Core().Services(api.NamespaceDefault).Get("kubernetes") Expect(err).NotTo(HaveOccurred()) }) It("should serve a basic endpoint from pods [Conformance]", func() { // TODO: use the ServiceTestJig here serviceName := "endpoint-test2" ns := f.Namespace.Name labels := map[string]string{ "foo": "bar", "baz": "blah", } By("creating service " + serviceName + " in namespace " + ns) defer func() { err := cs.Core().Services(ns).Delete(serviceName, nil) Expect(err).NotTo(HaveOccurred()) }() service := &api.Service{ ObjectMeta: api.ObjectMeta{ Name: serviceName, }, Spec: api.ServiceSpec{ Selector: labels, Ports: []api.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, }, } _, err := cs.Core().Services(ns).Create(service) Expect(err).NotTo(HaveOccurred()) validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{}) names := map[string]bool{} defer func() { for name := range names { err := cs.Core().Pods(ns).Delete(name, nil) Expect(err).NotTo(HaveOccurred()) } }() name1 := "pod1" name2 := "pod2" createPodOrFail(cs, ns, name1, labels, []api.ContainerPort{{ContainerPort: 80}}) names[name1] = true validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{name1: {80}}) createPodOrFail(cs, ns, name2, labels, []api.ContainerPort{{ContainerPort: 80}}) names[name2] = true validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{name1: {80}, name2: {80}}) deletePodOrFail(cs, ns, name1) delete(names, name1) validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{name2: {80}}) deletePodOrFail(cs, ns, name2) delete(names, name2) validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{}) }) It("should serve multiport endpoints from pods [Conformance]", func() { // TODO: use the ServiceTestJig here // repacking functionality is intentionally not tested here - it's better to test it in an integration test. serviceName := "multi-endpoint-test" ns := f.Namespace.Name defer func() { err := cs.Core().Services(ns).Delete(serviceName, nil) Expect(err).NotTo(HaveOccurred()) }() labels := map[string]string{"foo": "bar"} svc1port := "svc1" svc2port := "svc2" By("creating service " + serviceName + " in namespace " + ns) service := &api.Service{ ObjectMeta: api.ObjectMeta{ Name: serviceName, }, Spec: api.ServiceSpec{ Selector: labels, Ports: []api.ServicePort{ { Name: "portname1", Port: 80, TargetPort: intstr.FromString(svc1port), }, { Name: "portname2", Port: 81, TargetPort: intstr.FromString(svc2port), }, }, }, } _, err := cs.Core().Services(ns).Create(service) Expect(err).NotTo(HaveOccurred()) port1 := 100 port2 := 101 validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{}) names := map[string]bool{} defer func() { for name := range names { err := cs.Core().Pods(ns).Delete(name, nil) Expect(err).NotTo(HaveOccurred()) } }() containerPorts1 := []api.ContainerPort{ { Name: svc1port, ContainerPort: int32(port1), }, } containerPorts2 := []api.ContainerPort{ { Name: svc2port, ContainerPort: int32(port2), }, } podname1 := "pod1" podname2 := "pod2" createPodOrFail(cs, ns, podname1, labels, containerPorts1) names[podname1] = true validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{podname1: {port1}}) createPodOrFail(cs, ns, podname2, labels, containerPorts2) names[podname2] = true validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{podname1: {port1}, podname2: {port2}}) deletePodOrFail(cs, ns, podname1) delete(names, podname1) validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{podname2: {port2}}) deletePodOrFail(cs, ns, podname2) delete(names, podname2) validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{}) }) It("should preserve source pod IP for traffic thru service cluster IP", func() { serviceName := "sourceip-test" ns := f.Namespace.Name By("creating a TCP service " + serviceName + " with type=ClusterIP in namespace " + ns) jig := NewServiceTestJig(cs, serviceName) servicePort := 8080 tcpService := jig.CreateTCPServiceWithPort(ns, nil, int32(servicePort)) jig.SanityCheckService(tcpService, api.ServiceTypeClusterIP) defer func() { framework.Logf("Cleaning up the sourceip test service") err := cs.Core().Services(ns).Delete(serviceName, nil) Expect(err).NotTo(HaveOccurred()) }() serviceIp := tcpService.Spec.ClusterIP framework.Logf("sourceip-test cluster ip: %s", serviceIp) By("Picking multiple nodes") nodes := framework.GetReadySchedulableNodesOrDie(f.ClientSet) if len(nodes.Items) == 1 { framework.Skipf("The test requires two Ready nodes on %s, but found just one.", framework.TestContext.Provider) } node1 := nodes.Items[0] node2 := nodes.Items[1] By("Creating a webserver pod be part of the TCP service which echoes back source ip") serverPodName := "echoserver-sourceip" jig.launchEchoserverPodOnNode(f, node1.Name, serverPodName) defer func() { framework.Logf("Cleaning up the echo server pod") err := cs.Core().Pods(ns).Delete(serverPodName, nil) Expect(err).NotTo(HaveOccurred()) }() // Waiting for service to expose endpoint. validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{serverPodName: {servicePort}}) By("Retrieve sourceip from a pod on the same node") sourceIp1, execPodIp1 := execSourceipTest(f, cs, ns, node1.Name, serviceIp, servicePort) By("Verifying the preserved source ip") Expect(sourceIp1).To(Equal(execPodIp1)) By("Retrieve sourceip from a pod on a different node") sourceIp2, execPodIp2 := execSourceipTest(f, cs, ns, node2.Name, serviceIp, servicePort) By("Verifying the preserved source ip") Expect(sourceIp2).To(Equal(execPodIp2)) }) It("should be able to up and down services", func() { // TODO: use the ServiceTestJig here // this test uses framework.NodeSSHHosts that does not work if a Node only reports LegacyHostIP framework.SkipUnlessProviderIs(framework.ProvidersWithSSH...) ns := f.Namespace.Name numPods, servicePort := 3, 80 By("creating service1 in namespace " + ns) podNames1, svc1IP, err := startServeHostnameService(cs, ns, "service1", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) By("creating service2 in namespace " + ns) podNames2, svc2IP, err := startServeHostnameService(cs, ns, "service2", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) hosts, err := framework.NodeSSHHosts(cs) Expect(err).NotTo(HaveOccurred()) if len(hosts) == 0 { framework.Failf("No ssh-able nodes") } host := hosts[0] By("verifying service1 is up") framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames1, svc1IP, servicePort)) By("verifying service2 is up") framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames2, svc2IP, servicePort)) // Stop service 1 and make sure it is gone. By("stopping service1") framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, "service1")) By("verifying service1 is not up") framework.ExpectNoError(verifyServeHostnameServiceDown(cs, host, svc1IP, servicePort)) By("verifying service2 is still up") framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames2, svc2IP, servicePort)) // Start another service and verify both are up. By("creating service3 in namespace " + ns) podNames3, svc3IP, err := startServeHostnameService(cs, ns, "service3", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) if svc2IP == svc3IP { framework.Failf("service IPs conflict: %v", svc2IP) } By("verifying service2 is still up") framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames2, svc2IP, servicePort)) By("verifying service3 is up") framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames3, svc3IP, servicePort)) }) It("should work after restarting kube-proxy [Disruptive]", func() { // TODO: use the ServiceTestJig here framework.SkipUnlessProviderIs("gce", "gke") ns := f.Namespace.Name numPods, servicePort := 3, 80 svc1 := "service1" svc2 := "service2" defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, svc1)) }() podNames1, svc1IP, err := startServeHostnameService(cs, ns, svc1, servicePort, numPods) Expect(err).NotTo(HaveOccurred()) defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, svc2)) }() podNames2, svc2IP, err := startServeHostnameService(cs, ns, svc2, servicePort, numPods) Expect(err).NotTo(HaveOccurred()) if svc1IP == svc2IP { framework.Failf("VIPs conflict: %v", svc1IP) } hosts, err := framework.NodeSSHHosts(cs) Expect(err).NotTo(HaveOccurred()) if len(hosts) == 0 { framework.Failf("No ssh-able nodes") } host := hosts[0] framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames1, svc1IP, servicePort)) framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames2, svc2IP, servicePort)) By(fmt.Sprintf("Restarting kube-proxy on %v", host)) if err := framework.RestartKubeProxy(host); err != nil { framework.Failf("error restarting kube-proxy: %v", err) } framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames1, svc1IP, servicePort)) framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames2, svc2IP, servicePort)) By("Removing iptable rules") result, err := framework.SSH(` sudo iptables -t nat -F KUBE-SERVICES || true; sudo iptables -t nat -F KUBE-PORTALS-HOST || true; sudo iptables -t nat -F KUBE-PORTALS-CONTAINER || true`, host, framework.TestContext.Provider) if err != nil || result.Code != 0 { framework.LogSSHResult(result) framework.Failf("couldn't remove iptable rules: %v", err) } framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames1, svc1IP, servicePort)) framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames2, svc2IP, servicePort)) }) It("should work after restarting apiserver [Disruptive]", func() { // TODO: use the ServiceTestJig here framework.SkipUnlessProviderIs("gce", "gke") ns := f.Namespace.Name numPods, servicePort := 3, 80 defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, "service1")) }() podNames1, svc1IP, err := startServeHostnameService(cs, ns, "service1", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) hosts, err := framework.NodeSSHHosts(cs) Expect(err).NotTo(HaveOccurred()) if len(hosts) == 0 { framework.Failf("No ssh-able nodes") } host := hosts[0] framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames1, svc1IP, servicePort)) // Restart apiserver By("Restarting apiserver") if err := framework.RestartApiserver(cs.Discovery()); err != nil { framework.Failf("error restarting apiserver: %v", err) } By("Waiting for apiserver to come up by polling /healthz") if err := framework.WaitForApiserverUp(cs); err != nil { framework.Failf("error while waiting for apiserver up: %v", err) } framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames1, svc1IP, servicePort)) // Create a new service and check if it's not reusing IP. defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, "service2")) }() podNames2, svc2IP, err := startServeHostnameService(cs, ns, "service2", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) if svc1IP == svc2IP { framework.Failf("VIPs conflict: %v", svc1IP) } framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames1, svc1IP, servicePort)) framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames2, svc2IP, servicePort)) }) // TODO: Run this test against the userspace proxy and nodes // configured with a default deny firewall to validate that the // proxy whitelists NodePort traffic. It("should be able to create a functioning NodePort service", func() { serviceName := "nodeport-test" ns := f.Namespace.Name jig := NewServiceTestJig(cs, serviceName) nodeIP := pickNodeIP(jig.Client) // for later By("creating service " + serviceName + " with type=NodePort in namespace " + ns) service := jig.CreateTCPServiceOrFail(ns, func(svc *api.Service) { svc.Spec.Type = api.ServiceTypeNodePort }) jig.SanityCheckService(service, api.ServiceTypeNodePort) nodePort := int(service.Spec.Ports[0].NodePort) By("creating pod to be part of service " + serviceName) jig.RunOrFail(ns, nil) By("hitting the pod through the service's NodePort") jig.TestReachableHTTP(nodeIP, nodePort, kubeProxyLagTimeout) By("verifying the node port is locked") hostExec := framework.LaunchHostExecPod(f.ClientSet, f.Namespace.Name, "hostexec") // Even if the node-ip:node-port check above passed, this hostexec pod // might fall on a node with a laggy kube-proxy. cmd := fmt.Sprintf(`for i in $(seq 1 300); do if ss -ant46 'sport = :%d' | grep ^LISTEN; then exit 0; fi; sleep 1; done; exit 1`, nodePort) stdout, err := framework.RunHostCmd(hostExec.Namespace, hostExec.Name, cmd) if err != nil { framework.Failf("expected node port %d to be in use, stdout: %v. err: %v", nodePort, stdout, err) } }) It("should be able to change the type and ports of a service [Slow]", func() { // requires cloud load-balancer support framework.SkipUnlessProviderIs("gce", "gke", "aws") loadBalancerSupportsUDP := !framework.ProviderIs("aws") loadBalancerLagTimeout := loadBalancerLagTimeoutDefault if framework.ProviderIs("aws") { loadBalancerLagTimeout = loadBalancerLagTimeoutAWS } loadBalancerCreateTimeout := loadBalancerCreateTimeoutDefault largeClusterMinNodesNumber := 100 if nodes := framework.GetReadySchedulableNodesOrDie(cs); len(nodes.Items) > largeClusterMinNodesNumber { loadBalancerCreateTimeout = loadBalancerCreateTimeoutLarge } // This test is more monolithic than we'd like because LB turnup can be // very slow, so we lumped all the tests into one LB lifecycle. serviceName := "mutability-test" ns1 := f.Namespace.Name // LB1 in ns1 on TCP framework.Logf("namespace for TCP test: %s", ns1) By("creating a second namespace") namespacePtr, err := f.CreateNamespace("services", nil) Expect(err).NotTo(HaveOccurred()) ns2 := namespacePtr.Name // LB2 in ns2 on UDP framework.Logf("namespace for UDP test: %s", ns2) jig := NewServiceTestJig(cs, serviceName) nodeIP := pickNodeIP(jig.Client) // for later // Test TCP and UDP Services. Services with the same name in different // namespaces should get different node ports and load balancers. By("creating a TCP service " + serviceName + " with type=ClusterIP in namespace " + ns1) tcpService := jig.CreateTCPServiceOrFail(ns1, nil) jig.SanityCheckService(tcpService, api.ServiceTypeClusterIP) By("creating a UDP service " + serviceName + " with type=ClusterIP in namespace " + ns2) udpService := jig.CreateUDPServiceOrFail(ns2, nil) jig.SanityCheckService(udpService, api.ServiceTypeClusterIP) By("verifying that TCP and UDP use the same port") if tcpService.Spec.Ports[0].Port != udpService.Spec.Ports[0].Port { framework.Failf("expected to use the same port for TCP and UDP") } svcPort := int(tcpService.Spec.Ports[0].Port) framework.Logf("service port (TCP and UDP): %d", svcPort) By("creating a pod to be part of the TCP service " + serviceName) jig.RunOrFail(ns1, nil) By("creating a pod to be part of the UDP service " + serviceName) jig.RunOrFail(ns2, nil) // Change the services to NodePort. By("changing the TCP service to type=NodePort") tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) { s.Spec.Type = api.ServiceTypeNodePort }) jig.SanityCheckService(tcpService, api.ServiceTypeNodePort) tcpNodePort := int(tcpService.Spec.Ports[0].NodePort) framework.Logf("TCP node port: %d", tcpNodePort) By("changing the UDP service to type=NodePort") udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) { s.Spec.Type = api.ServiceTypeNodePort }) jig.SanityCheckService(udpService, api.ServiceTypeNodePort) udpNodePort := int(udpService.Spec.Ports[0].NodePort) framework.Logf("UDP node port: %d", udpNodePort) By("hitting the TCP service's NodePort") jig.TestReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout) By("hitting the UDP service's NodePort") jig.TestReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout) // Change the services to LoadBalancer. // Here we test that LoadBalancers can receive static IP addresses. This isn't // necessary, but is an additional feature this monolithic test checks. requestedIP := "" staticIPName := "" if framework.ProviderIs("gce", "gke") { By("creating a static load balancer IP") staticIPName = fmt.Sprintf("e2e-external-lb-test-%s", framework.RunId) requestedIP, err = createGCEStaticIP(staticIPName) Expect(err).NotTo(HaveOccurred()) defer func() { if staticIPName != "" { // Release GCE static IP - this is not kube-managed and will not be automatically released. if err := deleteGCEStaticIP(staticIPName); err != nil { framework.Logf("failed to release static IP %s: %v", staticIPName, err) } } }() framework.Logf("Allocated static load balancer IP: %s", requestedIP) } By("changing the TCP service to type=LoadBalancer") tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) { s.Spec.LoadBalancerIP = requestedIP // will be "" if not applicable s.Spec.Type = api.ServiceTypeLoadBalancer }) if loadBalancerSupportsUDP { By("changing the UDP service to type=LoadBalancer") udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) { s.Spec.Type = api.ServiceTypeLoadBalancer }) } serviceLBNames = append(serviceLBNames, getLoadBalancerName(tcpService)) if loadBalancerSupportsUDP { serviceLBNames = append(serviceLBNames, getLoadBalancerName(udpService)) } By("waiting for the TCP service to have a load balancer") // Wait for the load balancer to be created asynchronously tcpService = jig.WaitForLoadBalancerOrFail(ns1, tcpService.Name, loadBalancerCreateTimeout) jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer) if int(tcpService.Spec.Ports[0].NodePort) != tcpNodePort { framework.Failf("TCP Spec.Ports[0].NodePort changed (%d -> %d) when not expected", tcpNodePort, tcpService.Spec.Ports[0].NodePort) } if requestedIP != "" && getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]) != requestedIP { framework.Failf("unexpected TCP Status.LoadBalancer.Ingress (expected %s, got %s)", requestedIP, getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0])) } tcpIngressIP := getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]) framework.Logf("TCP load balancer: %s", tcpIngressIP) if framework.ProviderIs("gce", "gke") { // Do this as early as possible, which overrides the `defer` above. // This is mostly out of fear of leaking the IP in a timeout case // (as of this writing we're not 100% sure where the leaks are // coming from, so this is first-aid rather than surgery). By("demoting the static IP to ephemeral") if staticIPName != "" { // Deleting it after it is attached "demotes" it to an // ephemeral IP, which can be auto-released. if err := deleteGCEStaticIP(staticIPName); err != nil { framework.Failf("failed to release static IP %s: %v", staticIPName, err) } staticIPName = "" } } var udpIngressIP string if loadBalancerSupportsUDP { By("waiting for the UDP service to have a load balancer") // 2nd one should be faster since they ran in parallel. udpService = jig.WaitForLoadBalancerOrFail(ns2, udpService.Name, loadBalancerCreateTimeout) jig.SanityCheckService(udpService, api.ServiceTypeLoadBalancer) if int(udpService.Spec.Ports[0].NodePort) != udpNodePort { framework.Failf("UDP Spec.Ports[0].NodePort changed (%d -> %d) when not expected", udpNodePort, udpService.Spec.Ports[0].NodePort) } udpIngressIP = getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0]) framework.Logf("UDP load balancer: %s", udpIngressIP) By("verifying that TCP and UDP use different load balancers") if tcpIngressIP == udpIngressIP { framework.Failf("Load balancers are not different: %s", getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0])) } } By("hitting the TCP service's NodePort") jig.TestReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout) By("hitting the UDP service's NodePort") jig.TestReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout) By("hitting the TCP service's LoadBalancer") jig.TestReachableHTTP(tcpIngressIP, svcPort, loadBalancerLagTimeout) if loadBalancerSupportsUDP { By("hitting the UDP service's LoadBalancer") jig.TestReachableUDP(udpIngressIP, svcPort, loadBalancerLagTimeout) } // Change the services' node ports. By("changing the TCP service's NodePort") tcpService = jig.ChangeServiceNodePortOrFail(ns1, tcpService.Name, tcpNodePort) jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer) tcpNodePortOld := tcpNodePort tcpNodePort = int(tcpService.Spec.Ports[0].NodePort) if tcpNodePort == tcpNodePortOld { framework.Failf("TCP Spec.Ports[0].NodePort (%d) did not change", tcpNodePort) } if getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]) != tcpIngressIP { framework.Failf("TCP Status.LoadBalancer.Ingress changed (%s -> %s) when not expected", tcpIngressIP, getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0])) } framework.Logf("TCP node port: %d", tcpNodePort) By("changing the UDP service's NodePort") udpService = jig.ChangeServiceNodePortOrFail(ns2, udpService.Name, udpNodePort) if loadBalancerSupportsUDP { jig.SanityCheckService(udpService, api.ServiceTypeLoadBalancer) } else { jig.SanityCheckService(udpService, api.ServiceTypeNodePort) } udpNodePortOld := udpNodePort udpNodePort = int(udpService.Spec.Ports[0].NodePort) if udpNodePort == udpNodePortOld { framework.Failf("UDP Spec.Ports[0].NodePort (%d) did not change", udpNodePort) } if loadBalancerSupportsUDP && getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0]) != udpIngressIP { framework.Failf("UDP Status.LoadBalancer.Ingress changed (%s -> %s) when not expected", udpIngressIP, getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0])) } framework.Logf("UDP node port: %d", udpNodePort) By("hitting the TCP service's new NodePort") jig.TestReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout) By("hitting the UDP service's new NodePort") jig.TestReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout) By("checking the old TCP NodePort is closed") jig.TestNotReachableHTTP(nodeIP, tcpNodePortOld, kubeProxyLagTimeout) By("checking the old UDP NodePort is closed") jig.TestNotReachableUDP(nodeIP, udpNodePortOld, kubeProxyLagTimeout) By("hitting the TCP service's LoadBalancer") jig.TestReachableHTTP(tcpIngressIP, svcPort, loadBalancerLagTimeout) if loadBalancerSupportsUDP { By("hitting the UDP service's LoadBalancer") jig.TestReachableUDP(udpIngressIP, svcPort, loadBalancerLagTimeout) } // Change the services' main ports. By("changing the TCP service's port") tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) { s.Spec.Ports[0].Port++ }) jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer) svcPortOld := svcPort svcPort = int(tcpService.Spec.Ports[0].Port) if svcPort == svcPortOld { framework.Failf("TCP Spec.Ports[0].Port (%d) did not change", svcPort) } if int(tcpService.Spec.Ports[0].NodePort) != tcpNodePort { framework.Failf("TCP Spec.Ports[0].NodePort (%d) changed", tcpService.Spec.Ports[0].NodePort) } if getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]) != tcpIngressIP { framework.Failf("TCP Status.LoadBalancer.Ingress changed (%s -> %s) when not expected", tcpIngressIP, getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0])) } By("changing the UDP service's port") udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) { s.Spec.Ports[0].Port++ }) if loadBalancerSupportsUDP { jig.SanityCheckService(udpService, api.ServiceTypeLoadBalancer) } else { jig.SanityCheckService(udpService, api.ServiceTypeNodePort) } if int(udpService.Spec.Ports[0].Port) != svcPort { framework.Failf("UDP Spec.Ports[0].Port (%d) did not change", udpService.Spec.Ports[0].Port) } if int(udpService.Spec.Ports[0].NodePort) != udpNodePort { framework.Failf("UDP Spec.Ports[0].NodePort (%d) changed", udpService.Spec.Ports[0].NodePort) } if loadBalancerSupportsUDP && getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0]) != udpIngressIP { framework.Failf("UDP Status.LoadBalancer.Ingress changed (%s -> %s) when not expected", udpIngressIP, getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0])) } framework.Logf("service port (TCP and UDP): %d", svcPort) By("hitting the TCP service's NodePort") jig.TestReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout) By("hitting the UDP service's NodePort") jig.TestReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout) By("hitting the TCP service's LoadBalancer") jig.TestReachableHTTP(tcpIngressIP, svcPort, loadBalancerCreateTimeout) // this may actually recreate the LB if loadBalancerSupportsUDP { By("hitting the UDP service's LoadBalancer") jig.TestReachableUDP(udpIngressIP, svcPort, loadBalancerCreateTimeout) // this may actually recreate the LB) } // Change the services back to ClusterIP. By("changing TCP service back to type=ClusterIP") tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) { s.Spec.Type = api.ServiceTypeClusterIP s.Spec.Ports[0].NodePort = 0 }) // Wait for the load balancer to be destroyed asynchronously tcpService = jig.WaitForLoadBalancerDestroyOrFail(ns1, tcpService.Name, tcpIngressIP, svcPort, loadBalancerCreateTimeout) jig.SanityCheckService(tcpService, api.ServiceTypeClusterIP) By("changing UDP service back to type=ClusterIP") udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) { s.Spec.Type = api.ServiceTypeClusterIP s.Spec.Ports[0].NodePort = 0 }) if loadBalancerSupportsUDP { // Wait for the load balancer to be destroyed asynchronously udpService = jig.WaitForLoadBalancerDestroyOrFail(ns2, udpService.Name, udpIngressIP, svcPort, loadBalancerCreateTimeout) jig.SanityCheckService(udpService, api.ServiceTypeClusterIP) } By("checking the TCP NodePort is closed") jig.TestNotReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout) By("checking the UDP NodePort is closed") jig.TestNotReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout) By("checking the TCP LoadBalancer is closed") jig.TestNotReachableHTTP(tcpIngressIP, svcPort, loadBalancerLagTimeout) if loadBalancerSupportsUDP { By("checking the UDP LoadBalancer is closed") jig.TestNotReachableUDP(udpIngressIP, svcPort, loadBalancerLagTimeout) } }) It("should use same NodePort with same port but different protocols", func() { serviceName := "nodeports" ns := f.Namespace.Name t := NewServerTest(cs, ns, serviceName) defer func() { defer GinkgoRecover() errs := t.Cleanup() if len(errs) != 0 { framework.Failf("errors in cleanup: %v", errs) } }() By("creating service " + serviceName + " with same NodePort but different protocols in namespace " + ns) service := &api.Service{ ObjectMeta: api.ObjectMeta{ Name: t.ServiceName, Namespace: t.Namespace, }, Spec: api.ServiceSpec{ Selector: t.Labels, Type: api.ServiceTypeNodePort, Ports: []api.ServicePort{ { Name: "tcp-port", Port: 53, Protocol: api.ProtocolTCP, }, { Name: "udp-port", Port: 53, Protocol: api.ProtocolUDP, }, }, }, } result, err := t.CreateService(service) Expect(err).NotTo(HaveOccurred()) if len(result.Spec.Ports) != 2 { framework.Failf("got unexpected len(Spec.Ports) for new service: %v", result) } if result.Spec.Ports[0].NodePort != result.Spec.Ports[1].NodePort { framework.Failf("should use same NodePort for new service: %v", result) } }) It("should prevent NodePort collisions", func() { // TODO: use the ServiceTestJig here baseName := "nodeport-collision-" serviceName1 := baseName + "1" serviceName2 := baseName + "2" ns := f.Namespace.Name t := NewServerTest(cs, ns, serviceName1) defer func() { defer GinkgoRecover() errs := t.Cleanup() if len(errs) != 0 { framework.Failf("errors in cleanup: %v", errs) } }() By("creating service " + serviceName1 + " with type NodePort in namespace " + ns) service := t.BuildServiceSpec() service.Spec.Type = api.ServiceTypeNodePort result, err := t.CreateService(service) Expect(err).NotTo(HaveOccurred()) if result.Spec.Type != api.ServiceTypeNodePort { framework.Failf("got unexpected Spec.Type for new service: %v", result) } if len(result.Spec.Ports) != 1 { framework.Failf("got unexpected len(Spec.Ports) for new service: %v", result) } port := result.Spec.Ports[0] if port.NodePort == 0 { framework.Failf("got unexpected Spec.Ports[0].nodePort for new service: %v", result) } By("creating service " + serviceName2 + " with conflicting NodePort") service2 := t.BuildServiceSpec() service2.Name = serviceName2 service2.Spec.Type = api.ServiceTypeNodePort service2.Spec.Ports[0].NodePort = port.NodePort result2, err := t.CreateService(service2) if err == nil { framework.Failf("Created service with conflicting NodePort: %v", result2) } expectedErr := fmt.Sprintf("%d.*port is already allocated", port.NodePort) Expect(fmt.Sprintf("%v", err)).To(MatchRegexp(expectedErr)) By("deleting service " + serviceName1 + " to release NodePort") err = t.DeleteService(serviceName1) Expect(err).NotTo(HaveOccurred()) By("creating service " + serviceName2 + " with no-longer-conflicting NodePort") _, err = t.CreateService(service2) Expect(err).NotTo(HaveOccurred()) }) It("should check NodePort out-of-range", func() { // TODO: use the ServiceTestJig here serviceName := "nodeport-range-test" ns := f.Namespace.Name t := NewServerTest(cs, ns, serviceName) defer func() { defer GinkgoRecover() errs := t.Cleanup() if len(errs) != 0 { framework.Failf("errors in cleanup: %v", errs) } }() service := t.BuildServiceSpec() service.Spec.Type = api.ServiceTypeNodePort By("creating service " + serviceName + " with type NodePort in namespace " + ns) service, err := t.CreateService(service) Expect(err).NotTo(HaveOccurred()) if service.Spec.Type != api.ServiceTypeNodePort { framework.Failf("got unexpected Spec.Type for new service: %v", service) } if len(service.Spec.Ports) != 1 { framework.Failf("got unexpected len(Spec.Ports) for new service: %v", service) } port := service.Spec.Ports[0] if port.NodePort == 0 { framework.Failf("got unexpected Spec.Ports[0].nodePort for new service: %v", service) } if !ServiceNodePortRange.Contains(int(port.NodePort)) { framework.Failf("got unexpected (out-of-range) port for new service: %v", service) } outOfRangeNodePort := 0 rand.Seed(time.Now().UTC().UnixNano()) for { outOfRangeNodePort = 1 + rand.Intn(65535) if !ServiceNodePortRange.Contains(outOfRangeNodePort) { break } } By(fmt.Sprintf("changing service "+serviceName+" to out-of-range NodePort %d", outOfRangeNodePort)) result, err := updateService(cs, ns, serviceName, func(s *api.Service) { s.Spec.Ports[0].NodePort = int32(outOfRangeNodePort) }) if err == nil { framework.Failf("failed to prevent update of service with out-of-range NodePort: %v", result) } expectedErr := fmt.Sprintf("%d.*port is not in the valid range", outOfRangeNodePort) Expect(fmt.Sprintf("%v", err)).To(MatchRegexp(expectedErr)) By("deleting original service " + serviceName) err = t.DeleteService(serviceName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("creating service "+serviceName+" with out-of-range NodePort %d", outOfRangeNodePort)) service = t.BuildServiceSpec() service.Spec.Type = api.ServiceTypeNodePort service.Spec.Ports[0].NodePort = int32(outOfRangeNodePort) service, err = t.CreateService(service) if err == nil { framework.Failf("failed to prevent create of service with out-of-range NodePort (%d): %v", outOfRangeNodePort, service) } Expect(fmt.Sprintf("%v", err)).To(MatchRegexp(expectedErr)) }) It("should release NodePorts on delete", func() { // TODO: use the ServiceTestJig here serviceName := "nodeport-reuse" ns := f.Namespace.Name t := NewServerTest(cs, ns, serviceName) defer func() { defer GinkgoRecover() errs := t.Cleanup() if len(errs) != 0 { framework.Failf("errors in cleanup: %v", errs) } }() service := t.BuildServiceSpec() service.Spec.Type = api.ServiceTypeNodePort By("creating service " + serviceName + " with type NodePort in namespace " + ns) service, err := t.CreateService(service) Expect(err).NotTo(HaveOccurred()) if service.Spec.Type != api.ServiceTypeNodePort { framework.Failf("got unexpected Spec.Type for new service: %v", service) } if len(service.Spec.Ports) != 1 { framework.Failf("got unexpected len(Spec.Ports) for new service: %v", service) } port := service.Spec.Ports[0] if port.NodePort == 0 { framework.Failf("got unexpected Spec.Ports[0].nodePort for new service: %v", service) } if !ServiceNodePortRange.Contains(int(port.NodePort)) { framework.Failf("got unexpected (out-of-range) port for new service: %v", service) } nodePort := port.NodePort By("deleting original service " + serviceName) err = t.DeleteService(serviceName) Expect(err).NotTo(HaveOccurred()) hostExec := framework.LaunchHostExecPod(f.ClientSet, f.Namespace.Name, "hostexec") cmd := fmt.Sprintf(`! ss -ant46 'sport = :%d' | tail -n +2 | grep LISTEN`, nodePort) var stdout string if pollErr := wait.PollImmediate(framework.Poll, kubeProxyLagTimeout, func() (bool, error) { var err error stdout, err = framework.RunHostCmd(hostExec.Namespace, hostExec.Name, cmd) if err != nil { framework.Logf("expected node port (%d) to not be in use, stdout: %v", nodePort, stdout) return false, nil } return true, nil }); pollErr != nil { framework.Failf("expected node port (%d) to not be in use in %v, stdout: %v", nodePort, kubeProxyLagTimeout, stdout) } By(fmt.Sprintf("creating service "+serviceName+" with same NodePort %d", nodePort)) service = t.BuildServiceSpec() service.Spec.Type = api.ServiceTypeNodePort service.Spec.Ports[0].NodePort = nodePort service, err = t.CreateService(service) Expect(err).NotTo(HaveOccurred()) }) It("should create endpoints for unready pods", func() { serviceName := "never-ready" ns := f.Namespace.Name t := NewServerTest(cs, ns, serviceName) defer func() { defer GinkgoRecover() errs := t.Cleanup() if len(errs) != 0 { framework.Failf("errors in cleanup: %v", errs) } }() service := t.BuildServiceSpec() service.Annotations = map[string]string{endpoint.TolerateUnreadyEndpointsAnnotation: "true"} rcSpec := rcByNameContainer(t.name, 1, t.image, t.Labels, api.Container{ Name: t.name, Image: t.image, Ports: []api.ContainerPort{{ContainerPort: int32(80), Protocol: api.ProtocolTCP}}, ReadinessProbe: &api.Probe{ Handler: api.Handler{ Exec: &api.ExecAction{ Command: []string{"/bin/false"}, }, }, }, }, nil) By(fmt.Sprintf("createing RC %v with selectors %v", rcSpec.Name, rcSpec.Spec.Selector)) _, err := t.createRC(rcSpec) ExpectNoError(err) By(fmt.Sprintf("creating Service %v with selectors %v", service.Name, service.Spec.Selector)) _, err = t.CreateService(service) ExpectNoError(err) By("Verifying pods for RC " + t.name) ExpectNoError(framework.VerifyPods(t.Client, t.Namespace, t.name, false, 1)) svcName := fmt.Sprintf("%v.%v", serviceName, f.Namespace.Name) By("waiting for endpoints of Service with DNS name " + svcName) execPodName := createExecPodOrFail(f.ClientSet, f.Namespace.Name, "execpod-") cmd := fmt.Sprintf("wget -qO- %v", svcName) var stdout string if pollErr := wait.PollImmediate(framework.Poll, kubeProxyLagTimeout, func() (bool, error) { var err error stdout, err = framework.RunHostCmd(f.Namespace.Name, execPodName, cmd) if err != nil { framework.Logf("expected un-ready endpoint for Service %v, stdout: %v, err %v", t.name, stdout, err) return false, nil } return true, nil }); pollErr != nil { framework.Failf("expected un-ready endpoint for Service %v within %v, stdout: %v", t.name, kubeProxyLagTimeout, stdout) } }) It("should only allow access from service loadbalancer source ranges [Slow]", func() { // this feature currently supported only on GCE/GKE/AWS framework.SkipUnlessProviderIs("gce", "gke", "aws") loadBalancerCreateTimeout := loadBalancerCreateTimeoutDefault if nodes := framework.GetReadySchedulableNodesOrDie(cs); len(nodes.Items) > largeClusterMinNodesNumber { loadBalancerCreateTimeout = loadBalancerCreateTimeoutLarge } namespace := f.Namespace.Name serviceName := "lb-sourcerange" jig := NewServiceTestJig(cs, serviceName) By("Prepare allow source ips") // prepare the exec pods // acceptPod are allowed to access the loadbalancer acceptPodName := createExecPodOrFail(cs, namespace, "execpod-accept") dropPodName := createExecPodOrFail(cs, namespace, "execpod-drop") accpetPod, err := cs.Core().Pods(namespace).Get(acceptPodName) Expect(err).NotTo(HaveOccurred()) dropPod, err := cs.Core().Pods(namespace).Get(dropPodName) Expect(err).NotTo(HaveOccurred()) By("creating a pod to be part of the service " + serviceName) // This container is an nginx container listening on port 80 // See kubernetes/contrib/ingress/echoheaders/nginx.conf for content of response jig.RunOrFail(namespace, nil) // Create loadbalancer service with source range from node[0] and podAccept svc := jig.CreateTCPServiceOrFail(namespace, func(svc *api.Service) { svc.Spec.Type = api.ServiceTypeLoadBalancer svc.Spec.LoadBalancerSourceRanges = []string{accpetPod.Status.PodIP + "/32"} }) // Clean up loadbalancer service defer func() { jig.UpdateServiceOrFail(svc.Namespace, svc.Name, func(svc *api.Service) { svc.Spec.Type = api.ServiceTypeNodePort svc.Spec.LoadBalancerSourceRanges = nil }) Expect(cs.Core().Services(svc.Namespace).Delete(svc.Name, nil)).NotTo(HaveOccurred()) }() svc = jig.WaitForLoadBalancerOrFail(namespace, serviceName, loadBalancerCreateTimeout) jig.SanityCheckService(svc, api.ServiceTypeLoadBalancer) By("check reachability from different sources") svcIP := getIngressPoint(&svc.Status.LoadBalancer.Ingress[0]) checkReachabilityFromPod(true, namespace, acceptPodName, svcIP) checkReachabilityFromPod(false, namespace, dropPodName, svcIP) By("Update service LoadBalancerSourceRange and check reachability") jig.UpdateServiceOrFail(svc.Namespace, svc.Name, func(svc *api.Service) { // only allow access from dropPod svc.Spec.LoadBalancerSourceRanges = []string{dropPod.Status.PodIP + "/32"} }) checkReachabilityFromPod(false, namespace, acceptPodName, svcIP) checkReachabilityFromPod(true, namespace, dropPodName, svcIP) By("Delete LoadBalancerSourceRange field and check reachability") jig.UpdateServiceOrFail(svc.Namespace, svc.Name, func(svc *api.Service) { svc.Spec.LoadBalancerSourceRanges = nil }) checkReachabilityFromPod(true, namespace, acceptPodName, svcIP) checkReachabilityFromPod(true, namespace, dropPodName, svcIP) }) }) var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", func() { f := framework.NewDefaultFramework("esipp") loadBalancerCreateTimeout := loadBalancerCreateTimeoutDefault var cs clientset.Interface serviceLBNames := []string{} BeforeEach(func() { // requires cloud load-balancer support - this feature currently supported only on GCE/GKE framework.SkipUnlessProviderIs("gce", "gke") cs = f.ClientSet if nodes := framework.GetReadySchedulableNodesOrDie(cs); len(nodes.Items) > largeClusterMinNodesNumber { loadBalancerCreateTimeout = loadBalancerCreateTimeoutLarge } }) AfterEach(func() { if CurrentGinkgoTestDescription().Failed { describeSvc(f.Namespace.Name) } for _, lb := range serviceLBNames { framework.Logf("cleaning gce resource for %s", lb) cleanupServiceGCEResources(lb) } //reset serviceLBNames serviceLBNames = []string{} }) It("should work for type=LoadBalancer [Slow][Feature:ExternalTrafficLocalOnly]", func() { namespace := f.Namespace.Name serviceName := "external-local" jig := NewServiceTestJig(cs, serviceName) svc := jig.createOnlyLocalLoadBalancerService(namespace, serviceName, loadBalancerCreateTimeout, true) serviceLBNames = append(serviceLBNames, getLoadBalancerName(svc)) healthCheckNodePort := int(service.GetServiceHealthCheckNodePort(svc)) if healthCheckNodePort == 0 { framework.Failf("Service HealthCheck NodePort was not allocated") } defer func() { jig.ChangeServiceType(svc.Namespace, svc.Name, api.ServiceTypeClusterIP, loadBalancerCreateTimeout) // Make sure we didn't leak the health check node port. for name, ips := range jig.getEndpointNodes(svc) { _, fail, status := jig.TestHTTPHealthCheckNodePort(ips[0], healthCheckNodePort, "/healthz", 5) if fail < 2 { framework.Failf("Health check node port %v not released on node %v: %v", healthCheckNodePort, name, status) } break } Expect(cs.Core().Services(svc.Namespace).Delete(svc.Name, nil)).NotTo(HaveOccurred()) }() svcTCPPort := int(svc.Spec.Ports[0].Port) ingressIP := getIngressPoint(&svc.Status.LoadBalancer.Ingress[0]) By("reading clientIP using the TCP service's service port via its external VIP") content := jig.GetHTTPContent(ingressIP, svcTCPPort, kubeProxyLagTimeout, "/clientip") clientIP := content.String() framework.Logf("ClientIP detected by target pod using VIP:SvcPort is %s", clientIP) By("checking if Source IP is preserved") if strings.HasPrefix(clientIP, "10.") { framework.Failf("Source IP was NOT preserved") } }) It("should work for type=NodePort [Slow][Feature:ExternalTrafficLocalOnly]", func() { namespace := f.Namespace.Name serviceName := "external-local" jig := NewServiceTestJig(cs, serviceName) svc := jig.createOnlyLocalNodePortService(namespace, serviceName, true) defer func() { Expect(cs.Core().Services(svc.Namespace).Delete(svc.Name, nil)).NotTo(HaveOccurred()) }() tcpNodePort := int(svc.Spec.Ports[0].NodePort) endpointsNodeMap := jig.getEndpointNodes(svc) path := "/clientip" for nodeName, nodeIPs := range endpointsNodeMap { nodeIP := nodeIPs[0] By(fmt.Sprintf("reading clientIP using the TCP service's NodePort, on node %v: %v%v%v", nodeName, nodeIP, tcpNodePort, path)) content := jig.GetHTTPContent(nodeIP, tcpNodePort, kubeProxyLagTimeout, path) clientIP := content.String() framework.Logf("ClientIP detected by target pod using NodePort is %s", clientIP) if strings.HasPrefix(clientIP, "10.") { framework.Failf("Source IP was NOT preserved") } } }) It("should only target nodes with endpoints [Slow][Feature:ExternalTrafficLocalOnly]", func() { namespace := f.Namespace.Name serviceName := "external-local" jig := NewServiceTestJig(cs, serviceName) nodes := jig.getNodes(maxNodesForEndpointsTests) svc := jig.createOnlyLocalLoadBalancerService(namespace, serviceName, loadBalancerCreateTimeout, false) serviceLBNames = append(serviceLBNames, getLoadBalancerName(svc)) defer func() { jig.ChangeServiceType(svc.Namespace, svc.Name, api.ServiceTypeClusterIP, loadBalancerCreateTimeout) Expect(cs.Core().Services(svc.Namespace).Delete(svc.Name, nil)).NotTo(HaveOccurred()) }() healthCheckNodePort := int(service.GetServiceHealthCheckNodePort(svc)) if healthCheckNodePort == 0 { framework.Failf("Service HealthCheck NodePort was not allocated") } ips := collectAddresses(nodes, api.NodeExternalIP) if len(ips) == 0 { ips = collectAddresses(nodes, api.NodeLegacyHostIP) } ingressIP := getIngressPoint(&svc.Status.LoadBalancer.Ingress[0]) svcTCPPort := int(svc.Spec.Ports[0].Port) threshold := 2 path := "/healthz" for i := 0; i < len(nodes.Items); i++ { endpointNodeName := nodes.Items[i].Name By("creating a pod to be part of the service " + serviceName + " on node " + endpointNodeName) jig.RunOrFail(namespace, func(rc *api.ReplicationController) { rc.Name = serviceName if endpointNodeName != "" { rc.Spec.Template.Spec.NodeName = endpointNodeName } }) By(fmt.Sprintf("waiting for service endpoint on node %v", endpointNodeName)) jig.waitForEndpointOnNode(namespace, serviceName, endpointNodeName) // HealthCheck should pass only on the node where num(endpoints) > 0 // All other nodes should fail the healthcheck on the service healthCheckNodePort for n, publicIP := range ips { expectedSuccess := nodes.Items[n].Name == endpointNodeName framework.Logf("Health checking %s, http://%s:%d/%s, expectedSuccess %v", nodes.Items[n].Name, publicIP, healthCheckNodePort, path, expectedSuccess) pass, fail, err := jig.TestHTTPHealthCheckNodePort(publicIP, healthCheckNodePort, path, 5) if expectedSuccess && pass < threshold { framework.Failf("Expected %s successes on %v/%v, got %d, err %v", threshold, endpointNodeName, path, pass, err) } else if !expectedSuccess && fail < threshold { framework.Failf("Expected %s failures on %v/%v, got %d, err %v", threshold, endpointNodeName, path, fail, err) } // Make sure the loadbalancer picked up the helth check change jig.TestReachableHTTP(ingressIP, svcTCPPort, kubeProxyLagTimeout) } framework.ExpectNoError(framework.DeleteRCAndPods(f.ClientSet, namespace, serviceName)) } }) It("should work from pods [Slow][Feature:ExternalTrafficLocalOnly]", func() { namespace := f.Namespace.Name serviceName := "external-local" jig := NewServiceTestJig(cs, serviceName) nodes := jig.getNodes(maxNodesForEndpointsTests) svc := jig.createOnlyLocalLoadBalancerService(namespace, serviceName, loadBalancerCreateTimeout, true) serviceLBNames = append(serviceLBNames, getLoadBalancerName(svc)) defer func() { jig.ChangeServiceType(svc.Namespace, svc.Name, api.ServiceTypeClusterIP, loadBalancerCreateTimeout) Expect(cs.Core().Services(svc.Namespace).Delete(svc.Name, nil)).NotTo(HaveOccurred()) }() ingressIP := getIngressPoint(&svc.Status.LoadBalancer.Ingress[0]) path := fmt.Sprintf("%s:%d/clientip", ingressIP, int(svc.Spec.Ports[0].Port)) nodeName := nodes.Items[0].Name podName := "execpod-sourceip" By(fmt.Sprintf("Creating %v on node %v", podName, nodeName)) execPodName := createExecPodOnNode(f.ClientSet, namespace, nodeName, podName) defer func() { err := cs.Core().Pods(namespace).Delete(execPodName, nil) Expect(err).NotTo(HaveOccurred()) }() execPod, err := f.ClientSet.Core().Pods(namespace).Get(execPodName) ExpectNoError(err) framework.Logf("Waiting up to %v wget %v", kubeProxyLagTimeout, path) cmd := fmt.Sprintf(`wget -T 30 -qO- %v`, path) var srcIP string By(fmt.Sprintf("Hitting external lb %v from pod %v on node %v", ingressIP, podName, nodeName)) if pollErr := wait.PollImmediate(framework.Poll, loadBalancerCreateTimeoutDefault, func() (bool, error) { stdout, err := framework.RunHostCmd(execPod.Namespace, execPod.Name, cmd) if err != nil { framework.Logf("got err: %v, retry until timeout", err) return false, nil } srcIP = strings.TrimSpace(strings.Split(stdout, ":")[0]) return srcIP == execPod.Status.PodIP, nil }); pollErr != nil { framework.Failf("Source IP not preserved from %v, expected '%v' got '%v'", podName, execPod.Status.PodIP, srcIP) } }) It("should handle updates to source ip annotation [Slow][Feature:ExternalTrafficLocalOnly]", func() { namespace := f.Namespace.Name serviceName := "external-local" jig := NewServiceTestJig(cs, serviceName) nodes := jig.getNodes(maxNodesForEndpointsTests) if len(nodes.Items) < 2 { framework.Failf("Need at least 2 nodes to verify source ip from a node without endpoint") } svc := jig.createOnlyLocalLoadBalancerService(namespace, serviceName, loadBalancerCreateTimeout, true) serviceLBNames = append(serviceLBNames, getLoadBalancerName(svc)) defer func() { jig.ChangeServiceType(svc.Namespace, svc.Name, api.ServiceTypeClusterIP, loadBalancerCreateTimeout) Expect(cs.Core().Services(svc.Namespace).Delete(svc.Name, nil)).NotTo(HaveOccurred()) }() // save the health check node port because it disappears when lift the annotation. healthCheckNodePort := int(service.GetServiceHealthCheckNodePort(svc)) By("turning ESIPP off") svc = jig.UpdateServiceOrFail(svc.Namespace, svc.Name, func(svc *api.Service) { svc.ObjectMeta.Annotations[service.BetaAnnotationExternalTraffic] = service.AnnotationValueExternalTrafficGlobal }) if service.GetServiceHealthCheckNodePort(svc) > 0 { framework.Failf("Service HealthCheck NodePort annotation still present") } endpointNodeMap := jig.getEndpointNodes(svc) noEndpointNodeMap := map[string][]string{} for _, n := range nodes.Items { if _, ok := endpointNodeMap[n.Name]; ok { continue } noEndpointNodeMap[n.Name] = getNodeAddresses(&n, api.NodeExternalIP) } svcTCPPort := int(svc.Spec.Ports[0].Port) svcNodePort := int(svc.Spec.Ports[0].NodePort) ingressIP := getIngressPoint(&svc.Status.LoadBalancer.Ingress[0]) path := "/clientip" By(fmt.Sprintf("endpoints present on nodes %v, absent on nodes %v", endpointNodeMap, noEndpointNodeMap)) for nodeName, nodeIPs := range noEndpointNodeMap { By(fmt.Sprintf("Checking %v (%v:%v%v) proxies to endpoints on another node", nodeName, nodeIPs[0], svcNodePort, path)) jig.GetHTTPContent(nodeIPs[0], svcNodePort, kubeProxyLagTimeout, path) } for nodeName, nodeIPs := range endpointNodeMap { By(fmt.Sprintf("checking kube-proxy health check fails on node with endpoint (%s), public IP %s", nodeName, nodeIPs[0])) var body bytes.Buffer var result bool var err error if pollErr := wait.PollImmediate(framework.Poll, timeout, func() (bool, error) { result, err = testReachableHTTPWithContent(nodeIPs[0], healthCheckNodePort, "/healthz", "", &body) return !result, nil }); pollErr != nil { framework.Failf("Kube-proxy still exposing health check on node %v:%v, after ESIPP was turned off. Last err %v, last body %v", nodeName, healthCheckNodePort, err, body.String()) } } // Poll till kube-proxy re-adds the MASQUERADE rule on the node. By(fmt.Sprintf("checking source ip is NOT preserved through loadbalancer %v", ingressIP)) var clientIP string pollErr := wait.PollImmediate(framework.Poll, kubeProxyLagTimeout, func() (bool, error) { content := jig.GetHTTPContent(ingressIP, svcTCPPort, kubeProxyLagTimeout, "/clientip") clientIP = content.String() if strings.HasPrefix(clientIP, "10.") { return true, nil } return false, nil }) if pollErr != nil { framework.Failf("Source IP WAS preserved even after ESIPP turned off. Got %v, expected a ten-dot cluster ip.", clientIP) } // TODO: We need to attempt to create another service with the previously // allocated healthcheck nodePort. If the health check nodePort has been // freed, the new service creation will succeed, upon which we cleanup. // If the health check nodePort has NOT been freed, the new service // creation will fail. By("turning ESIPP annotation back on") svc = jig.UpdateServiceOrFail(svc.Namespace, svc.Name, func(svc *api.Service) { svc.ObjectMeta.Annotations[service.BetaAnnotationExternalTraffic] = service.AnnotationValueExternalTrafficLocal // Request the same healthCheckNodePort as before, to test the user-requested allocation path svc.ObjectMeta.Annotations[service.BetaAnnotationHealthCheckNodePort] = fmt.Sprintf("%d", healthCheckNodePort) }) pollErr = wait.PollImmediate(framework.Poll, kubeProxyLagTimeout, func() (bool, error) { content := jig.GetHTTPContent(ingressIP, svcTCPPort, kubeProxyLagTimeout, path) clientIP = content.String() By(fmt.Sprintf("Endpoint %v:%v%v returned client ip %v", ingressIP, svcTCPPort, path, clientIP)) if !strings.HasPrefix(clientIP, "10.") { return true, nil } return false, nil }) if pollErr != nil { framework.Failf("Source IP (%v) is not the client IP even after ESIPP turned on, expected a public IP.", clientIP) } }) }) // updateService fetches a service, calls the update function on it, // and then attempts to send the updated service. It retries up to 2 // times in the face of timeouts and conflicts. func updateService(c clientset.Interface, namespace, serviceName string, update func(*api.Service)) (*api.Service, error)
func getContainerPortsByPodUID(endpoints *api.Endpoints) PortsByPodUID { m := PortsByPodUID{} for _, ss := range endpoints.Subsets { for _, port := range ss.Ports { for _, addr := range ss.Addresses { containerPort := port.Port hostPort := port.Port // use endpoint annotations to recover the container port in a Mesos setup // compare contrib/mesos/pkg/service/endpoints_controller.syncService key := fmt.Sprintf("k8s.mesosphere.io/containerPort_%s_%s_%d", port.Protocol, addr.IP, hostPort) mesosContainerPortString := endpoints.Annotations[key] if mesosContainerPortString != "" { mesosContainerPort, err := strconv.Atoi(mesosContainerPortString) if err != nil { continue } containerPort = int32(mesosContainerPort) framework.Logf("Mapped mesos host port %d to container port %d via annotation %s=%s", hostPort, containerPort, key, mesosContainerPortString) } // framework.Logf("Found pod %v, host port %d and container port %d", addr.TargetRef.UID, hostPort, containerPort) if _, ok := m[addr.TargetRef.UID]; !ok { m[addr.TargetRef.UID] = make([]int, 0) } m[addr.TargetRef.UID] = append(m[addr.TargetRef.UID], int(containerPort)) } } } return m } type PortsByPodName map[string][]int type PortsByPodUID map[types.UID][]int func translatePodNameToUIDOrFail(c clientset.Interface, ns string, expectedEndpoints PortsByPodName) PortsByPodUID { portsByUID := make(PortsByPodUID) for name, portList := range expectedEndpoints { pod, err := c.Core().Pods(ns).Get(name) if err != nil { framework.Failf("failed to get pod %s, that's pretty weird. validation failed: %s", name, err) } portsByUID[pod.ObjectMeta.UID] = portList } // framework.Logf("successfully translated pod names to UIDs: %v -> %v on namespace %s", expectedEndpoints, portsByUID, ns) return portsByUID } func validatePortsOrFail(endpoints PortsByPodUID, expectedEndpoints PortsByPodUID) { if len(endpoints) != len(expectedEndpoints) { // should not happen because we check this condition before framework.Failf("invalid number of endpoints got %v, expected %v", endpoints, expectedEndpoints) } for podUID := range expectedEndpoints { if _, ok := endpoints[podUID]; !ok { framework.Failf("endpoint %v not found", podUID) } if len(endpoints[podUID]) != len(expectedEndpoints[podUID]) { framework.Failf("invalid list of ports for uid %v. Got %v, expected %v", podUID, endpoints[podUID], expectedEndpoints[podUID]) } sort.Ints(endpoints[podUID]) sort.Ints(expectedEndpoints[podUID]) for index := range endpoints[podUID] { if endpoints[podUID][index] != expectedEndpoints[podUID][index] { framework.Failf("invalid list of ports for uid %v. Got %v, expected %v", podUID, endpoints[podUID], expectedEndpoints[podUID]) } } } } func validateEndpointsOrFail(c clientset.Interface, namespace, serviceName string, expectedEndpoints PortsByPodName) { By(fmt.Sprintf("waiting up to %v for service %s in namespace %s to expose endpoints %v", framework.ServiceStartTimeout, serviceName, namespace, expectedEndpoints)) i := 1 for start := time.Now(); time.Since(start) < framework.ServiceStartTimeout; time.Sleep(1 * time.Second) { endpoints, err := c.Core().Endpoints(namespace).Get(serviceName) if err != nil { framework.Logf("Get endpoints failed (%v elapsed, ignoring for 5s): %v", time.Since(start), err) continue } // framework.Logf("Found endpoints %v", endpoints) portsByPodUID := getContainerPortsByPodUID(endpoints) // framework.Logf("Found port by pod UID %v", portsByPodUID) expectedPortsByPodUID := translatePodNameToUIDOrFail(c, namespace, expectedEndpoints) if len(portsByPodUID) == len(expectedEndpoints) { validatePortsOrFail(portsByPodUID, expectedPortsByPodUID) framework.Logf("successfully validated that service %s in namespace %s exposes endpoints %v (%v elapsed)", serviceName, namespace, expectedEndpoints, time.Since(start)) return } if i%5 == 0 { framework.Logf("Unexpected endpoints: found %v, expected %v (%v elapsed, will retry)", portsByPodUID, expectedEndpoints, time.Since(start)) } i++ } if pods, err := c.Core().Pods(api.NamespaceAll).List(api.ListOptions{}); err == nil { for _, pod := range pods.Items { framework.Logf("Pod %s\t%s\t%s\t%s", pod.Namespace, pod.Name, pod.Spec.NodeName, pod.DeletionTimestamp) } } else { framework.Logf("Can't list pod debug info: %v", err) } framework.Failf("Timed out waiting for service %s in namespace %s to expose endpoints %v (%v elapsed)", serviceName, namespace, expectedEndpoints, framework.ServiceStartTimeout) } // newExecPodSpec returns the pod spec of exec pod func newExecPodSpec(ns, generateName string) *api.Pod { immediate := int64(0) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ GenerateName: generateName, Namespace: ns, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &immediate, Containers: []api.Container{ { Name: "exec", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sh", "-c", "while true; do sleep 5; done"}, }, }, }, } return pod } // createExecPodOrFail creates a simple busybox pod in a sleep loop used as a // vessel for kubectl exec commands. // Returns the name of the created pod. func createExecPodOrFail(client clientset.Interface, ns, generateName string) string { framework.Logf("Creating new exec pod") execPod := newExecPodSpec(ns, generateName) created, err := client.Core().Pods(ns).Create(execPod) Expect(err).NotTo(HaveOccurred()) err = wait.PollImmediate(framework.Poll, 5*time.Minute, func() (bool, error) { retrievedPod, err := client.Core().Pods(execPod.Namespace).Get(created.Name) if err != nil { return false, nil } return retrievedPod.Status.Phase == api.PodRunning, nil }) Expect(err).NotTo(HaveOccurred()) return created.Name } // createExecPodOnNode launches a exec pod in the given namespace and node // waits until it's Running, created pod name would be returned func createExecPodOnNode(client clientset.Interface, ns, nodeName, generateName string) string { framework.Logf("Creating exec pod %q in namespace %q", generateName, ns) execPod := newExecPodSpec(ns, generateName) execPod.Spec.NodeName = nodeName created, err := client.Core().Pods(ns).Create(execPod) Expect(err).NotTo(HaveOccurred()) err = wait.PollImmediate(framework.Poll, 5*time.Minute, func() (bool, error) { retrievedPod, err := client.Core().Pods(execPod.Namespace).Get(created.Name) if err != nil { return false, nil } return retrievedPod.Status.Phase == api.PodRunning, nil }) Expect(err).NotTo(HaveOccurred()) return created.Name } func createPodOrFail(c clientset.Interface, ns, name string, labels map[string]string, containerPorts []api.ContainerPort) { By(fmt.Sprintf("creating pod %s in namespace %s", name, ns)) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: name, Labels: labels, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: "pause", Image: framework.GetPauseImageName(c), Ports: containerPorts, // Add a dummy environment variable to work around a docker issue. // https://github.com/docker/docker/issues/14203 Env: []api.EnvVar{{Name: "FOO", Value: " "}}, }, }, }, } _, err := c.Core().Pods(ns).Create(pod) Expect(err).NotTo(HaveOccurred()) } func deletePodOrFail(c clientset.Interface, ns, name string) { By(fmt.Sprintf("deleting pod %s in namespace %s", name, ns)) err := c.Core().Pods(ns).Delete(name, nil) Expect(err).NotTo(HaveOccurred()) } func getNodeAddresses(node *api.Node, addressType api.NodeAddressType) (ips []string) { for j := range node.Status.Addresses { nodeAddress := &node.Status.Addresses[j] if nodeAddress.Type == addressType { ips = append(ips, nodeAddress.Address) } } return } func collectAddresses(nodes *api.NodeList, addressType api.NodeAddressType) []string { ips := []string{} for i := range nodes.Items { ips = append(ips, getNodeAddresses(&nodes.Items[i], addressType)...) } return ips } func getNodePublicIps(c clientset.Interface) ([]string, error) { nodes := framework.GetReadySchedulableNodesOrDie(c) ips := collectAddresses(nodes, api.NodeExternalIP) if len(ips) == 0 { ips = collectAddresses(nodes, api.NodeLegacyHostIP) } return ips, nil } func pickNodeIP(c clientset.Interface) string { publicIps, err := getNodePublicIps(c) Expect(err).NotTo(HaveOccurred()) if len(publicIps) == 0 { framework.Failf("got unexpected number (%d) of public IPs", len(publicIps)) } ip := publicIps[0] return ip } func testReachableHTTP(ip string, port int, request string, expect string) (bool, error) { return testReachableHTTPWithContent(ip, port, request, expect, nil) } func testReachableHTTPWithContent(ip string, port int, request string, expect string, content *bytes.Buffer) (bool, error) { url := fmt.Sprintf("http://%s:%d%s", ip, port, request) if ip == "" { framework.Failf("Got empty IP for reachability check (%s)", url) return false, nil } if port == 0 { framework.Failf("Got port==0 for reachability check (%s)", url) return false, nil } framework.Logf("Testing HTTP reachability of %v", url) resp, err := httpGetNoConnectionPool(url) if err != nil { framework.Logf("Got error testing for reachability of %s: %v", url, err) return false, nil } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { framework.Logf("Got error reading response from %s: %v", url, err) return false, nil } if resp.StatusCode != 200 { return false, fmt.Errorf("received non-success return status %q trying to access %s; got body: %s", resp.Status, url, string(body)) } if !strings.Contains(string(body), expect) { return false, fmt.Errorf("received response body without expected substring %q: %s", expect, string(body)) } if content != nil { content.Write(body) } return true, nil } func testHTTPHealthCheckNodePort(ip string, port int, request string) (bool, error) { url := fmt.Sprintf("http://%s:%d%s", ip, port, request) if ip == "" || port == 0 { framework.Failf("Got empty IP for reachability check (%s)", url) return false, fmt.Errorf("Invalid input ip or port") } framework.Logf("Testing HTTP health check on %v", url) resp, err := httpGetNoConnectionPool(url) if err != nil { framework.Logf("Got error testing for reachability of %s: %v", url, err) return false, err } defer resp.Body.Close() if err != nil { framework.Logf("Got error reading response from %s: %v", url, err) return false, err } // HealthCheck responder returns 503 for no local endpoints if resp.StatusCode == 503 { return false, nil } // HealthCheck responder returns 200 for non-zero local endpoints if resp.StatusCode == 200 { return true, nil } return false, fmt.Errorf("Unexpected HTTP response code %s from health check responder at %s", resp.Status, url) } func testNotReachableHTTP(ip string, port int) (bool, error) { url := fmt.Sprintf("http://%s:%d", ip, port) if ip == "" { framework.Failf("Got empty IP for non-reachability check (%s)", url) return false, nil } if port == 0 { framework.Failf("Got port==0 for non-reachability check (%s)", url) return false, nil } framework.Logf("Testing HTTP non-reachability of %v", url) resp, err := httpGetNoConnectionPool(url) if err != nil { framework.Logf("Confirmed that %s is not reachable", url) return true, nil } resp.Body.Close() return false, nil } func testReachableUDP(ip string, port int, request string, expect string) (bool, error) { uri := fmt.Sprintf("udp://%s:%d", ip, port) if ip == "" { framework.Failf("Got empty IP for reachability check (%s)", uri) return false, nil } if port == 0 { framework.Failf("Got port==0 for reachability check (%s)", uri) return false, nil } framework.Logf("Testing UDP reachability of %v", uri) con, err := net.Dial("udp", ip+":"+strconv.Itoa(port)) if err != nil { return false, fmt.Errorf("Failed to dial %s:%d: %v", ip, port, err) } _, err = con.Write([]byte(fmt.Sprintf("%s\n", request))) if err != nil { return false, fmt.Errorf("Failed to send request: %v", err) } var buf []byte = make([]byte, len(expect)+1) err = con.SetDeadline(time.Now().Add(3 * time.Second)) if err != nil { return false, fmt.Errorf("Failed to set deadline: %v", err) } _, err = con.Read(buf) if err != nil { return false, nil } if !strings.Contains(string(buf), expect) { return false, fmt.Errorf("Failed to retrieve %q, got %q", expect, string(buf)) } framework.Logf("Successfully reached %v", uri) return true, nil } func testNotReachableUDP(ip string, port int, request string) (bool, error) { uri := fmt.Sprintf("udp://%s:%d", ip, port) if ip == "" { framework.Failf("Got empty IP for reachability check (%s)", uri) return false, nil } if port == 0 { framework.Failf("Got port==0 for reachability check (%s)", uri) return false, nil } framework.Logf("Testing UDP non-reachability of %v", uri) con, err := net.Dial("udp", ip+":"+strconv.Itoa(port)) if err != nil { framework.Logf("Confirmed that %s is not reachable", uri) return true, nil } _, err = con.Write([]byte(fmt.Sprintf("%s\n", request))) if err != nil { framework.Logf("Confirmed that %s is not reachable", uri) return true, nil } var buf []byte = make([]byte, 1) err = con.SetDeadline(time.Now().Add(3 * time.Second)) if err != nil { return false, fmt.Errorf("Failed to set deadline: %v", err) } _, err = con.Read(buf) if err != nil { framework.Logf("Confirmed that %s is not reachable", uri) return true, nil } return false, nil } // Creates a replication controller that serves its hostname and a service on top of it. func startServeHostnameService(c clientset.Interface, ns, name string, port, replicas int) ([]string, string, error) { podNames := make([]string, replicas) By("creating service " + name + " in namespace " + ns) _, err := c.Core().Services(ns).Create(&api.Service{ ObjectMeta: api.ObjectMeta{ Name: name, }, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Port: int32(port), TargetPort: intstr.FromInt(9376), Protocol: "TCP", }}, Selector: map[string]string{ "name": name, }, }, }) if err != nil { return podNames, "", err } var createdPods []*api.Pod maxContainerFailures := 0 config := testutils.RCConfig{ Client: c, Image: "gcr.io/google_containers/serve_hostname:v1.4", Name: name, Namespace: ns, PollInterval: 3 * time.Second, Timeout: framework.PodReadyBeforeTimeout, Replicas: replicas, CreatedPods: &createdPods, MaxContainerFailures: &maxContainerFailures, } err = framework.RunRC(config) if err != nil { return podNames, "", err } if len(createdPods) != replicas { return podNames, "", fmt.Errorf("Incorrect number of running pods: %v", len(createdPods)) } for i := range createdPods { podNames[i] = createdPods[i].ObjectMeta.Name } sort.StringSlice(podNames).Sort() service, err := c.Core().Services(ns).Get(name) if err != nil { return podNames, "", err } if service.Spec.ClusterIP == "" { return podNames, "", fmt.Errorf("Service IP is blank for %v", name) } serviceIP := service.Spec.ClusterIP return podNames, serviceIP, nil } func stopServeHostnameService(clientset clientset.Interface, ns, name string) error { if err := framework.DeleteRCAndPods(clientset, ns, name); err != nil { return err } if err := clientset.Core().Services(ns).Delete(name, nil); err != nil { return err } return nil } // verifyServeHostnameServiceUp wgets the given serviceIP:servicePort from the // given host and from within a pod. The host is expected to be an SSH-able node // in the cluster. Each pod in the service is expected to echo its name. These // names are compared with the given expectedPods list after a sort | uniq. func verifyServeHostnameServiceUp(c clientset.Interface, ns, host string, expectedPods []string, serviceIP string, servicePort int) error { execPodName := createExecPodOrFail(c, ns, "execpod-") defer func() { deletePodOrFail(c, ns, execPodName) }() // Loop a bunch of times - the proxy is randomized, so we want a good // chance of hitting each backend at least once. buildCommand := func(wget string) string { return fmt.Sprintf("for i in $(seq 1 %d); do %s http://%s:%d 2>&1 || true; echo; done", 50*len(expectedPods), wget, serviceIP, servicePort) } commands := []func() string{ // verify service from node func() string { cmd := "set -e; " + buildCommand("wget -q --timeout=0.2 --tries=1 -O -") framework.Logf("Executing cmd %q on host %v", cmd, host) result, err := framework.SSH(cmd, host, framework.TestContext.Provider) if err != nil || result.Code != 0 { framework.LogSSHResult(result) framework.Logf("error while SSH-ing to node: %v", err) } return result.Stdout }, // verify service from pod func() string { cmd := buildCommand("wget -q -T 1 -O -") framework.Logf("Executing cmd %q in pod %v/%v", cmd, ns, execPodName) // TODO: Use exec-over-http via the netexec pod instead of kubectl exec. output, err := framework.RunHostCmd(ns, execPodName, cmd) if err != nil { framework.Logf("error while kubectl execing %q in pod %v/%v: %v\nOutput: %v", cmd, ns, execPodName, err, output) } return output }, } expectedEndpoints := sets.NewString(expectedPods...) By(fmt.Sprintf("verifying service has %d reachable backends", len(expectedPods))) for _, cmdFunc := range commands { passed := false gotEndpoints := sets.NewString() // Retry cmdFunc for a while for start := time.Now(); time.Since(start) < kubeProxyLagTimeout; time.Sleep(5 * time.Second) { for _, endpoint := range strings.Split(cmdFunc(), "\n") { trimmedEp := strings.TrimSpace(endpoint) if trimmedEp != "" { gotEndpoints.Insert(trimmedEp) } } // TODO: simply checking that the retrieved endpoints is a superset // of the expected allows us to ignore intermitten network flakes that // result in output like "wget timed out", but these should be rare // and we need a better way to track how often it occurs. if gotEndpoints.IsSuperset(expectedEndpoints) { if !gotEndpoints.Equal(expectedEndpoints) { framework.Logf("Ignoring unexpected output wgetting endpoints of service %s: %v", serviceIP, gotEndpoints.Difference(expectedEndpoints)) } passed = true break } framework.Logf("Unable to reach the following endpoints of service %s: %v", serviceIP, expectedEndpoints.Difference(gotEndpoints)) } if !passed { // Sort the lists so they're easier to visually diff. exp := expectedEndpoints.List() got := gotEndpoints.List() sort.StringSlice(exp).Sort() sort.StringSlice(got).Sort() return fmt.Errorf("service verification failed for: %s\nexpected %v\nreceived %v", serviceIP, exp, got) } } return nil } func verifyServeHostnameServiceDown(c clientset.Interface, host string, serviceIP string, servicePort int) error { command := fmt.Sprintf( "curl -s --connect-timeout 2 http://%s:%d && exit 99", serviceIP, servicePort) for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) { result, err := framework.SSH(command, host, framework.TestContext.Provider) if err != nil { framework.LogSSHResult(result) framework.Logf("error while SSH-ing to node: %v", err) } if result.Code != 99 { return nil } framework.Logf("service still alive - still waiting") } return fmt.Errorf("waiting for service to be down timed out") } // Does an HTTP GET, but does not reuse TCP connections // This masks problems where the iptables rule has changed, but we don't see it // This is intended for relatively quick requests (status checks), so we set a short (5 seconds) timeout func httpGetNoConnectionPool(url string) (*http.Response, error) { tr := utilnet.SetTransportDefaults(&http.Transport{ DisableKeepAlives: true, }) client := &http.Client{ Transport: tr, Timeout: 5 * time.Second, } return client.Get(url) } // A test jig to help testing. type ServiceTestJig struct { ID string Name string Client clientset.Interface Labels map[string]string } // NewServiceTestJig allocates and inits a new ServiceTestJig. func NewServiceTestJig(client clientset.Interface, name string) *ServiceTestJig { j := &ServiceTestJig{} j.Client = client j.Name = name j.ID = j.Name + "-" + string(uuid.NewUUID()) j.Labels = map[string]string{"testid": j.ID} return j } // newServiceTemplate returns the default api.Service template for this jig, but // does not actually create the Service. The default Service has the same name // as the jig and exposes the given port. func (j *ServiceTestJig) newServiceTemplate(namespace string, proto api.Protocol, port int32) *api.Service { service := &api.Service{ ObjectMeta: api.ObjectMeta{ Namespace: namespace, Name: j.Name, Labels: j.Labels, }, Spec: api.ServiceSpec{ Selector: j.Labels, Ports: []api.ServicePort{ { Protocol: proto, Port: port, }, }, }, } return service } // CreateTCPServiceWithPort creates a new TCP Service with given port based on the // jig's defaults. Callers can provide a function to tweak the Service object before // it is created. func (j *ServiceTestJig) CreateTCPServiceWithPort(namespace string, tweak func(svc *api.Service), port int32) *api.Service { svc := j.newServiceTemplate(namespace, api.ProtocolTCP, port) if tweak != nil { tweak(svc) } result, err := j.Client.Core().Services(namespace).Create(svc) if err != nil { framework.Failf("Failed to create TCP Service %q: %v", svc.Name, err) } return result } // CreateTCPServiceOrFail creates a new TCP Service based on the jig's // defaults. Callers can provide a function to tweak the Service object before // it is created. func (j *ServiceTestJig) CreateTCPServiceOrFail(namespace string, tweak func(svc *api.Service)) *api.Service { svc := j.newServiceTemplate(namespace, api.ProtocolTCP, 80) if tweak != nil { tweak(svc) } result, err := j.Client.Core().Services(namespace).Create(svc) if err != nil { framework.Failf("Failed to create TCP Service %q: %v", svc.Name, err) } return result } // CreateUDPServiceOrFail creates a new UDP Service based on the jig's // defaults. Callers can provide a function to tweak the Service object before // it is created. func (j *ServiceTestJig) CreateUDPServiceOrFail(namespace string, tweak func(svc *api.Service)) *api.Service { svc := j.newServiceTemplate(namespace, api.ProtocolUDP, 80) if tweak != nil { tweak(svc) } result, err := j.Client.Core().Services(namespace).Create(svc) if err != nil { framework.Failf("Failed to create UDP Service %q: %v", svc.Name, err) } return result } func (j *ServiceTestJig) ChangeServiceType(namespace, name string, newType api.ServiceType, timeout time.Duration) { ingressIP := "" svc := j.UpdateServiceOrFail(namespace, name, func(s *api.Service) { for _, ing := range s.Status.LoadBalancer.Ingress { if ing.IP != "" { ingressIP = ing.IP } } s.Spec.Type = newType s.Spec.Ports[0].NodePort = 0 }) if ingressIP != "" { j.WaitForLoadBalancerDestroyOrFail(namespace, svc.Name, ingressIP, int(svc.Spec.Ports[0].Port), timeout) } } // createOnlyLocalNodePortService creates a loadbalancer service and sanity checks its // nodePort. If createPod is true, it also creates an RC with 1 replica of // the standard netexec container used everywhere in this test. func (j *ServiceTestJig) createOnlyLocalNodePortService(namespace, serviceName string, createPod bool) *api.Service { By("creating a service " + namespace + "/" + serviceName + " with type=NodePort and annotation for local-traffic-only") svc := j.CreateTCPServiceOrFail(namespace, func(svc *api.Service) { svc.Spec.Type = api.ServiceTypeNodePort svc.ObjectMeta.Annotations = map[string]string{ service.BetaAnnotationExternalTraffic: service.AnnotationValueExternalTrafficLocal} svc.Spec.Ports = []api.ServicePort{{Protocol: "TCP", Port: 80}} }) if createPod { By("creating a pod to be part of the service " + serviceName) j.RunOrFail(namespace, nil) } j.SanityCheckService(svc, api.ServiceTypeNodePort) return svc } // createOnlyLocalLoadBalancerService creates a loadbalancer service and waits for it to // acquire an ingress IP. If createPod is true, it also creates an RC with 1 // replica of the standard netexec container used everywhere in this test. func (j *ServiceTestJig) createOnlyLocalLoadBalancerService(namespace, serviceName string, timeout time.Duration, createPod bool) *api.Service { By("creating a service " + namespace + "/" + serviceName + " with type=LoadBalancer and annotation for local-traffic-only") svc := j.CreateTCPServiceOrFail(namespace, func(svc *api.Service) { svc.Spec.Type = api.ServiceTypeLoadBalancer // We need to turn affinity off for our LB distribution tests svc.Spec.SessionAffinity = api.ServiceAffinityNone svc.ObjectMeta.Annotations = map[string]string{ service.BetaAnnotationExternalTraffic: service.AnnotationValueExternalTrafficLocal} svc.Spec.Ports = []api.ServicePort{{Protocol: "TCP", Port: 80}} }) if createPod { By("creating a pod to be part of the service " + serviceName) j.RunOrFail(namespace, nil) } By("waiting for loadbalancer for service " + namespace + "/" + serviceName) svc = j.WaitForLoadBalancerOrFail(namespace, serviceName, timeout) j.SanityCheckService(svc, api.ServiceTypeLoadBalancer) return svc } // getEndpointNodes returns a map of nodenames:external-ip on which the // endpoints of the given Service are running. func (j *ServiceTestJig) getEndpointNodes(svc *api.Service) map[string][]string { nodes := j.getNodes(maxNodesForEndpointsTests) endpoints, err := j.Client.Core().Endpoints(svc.Namespace).Get(svc.Name) if err != nil { framework.Failf("Get endpoints for service %s/%s failed (%s)", svc.Namespace, svc.Name, err) } if len(endpoints.Subsets) == 0 { framework.Failf("Endpoint has no subsets, cannot determine node addresses.") } epNodes := sets.NewString() for _, ss := range endpoints.Subsets { for _, e := range ss.Addresses { if e.NodeName != nil { epNodes.Insert(*e.NodeName) } } } nodeMap := map[string][]string{} for _, n := range nodes.Items { if epNodes.Has(n.Name) { nodeMap[n.Name] = getNodeAddresses(&n, api.NodeExternalIP) } } return nodeMap } // getNodes returns the first maxNodesForTest nodes. Useful in large clusters // where we don't eg: want to create an endpoint per node. func (j *ServiceTestJig) getNodes(maxNodesForTest int) (nodes *api.NodeList) { nodes = framework.GetReadySchedulableNodesOrDie(j.Client) if len(nodes.Items) <= maxNodesForTest { maxNodesForTest = len(nodes.Items) } nodes.Items = nodes.Items[:maxNodesForTest] return nodes } func (j *ServiceTestJig) waitForEndpointOnNode(namespace, serviceName, nodeName string) { err := wait.PollImmediate(framework.Poll, loadBalancerCreateTimeoutDefault, func() (bool, error) { endpoints, err := j.Client.Core().Endpoints(namespace).Get(serviceName) if err != nil { framework.Logf("Get endpoints for service %s/%s failed (%s)", namespace, serviceName, err) return false, nil } // TODO: Handle multiple endpoints if len(endpoints.Subsets[0].Addresses) == 0 { framework.Logf("Expected Ready endpoints - found none") return false, nil } epHostName := *endpoints.Subsets[0].Addresses[0].NodeName framework.Logf("Pod for service %s/%s is on node %s", namespace, serviceName, epHostName) if epHostName != nodeName { framework.Logf("Found endpoint on wrong node, expected %v, got %v", nodeName, epHostName) return false, nil } return true, nil }) framework.ExpectNoError(err) } func (j *ServiceTestJig) SanityCheckService(svc *api.Service, svcType api.ServiceType) { if svc.Spec.Type != svcType { framework.Failf("unexpected Spec.Type (%s) for service, expected %s", svc.Spec.Type, svcType) } expectNodePorts := false if svcType != api.ServiceTypeClusterIP { expectNodePorts = true } for i, port := range svc.Spec.Ports { hasNodePort := (port.NodePort != 0) if hasNodePort != expectNodePorts { framework.Failf("unexpected Spec.Ports[%d].NodePort (%d) for service", i, port.NodePort) } if hasNodePort { if !ServiceNodePortRange.Contains(int(port.NodePort)) { framework.Failf("out-of-range nodePort (%d) for service", port.NodePort) } } } expectIngress := false if svcType == api.ServiceTypeLoadBalancer { expectIngress = true } hasIngress := len(svc.Status.LoadBalancer.Ingress) != 0 if hasIngress != expectIngress { framework.Failf("unexpected number of Status.LoadBalancer.Ingress (%d) for service", len(svc.Status.LoadBalancer.Ingress)) } if hasIngress { for i, ing := range svc.Status.LoadBalancer.Ingress { if ing.IP == "" && ing.Hostname == "" { framework.Failf("unexpected Status.LoadBalancer.Ingress[%d] for service: %#v", i, ing) } } } } // UpdateService fetches a service, calls the update function on it, and // then attempts to send the updated service. It tries up to 3 times in the // face of timeouts and conflicts. func (j *ServiceTestJig) UpdateService(namespace, name string, update func(*api.Service)) (*api.Service, error) { for i := 0; i < 3; i++ { service, err := j.Client.Core().Services(namespace).Get(name) if err != nil { return nil, fmt.Errorf("Failed to get Service %q: %v", name, err) } update(service) service, err = j.Client.Core().Services(namespace).Update(service) if err == nil { return service, nil } if !errors.IsConflict(err) && !errors.IsServerTimeout(err) { return nil, fmt.Errorf("Failed to update Service %q: %v", name, err) } } return nil, fmt.Errorf("Too many retries updating Service %q", name) } // UpdateServiceOrFail fetches a service, calls the update function on it, and // then attempts to send the updated service. It tries up to 3 times in the // face of timeouts and conflicts. func (j *ServiceTestJig) UpdateServiceOrFail(namespace, name string, update func(*api.Service)) *api.Service { svc, err := j.UpdateService(namespace, name, update) if err != nil { framework.Failf(err.Error()) } return svc } func (j *ServiceTestJig) ChangeServiceNodePortOrFail(namespace, name string, initial int) *api.Service { var err error var service *api.Service for i := 1; i < ServiceNodePortRange.Size; i++ { offs1 := initial - ServiceNodePortRange.Base offs2 := (offs1 + i) % ServiceNodePortRange.Size newPort := ServiceNodePortRange.Base + offs2 service, err = j.UpdateService(namespace, name, func(s *api.Service) { s.Spec.Ports[0].NodePort = int32(newPort) }) if err != nil && strings.Contains(err.Error(), "provided port is already allocated") { framework.Logf("tried nodePort %d, but it is in use, will try another", newPort) continue } // Otherwise err was nil or err was a real error break } if err != nil { framework.Failf("Could not change the nodePort: %v", err) } return service } func (j *ServiceTestJig) WaitForLoadBalancerOrFail(namespace, name string, timeout time.Duration) *api.Service { var service *api.Service framework.Logf("Waiting up to %v for service %q to have a LoadBalancer", timeout, name) pollFunc := func() (bool, error) { svc, err := j.Client.Core().Services(namespace).Get(name) if err != nil { return false, err } if len(svc.Status.LoadBalancer.Ingress) > 0 { service = svc return true, nil } return false, nil } if err := wait.PollImmediate(framework.Poll, timeout, pollFunc); err != nil { framework.Failf("Timeout waiting for service %q to have a load balancer", name) } return service } func (j *ServiceTestJig) WaitForLoadBalancerDestroyOrFail(namespace, name string, ip string, port int, timeout time.Duration) *api.Service { // TODO: once support ticket 21807001 is resolved, reduce this timeout back to something reasonable defer func() { if err := framework.EnsureLoadBalancerResourcesDeleted(ip, strconv.Itoa(port)); err != nil { framework.Logf("Failed to delete cloud resources for service: %s %d (%v)", ip, port, err) } }() var service *api.Service framework.Logf("Waiting up to %v for service %q to have no LoadBalancer", timeout, name) pollFunc := func() (bool, error) { svc, err := j.Client.Core().Services(namespace).Get(name) if err != nil { return false, err } if len(svc.Status.LoadBalancer.Ingress) == 0 { service = svc return true, nil } return false, nil } if err := wait.PollImmediate(framework.Poll, timeout, pollFunc); err != nil { framework.Failf("Timeout waiting for service %q to have no load balancer", name) } return service } func (j *ServiceTestJig) TestReachableHTTP(host string, port int, timeout time.Duration) { if err := wait.PollImmediate(framework.Poll, timeout, func() (bool, error) { return testReachableHTTP(host, port, "/echo?msg=hello", "hello") }); err != nil { framework.Failf("Could not reach HTTP service through %v:%v after %v: %v", host, port, timeout, err) } } func (j *ServiceTestJig) TestNotReachableHTTP(host string, port int, timeout time.Duration) { if err := wait.PollImmediate(framework.Poll, timeout, func() (bool, error) { return testNotReachableHTTP(host, port) }); err != nil { framework.Failf("Could still reach HTTP service through %v:%v after %v: %v", host, port, timeout, err) } } func (j *ServiceTestJig) TestReachableUDP(host string, port int, timeout time.Duration) { if err := wait.PollImmediate(framework.Poll, timeout, func() (bool, error) { return testReachableUDP(host, port, "echo hello", "hello") }); err != nil { framework.Failf("Could not reach UDP service through %v:%v after %v: %v", host, port, timeout, err) } } func (j *ServiceTestJig) TestNotReachableUDP(host string, port int, timeout time.Duration) { if err := wait.PollImmediate(framework.Poll, timeout, func() (bool, error) { return testNotReachableUDP(host, port, "echo hello") }); err != nil { framework.Failf("Could still reach UDP service through %v:%v after %v: %v", host, port, timeout, err) } } func (j *ServiceTestJig) GetHTTPContent(host string, port int, timeout time.Duration, url string) bytes.Buffer { var body bytes.Buffer var err error if pollErr := wait.PollImmediate(framework.Poll, timeout, func() (bool, error) { result, err := testReachableHTTPWithContent(host, port, url, "", &body) if err != nil { framework.Logf("Error hitting %v:%v%v, retrying: %v", host, port, url, err) return false, nil } return result, nil }); pollErr != nil { framework.Failf("Could not reach HTTP service through %v:%v%v after %v: %v", host, port, url, timeout, err) } return body } func (j *ServiceTestJig) TestHTTPHealthCheckNodePort(host string, port int, request string, tries int) (pass, fail int, statusMsg string) { for i := 0; i < tries; i++ { success, err := testHTTPHealthCheckNodePort(host, port, request) if success { pass++ } else { fail++ } statusMsg += fmt.Sprintf("\nAttempt %d Error %v", i, err) time.Sleep(1 * time.Second) } return pass, fail, statusMsg } func getIngressPoint(ing *api.LoadBalancerIngress) string { host := ing.IP if host == "" { host = ing.Hostname } return host } // newRCTemplate returns the default api.ReplicationController object for // this jig, but does not actually create the RC. The default RC has the same // name as the jig and runs the "netexec" container. func (j *ServiceTestJig) newRCTemplate(namespace string) *api.ReplicationController { rc := &api.ReplicationController{ ObjectMeta: api.ObjectMeta{ Namespace: namespace, Name: j.Name, Labels: j.Labels, }, Spec: api.ReplicationControllerSpec{ Replicas: 1, Selector: j.Labels, Template: &api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: j.Labels, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: "netexec", Image: "gcr.io/google_containers/netexec:1.7", Args: []string{"--http-port=80", "--udp-port=80"}, ReadinessProbe: &api.Probe{ PeriodSeconds: 3, Handler: api.Handler{ HTTPGet: &api.HTTPGetAction{ Port: intstr.FromInt(80), Path: "/hostName", }, }, }, }, }, TerminationGracePeriodSeconds: new(int64), }, }, }, } return rc } // RunOrFail creates a ReplicationController and Pod(s) and waits for the // Pod(s) to be running. Callers can provide a function to tweak the RC object // before it is created. func (j *ServiceTestJig) RunOrFail(namespace string, tweak func(rc *api.ReplicationController)) *api.ReplicationController { rc := j.newRCTemplate(namespace) if tweak != nil { tweak(rc) } result, err := j.Client.Core().ReplicationControllers(namespace).Create(rc) if err != nil { framework.Failf("Failed to created RC %q: %v", rc.Name, err) } pods, err := j.waitForPodsCreated(namespace, int(rc.Spec.Replicas)) if err != nil { framework.Failf("Failed to create pods: %v", err) } if err := j.waitForPodsReady(namespace, pods); err != nil { framework.Failf("Failed waiting for pods to be running: %v", err) } return result } func (j *ServiceTestJig) waitForPodsCreated(namespace string, replicas int) ([]string, error) { timeout := 2 * time.Minute // List the pods, making sure we observe all the replicas. label := labels.SelectorFromSet(labels.Set(j.Labels)) framework.Logf("Waiting up to %v for %d pods to be created", timeout, replicas) for start := time.Now(); time.Since(start) < timeout; time.Sleep(2 * time.Second) { options := api.ListOptions{LabelSelector: label} pods, err := j.Client.Core().Pods(namespace).List(options) if err != nil { return nil, err } found := []string{} for _, pod := range pods.Items { if pod.DeletionTimestamp != nil { continue } found = append(found, pod.Name) } if len(found) == replicas { framework.Logf("Found all %d pods", replicas) return found, nil } framework.Logf("Found %d/%d pods - will retry", len(found), replicas) } return nil, fmt.Errorf("Timeout waiting for %d pods to be created", replicas) } func (j *ServiceTestJig) waitForPodsReady(namespace string, pods []string) error { timeout := 2 * time.Minute if !framework.CheckPodsRunningReady(j.Client, namespace, pods, timeout) { return fmt.Errorf("Timeout waiting for %d pods to be ready", len(pods)) } return nil } // Simple helper class to avoid too much boilerplate in tests type ServiceTestFixture struct { ServiceName string Namespace string Client clientset.Interface TestId string Labels map[string]string rcs map[string]bool services map[string]bool name string image string } func NewServerTest(client clientset.Interface, namespace string, serviceName string) *ServiceTestFixture { t := &ServiceTestFixture{} t.Client = client t.Namespace = namespace t.ServiceName = serviceName t.TestId = t.ServiceName + "-" + string(uuid.NewUUID()) t.Labels = map[string]string{ "testid": t.TestId, } t.rcs = make(map[string]bool) t.services = make(map[string]bool) t.name = "webserver" t.image = "gcr.io/google_containers/test-webserver:e2e" return t } // Build default config for a service (which can then be changed) func (t *ServiceTestFixture) BuildServiceSpec() *api.Service { service := &api.Service{ ObjectMeta: api.ObjectMeta{ Name: t.ServiceName, Namespace: t.Namespace, }, Spec: api.ServiceSpec{ Selector: t.Labels, Ports: []api.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, }, } return service } // CreateWebserverRC creates rc-backed pods with the well-known webserver // configuration and records it for cleanup. func (t *ServiceTestFixture) CreateWebserverRC(replicas int32) *api.ReplicationController { rcSpec := rcByNamePort(t.name, replicas, t.image, 80, api.ProtocolTCP, t.Labels, nil) rcAct, err := t.createRC(rcSpec) if err != nil { framework.Failf("Failed to create rc %s: %v", rcSpec.Name, err) } if err := framework.VerifyPods(t.Client, t.Namespace, t.name, false, replicas); err != nil { framework.Failf("Failed to create %d pods with name %s: %v", replicas, t.name, err) } return rcAct } // createRC creates a replication controller and records it for cleanup. func (t *ServiceTestFixture) createRC(rc *api.ReplicationController) (*api.ReplicationController, error) { rc, err := t.Client.Core().ReplicationControllers(t.Namespace).Create(rc) if err == nil { t.rcs[rc.Name] = true } return rc, err } // Create a service, and record it for cleanup func (t *ServiceTestFixture) CreateService(service *api.Service) (*api.Service, error) { result, err := t.Client.Core().Services(t.Namespace).Create(service) if err == nil { t.services[service.Name] = true } return result, err } // Delete a service, and remove it from the cleanup list func (t *ServiceTestFixture) DeleteService(serviceName string) error { err := t.Client.Core().Services(t.Namespace).Delete(serviceName, nil) if err == nil { delete(t.services, serviceName) } return err } func (t *ServiceTestFixture) Cleanup() []error { var errs []error for rcName := range t.rcs { By("stopping RC " + rcName + " in namespace " + t.Namespace) // First, resize the RC to 0. old, err := t.Client.Core().ReplicationControllers(t.Namespace).Get(rcName) if err != nil { errs = append(errs, err) } old.Spec.Replicas = 0 if _, err := t.Client.Core().ReplicationControllers(t.Namespace).Update(old); err != nil { errs = append(errs, err) } // TODO(mikedanese): Wait. // Then, delete the RC altogether. if err := t.Client.Core().ReplicationControllers(t.Namespace).Delete(rcName, nil); err != nil { errs = append(errs, err) } } for serviceName := range t.services { By("deleting service " + serviceName + " in namespace " + t.Namespace) err := t.Client.Core().Services(t.Namespace).Delete(serviceName, nil) if err != nil { errs = append(errs, err) } } return errs } // newEchoServerPodSpec returns the pod spec of echo server pod func newEchoServerPodSpec(podName string) *api.Pod { port := 8080 pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: podName, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: "echoserver", Image: "gcr.io/google_containers/echoserver:1.4", Ports: []api.ContainerPort{{ContainerPort: int32(port)}}, }, }, RestartPolicy: api.RestartPolicyNever, }, } return pod } // launchEchoserverPodOnNode launches a pod serving http on port 8080 to act // as the target for source IP preservation test. The client's source ip would // be echoed back by the web server. func (j *ServiceTestJig) launchEchoserverPodOnNode(f *framework.Framework, nodeName, podName string) { framework.Logf("Creating echo server pod %q in namespace %q", podName, f.Namespace.Name) pod := newEchoServerPodSpec(podName) pod.Spec.NodeName = nodeName pod.ObjectMeta.Labels = j.Labels podClient := f.ClientSet.Core().Pods(f.Namespace.Name) _, err := podClient.Create(pod) framework.ExpectNoError(err) framework.ExpectNoError(f.WaitForPodRunning(podName)) framework.Logf("Echo server pod %q in namespace %q running", pod.Name, f.Namespace.Name) } func execSourceipTest(f *framework.Framework, c clientset.Interface, ns, nodeName, serviceIP string, servicePort int) (string, string) { framework.Logf("Creating an exec pod on node %v", nodeName) execPodName := createExecPodOnNode(f.ClientSet, ns, nodeName, fmt.Sprintf("execpod-sourceip-%s", nodeName)) defer func() { framework.Logf("Cleaning up the exec pod") err := c.Core().Pods(ns).Delete(execPodName, nil) Expect(err).NotTo(HaveOccurred()) }() execPod, err := f.ClientSet.Core().Pods(ns).Get(execPodName) ExpectNoError(err) var stdout string timeout := 2 * time.Minute framework.Logf("Waiting up to %v wget %s:%d", timeout, serviceIP, servicePort) cmd := fmt.Sprintf(`wget -T 30 -qO- %s:%d | grep client_address`, serviceIP, servicePort) for start := time.Now(); time.Since(start) < timeout; time.Sleep(2) { stdout, err = framework.RunHostCmd(execPod.Namespace, execPod.Name, cmd) if err != nil { framework.Logf("got err: %v, retry until timeout", err) continue } // Need to check output because wget -q might omit the error. if strings.TrimSpace(stdout) == "" { framework.Logf("got empty stdout, retry until timeout") continue } break } ExpectNoError(err) // The stdout return from RunHostCmd seems to come with "\n", so TrimSpace is needed. // Desired stdout in this format: client_address=x.x.x.x outputs := strings.Split(strings.TrimSpace(stdout), "=") if len(outputs) != 2 { // Fail the test if output format is unexpected. framework.Failf("exec pod returned unexpected stdout format: [%v]\n", stdout) } return execPod.Status.PodIP, outputs[1] } func getLoadBalancerName(service *api.Service) string { //GCE requires that the name of a load balancer starts with a lower case letter. ret := "a" + string(service.UID) ret = strings.Replace(ret, "-", "", -1) //AWS requires that the name of a load balancer is shorter than 32 bytes. if len(ret) > 32 { ret = ret[:32] } return ret } func cleanupServiceGCEResources(loadBalancerName string) { if pollErr := wait.Poll(5*time.Second, lbCleanupTimeout, func() (bool, error) { if err := framework.CleanupGCEResources(loadBalancerName); err != nil { framework.Logf("Still waiting for glbc to cleanup: %v", err) return false, nil } return true, nil }); pollErr != nil { framework.Failf("Failed to cleanup service GCE resources.") } } func describeSvc(ns string) { framework.Logf("\nOutput of kubectl describe svc:\n") desc, _ := framework.RunKubectl( "describe", "svc", fmt.Sprintf("--namespace=%v", ns)) framework.Logf(desc) } func checkReachabilityFromPod(expectToBeReachable bool, namespace, pod, target string) { cmd := fmt.Sprintf("wget -T 5 -qO- %q", target) err := wait.PollImmediate(framework.Poll, 2*time.Minute, func() (bool, error) { _, err := framework.RunHostCmd(namespace, pod, cmd) if expectToBeReachable && err != nil { framework.Logf("Expect target to be reachable. But got err: %v. Retry until timeout", err) return false, nil } if !expectToBeReachable && err == nil { framework.Logf("Expect target NOT to be reachable. But it is reachable. Retry until timeout") return false, nil } return true, nil }) Expect(err).NotTo(HaveOccurred()) }
{ var service *api.Service var err error for i := 0; i < 3; i++ { service, err = c.Core().Services(namespace).Get(serviceName) if err != nil { return service, err } update(service) service, err = c.Core().Services(namespace).Update(service) if !errors.IsConflict(err) && !errors.IsServerTimeout(err) { return service, err } } return service, err }
topic_000000000000033A.html.js
var breadcrumbs=[['-1',"",""],['2',"VitNX3 Documentation","topic_00000000000016E1.html"],['789',"VitNX3.Functions.Win32 Namespace","topic_00000000000000C6.html"],['790',"Constants Class","topic_00000000000001C1.html"],['1979',"ResultWin32 Class","topic_00000000000001F4.html"],['1982',"Fields","topic_00000000000001F4_vars--.html"],['3086',"ERROR_JOURNAL_DELETE_IN_PROGRESS Field","topic_000000000000033A.html"]];
gen_vocab_vecs.py
import spacy, numpy, random, pickle, pandas, sys import sklearn.neighbors as nbs from spacy.lookups import load_lookups MIN_PROB = -18 #load NLP tool spaCy print("Loading spaCy...")
lookups = load_lookups("en", ["lexeme_prob"]) nlp.vocab.lookups.add_table("lexeme_prob", lookups.get_table("lexeme_prob")) #get plaintext words as list from spacy vocab. ensure they have wordvector, are lowercase, and aren't too rare print("Total number of words in spaCy vocab=",len(nlp.vocab.strings)) print("Getting words...") words = [word for word in nlp.vocab.strings if nlp.vocab.has_vector(word) and word.islower() and nlp.vocab[word].prob >= MIN_PROB] print("Retrieved ",len(words),"lowercase words with vectors and prob >=.",MIN_PROB) #get wordvectors for all words as numpy array print("Total number of wordvectors=",len(nlp.vocab.vectors)) print("Getting wordvectors...") wordvecs = numpy.array([nlp.vocab.get_vector(word) for word in words]) print("Retrieved=",len(wordvecs),"wordvectors.") #ensure the list of words corresponds to the list of wordvectors assert len(words) == len(wordvecs) spot_check = random.choice(range(0,len(words))) assert numpy.array_equal(nlp(words[spot_check]).vector,wordvecs[spot_check]) print("Spot check passed.") #pickle the entire vocab #pickle.HIGHEST_PROTOCOL depends on Python version with open('vocab.pkl', 'wb') as f: pickle.dump(words,f,protocol=4) print("Dumped vocab words to pickle file vocab.pkl") #place all wordvectors in balltree, and pickle entire tree tree = nbs.BallTree(wordvecs) with open('balltree.pkl', 'wb') as f: pickle.dump(tree,f,protocol=4) print("Dumped wordvector BallTree to pickle file balltree.pkl") #create word:vector dict and pickle it dict = dict(zip(words,wordvecs)) with open('dict.pkl', 'wb') as f: pickle.dump(dict,f,protocol=4) print("Dumped word2vec dictionary in dict.pkl")
nlp=spacy.load("en_core_web_lg") print("spaCy loaded.") #load lexeme probability table
script.py
#!/usr/bin/python3 import tkinter as tk from tkinter import * from tkinter.ttk import * from Crypto import Random from Crypto.Cipher import AES from Crypto.Hash import SHA256 import os import os.path from os import listdir from os.path import isfile, join #import time import ctypes #import threading import hashlib import random import binascii #add admin to read write C: Files try: def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if is_admin(): def initilise(): global check_file check_file = open('hyde.law','w+') check_file.write('setting_window_off') check_file.close() os.system('mkdir .hydefiles') ctypes.windll.shcore.SetProcessDpiAwareness(1) global label,window window = tk.Tk() #creates window window.tk.call('tk', 'scaling', 2.0) window.geometry("1050x380") window.resizable(width=False,height=False) window.title("Mr. Hyde") try: window.iconbitmap('hyde.ico') except: pass window.configure(bg='#333338') label = tk.Label(text = "Mr. Hyde" ,fg="#d6d6c2",bg="#333338") label.place(relx=.5,rely=.5,anchor="c") def clear_label(): label.place_forget() label1 = tk.Label(text = "Encrypt Your Files with 'AES-256'" ,fg="white",bg="#333338") label1.pack() open_files_button = tk.Button(text='Select Files',activebackground='black',highlightcolor='black',bd=1,relief='flat',height=0,width=12,fg='white',bg='#338237',command=open_files,master=window) open_files_button.pack(anchor='nw',pady=50,padx=10,side='left') password_entry = tk.Entry(width=15,show='*') password_entry.place(x=600,y=82,height=42) encrypt_button = tk.Button(text='Encrypt',activebackground='black',highlightcolor='black',bd=1,relief='flat',height=0,width=12,fg='white',bg='#338237',command=lambda:encrypt_section(password_entry,select_files_label),master=window) encrypt_button.place(x=910,y=82) decrypt_button = tk.Button(text='Decrypt',activebackground='black',highlightcolor='black',bd=1,relief='flat',height=0,width=12,fg='white',bg='#338237',command=lambda:decrypt_section(password_entry,select_files_label),master=window) decrypt_button.place(x=770,y=82) password_label = tk.Label(text='Password',fg='#d6d6c2',bg='#333338') password_label.place(x=500,y=85) select_files_label = tk.Label(text='files not selected',fg='#d6d6c2',bg='#333338') select_files_label.place(x=460,y=220) setting_button = tk.Button(text='setting',activebackground='black',highlightcolor='black',bd=1,relief='flat',height=0,width=5,fg='white',bg='#338237',command=lambda :setting_window(check_file))#,master=window) setting_button.place(x=980,y=12,height=30) def open_files():#selects files to encrypt decrypt from tkinter import filedialog global window_filename,enc_file_list,mylist,enc_file_scroll,file_to_encrypt_label enc_file_list = [] window_filename = filedialog.askopenfilenames(initialdir = "/",title = "Select file",filetypes = (("all files","*.*"),("enc files","*.enc"),("jpeg files","*.jpg"))) enc_file_list.append(window_filename) file_to_encrypt_label = tk.Label(text='Files to Encrypt',justify='left',fg='#d6d6c2',bg='#333338') enc_file_scroll = tk.Scrollbar(window,width=16,elementborderwidth=0,highlightcolor='green',bg='green',bd=0,activebackground='green') mylist = Listbox(window,width='90',height='7',yscrollcommand=enc_file_scroll.set,bg='green',bd=0,fg='#d6d6c2') if window_filename: for i in window_filename: mylist.insert(END,' ' + i) mylist.place(x='65',y='160') enc_file_scroll.place(x='975',y='160',height=185)#anchor='w',fill='y',side='right',pady=50,padx=20) file_to_encrypt_label.place(x=70,y=125) enc_file_scroll.config(command=mylist.yview) mainloop() def
(check_file):#setting window code global default_password_entry,setting check_file = open('hyde.law','r+') check_file_lines = check_file.readlines() setting_flag = check_file_lines[0] if setting_flag == 'setting_window_off': setting = tk.Tk() setting.tk.call('tk', 'scaling', 2.0) setting.geometry("570x300") setting.resizable(width=False,height=False) setting.title('Setting') setting.configure(bg='#333338') try: setting.iconbitmap('setting.ico') except: pass setting_info_label = tk.Label(bg='#333338',fg='#d6d6c2',text='Mr.Hyde uses AES-256 bit Encryption algorithm \n Users be advised',master=setting) setting_info_label.pack() default_password_label = tk.Label(bg='#333338',fg='#d6d6c2',text='Default password',master=setting) default_password_label.pack(anchor='w',padx='10',pady='30')#place(x=30,y=80) default_password_entry = tk.Entry(width='15',show='*',master=setting) default_password_entry.place(x=140,y=80) default_password_warning = tk.Label(bg='white',fg='red',text='1:The use of default password is not recommended. Remember password instead. \n 2: If you decide to use default password,\n there is no need to set a password in the main window.',master=setting) default_password_warning.place(x=10,y=150) set_default_password = tk.Button(text='set password',activebackground='black',highlightcolor='black',bd=1,relief='flat',height=0,width=13,fg='white',bg='#338237',command=set_default_password_section,master=setting)#,master=window) set_default_password.place(x=280,y=80,height=25) check_file = open('hyde.law','w+') check_file.write('setting_window_on') check_file.close() def on_closing(): #jugad pe jugad check_file = open('hyde.law','w+') check_file.write('setting_window_off') check_file.close() setting.destroy() def close_everything(): window.destroy() setting.destroy() setting.protocol('WM_DELETE_WINDOW',on_closing) window.protocol('WM_DELETE_WINDOW',close_everything) def get_default_password_section(default_password_file_list):#does what the function name says global default_key default_key = '' for file,sun in zip(default_password_file_list,range(0,8)): file_extract = open(file,'r+') file_extract = file_extract.readlines() bun= sun * 8 default_key = default_key + file_extract[0][bun:bun+8] return default_key #print(key) def set_default_password_section():#sets default password os.system('mkdir .hydefiles') global default_password_file_list default_password_file_list = ['.hydefiles/0okq7sgzt00emuwr.law','.hydefiles/dz5a0l17zehztni8.law','.hydefiles/uv8wbbi1zylip4v6.law','.hydefiles/0pk588qx1m1m5bf2.law','.hydefiles/nzlcnrcv88rrnghh.law','.hydefiles/kcf609aheo3rksm4.law','.hydefiles/q05y5cmdos60n58s.law','.hydefiles/5kcsxvpb5srx24vz.law'] default_password = default_password_entry.get() if default_password != '': salt_value = '' hex_list = ['a','b','c','d','e','f','1','2','3','4','5','6','7','8','9','0'] for salt_char in range(0,8): salt_value += random.choice(hex_list) #salt_value += salt_value #print(salt_value) salt_file = open('.hydefiles/default_salt.law','w+') salt_file.write(salt_value) salt_file.close() default_password = str(default_password+salt_value) default_key = hashlib.sha256(default_password.encode('utf-8')).hexdigest() #print(default_key) #print(default_password) for file,sun in zip(default_password_file_list,range(0,8)): seti = '' for bill in range(0,65): seti = random.choice(hex_list) + seti #print(seti) seti2 = seti #for sun in range(0,8): if sun == 0: bun = sun * 7 seti = default_key[bun:bun+8] + seti2[9:65] default_password_file = open(file,'w+') default_password_file.write(seti) default_password_file.close() #print(seti) else: bun2 = sun * 8 seti = seti2[0:bun2]+ default_key[bun2:bun2+8] + seti2[bun2+9:65] #print(seti) default_password_file = open(file,'w+') default_password_file.write(seti) default_password_file.close() #print('setting default password') else: try: import shutil shutil.rmtree('.hydefiles') MessageBox = ctypes.windll.user32.MessageBoxW MessageBox(None, 'Blank Password Not Allowed','Error', 0) except: pass check_file = open('hyde.law','w+') check_file.write('setting_window_off') check_file.close() setting.destroy() get_default_password_section(default_password_file_list) def encrypt_section(password_entry,select_files_label):#Encrypt Section try: default_password_file_list = ['.hydefiles/0okq7sgzt00emuwr.law','.hydefiles/dz5a0l17zehztni8.law','.hydefiles/uv8wbbi1zylip4v6.law','.hydefiles/0pk588qx1m1m5bf2.law','.hydefiles/nzlcnrcv88rrnghh.law','.hydefiles/kcf609aheo3rksm4.law','.hydefiles/q05y5cmdos60n58s.law','.hydefiles/5kcsxvpb5srx24vz.law'] #IV = 16 * '\x00' #mode = AES.MODE_CBC password_entry_for_encryption = password_entry.get() def pad(s): return s + b"\0" * (AES.block_size - len(s) % AES.block_size) if password_entry_for_encryption == '': key = get_default_password_section(default_password_file_list) check_sum_key = key.lower() key = binascii.unhexlify(key) #print(key) else: hex_list = ['a','b','c','d','e','f','1','2','3','4','5','6','7','8','9','0'] salt_value = '' for salt_char in range(0,8): salt_value += random.choice(hex_list) password_entry_for_encryption = password_entry_for_encryption + salt_value not_defalt_salt = open('.hydefiles/salt.law','a') key = hashlib.sha256(password_entry_for_encryption.encode('utf-8')).digest() check_sum_key = hashlib.sha256(password_entry_for_encryption.encode('utf-8')).hexdigest() not_defalt_salt.write(check_sum_key[30:36]+'---'+salt_value+'\n') not_defalt_salt.close() hex_list = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] #print(a) num = check_sum_key[30:36] ''' for hex_i in check_sum_key: for hex_b in hex_list: if hex_i == hex_b: num += hex_list.index(hex_b)# * check_sum_key.index(hex_i) ''' #print(str(num)) enc_counter = 0 progress = Progressbar(window,orient=HORIZONTAL,length=926,mode='determinate') progress.place(anchor='w',x=65,y=360) prog = 100 / len(window_filename) for file_to_encrypt in window_filename: if file_to_encrypt.endswith('.enc'): enc_counter+=1 else: progress['value'] = prog window.update_idletasks() prog = prog + prog fh = open(file_to_encrypt,'rb') message = fh.read() fh.close() message = pad(message) iv = Random.new().read(AES.block_size) cipher = AES.new(key,AES.MODE_CBC,iv) encrypted_text = iv + cipher.encrypt(message) fh = open(file_to_encrypt + str(num) + '.enc','wb') fh.write(encrypted_text) fh.close() os.remove(file_to_encrypt) #print(file_to_encrypt) if enc_counter !=0: MessageBox = ctypes.windll.user32.MessageBoxW MessageBox(None, 'Already encrypted', 'Error', 0) mylist.delete(0,END) enc_file_scroll.place_forget() mylist.place_forget() progress.place_forget() file_to_encrypt_label.place_forget() password_entry.delete(0,END) MessageBox = ctypes.windll.user32.MessageBoxW MessageBox(None, 'Selected Files Encrypted','Success', 0) #window_filename = {} except: progress.place_forget() try: mylist.place_forget() except: pass MessageBox = ctypes.windll.user32.MessageBoxW MessageBox(None, 'Select Files First', 'Error', 0) password_entry.delete(0,END) finally: pass def decrypt_section(password_entry,select_files_label):#Decrypt section try: def unpad(s): return s[:-ord(s[len(s)-1:])] default_password_file_list = ['.hydefiles/0okq7sgzt00emuwr.law','.hydefiles/dz5a0l17zehztni8.law','.hydefiles/uv8wbbi1zylip4v6.law','.hydefiles/0pk588qx1m1m5bf2.law','.hydefiles/nzlcnrcv88rrnghh.law','.hydefiles/kcf609aheo3rksm4.law','.hydefiles/q05y5cmdos60n58s.law','.hydefiles/5kcsxvpb5srx24vz.law'] password_entry_for_encryption = password_entry.get() if password_entry_for_encryption == '': key = get_default_password_section(default_password_file_list) check_sum_key = key.lower() key = binascii.unhexlify(key) #print(key) else: not_defalt_salt = open('.hydefiles/salt.law','r+') salt_lines = not_defalt_salt.readlines() #salt_lines = salt_lines[0].strip(' ') #print(salt_lines) for check_salt_value in salt_lines: for file_to_check in window_filename: if str(check_salt_value[0:6]) == str(file_to_check[-10:-4]): #print('here') salt_lines = check_salt_value[-9:-1] #print(salt_lines) #print(check_salt_value) #ashdkjahsdjh = input("inpput here") #print(str(file_to_check[-10:-4])+'---'+check_salt_value[0:6]) password_entry_for_encryption2 = password_entry_for_encryption password_entry_for_encryption = password_entry_for_encryption + salt_lines key = hashlib.sha256(password_entry_for_encryption.encode('utf-8')).digest() check_sum_key = hashlib.sha256(password_entry_for_encryption.encode('utf-8')).hexdigest() hex_list = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] #print(a) num = str(check_sum_key[30:36]).strip(' ') #print(num+'---'+salt_lines) #asdasdasrca = input('here2') ''' for hex_i in check_sum_key: for hex_b in hex_list: if hex_i == hex_b: num += hex_list.index(hex_b) ''' invalid_counter = 0 progress = Progressbar(window,orient=HORIZONTAL,length=926,mode='determinate') progress.place(anchor='w',x=65,y=360) prog = 100 / len(window_filename) for file_to_decrypt in window_filename: #print(str(file_to_decrypt[-10:-4])) if num == str(file_to_decrypt[-10:-4]): progress['value'] = prog window.update_idletasks() prog = prog + prog fd = open(file_to_decrypt,'rb') message = fd.read() fd.close() iv = message[:AES.block_size] cipher = AES.new(key,AES.MODE_CBC,iv) plaintext = cipher.decrypt(message[AES.block_size:]) write_message = plaintext.rstrip(b"\0") remove_file = file_to_decrypt file_to_decrypt = file_to_decrypt[0:-10] fd = open(file_to_decrypt,'wb') fd.write(write_message) fd.close() os.remove(remove_file) else: #print('key_invalid') invalid_counter +=1 #entry1.delete(0,tk.END) if invalid_counter != 0 : MessageBox = ctypes.windll.user32.MessageBoxW MessageBox(None, 'Invalid key used for '+str(invalid_counter)+' files','Error', 0) progress.place_forget() password_entry.delete(0,END) else: file_to_encrypt_label.place_forget() enc_file_scroll.place_forget() mylist.place_forget() progress.place_forget() password_entry.delete(0,END) MessageBox = ctypes.windll.user32.MessageBoxW MessageBox(None, 'Selected Files Decrypted','Success', 0) except: progress.place_forget() try: mylist.place_forget() except: pass MessageBox = ctypes.windll.user32.MessageBoxW MessageBox(None, 'Select Files First', 'Error', 0) password_entry.delete(0,END) finally: pass #window_filename = {} #print(window_filename) initilise() #initialise window label.after(3000,clear_label) #app_name label intro window.mainloop() else: ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1) is_admin() except IOError as e: error_file = open('error.log','a+') error_file.write(e+'\n') error_file.close()
setting_window
merge_two_sorted_lists.py
""" Enlace al problema: https://leetcode.com/problems/merge-two-sorted-lists/ Si deseas probar la solución sólo tienes que copiar la clase Solution ya que dicha clase es la que se ejecuta en la plataforma de LeetCode. """ class ListNode:
self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: headOne, headTwo = l1, l2 merged = ListNode(0) newHead = merged while headOne and headTwo: if headOne.val <= headTwo.val: newHead.next = headOne headOne = headOne.next else: newHead.next = headTwo headTwo = headTwo.next newHead = newHead.next remainElements = headTwo if not headOne else headOne newHead.next = remainElements return merged.next if __name__ == "__main__": l1 = ListNode(1) l1.next = ListNode(2) l1.next.next = ListNode(4) l2 = ListNode(1) l2.next = ListNode(3) l2.next.next = ListNode(4) solution = Solution() print(solution.mergeTwoLists(l1, l2))
def __init__(self, val=0, next=None): self.val = val
filesystem.go
package provider import ( "context" "io" "net/http" "os" ) // Filesystem provides a way to load files from the filesystem. type Filesystem struct { Dir http.Dir } // Provide provides a file via the virtual http.Dir filesystem. func (fp *Filesystem) Provide(ctx context.Context, filename string) (io.ReadCloser, error) { // Try to open the image from the virtual filesystem. f, err := fp.Dir.Open(filename) if err != nil
return f, nil }
{ if _, ok := err.(*os.PathError); ok { return nil, ErrNotFound } return nil, err }
noticia.dto.ts
export class
{ created_at: string; title: string; author: string; }
NoticiasDTO
main.py
import time from datetime import datetime from requests import Response import json import os import TunnelSSH import Helpers import SettingsStorage import sys def create_tunnel(tun: dict): timeout_time: datetime = datetime.fromisoformat(tun["timeout_time"]) if timeout_time <= datetime.utcnow(): Helpers.log_that("Tunnel already not valid") return if tun["connection_type"] == Helpers.ConnectionTypeEnum.ssh_tunnel: TunnelSSH.create_ssh_tunnel(tun) def destroy_tunnel(tun: dict): if tun["connection_type"] == Helpers.ConnectionTypeEnum.ssh_tunnel: TunnelSSH.destroy_ssh_tunnel(tun) def destroy_expired_tunnels():
def act_on_tunnel(tun: dict): Helpers.log_that(tun) tunnel_id: int = tun["id"] type: Helpers.ConnectionTypeEnum = tun["connection_type"] state: Helpers.ConnectionStateEnum = tun["connection_state"] port_to_tunnel: int = tun["port_to_tunnel"] timeout_time: datetime = tun["timeout_time"] temporaray_pubkey: str = tun["temporary_pubkey_for_agent_ssh"] remote_ssh_server: str = tun["remote_ssh_server"] remote_ssh_fingerprint: str = tun["remote_ssh_fingerprint"] remote_ssh_username: str = tun["remote_ssh_fingerprint"] reverse_port: int = tun["reverse_port"] remote_ssh_port: int = tun["remote_ssh_port"] temporary_tunnel_privkey: str = tun["temporary_tunnel_privkey"] if state == Helpers.ConnectionStateEnum.connected: # first check what should we do: Helpers.log_that("Requesting connection that should already be connected, ignore") return elif state == Helpers.ConnectionStateEnum.requested: Helpers.log_that("Requesting new connection, act upon that!") create_tunnel(tun) elif state == Helpers.ConnectionStateEnum.disconnect_requested: Helpers.log_that("Requesting to destroy the connection id {}".format(tunnel_id)) destroy_tunnel(tun) def parse_success_resp(resp: Response): j: dict = resp.json() keys = j.keys() if "message" in keys and len(j["message"]) > 0: Helpers.log_that(j["message"]) if "tunnels_requesting_action" in keys and len(j["tunnels_requesting_action"]) > 0: Helpers.log_that("There are {} tunnels requesting action:".format(len(j["tunnels_requesting_action"]))) for tun in j["tunnels_requesting_action"]: act_on_tunnel(tun) def main(): # Our small local "db" consisting of Tunnels which are active while True: # Do this all the time try: # First check if this is installed, if not, send the installation data if not SettingsStorage.is_installed: resp: Response = Helpers.ReqSession.post(SettingsStorage.server_url + "/agents/agent_install", json=Helpers.get_install_json()) if resp.status_code == 200: SettingsStorage.is_installed = True SettingsStorage.datajson["is_installed"] = True Helpers.log_that("Successfully Installed!") else: msg = "" if "detail" in resp.json().keys(): msg = resp.json()["detail"] Helpers.log_that( "Error when trying to install the agent. Code {}, with message {}".format(str(resp.status_code), msg)) # First check if we have any Tunnel that should be disconnected TBD destroy_expired_tunnels() Helpers.remove_expired_ssh_auth_keys() resp: Response = Helpers.ReqSession.post(SettingsStorage.server_url + "/agents/query", json=Helpers.get_query_json()) if resp.status_code == 200: parse_success_resp(resp) else: msg = "" if "detail" in resp.json().keys(): msg = resp.json()["detail"] Helpers.log_that( "Error when querying the API. Code {}, with message {}".format(str(resp.status_code), msg)) except ValueError as e: Helpers.log_that("Could not process some value" + str(e.args)) except Exception as e: Helpers.log_that("Could not connect to server " + str(e.args)) datafile = open(os.path.join(sys.path[0], "data.json"), "w") json.dump(SettingsStorage.datajson, datafile) datafile.close() time.sleep(SettingsStorage.interval_seconds) if __name__ == "__main__": # execute only if run as a script main()
for tun in SettingsStorage.datajson["tunnels"]: timeout_time: datetime = datetime.fromisoformat(tun["timeout_time"]) if timeout_time <= datetime.utcnow(): Helpers.log_that("A tunnel has expired, destroy") destroy_tunnel(tun)
TriggerDeployment.py
# #Copyright 2020 XEBIALABS # #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 sys import time import com.xhaus.jyson.JysonCodec as json print "Executing triggerBambooDeployment.py\n" if bambooServer is None: print "No server provided." sys.exit(1) contentType = 'application/json' headers = {'accept' : 'application/json'} def
(projectName): print "Executing getProjectId() with projectName %s\n" % projectName response = request.get('rest/api/latest/deploy/project/all', contentType=contentType, headers=headers) for item in json.loads(response.response): if item['name'] == projectName: print "Project ID for %s is %s\n" % (projectName, item['id']) return item['id'] print "Error: project not found for %s\n" % projectName sys.exit(1) def getEnvironmentId(projectId, environmentName): print "Executing getEnvironmentId() with projectId %s and environmentName %s\n" % (projectId, environmentName) response = request.get('rest/api/latest/deploy/project/%s' % projectId, contentType=contentType, headers=headers) for item in json.loads(response.response)['environments']: if item['name'] == environmentName: print "Environment ID for %s is %s\n" % (environmentName, item['id']) return item['id'] print "Error: environment not found for %s, %s\n" % (projectName, environmentName) sys.exit(1) def getVersionId(projectId, versionName): print "Executing getVersionId() with projectId %s and versionName %s\n" % (projectId, versionName) response = request.get('rest/api/latest/deploy/project/%s/versions' % projectId, contentType=contentType, headers=headers) for item in json.loads(response.response)['versions']: if item['name'] == versionName: print "Version ID for %s is %s\n" % (versionName, item['id']) return item['id'] print "Error: version not found for %s, %s, %s\n" % (projectName, environmentName, versionName) sys.exit(1) def triggerDeployment(environmentId, versionId): print "Executing triggerDeployment() with environmentId %s and versionId %s\n" % (environmentId, versionId) response = request.post('rest/api/latest/queue/deployment?environmentId=%s&versionId=%s' % (environmentId, versionId), '{}', contentType=contentType, headers=headers) result = json.loads(response.response) print (result['deploymentResultId'], result['link']['href']) return (result['deploymentResultId'], result['link']['href']) credentials = CredentialsFallback(bambooServer, username, password).getCredentials() request = HttpRequest(bambooServer, credentials['username'], credentials['password']) projectId = getProjectId(projectName) environmentId = getEnvironmentId(projectId, environmentName) versionId = getVersionId(projectId, versionName) (deploymentResultId, href) = triggerDeployment(environmentId, versionId)
getProjectId
memory_test.go
package memory import ( "fmt" "io/ioutil" "os" "path/filepath" "testing" "time" "github.com/stretchr/testify/assert" "github.com/yunfeiyang1916/toolkit/framework/config/encoder/json" "github.com/yunfeiyang1916/toolkit/framework/config/reader/toml" "github.com/yunfeiyang1916/toolkit/framework/config/source" "github.com/yunfeiyang1916/toolkit/framework/config/source/file" ) type Hosts struct { Database struct { Address string `json:"address"` Port float64 `json:"port"` //json的整型在golang是float64 } `json:"database"` } type JsonData struct { Data Hosts `json:"hosts" toml:"hosts"` } func createFile(fileType string) *os.File { path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d.%s", time.Now().UnixNano(), fileType)) fh, err := os.Create(path) if err != nil { fmt.Println(err) } return fh } func TestMemory_Listen(t *testing.T) { data1 := []byte(`{ "hosts": { "database": { "address": "10.0.0.1", "port": 3306 } } }`) _ = data1 data2 := []byte(`{ "hosts": { "database": { "address": "101.0.0.2", "port": 3306 } } }`) _ = data2 f1 := createFile("json") defer func() { f1.Close() os.Remove(f1.Name()) }() err := ioutil.WriteFile(f1.Name(), []byte(data2), 0644) if err != nil { t.Fatal(err) } go func() { tick := time.NewTicker(500 * time.Millisecond) change := make(chan bool, 1) value := true for { select { case <-tick.C: change <- value case v := <-change: var data []byte if v { data = data1 value = false //下次用data2 } else { data = data2 value = true //下次用data1 } err := ioutil.WriteFile(f1.Name(), []byte(data), 0644) if err != nil { t.Fatal(err) } fmt.Println("file had lisChan...") } } }() time.Sleep(1 * time.Second) s := file.NewSource( file.WithPath(f1.Name()), source.WithEncoder(json.NewEncoder())) m := NewLoader() m.Load(s) m.Sync() sp, _ := m.Snapshot() //fmt.Println(sp.ChangeSet.Data) w, err := m.Watch("hosts", "database") if err != nil { panic(err) } go func() { sp1, err := w.Next() if err == nil { fmt.Println(">>>>>>", sp1.ChangeSet) } }() time.Sleep(5 * time.Second) w.Stop() reader := toml.NewReader() v, _ := reader.Values(sp.ChangeSet) j := &JsonData{} v.Scan(j) fmt.Println(j) r := m.Listen(j) time.Sleep(100 * time.Millisecond) port := r.Load().(*JsonData).Data.Database.Port m.Close()
assert.Equal(t, int(port), 3306) }
willplus_arc.rs
use std::{ fs::File, io::Write, path::{Path, PathBuf}, }; use super::Scheme; use crate::archive::{self, FileContents, NavigableDirectory}; use anyhow::Context; use bytes::BytesMut; use positioned_io::RandomAccessFile; use positioned_io_preview::ReadAt; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use scroll::{ctx, Pread, LE}; #[derive(Debug, Clone)] pub enum ArcScheme { Universal, } impl Scheme for ArcScheme { fn extract( &self, file_path: &Path, ) -> anyhow::Result<(Box<dyn crate::archive::Archive>, NavigableDirectory)> { let mut buf = vec![0; 8]; let file = RandomAccessFile::open(file_path)?; file.read_exact_at(0, &mut buf)?; let header = buf.pread_with::<ArcHeader>(0, LE)?; log::debug!("Header: {:#?}", header); let mut file_entries = Vec::with_capacity(header.entry_count as usize); buf.resize(header.entries_size as usize, 0); file.read_exact_at(8, &mut buf)?; let off = &mut 0; for _ in 0..header.entry_count { file_entries.push(buf.gread::<ArcFileEntry>(off)?); } let root_dir = ArcArchive::new_root_dir(&file_entries); let navigable_dir = archive::NavigableDirectory::new(root_dir); Ok(( Box::new(ArcArchive { file, header, file_entries, }), navigable_dir, )) } fn
(&self) -> String { format!( "[WILLPLUS ARC] {}", match self { Self::Universal => "Universal", } ) } fn get_schemes() -> Vec<Box<dyn Scheme>> where Self: Sized, { vec![Box::new(Self::Universal)] } } #[derive(Debug)] struct ArcArchive { file: RandomAccessFile, header: ArcHeader, file_entries: Vec<ArcFileEntry>, } impl archive::Archive for ArcArchive { fn extract( &self, entry: &archive::FileEntry, ) -> anyhow::Result<archive::FileContents> { self.file_entries .iter() .find(|e| e.full_path == entry.full_path) .map(|e| self.extract(e)) .context("File not found")? } fn extract_all(&self, output_path: &Path) -> anyhow::Result<()> { self.file_entries.par_iter().try_for_each(|entry| { let file_contents = self.extract(entry)?; let mut output_file_name = PathBuf::from(output_path); output_file_name.push(&entry.full_path); std::fs::create_dir_all( &output_file_name .parent() .context("Could not get parent directory")?, )?; log::debug!( "Extracting resource: {:?} {:X?}", output_file_name, entry ); File::create(output_file_name)? .write_all(&file_contents.contents)?; Ok(()) }) } } impl ArcArchive { fn new_root_dir(entries: &[ArcFileEntry]) -> archive::Directory { archive::Directory::new( entries .iter() .map(|entry| { let file_offset = entry.file_offset as u64; let file_size = entry.file_size as u64; archive::FileEntry { file_name: entry .full_path .to_str() .expect("Not valid UTF-8") .to_string(), full_path: entry.full_path.clone(), file_offset, file_size, } }) .collect(), ) } fn extract(&self, entry: &ArcFileEntry) -> anyhow::Result<FileContents> { let mut buf = BytesMut::with_capacity(entry.file_size as usize); buf.resize(entry.file_size as usize, 0); self.file.read_exact_at( 8 + self.header.entries_size as u64 + entry.file_offset as u64, &mut buf, )?; Ok(FileContents { contents: buf.freeze(), type_hint: None, }) } } #[derive(Debug, Pread, Copy, Clone)] struct ArcHeader { entry_count: u32, entries_size: u32, } #[derive(Debug)] struct ArcFileEntry { file_size: u32, file_offset: u64, full_path: PathBuf, } impl<'a> ctx::TryFromCtx<'a, ()> for ArcFileEntry { type Error = anyhow::Error; fn try_from_ctx( buf: &'a [u8], _ctx: (), ) -> Result<(Self, usize), Self::Error> { let off = &mut 0; let file_size = buf.gread_with::<u32>(off, LE)?; let file_offset = buf.gread_with::<u32>(off, LE)? as u64; let name = &buf[*off..] .chunks_exact(2) .take_while(|c| !(c[0] == 0 && c[1] == 0)) .map(|c| c[0] as u16 + ((c[1] as u16) << 8)) .collect::<Vec<u16>>(); let full_path = PathBuf::from(String::from_utf16(name)?); *off += name.len() * 2 + 2; Ok(( ArcFileEntry { file_size, file_offset, full_path, }, *off, )) } }
get_name
useDestinations.js
import { graphql, useStaticQuery } from 'gatsby'; export default function
() { const { gcms = {} } = useStaticQuery( graphql` query { gcms { destinations { id name peakNumber winter location { latitude longitude } } } } ` ); let { destinations } = gcms; return { destinations, }; }
useDestinations
lib.rs
#[derive(Debug)] pub struct HorizontalPosition(i32); #[derive(Debug)] pub enum MovementCostStrategy { Fixed, Linear, } #[derive(Debug)] pub struct PositionCost { pub position: HorizontalPosition, pub cost: i32, } #[derive(Debug)] pub struct CrabSwarm { crab_positions: Vec<HorizontalPosition>, } impl From<&Vec<i32>> for CrabSwarm { fn from(crab_positions: &Vec<i32>) -> Self { CrabSwarm { crab_positions: crab_positions .iter() .map(|x| HorizontalPosition(*x)) .collect(), } } } impl CrabSwarm { pub fn get_alignment_cost( &self, position: &HorizontalPosition, strategy: &MovementCostStrategy, ) -> i32 { let HorizontalPosition(x1) = position; let costs = self.crab_positions.iter().map(|HorizontalPosition(x2)| { let distance = (x1 - x2).abs(); match strategy { &MovementCostStrategy::Fixed => distance, &MovementCostStrategy::Linear => (0..=distance).sum(), } }); costs.sum() } pub fn get_best_alignment(&self, strategy: &MovementCostStrategy) -> PositionCost { let min_position = self .crab_positions .iter() .map(|HorizontalPosition(x)| *x) .min() .unwrap_or(0); let max_position = self .crab_positions .iter() .map(|HorizontalPosition(x)| *x) .max() .unwrap_or(0); let candidates: Vec<PositionCost> = (min_position..=max_position) .map(|x| { let position = HorizontalPosition(x); let cost = self.get_alignment_cost(&position, strategy); PositionCost { position, cost } }) .collect(); candidates .into_iter() .min_by(|left, right| left.cost.cmp(&right.cost)) .unwrap() } } #[cfg(test)] mod test { use super::*; #[test] fn it_matches_fixed_cost_fixture() { let swarm = CrabSwarm::from(&vec![16, 1, 2, 0, 4, 2, 7, 1, 2, 14]); assert_eq!( swarm.get_alignment_cost(&HorizontalPosition(2), &MovementCostStrategy::Fixed), 37 ); assert_eq!( swarm.get_alignment_cost(&HorizontalPosition(1), &MovementCostStrategy::Fixed), 41 ); assert_eq!( swarm.get_alignment_cost(&HorizontalPosition(3), &MovementCostStrategy::Fixed), 39 ); assert_eq!( swarm.get_alignment_cost(&HorizontalPosition(10), &MovementCostStrategy::Fixed), 71 ); let PositionCost { position, cost } = swarm.get_best_alignment(&MovementCostStrategy::Fixed); assert_eq!(position.0, 2); assert_eq!(cost, 37); } #[test] fn
() { let swarm = CrabSwarm::from(&vec![16, 1, 2, 0, 4, 2, 7, 1, 2, 14]); assert_eq!( swarm.get_alignment_cost(&HorizontalPosition(5), &MovementCostStrategy::Linear), 168 ); assert_eq!( swarm.get_alignment_cost(&HorizontalPosition(2), &MovementCostStrategy::Linear), 206 ); let PositionCost { position, cost } = swarm.get_best_alignment(&MovementCostStrategy::Linear); assert_eq!(position.0, 5); assert_eq!(cost, 168); } }
it_matches_linear_cost_fixture
models.py
from typing import Any, Dict, Protocol, Tuple from django.db import models from examples.models import Example from labels.models import Category, Relation, Span, TextLabel from projects.models import Project DATA = "data" class ExportedExampleManager(models.Manager): def confirmed(self, project: Project, user=None): if project.collaborative_annotation: return self.filter(project=project).exclude(states=None) else: assert user is not None return self.filter(project=project, states__confirmed_by=user) class ExportedExample(Example): objects = ExportedExampleManager() def to_dict(self, is_text_project=True) -> Dict[str, Any]: return {"id": self.id, DATA: self.text if is_text_project else self.upload_name, **self.meta} class Meta: proxy = True class ExportedLabel(Protocol): objects: models.Manager def
(self) -> Dict[str, Any]: raise NotImplementedError("Please implement this method in the subclass.") def to_string(self) -> str: raise NotImplementedError("Please implement this method in the subclass.") def to_tuple(self) -> Tuple: raise NotImplementedError("Please implement this method in the subclass.") class ExportedCategory(Category): def to_string(self) -> str: return self.label.text class Meta: proxy = True class ExportedSpan(Span): def to_dict(self): return { "id": self.id, "label": self.label.text, "start_offset": self.start_offset, "end_offset": self.end_offset, } def to_tuple(self): return self.start_offset, self.end_offset, self.label.text class Meta: proxy = True class ExportedRelation(Relation): def to_dict(self): return {"id": self.id, "from_id": self.from_id.id, "to_id": self.to_id.id, "type": self.type.text} class Meta: proxy = True class ExportedText(TextLabel): def to_string(self) -> str: return self.text class Meta: proxy = True
to_dict
tag.js
'use strict'; module.exports = (sequelize, DataTypes) => {
tag.associate = function(models) { // associations can be defined here tag.belongsToMany(models.bookmark, { through: 'bookmark_tags', onDelete: "CASCADE" }) }; return tag; };
const tag = sequelize.define('tag', { name: DataTypes.STRING, }, {});
get_public_ip_address.py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs __all__ = [ 'GetPublicIPAddressResult', 'AwaitableGetPublicIPAddressResult', 'get_public_ip_address', ] @pulumi.output_type class GetPublicIPAddressResult: """ Public IP address resource. """ def
(__self__, dns_settings=None, etag=None, id=None, idle_timeout_in_minutes=None, ip_address=None, ip_configuration=None, location=None, name=None, provisioning_state=None, public_ip_address_version=None, public_ip_allocation_method=None, resource_guid=None, tags=None, type=None): if dns_settings and not isinstance(dns_settings, dict): raise TypeError("Expected argument 'dns_settings' to be a dict") pulumi.set(__self__, "dns_settings", dns_settings) if etag and not isinstance(etag, str): raise TypeError("Expected argument 'etag' to be a str") pulumi.set(__self__, "etag", etag) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if idle_timeout_in_minutes and not isinstance(idle_timeout_in_minutes, int): raise TypeError("Expected argument 'idle_timeout_in_minutes' to be a int") pulumi.set(__self__, "idle_timeout_in_minutes", idle_timeout_in_minutes) if ip_address and not isinstance(ip_address, str): raise TypeError("Expected argument 'ip_address' to be a str") pulumi.set(__self__, "ip_address", ip_address) if ip_configuration and not isinstance(ip_configuration, dict): raise TypeError("Expected argument 'ip_configuration' to be a dict") pulumi.set(__self__, "ip_configuration", ip_configuration) if location and not isinstance(location, str): raise TypeError("Expected argument 'location' to be a str") pulumi.set(__self__, "location", location) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if public_ip_address_version and not isinstance(public_ip_address_version, str): raise TypeError("Expected argument 'public_ip_address_version' to be a str") pulumi.set(__self__, "public_ip_address_version", public_ip_address_version) if public_ip_allocation_method and not isinstance(public_ip_allocation_method, str): raise TypeError("Expected argument 'public_ip_allocation_method' to be a str") pulumi.set(__self__, "public_ip_allocation_method", public_ip_allocation_method) if resource_guid and not isinstance(resource_guid, str): raise TypeError("Expected argument 'resource_guid' to be a str") pulumi.set(__self__, "resource_guid", resource_guid) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter(name="dnsSettings") def dns_settings(self) -> Optional['outputs.PublicIPAddressDnsSettingsResponse']: """ The FQDN of the DNS record associated with the public IP address. """ return pulumi.get(self, "dns_settings") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter(name="idleTimeoutInMinutes") def idle_timeout_in_minutes(self) -> Optional[int]: """ The idle timeout of the public IP address. """ return pulumi.get(self, "idle_timeout_in_minutes") @property @pulumi.getter(name="ipAddress") def ip_address(self) -> Optional[str]: return pulumi.get(self, "ip_address") @property @pulumi.getter(name="ipConfiguration") def ip_configuration(self) -> 'outputs.IPConfigurationResponse': """ IPConfiguration """ return pulumi.get(self, "ip_configuration") @property @pulumi.getter def location(self) -> Optional[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="publicIPAddressVersion") def public_ip_address_version(self) -> Optional[str]: """ The public IP address version. Possible values are: 'IPv4' and 'IPv6'. """ return pulumi.get(self, "public_ip_address_version") @property @pulumi.getter(name="publicIPAllocationMethod") def public_ip_allocation_method(self) -> Optional[str]: """ The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. """ return pulumi.get(self, "public_ip_allocation_method") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> Optional[str]: """ The resource GUID property of the public IP resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") class AwaitableGetPublicIPAddressResult(GetPublicIPAddressResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetPublicIPAddressResult( dns_settings=self.dns_settings, etag=self.etag, id=self.id, idle_timeout_in_minutes=self.idle_timeout_in_minutes, ip_address=self.ip_address, ip_configuration=self.ip_configuration, location=self.location, name=self.name, provisioning_state=self.provisioning_state, public_ip_address_version=self.public_ip_address_version, public_ip_allocation_method=self.public_ip_allocation_method, resource_guid=self.resource_guid, tags=self.tags, type=self.type) def get_public_ip_address(expand: Optional[str] = None, public_ip_address_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPublicIPAddressResult: """ Public IP address resource. :param str expand: Expands referenced resources. :param str public_ip_address_name: The name of the subnet. :param str resource_group_name: The name of the resource group. """ __args__ = dict() __args__['expand'] = expand __args__['publicIpAddressName'] = public_ip_address_name __args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:network/v20161201:getPublicIPAddress', __args__, opts=opts, typ=GetPublicIPAddressResult).value return AwaitableGetPublicIPAddressResult( dns_settings=__ret__.dns_settings, etag=__ret__.etag, id=__ret__.id, idle_timeout_in_minutes=__ret__.idle_timeout_in_minutes, ip_address=__ret__.ip_address, ip_configuration=__ret__.ip_configuration, location=__ret__.location, name=__ret__.name, provisioning_state=__ret__.provisioning_state, public_ip_address_version=__ret__.public_ip_address_version, public_ip_allocation_method=__ret__.public_ip_allocation_method, resource_guid=__ret__.resource_guid, tags=__ret__.tags, type=__ret__.type)
__init__
struct_object_in_list_project_custom_fields.go
package devops_rdc
//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 Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // ObjectInListProjectCustomFields is a nested struct in devops_rdc response type ObjectInListProjectCustomFields struct { CustomField []CustomField `json:"CustomField" xml:"CustomField"` }
//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 //
process_unvote.rs
use crate::{ error::GovernanceError, state::{ enums::ProposalState, proposal::get_proposal_data, scopes::scope::get_scope_data_for_governance, vote_power_owner_record::get_vote_power_owner_record_data_for_owner, vote_record::{get_vote_record_data_for_proposal_and_token_owner, VoteRecordV2}, }, }; use shared::account::{dispose_account, get_account_data}; use solana_program::{ account_info::{next_account_info, AccountInfo}, clock::Clock, entrypoint::ProgramResult, msg, pubkey::Pubkey, sysvar::Sysvar, }; pub fn process_uncast_vote(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult { let accounts_iter = &mut accounts.iter(); let proposal_info = next_account_info(accounts_iter)?; let vote_record_info = next_account_info(accounts_iter)?; let vote_power_owner_record_info = next_account_info(accounts_iter)?; let governing_owner_record_info = next_account_info(accounts_iter)?; let scope_info = next_account_info(accounts_iter)?; let proposal = get_proposal_data(program_id, proposal_info)?; let scope = get_scope_data_for_governance(program_id, scope_info, &proposal.governance)?; let mut token_owner_record_data = get_vote_power_owner_record_data_for_owner( program_id, vote_power_owner_record_info, governing_owner_record_info, )?; let mut vote_record_data = get_vote_record_data_for_proposal_and_token_owner( program_id, vote_record_info, proposal_info.key, governing_owner_record_info, )?; vote_record_data.assert_can_relinquish_vote()?; let clock = Clock::get()?; // If the Proposal is still being voted on then the token owner vote will be withdrawn and it won't count towards the vote outcome // Note: If there is no tipping point the proposal can be still in Voting state but already past the configured max_voting_time // It means it awaits manual finalization (FinalizeVote) and it should no longer be possible to withdraw the vote and we only release the tokens if proposal.state == ProposalState::Voting && !proposal.has_vote_time_ended(&scope.config.time_config, clock.unix_timestamp) { let beneficiary_info = next_account_info(accounts_iter)?; // Note: It's only required to sign by governing_authority if relinquishing the vote results in vote change // If the Proposal is already decided then anybody can prune active votes for token owner token_owner_record_data .assert_token_owner_or_delegate_is_signer(governing_owner_record_info)?; vote_record_data.assert_vote_equals(&proposal.perform_voting( program_id, vote_record_data.vote_weight, false, &token_owner_record_data.source, scope_info.key, &scope, proposal_info.key, accounts_iter, )?)?; proposal.serialize(&mut *proposal_info.data.borrow_mut())?; dispose_account(vote_record_info, beneficiary_info); // Connect adjacent votes (TODO cleanup this mess) let previous = if let Some(previous_vote) = vote_record_data.previous_vote { let vote_record_info = next_account_info(accounts_iter)?; if &previous_vote != vote_record_info.key { return Err(GovernanceError::InvalidVoteRecord.into()); } let vote_record_data = get_account_data::<VoteRecordV2>(program_id, vote_record_info)?; Some((vote_record_info, vote_record_data)) } else { None }; let next = if let Some(next_vote) = vote_record_data.next_vote
else { None }; if previous.is_some() && next.is_some() { let mut previous = previous.unwrap(); let mut next = next.unwrap(); previous.1.next_vote = Some(*next.0.key); previous.1.serialize(&mut *previous.0.data.borrow_mut())?; next.1.previous_vote = Some(*previous.0.key); next.1.serialize(&mut *next.0.data.borrow_mut())?; } else if previous.is_some() { let mut previous = previous.unwrap(); previous.1.next_vote = None; previous.1.serialize(&mut *previous.0.data.borrow_mut())?; } else if next.is_some() { let mut next = next.unwrap(); next.1.previous_vote = None; next.1.serialize(&mut *next.0.data.borrow_mut())?; token_owner_record_data.first_vote = Some(*next.0.key); } else { // None, None token_owner_record_data.first_vote = None; } // Update total votes counts token_owner_record_data.total_votes_count = token_owner_record_data .total_votes_count .checked_sub(1) .unwrap(); } else { vote_record_data.is_relinquished = true; vote_record_data.serialize(&mut *vote_record_info.data.borrow_mut())?; } // If the Proposal has been already voted on then we only have to decrease unrelinquished_votes_count token_owner_record_data.unrelinquished_votes_count = token_owner_record_data .unrelinquished_votes_count .checked_sub(1) .unwrap(); token_owner_record_data.serialize(&mut *vote_power_owner_record_info.data.borrow_mut())?; msg!("XXXXX"); Ok(()) }
{ let vote_record_info = next_account_info(accounts_iter)?; if &next_vote != vote_record_info.key { return Err(GovernanceError::InvalidVoteRecord.into()); } let vote_record_data = get_account_data::<VoteRecordV2>(program_id, vote_record_info)?; Some((vote_record_info, vote_record_data)) }
compiler.go
package main import ( "bytes" "encoding/json" "fmt" "os/exec" "syscall" "time" "github.com/si9ma/KillOJ-common/codelang" "github.com/si9ma/KillOJ-common/tip" "github.com/si9ma/KillOJ-common/judge" log "github.com/sirupsen/logrus" "github.com/urfave/cli" ) var COMPILER_TIMEOUT_ERR error var COMPILER_RUN_ERR error var compileCmd = cli.Command{ Name: "compile", Usage: "compile source code", Description: `The compile command use to compile source code`, Flags: []cli.Flag{ cli.StringFlag{ Name: "lang", Value: "", Usage: `language of source code`, }, cli.StringFlag{ Name: "base-dir,dir", Value: "", Usage: "base directory of source code", }, cli.StringFlag{ Name: "src,s", Value: "", Usage: "source code file", }, cli.IntFlag{ Name: "timeout", Value: 60000, Usage: "compile timeout in milliseconds", }, }, Action: func(ctx *cli.Context) error { compiler := NewCompiler(ctx) defer compiler.handleResult() if compiler.err != nil { return nil // error from NewCompiler(ctx) } // lang/dir/src is required if compiler.err = checkCmdStrArgsExist(ctx, []string{"lang", "dir", "src"}); compiler.err != nil
// compile time limit time.AfterFunc(time.Duration(compiler.timeout)*time.Millisecond, func() { if compiler.cmd.Process != nil { COMPILER_TIMEOUT_ERR = fmt.Errorf("compile too long(limit %dms)", compiler.timeout) compiler.err = COMPILER_TIMEOUT_ERR _ = syscall.Kill(-compiler.cmd.Process.Pid, syscall.SIGKILL) } }) if err := compiler.cmd.Run(); err != nil { COMPILER_RUN_ERR = err compiler.err = COMPILER_RUN_ERR } return nil // return nil, handle error by self }, } type Lang struct { Command string SubCommand string Args []string } var langCompilerMap = map[string]Lang{ codelang.LangC.Name: { Command: "/usr/bin/gcc", Args: []string{"-save-temps", "-std=c11", "-fmax-errors=10", "-static", "-o", "Main"}, }, codelang.LangCPP.Name: { Command: "/usr/bin/g++", Args: []string{"-save-temps", "-std=c++11", "-fmax-errors=10", "-static", "-o", "Main"}, }, codelang.LangGo.Name: { Command: "/usr/bin/go", SubCommand: "build", Args: []string{"-o", "Main"}, }, codelang.LangJava.Name: { Command: "/usr/bin/javac", Args: []string{"-J-Xmx500m", "-Xmaxwarns", "10", "-Xmaxerrs", "10"}, // heap memory limit to 500m, max error and warn limit to 10 }, } type Compiler struct { id string lang string err error cmd *exec.Cmd // compiler cmd baseDir string src string // source code file name stdOut bytes.Buffer stdErr bytes.Buffer timeout int64 // timeout in ms } func NewCompiler(ctx *cli.Context) *Compiler { compiler := &Compiler{ id: getGlbString(ctx, "id"), lang: getString(ctx, "lang"), baseDir: getString(ctx, "dir"), src: getString(ctx, "src"), timeout: ctx.Int64("timeout"), } if lang, ok := langCompilerMap[compiler.lang]; ok { params := append(lang.Args, compiler.src) // check if need sub cmd(eg: go build) if lang.SubCommand != "" { params = append([]string{lang.SubCommand}, params...) } compiler.cmd = exec.Command(lang.Command, params...) } else { compiler.err = fmt.Errorf("language %s is not supported", compiler.lang) return compiler } compiler.cmd.SysProcAttr = &syscall.SysProcAttr{ Setpgid: true, } compiler.cmd.Dir = compiler.baseDir compiler.cmd.Stdout = &compiler.stdOut compiler.cmd.Stderr = &compiler.stdErr return compiler } func (c *Compiler) handleResult() { result := &judge.InnerResult{ ID: c.id, ResultType: judge.CompileResType, StdErr: c.stdErr.String(), TimeLimit: c.timeout, } // handle error if c.err != nil { result.Message = c.err.Error() result.Status = judge.FAIL switch c.err { case COMPILER_TIMEOUT_ERR: result.Errno = judge.COMPILE_TIMEOUT result.Message = judge.GetInnerErrorMsgByErrNo(judge.COMPILE_TIMEOUT) case COMPILER_RUN_ERR: result.Errno = judge.INNER_COMPILER_ERR default: result.Errno = judge.OUTER_COMPILER_ERR } } else { result.Status = judge.SUCCESS result.Message = tip.CompileSuccessTip.String() } res, _ := json.Marshal(result) fmt.Println(string(res)) // log result log.WithFields(log.Fields{ "id": c.id, "lang": c.lang, "src": c.src, "baseDir": c.baseDir, "timeout": c.timeout, "result": result, }).Info("compile result") }
{ return nil // return nil, handle error by self }
app.go
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package v1 import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Creates an app associated with a developer. This API associates the developer app with the specified API product and auto-generates an API key for the app to use in calls to API proxies inside that API product. The `name` is the unique ID of the app that you can use in API calls. The `DisplayName` (set as an attribute) appears in the UI. If you don't set the `DisplayName` attribute, the `name` appears in the UI. type App struct { pulumi.CustomResourceState // List of API products associated with the developer app. ApiProducts pulumi.StringArrayOutput `pulumi:"apiProducts"` // Developer app family. AppFamily pulumi.StringOutput `pulumi:"appFamily"` // ID of the developer app. AppId pulumi.StringOutput `pulumi:"appId"` // List of attributes for the developer app. Attributes GoogleCloudApigeeV1AttributeResponseArrayOutput `pulumi:"attributes"` // Callback URL used by OAuth 2.0 authorization servers to communicate authorization codes back to developer apps. CallbackUrl pulumi.StringOutput `pulumi:"callbackUrl"` // Time the developer app was created in milliseconds since epoch. CreatedAt pulumi.StringOutput `pulumi:"createdAt"` // Set of credentials for the developer app consisting of the consumer key/secret pairs associated with the API products. Credentials GoogleCloudApigeeV1CredentialResponseArrayOutput `pulumi:"credentials"` // ID of the developer. DeveloperId pulumi.StringOutput `pulumi:"developerId"` // Expiration time, in milliseconds, for the consumer key that is generated for the developer app. If not set or left to the default value of `-1`, the API key never expires. The expiration time can't be updated after it is set. KeyExpiresIn pulumi.StringOutput `pulumi:"keyExpiresIn"` // Time the developer app was modified in milliseconds since epoch. LastModifiedAt pulumi.StringOutput `pulumi:"lastModifiedAt"` // Name of the developer app. Name pulumi.StringOutput `pulumi:"name"` // Scopes to apply to the developer app. The specified scopes must already exist for the API product that you associate with the developer app. Scopes pulumi.StringArrayOutput `pulumi:"scopes"` // Status of the credential. Valid values include `approved` or `revoked`. Status pulumi.StringOutput `pulumi:"status"` } // NewApp registers a new resource with the given unique name, arguments, and options. func NewApp(ctx *pulumi.Context, name string, args *AppArgs, opts ...pulumi.ResourceOption) (*App, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.DeveloperId == nil { return nil, errors.New("invalid value for required argument 'DeveloperId'") } if args.OrganizationId == nil { return nil, errors.New("invalid value for required argument 'OrganizationId'") } var resource App err := ctx.RegisterResource("google-native:apigee/v1:App", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetApp gets an existing App resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetApp(ctx *pulumi.Context, name string, id pulumi.IDInput, state *AppState, opts ...pulumi.ResourceOption) (*App, error)
// Input properties used for looking up and filtering App resources. type appState struct { } type AppState struct { } func (AppState) ElementType() reflect.Type { return reflect.TypeOf((*appState)(nil)).Elem() } type appArgs struct { // List of API products associated with the developer app. ApiProducts []string `pulumi:"apiProducts"` // Developer app family. AppFamily *string `pulumi:"appFamily"` // ID of the developer app. AppId *string `pulumi:"appId"` // List of attributes for the developer app. Attributes []GoogleCloudApigeeV1Attribute `pulumi:"attributes"` // Callback URL used by OAuth 2.0 authorization servers to communicate authorization codes back to developer apps. CallbackUrl *string `pulumi:"callbackUrl"` // ID of the developer. DeveloperId string `pulumi:"developerId"` // Expiration time, in milliseconds, for the consumer key that is generated for the developer app. If not set or left to the default value of `-1`, the API key never expires. The expiration time can't be updated after it is set. KeyExpiresIn *string `pulumi:"keyExpiresIn"` // Name of the developer app. Name *string `pulumi:"name"` OrganizationId string `pulumi:"organizationId"` // Scopes to apply to the developer app. The specified scopes must already exist for the API product that you associate with the developer app. Scopes []string `pulumi:"scopes"` // Status of the credential. Valid values include `approved` or `revoked`. Status *string `pulumi:"status"` } // The set of arguments for constructing a App resource. type AppArgs struct { // List of API products associated with the developer app. ApiProducts pulumi.StringArrayInput // Developer app family. AppFamily pulumi.StringPtrInput // ID of the developer app. AppId pulumi.StringPtrInput // List of attributes for the developer app. Attributes GoogleCloudApigeeV1AttributeArrayInput // Callback URL used by OAuth 2.0 authorization servers to communicate authorization codes back to developer apps. CallbackUrl pulumi.StringPtrInput // ID of the developer. DeveloperId pulumi.StringInput // Expiration time, in milliseconds, for the consumer key that is generated for the developer app. If not set or left to the default value of `-1`, the API key never expires. The expiration time can't be updated after it is set. KeyExpiresIn pulumi.StringPtrInput // Name of the developer app. Name pulumi.StringPtrInput OrganizationId pulumi.StringInput // Scopes to apply to the developer app. The specified scopes must already exist for the API product that you associate with the developer app. Scopes pulumi.StringArrayInput // Status of the credential. Valid values include `approved` or `revoked`. Status pulumi.StringPtrInput } func (AppArgs) ElementType() reflect.Type { return reflect.TypeOf((*appArgs)(nil)).Elem() } type AppInput interface { pulumi.Input ToAppOutput() AppOutput ToAppOutputWithContext(ctx context.Context) AppOutput } func (*App) ElementType() reflect.Type { return reflect.TypeOf((**App)(nil)).Elem() } func (i *App) ToAppOutput() AppOutput { return i.ToAppOutputWithContext(context.Background()) } func (i *App) ToAppOutputWithContext(ctx context.Context) AppOutput { return pulumi.ToOutputWithContext(ctx, i).(AppOutput) } type AppOutput struct{ *pulumi.OutputState } func (AppOutput) ElementType() reflect.Type { return reflect.TypeOf((**App)(nil)).Elem() } func (o AppOutput) ToAppOutput() AppOutput { return o } func (o AppOutput) ToAppOutputWithContext(ctx context.Context) AppOutput { return o } func init() { pulumi.RegisterInputType(reflect.TypeOf((*AppInput)(nil)).Elem(), &App{}) pulumi.RegisterOutputType(AppOutput{}) }
{ var resource App err := ctx.ReadResource("google-native:apigee/v1:App", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil }
tenant.go
package tenant import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) // Db type type Db struct { ID int Name string Host string Port int Dbname string User string Password string } var db *sqlx.DB var catalog map[string]*sqlx.DB // Init データベースに接続 func Init() error { catalog = make(map[string]*sqlx.DB) var err error db, err = sqlx.Open("mysql", "root:@(127.0.0.1:3306)/test_admin") return err } func GetTenantDb(name string) (*sqlx.DB, error) { connection, exist := catalog[name] if exist { return connection, nil } con := Db{} err := db.Get(&con, "SELECT * FROM db WHERE name = ? LIMIT 1", name) if err != nil { return nil, er
pen("mysql", fmt.Sprintf("%s:%s@(%s:%d)/%s", con.User, con.Password, con.Host, con.Port, con.Dbname)) if err != nil { return nil, err } catalog[name] = a return a, nil }
r } a, err := sqlx.O
views.py
from django.shortcuts import render from products.models import Product from products.constants import ORDER_BY_CHOICES # Create your views here. def search_products(request): """ View that returns search results """ # Filter the products based on search results products = Product.objects.filter(name__icontains=request.GET['q']) # Get search request for page title on list of products page. search_request = request.GET['q'] template = 'list_of_products.html' context = {'products': products,
'page_title': 'Search Results', 'search_request': search_request, 'order_by_choices': ORDER_BY_CHOICES} return render(request, template, context)
distribute.py
import tensorflow as tf from tensorflow.python.client import device_lib def get_available_gpus(): local_device_protos = device_lib.list_local_devices()
def split_nest(nest, num_or_size_splits, axis=0): """Split nested structure. Examples -------- >>> split_nest({'a': shape(10, 20), 'b': shape(4, 15)}, 2, axis=0) >>> [{'a': shape(5, 20), 'b': shape(2, 15)}, {'a': shape(5, 20), 'b': shape(2, 15)}] """ flatten = tf.nest.flatten(nest) split_flatten = [tf.split(x, num_or_size_splits, axis=axis) for x in flatten] return [tf.nest.pack_sequence_as(nest, x) for x in zip(*split_flatten)] def parameter_server_strategy_run(devices, fn, split_args, split_kwargs=None): split_kwargs = [{}] * len(devices) if split_kwargs is None else split_kwargs assert len(devices) == len(split_args) == len(split_kwargs) split_returns = [] for device, args, kwargs in zip(devices, split_args, split_kwargs): with tf.device(device): args = args if isinstance(args, (list, tuple)) else (args,) split_returns.append(fn(*args, **kwargs)) return split_returns parellel_run = parameter_server_strategy_run def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Parameters ---------- tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradient calculation for each tower. Returns ------- List of pairs of (gradient, variable) where the gradient has been averaged across all towers. """ average_grads = [] for grad_and_vars in zip(*tower_grads): # Note that each grad_and_vars looks like the following: # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) grads = [] for g, _ in grad_and_vars: # Add 0 dimension to the gradients to represent the tower. expanded_g = tf.expand_dims(g, 0) # Append on a 'tower' dimension which we will average over below. grads.append(expanded_g) # Average over the 'tower' dimension. grad = tf.concat(axis=0, values=grads) grad = tf.reduce_mean(grad, 0) # Keep in mind that the Variables are redundant because they are shared # across towers. So .. we will just return the first tower's pointer to # the Variable. v = grad_and_vars[0][1] grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads
return [x.name for x in local_device_protos if x.device_type == 'GPU'] gpus = get_available_gpus
add.go
// Package ipfsadd is a simplified copy of go-ipfs/core/coreunix/add.go package ipfsadd import ( "context" "errors" "fmt" "io" gopath "path" "github.com/ipfs/ipfs-cluster/api" cid "github.com/ipfs/go-cid" chunker "github.com/ipfs/go-ipfs-chunker" files "github.com/ipfs/go-ipfs-files" posinfo "github.com/ipfs/go-ipfs-posinfo" ipld "github.com/ipfs/go-ipld-format" logging "github.com/ipfs/go-log" dag "github.com/ipfs/go-merkledag" mfs "github.com/ipfs/go-mfs" unixfs "github.com/ipfs/go-unixfs" balanced "github.com/ipfs/go-unixfs/importer/balanced" ihelper "github.com/ipfs/go-unixfs/importer/helpers" trickle "github.com/ipfs/go-unixfs/importer/trickle" ) var log = logging.Logger("coreunix") // how many bytes of progress to wait before sending a progress update message const progressReaderIncrement = 1024 * 256 var liveCacheSize = uint64(256 << 10) // NewAdder Returns a new Adder used for a file add operation. func NewAdder(ctx context.Context, ds ipld.DAGService) (*Adder, error) { // Cluster: we don't use pinner nor GCLocker. return &Adder{ ctx: ctx, dagService: ds, Progress: false, Trickle: false, Chunker: "", }, nil } // Adder holds the switches passed to the `add` command. type Adder struct { ctx context.Context dagService ipld.DAGService Out chan *api.AddedOutput Progress bool Trickle bool RawLeaves bool Silent bool NoCopy bool Chunker string mroot *mfs.Root tempRoot cid.Cid CidBuilder cid.Builder liveNodes uint64 lastFile mfs.FSNode } func (adder *Adder) mfsRoot() (*mfs.Root, error) { if adder.mroot != nil { return adder.mroot, nil } rnode := unixfs.EmptyDirNode() rnode.SetCidBuilder(adder.CidBuilder) mr, err := mfs.NewRoot(adder.ctx, adder.dagService, rnode, nil) if err != nil { return nil, err } adder.mroot = mr return adder.mroot, nil } // SetMfsRoot sets `r` as the root for Adder. func (adder *Adder) SetMfsRoot(r *mfs.Root) { adder.mroot = r } // Constructs a node from reader's data, and adds it. Doesn't pin. func (adder *Adder) add(reader io.Reader) (ipld.Node, error) { chnk, err := chunker.FromString(reader, adder.Chunker) if err != nil { return nil, err } // Cluster: we don't do batching/use BufferedDS. params := ihelper.DagBuilderParams{ Dagserv: adder.dagService, RawLeaves: adder.RawLeaves, Maxlinks: ihelper.DefaultLinksPerBlock, NoCopy: adder.NoCopy, CidBuilder: adder.CidBuilder, } db, err := params.New(chnk) if err != nil { return nil, err } var nd ipld.Node if adder.Trickle { nd, err = trickle.Layout(db) } else { nd, err = balanced.Layout(db) } if err != nil
return nd, nil } // RootNode returns the mfs root node func (adder *Adder) curRootNode() (ipld.Node, error) { mr, err := adder.mfsRoot() if err != nil { return nil, err } root, err := mr.GetDirectory().GetNode() if err != nil { return nil, err } // if one root file, use that hash as root. if len(root.Links()) == 1 { nd, err := root.Links()[0].GetNode(adder.ctx, adder.dagService) if err != nil { return nil, err } root = nd } return root, err } // PinRoot recursively pins the root node of Adder and // writes the pin state to the backing datastore. // Cluster: we don't pin. Former Finalize(). func (adder *Adder) PinRoot(root ipld.Node) error { rnk := root.Cid() err := adder.dagService.Add(adder.ctx, root) if err != nil { return err } if adder.tempRoot.Defined() { adder.tempRoot = rnk } return nil } func (adder *Adder) outputDirs(path string, fsn mfs.FSNode) error { switch fsn := fsn.(type) { case *mfs.File: return nil case *mfs.Directory: names, err := fsn.ListNames(adder.ctx) if err != nil { return err } for _, name := range names { child, err := fsn.Child(name) if err != nil { // This fails when Child is of type *mfs.File // because it tries to get them from the DAG // service (does not implement this and returns // a "not found" error) // *mfs.Files are ignored in the recursive call // anyway. // For Cluster, we just ignore errors here. continue } childpath := gopath.Join(path, name) err = adder.outputDirs(childpath, child) if err != nil { return err } fsn.Uncache(name) } nd, err := fsn.GetNode() if err != nil { return err } return outputDagnode(adder.Out, path, nd) default: return fmt.Errorf("unrecognized fsn type: %#v", fsn) } } func (adder *Adder) addNode(node ipld.Node, path string) error { // patch it into the root if path == "" { path = node.Cid().String() } if pi, ok := node.(*posinfo.FilestoreNode); ok { node = pi.Node } mr, err := adder.mfsRoot() if err != nil { return err } dir := gopath.Dir(path) if dir != "." { opts := mfs.MkdirOpts{ Mkparents: true, Flush: false, CidBuilder: adder.CidBuilder, } if err := mfs.Mkdir(mr, dir, opts); err != nil { return err } } if err := mfs.PutNode(mr, path, node); err != nil { return err } // Cluster: cache the last file added. // This avoids using the DAGService to get the first children // if the MFS root when not wrapping. lastFile, err := mfs.NewFile(path, node, nil, adder.dagService) if err != nil { return err } adder.lastFile = lastFile if !adder.Silent { return outputDagnode(adder.Out, path, node) } return nil } // AddAllAndPin adds the given request's files and pin them. // Cluster: we don'pin. Former AddFiles. func (adder *Adder) AddAllAndPin(file files.Node) (ipld.Node, error) { if err := adder.addFileNode("", file, true); err != nil { return nil, err } // get root mr, err := adder.mfsRoot() if err != nil { return nil, err } var root mfs.FSNode rootdir := mr.GetDirectory() root = rootdir err = root.Flush() if err != nil { return nil, err } // if adding a file without wrapping, swap the root to it (when adding a // directory, mfs root is the directory) _, dir := file.(files.Directory) var name string if !dir { children, err := rootdir.ListNames(adder.ctx) if err != nil { return nil, err } if len(children) == 0 { return nil, fmt.Errorf("expected at least one child dir, got none") } // Replace root with the first child name = children[0] root, err = rootdir.Child(name) if err != nil { // Cluster: use the last file we added // if we have one. if adder.lastFile == nil { return nil, err } root = adder.lastFile } } err = mr.Close() if err != nil { return nil, err } nd, err := root.GetNode() if err != nil { return nil, err } // output directory events err = adder.outputDirs(name, root) if err != nil { return nil, err } // Cluster: call PinRoot which adds the root cid to the DAGService. // Unsure if this a bug in IPFS when not pinning. Or it would get added // twice. return nd, adder.PinRoot(nd) } // Cluster: we don't Pause for GC func (adder *Adder) addFileNode(path string, file files.Node, toplevel bool) error { defer file.Close() if adder.liveNodes >= liveCacheSize { // TODO: A smarter cache that uses some sort of lru cache with an eviction handler mr, err := adder.mfsRoot() if err != nil { return err } if err := mr.FlushMemFree(adder.ctx); err != nil { return err } adder.liveNodes = 0 } adder.liveNodes++ switch f := file.(type) { case files.Directory: return adder.addDir(path, f, toplevel) case *files.Symlink: return adder.addSymlink(path, f) case files.File: return adder.addFile(path, f) default: return errors.New("unknown file type") } } func (adder *Adder) addSymlink(path string, l *files.Symlink) error { sdata, err := unixfs.SymlinkData(l.Target) if err != nil { return err } dagnode := dag.NodeWithData(sdata) dagnode.SetCidBuilder(adder.CidBuilder) err = adder.dagService.Add(adder.ctx, dagnode) if err != nil { return err } return adder.addNode(dagnode, path) } func (adder *Adder) addFile(path string, file files.File) error { // if the progress flag was specified, wrap the file so that we can send // progress updates to the client (over the output channel) var reader io.Reader = file if adder.Progress { rdr := &progressReader{file: reader, path: path, out: adder.Out} if fi, ok := file.(files.FileInfo); ok { reader = &progressReader2{rdr, fi} } else { reader = rdr } } dagnode, err := adder.add(reader) if err != nil { return err } // patch it into the root return adder.addNode(dagnode, path) } func (adder *Adder) addDir(path string, dir files.Directory, toplevel bool) error { log.Infof("adding directory: %s", path) if !(toplevel && path == "") { mr, err := adder.mfsRoot() if err != nil { return err } err = mfs.Mkdir(mr, path, mfs.MkdirOpts{ Mkparents: true, Flush: false, CidBuilder: adder.CidBuilder, }) if err != nil { return err } } it := dir.Entries() for it.Next() { fpath := gopath.Join(path, it.Name()) err := adder.addFileNode(fpath, it.Node(), false) if err != nil { return err } } return it.Err() } // outputDagnode sends dagnode info over the output channel. // Cluster: we use *api.AddedOutput instead of coreiface events. func outputDagnode(out chan *api.AddedOutput, name string, dn ipld.Node) error { if out == nil { return nil } s, err := dn.Size() if err != nil { return err } out <- &api.AddedOutput{ Cid: dn.Cid(), Name: name, Size: s, } return nil } type progressReader struct { file io.Reader path string out chan *api.AddedOutput bytes int64 lastProgress int64 } func (i *progressReader) Read(p []byte) (int, error) { n, err := i.file.Read(p) i.bytes += int64(n) if i.bytes-i.lastProgress >= progressReaderIncrement || err == io.EOF { i.lastProgress = i.bytes i.out <- &api.AddedOutput{ Name: i.path, Bytes: uint64(i.bytes), } } return n, err } type progressReader2 struct { *progressReader files.FileInfo } func (i *progressReader2) Read(p []byte) (int, error) { return i.progressReader.Read(p) }
{ return nil, err }
router.rs
use std::fmt::{self, Formatter}; use std::sync::Arc; use super::filter; use super::{Filter, FnFilter, PathFilter, PathState}; use crate::http::Request; use crate::Handler; /// Router struct is used for route request to different handlers. pub struct Router { pub(crate) routers: Vec<Router>, pub(crate) filters: Vec<Box<dyn Filter>>, pub(crate) hoops: Vec<Arc<dyn Handler>>, pub(crate) handler: Option<Arc<dyn Handler>>, } #[doc(hidden)] pub struct DetectMatched { pub hoops: Vec<Arc<dyn Handler>>, pub handler: Arc<dyn Handler>, } impl Default for Router { fn default() -> Self { Self::new() } } impl Router { /// Create a new Router. pub fn new() -> Router { Router { routers: Vec::new(), filters: Vec::new(), hoops: Vec::new(), handler: None, } } /// Get current router's children reference. #[inline] pub fn routers(&self) -> &Vec<Router> { &self.routers } /// Get current router's children mutable reference. #[inline] pub fn routers_mut(&mut self) -> &mut Vec<Router> { &mut self.routers } /// Get current router's middlewares reference. #[inline] pub fn hoops(&self) -> &Vec<Arc<dyn Handler>> { &self.hoops } /// Get current router's middlewares mutable reference. #[inline] pub fn hoops_mut(&mut self) -> &mut Vec<Arc<dyn Handler>> { &mut self.hoops } /// Get current router's filters reference. #[inline] pub fn filters(&self) -> &Vec<Box<dyn Filter>> { &self.filters } /// Get current router's filters mutable reference. #[inline] pub fn filters_mut(&mut self) -> &mut Vec<Box<dyn Filter>> { &mut self.filters } /// Detect current router is matched for current request. pub fn detect(&self, req: &mut Request, path_state: &mut PathState) -> Option<DetectMatched> { for filter in &self.filters { if !filter.filter(req, path_state) { return None; } } if !self.routers.is_empty() { let original_cursor = path_state.cursor; for child in &self.routers { if let Some(dm) = child.detect(req, path_state) { return Some(DetectMatched { hoops: [&self.hoops[..], &dm.hoops[..]].concat(), handler: dm.handler.clone(), }); } else { path_state.cursor = original_cursor; } } } if let Some(handler) = self.handler.clone() { if path_state.ended() { return Some(DetectMatched { hoops: self.hoops.clone(), handler: handler.clone(), }); } } None } /// Push a router as child of current router. #[inline] pub fn push(mut self, router: Router) -> Self { self.routers.push(router); self } /// Append all routers in a Vec as children of current router. #[inline] pub fn append(mut self, others: Vec<Router>) -> Self { let mut others = others; self.routers.append(&mut others); self } /// Add a handler as middleware, it will run the handler in current router or it's descendants /// handle the request. #[inline] pub fn with_hoop<H: Handler>(handler: H) -> Self { Router::new().hoop(handler) } /// Add a handler as middleware, it will run the handler in current router or it's descendants /// handle the request. #[inline] pub fn hoop<H: Handler>(mut self, handler: H) -> Self { self.hoops.push(Arc::new(handler)); self } /// Create a new router and set path filter. /// /// # Panics /// /// Panics if path value is not in correct format. #[inline] pub fn with_path(path: impl Into<String>) -> Self { Router::new().filter(PathFilter::new(path)) } /// Create a new path filter for current router. /// /// # Panics /// /// Panics if path value is not in correct format. #[inline] pub fn path(self, path: impl Into<String>) -> Self { self.filter(PathFilter::new(path)) } /// Add a filter for current router. #[inline] pub fn filter(mut self, filter: impl Filter + Sized) -> Self { self.filters.push(Box::new(filter)); self } /// Create a new FnFilter from Fn. #[inline] pub fn filter_fn<T>(mut self, func: T) -> Self where T: Fn(&mut Request, &mut PathState) -> bool + Send + Sync + 'static, { self.filters.push(Box::new(FnFilter(func))); self } /// Set current router's handler. #[inline] pub fn handle<H: Handler>(mut self, handler: H) -> Self { self.handler = Some(Arc::new(handler)); self } /// When you want write router chain, this function will be useful, /// You can write your custom logic in FnOnce. #[inline] pub fn then<F>(self, func: F) -> Self where F: FnOnce(Self) -> Self, { func(self) } /// Create a new child router with MethodFilter to filter get method and set this child router's handler. #[inline] pub fn get<H: Handler>(self, handler: H) -> Self { self.push(Router::new().filter(filter::get()).handle(handler)) } /// Create a new child router with MethodFilter to filter post method and set this child router's handler. #[inline] pub fn post<H: Handler>(self, handler: H) -> Self { self.push(Router::new().filter(filter::post()).handle(handler)) } /// Create a new child router with MethodFilter to filter put method and set this child router's handler. #[inline] pub fn put<H: Handler>(self, handler: H) -> Self { self.push(Router::new().filter(filter::put()).handle(handler)) } /// Create a new child router with MethodFilter to filter delete method and set this child router's handler. #[inline] pub fn delete<H: Handler>(self, handler: H) -> Self
/// Create a new child router with MethodFilter to filter patch method and set this child router's handler. #[inline] pub fn patch<H: Handler>(self, handler: H) -> Self { self.push(Router::new().filter(filter::patch()).handle(handler)) } /// Create a new child router with MethodFilter to filter head method and set this child router's handler. #[inline] pub fn head<H: Handler>(self, handler: H) -> Self { self.push(Router::new().filter(filter::head()).handle(handler)) } /// Create a new child router with MethodFilter to filter options method and set this child router's handler. #[inline] pub fn options<H: Handler>(self, handler: H) -> Self { self.push(Router::new().filter(filter::options()).handle(handler)) } } static SYMBOL_DOWN: &str = "│"; static SYMBOL_TEE: &str = "├"; static SYMBOL_ELL: &str = "└"; static SYMBOL_RIGHT: &str = "─"; impl fmt::Debug for Router { fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn print(f: &mut Formatter, prefix: &str, last: bool, router: &Router) -> fmt::Result { let mut path = "".to_owned(); let mut others = Vec::with_capacity(router.filters.len()); if router.filters.is_empty() { path = "!NULL!".to_owned(); } else { for filter in &router.filters { let info = format!("{:?}", filter); if info.starts_with("path:") { path = info.split_once(':').unwrap().1.to_owned(); } else { let mut parts = info.splitn(2, ':').collect::<Vec<_>>(); if !parts.is_empty() { others.push(parts.pop().unwrap().to_owned()); } } } } let cp = if last { format!("{}{}{}{}", prefix, SYMBOL_ELL, SYMBOL_RIGHT, SYMBOL_RIGHT) } else { format!("{}{}{}{}", prefix, SYMBOL_TEE, SYMBOL_RIGHT, SYMBOL_RIGHT) }; if !others.is_empty() { writeln!(f, "{}{}[{}]", cp, path, others.join(","))?; } else { writeln!(f, "{}{}", cp, path)?; } let routers = router.routers(); if !routers.is_empty() { let np = if last { format!("{} ", prefix) } else { format!("{}{} ", prefix, SYMBOL_DOWN) }; for (i, router) in routers.iter().enumerate() { print(f, &np, i == routers.len() - 1, router)?; } } Ok(()) } print(f, "", true, self) } } #[cfg(test)] mod tests { use super::{PathState, Router}; use crate::fn_handler; use crate::{Request, Response}; use async_trait::async_trait; #[fn_handler] async fn fake_handler(_res: &mut Response) {} #[test] fn test_router_debug() { let router = Router::default() .push( Router::with_path("users") .push(Router::with_path("<id>").push(Router::with_path("emails").get(fake_handler))) .push( Router::with_path("<id>/articles/<aid>") .get(fake_handler) .delete(fake_handler), ), ) .push( Router::with_path("articles") .push( Router::with_path("<id>/authors/<aid>") .get(fake_handler) .delete(fake_handler), ) .push(Router::with_path("<id>").get(fake_handler).delete(fake_handler)), ); assert_eq!( format!("{:?}", router), r#"└──!NULL! ├──users │ ├──<id> │ │ └──emails │ │ └──[GET] │ └──<id>/articles/<aid> │ ├──[GET] │ └──[DELETE] └──articles ├──<id>/authors/<aid> │ ├──[GET] │ └──[DELETE] └──<id> ├──[GET] └──[DELETE] "# ); } #[test] fn test_router_detect1() { let router = Router::default().push( Router::with_path("users") .push(Router::with_path("<id>").push(Router::with_path("emails").get(fake_handler))), ); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/emails") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); } #[test] fn test_router_detect2() { let router = Router::new() .push(Router::with_path("users").push(Router::with_path("<id>").get(fake_handler))) .push( Router::with_path("users") .push(Router::with_path("<id>").push(Router::with_path("emails").get(fake_handler))), ); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/emails") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); } #[test] fn test_router_detect3() { let router = Router::new().push( Router::with_path("users").push( Router::with_path(r"<id:/\d+/>") .push(Router::new().push(Router::with_path("facebook/insights/<**rest>").handle(fake_handler))), ), ); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/facebook/insights") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/facebook/insights/23") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); // assert_eq!(format!("{:?}", path_state), ""); assert!(matched.is_some()); } #[test] fn test_router_detect4() { let router = Router::new().push( Router::with_path("users").push( Router::with_path(r"<id:/\d+/>") .push(Router::new().push(Router::with_path("facebook/insights/<*rest>").handle(fake_handler))), ), ); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/facebook/insights") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); // assert_eq!(format!("{:?}", path_state), ""); assert!(matched.is_none()); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/facebook/insights/23") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); } #[test] fn test_router_detect5() { let router = Router::new().push(Router::with_path("users").push(Router::with_path(r"<id:/\d+/>").push( Router::new().push( Router::with_path("facebook/insights").push(Router::with_path("<**rest>").handle(fake_handler)), ), ))); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/facebook/insights") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/facebook/insights/23") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); assert_eq!(path_state.params["id"], "12"); } #[test] fn test_router_detect6() { let router = Router::new().push(Router::with_path("users").push(Router::with_path(r"<id:/\d+/>").push( Router::new().push( Router::with_path("facebook/insights").push(Router::new().path("<*rest>").handle(fake_handler)), ), ))); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/facebook/insights") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_none()); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/facebook/insights/23") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); } #[test] fn test_router_detect_utf8() { let router = Router::new().push(Router::with_path("用户").push(Router::with_path(r"<id:/\d+/>").push( Router::new().push( Router::with_path("facebook/insights").push(Router::with_path("<*rest>").handle(fake_handler)), ), ))); let mut req: Request = hyper::Request::builder() .uri("http://local.host/%E7%94%A8%E6%88%B7/12/facebook/insights") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_none()); let mut req: Request = hyper::Request::builder() .uri("http://local.host/%E7%94%A8%E6%88%B7/12/facebook/insights/23") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); } #[test] fn test_router_detect9() { let router = Router::new().push(Router::with_path("users/<*sub:/(images|css)/>/<filename>").handle(fake_handler)); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/m.jpg") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_none()); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/css/m.jpg") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); } #[test] fn test_router_detect10() { let router = Router::new().push(Router::with_path(r"users/<*sub:/(images|css)/.+/>").handle(fake_handler)); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/12/m.jpg") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_none()); let mut req: Request = hyper::Request::builder() .uri("http://local.host/users/css/abc/m.jpg") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); } #[test] fn test_router_detect11() { let router = Router::new().push(Router::with_path(r"avatars/<width:/\d+/>x<height:/\d+/>.<ext>").handle(fake_handler)); let mut req: Request = hyper::Request::builder() .uri("http://local.host/avatars/321x641f.webp") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_none()); let mut req: Request = hyper::Request::builder() .uri("http://local.host/avatars/320x640.webp") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); } #[test] fn test_router_detect12() { let router = Router::new().push(Router::with_path("/.well-known/acme-challenge/<token>").handle(fake_handler)); let mut req: Request = hyper::Request::builder() .uri("http://local.host/.well-known/acme-challenge/q1XXrxIx79uXNl3I") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); } #[test] fn test_router_detect13() { let router = Router::new() .path("user/<id:/[0-9a-z]{8}(-[0-9a-z]{4}){3}-[0-9a-z]{12}/>") .get(fake_handler); let mut req: Request = hyper::Request::builder() .uri("http://local.host/user/726d694c-7af0-4bb0-9d22-706f7e38641e") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_some()); let mut req: Request = hyper::Request::builder() .uri("http://local.host/user/726d694c-7af0-4bb0-9d22-706f7e386e") .body(hyper::Body::empty()) .unwrap() .into(); let mut path_state = PathState::new(req.uri().path()); let matched = router.detect(&mut req, &mut path_state); assert!(matched.is_none()); } }
{ self.push(Router::new().filter(filter::delete()).handle(handler)) }
options.go
package netw import "github.com/xiaomingping/game/iface" type Option func(s *Server) // 只要实现Packet 接口可自由实现数据包解析格式,如果没有则使用默认解析格式 func WithPacket(pack iface.Packet) Option { return func(s *Server) { s.packet = pack } }
identity_detail.go
// Code generated by go-swagger; DO NOT EDIT. // // Copyright NetFoundry Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // // __ __ _ // \ \ / / (_) // \ \ /\ / /_ _ _ __ _ __ _ _ __ __ _ // \ \/ \/ / _` | '__| '_ \| | '_ \ / _` | // \ /\ / (_| | | | | | | | | | | (_| | : This file is generated, do not edit it. // \/ \/ \__,_|_| |_| |_|_|_| |_|\__, | // __/ | // |___/ package rest_model // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // IdentityDetail Detail of a specific identity // // swagger:model identityDetail type IdentityDetail struct { BaseEntity // app data AppData *Tags `json:"appData,omitempty"` // auth policy Id // Required: true AuthPolicyID *string `json:"authPolicyId"` // authenticators // Required: true Authenticators *IdentityAuthenticators `json:"authenticators"` // default hosting cost // Required: true DefaultHostingCost *TerminatorCost `json:"defaultHostingCost"` // default hosting precedence DefaultHostingPrecedence TerminatorPrecedence `json:"defaultHostingPrecedence,omitempty"` // disabled // Required: true Disabled *bool `json:"disabled"` // disabled at // Format: date-time DisabledAt *strfmt.DateTime `json:"disabledAt,omitempty"` // disabled until // Format: date-time DisabledUntil *strfmt.DateTime `json:"disabledUntil,omitempty"` // enrollment // Required: true Enrollment *IdentityEnrollments `json:"enrollment"` // env info // Required: true EnvInfo *EnvInfo `json:"envInfo"` // external Id // Required: true ExternalID *string `json:"externalId"` // has Api session // Required: true HasAPISession *bool `json:"hasApiSession"` // has edge router connection // Required: true HasEdgeRouterConnection *bool `json:"hasEdgeRouterConnection"` // is admin // Required: true IsAdmin *bool `json:"isAdmin"` // is default admin // Required: true IsDefaultAdmin *bool `json:"isDefaultAdmin"` // is mfa enabled // Required: true IsMfaEnabled *bool `json:"isMfaEnabled"` // name // Required: true Name *string `json:"name"` // role attributes // Required: true RoleAttributes *Attributes `json:"roleAttributes"` // sdk info // Required: true SdkInfo *SdkInfo `json:"sdkInfo"` // service hosting costs // Required: true ServiceHostingCosts TerminatorCostMap `json:"serviceHostingCosts"` // service hosting precedences // Required: true ServiceHostingPrecedences TerminatorPrecedenceMap `json:"serviceHostingPrecedences"` // type // Required: true Type *EntityRef `json:"type"` // type Id // Required: true TypeID *string `json:"typeId"` } // UnmarshalJSON unmarshals this object from a JSON structure func (m *IdentityDetail) UnmarshalJSON(raw []byte) error { // AO0 var aO0 BaseEntity if err := swag.ReadJSON(raw, &aO0); err != nil { return err } m.BaseEntity = aO0 // AO1 var dataAO1 struct { AppData *Tags `json:"appData,omitempty"` AuthPolicyID *string `json:"authPolicyId"` Authenticators *IdentityAuthenticators `json:"authenticators"` DefaultHostingCost *TerminatorCost `json:"defaultHostingCost"` DefaultHostingPrecedence TerminatorPrecedence `json:"defaultHostingPrecedence,omitempty"` Disabled *bool `json:"disabled"` DisabledAt *strfmt.DateTime `json:"disabledAt,omitempty"` DisabledUntil *strfmt.DateTime `json:"disabledUntil,omitempty"` Enrollment *IdentityEnrollments `json:"enrollment"` EnvInfo *EnvInfo `json:"envInfo"` ExternalID *string `json:"externalId"` HasAPISession *bool `json:"hasApiSession"` HasEdgeRouterConnection *bool `json:"hasEdgeRouterConnection"` IsAdmin *bool `json:"isAdmin"` IsDefaultAdmin *bool `json:"isDefaultAdmin"` IsMfaEnabled *bool `json:"isMfaEnabled"` Name *string `json:"name"` RoleAttributes *Attributes `json:"roleAttributes"` SdkInfo *SdkInfo `json:"sdkInfo"` ServiceHostingCosts TerminatorCostMap `json:"serviceHostingCosts"` ServiceHostingPrecedences TerminatorPrecedenceMap `json:"serviceHostingPrecedences"` Type *EntityRef `json:"type"` TypeID *string `json:"typeId"` } if err := swag.ReadJSON(raw, &dataAO1); err != nil { return err } m.AppData = dataAO1.AppData m.AuthPolicyID = dataAO1.AuthPolicyID m.Authenticators = dataAO1.Authenticators m.DefaultHostingCost = dataAO1.DefaultHostingCost m.DefaultHostingPrecedence = dataAO1.DefaultHostingPrecedence m.Disabled = dataAO1.Disabled m.DisabledAt = dataAO1.DisabledAt m.DisabledUntil = dataAO1.DisabledUntil m.Enrollment = dataAO1.Enrollment m.EnvInfo = dataAO1.EnvInfo m.ExternalID = dataAO1.ExternalID m.HasAPISession = dataAO1.HasAPISession m.HasEdgeRouterConnection = dataAO1.HasEdgeRouterConnection m.IsAdmin = dataAO1.IsAdmin m.IsDefaultAdmin = dataAO1.IsDefaultAdmin m.IsMfaEnabled = dataAO1.IsMfaEnabled m.Name = dataAO1.Name m.RoleAttributes = dataAO1.RoleAttributes m.SdkInfo = dataAO1.SdkInfo m.ServiceHostingCosts = dataAO1.ServiceHostingCosts m.ServiceHostingPrecedences = dataAO1.ServiceHostingPrecedences m.Type = dataAO1.Type m.TypeID = dataAO1.TypeID return nil } // MarshalJSON marshals this object to a JSON structure func (m IdentityDetail) MarshalJSON() ([]byte, error) { _parts := make([][]byte, 0, 2) aO0, err := swag.WriteJSON(m.BaseEntity) if err != nil { return nil, err } _parts = append(_parts, aO0) var dataAO1 struct { AppData *Tags `json:"appData,omitempty"` AuthPolicyID *string `json:"authPolicyId"` Authenticators *IdentityAuthenticators `json:"authenticators"` DefaultHostingCost *TerminatorCost `json:"defaultHostingCost"` DefaultHostingPrecedence TerminatorPrecedence `json:"defaultHostingPrecedence,omitempty"` Disabled *bool `json:"disabled"` DisabledAt *strfmt.DateTime `json:"disabledAt,omitempty"` DisabledUntil *strfmt.DateTime `json:"disabledUntil,omitempty"` Enrollment *IdentityEnrollments `json:"enrollment"` EnvInfo *EnvInfo `json:"envInfo"` ExternalID *string `json:"externalId"` HasAPISession *bool `json:"hasApiSession"` HasEdgeRouterConnection *bool `json:"hasEdgeRouterConnection"` IsAdmin *bool `json:"isAdmin"` IsDefaultAdmin *bool `json:"isDefaultAdmin"` IsMfaEnabled *bool `json:"isMfaEnabled"` Name *string `json:"name"` RoleAttributes *Attributes `json:"roleAttributes"` SdkInfo *SdkInfo `json:"sdkInfo"` ServiceHostingCosts TerminatorCostMap `json:"serviceHostingCosts"` ServiceHostingPrecedences TerminatorPrecedenceMap `json:"serviceHostingPrecedences"` Type *EntityRef `json:"type"` TypeID *string `json:"typeId"` } dataAO1.AppData = m.AppData dataAO1.AuthPolicyID = m.AuthPolicyID dataAO1.Authenticators = m.Authenticators dataAO1.DefaultHostingCost = m.DefaultHostingCost dataAO1.DefaultHostingPrecedence = m.DefaultHostingPrecedence dataAO1.Disabled = m.Disabled dataAO1.DisabledAt = m.DisabledAt dataAO1.DisabledUntil = m.DisabledUntil dataAO1.Enrollment = m.Enrollment dataAO1.EnvInfo = m.EnvInfo dataAO1.ExternalID = m.ExternalID dataAO1.HasAPISession = m.HasAPISession
dataAO1.HasEdgeRouterConnection = m.HasEdgeRouterConnection dataAO1.IsAdmin = m.IsAdmin dataAO1.IsDefaultAdmin = m.IsDefaultAdmin dataAO1.IsMfaEnabled = m.IsMfaEnabled dataAO1.Name = m.Name dataAO1.RoleAttributes = m.RoleAttributes dataAO1.SdkInfo = m.SdkInfo dataAO1.ServiceHostingCosts = m.ServiceHostingCosts dataAO1.ServiceHostingPrecedences = m.ServiceHostingPrecedences dataAO1.Type = m.Type dataAO1.TypeID = m.TypeID jsonDataAO1, errAO1 := swag.WriteJSON(dataAO1) if errAO1 != nil { return nil, errAO1 } _parts = append(_parts, jsonDataAO1) return swag.ConcatJSON(_parts...), nil } // Validate validates this identity detail func (m *IdentityDetail) Validate(formats strfmt.Registry) error { var res []error // validation for a type composition with BaseEntity if err := m.BaseEntity.Validate(formats); err != nil { res = append(res, err) } if err := m.validateAppData(formats); err != nil { res = append(res, err) } if err := m.validateAuthPolicyID(formats); err != nil { res = append(res, err) } if err := m.validateAuthenticators(formats); err != nil { res = append(res, err) } if err := m.validateDefaultHostingCost(formats); err != nil { res = append(res, err) } if err := m.validateDefaultHostingPrecedence(formats); err != nil { res = append(res, err) } if err := m.validateDisabled(formats); err != nil { res = append(res, err) } if err := m.validateDisabledAt(formats); err != nil { res = append(res, err) } if err := m.validateDisabledUntil(formats); err != nil { res = append(res, err) } if err := m.validateEnrollment(formats); err != nil { res = append(res, err) } if err := m.validateEnvInfo(formats); err != nil { res = append(res, err) } if err := m.validateExternalID(formats); err != nil { res = append(res, err) } if err := m.validateHasAPISession(formats); err != nil { res = append(res, err) } if err := m.validateHasEdgeRouterConnection(formats); err != nil { res = append(res, err) } if err := m.validateIsAdmin(formats); err != nil { res = append(res, err) } if err := m.validateIsDefaultAdmin(formats); err != nil { res = append(res, err) } if err := m.validateIsMfaEnabled(formats); err != nil { res = append(res, err) } if err := m.validateName(formats); err != nil { res = append(res, err) } if err := m.validateRoleAttributes(formats); err != nil { res = append(res, err) } if err := m.validateSdkInfo(formats); err != nil { res = append(res, err) } if err := m.validateServiceHostingCosts(formats); err != nil { res = append(res, err) } if err := m.validateServiceHostingPrecedences(formats); err != nil { res = append(res, err) } if err := m.validateType(formats); err != nil { res = append(res, err) } if err := m.validateTypeID(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *IdentityDetail) validateAppData(formats strfmt.Registry) error { if swag.IsZero(m.AppData) { // not required return nil } if m.AppData != nil { if err := m.AppData.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("appData") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("appData") } return err } } return nil } func (m *IdentityDetail) validateAuthPolicyID(formats strfmt.Registry) error { if err := validate.Required("authPolicyId", "body", m.AuthPolicyID); err != nil { return err } return nil } func (m *IdentityDetail) validateAuthenticators(formats strfmt.Registry) error { if err := validate.Required("authenticators", "body", m.Authenticators); err != nil { return err } if m.Authenticators != nil { if err := m.Authenticators.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("authenticators") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("authenticators") } return err } } return nil } func (m *IdentityDetail) validateDefaultHostingCost(formats strfmt.Registry) error { if err := validate.Required("defaultHostingCost", "body", m.DefaultHostingCost); err != nil { return err } if err := validate.Required("defaultHostingCost", "body", m.DefaultHostingCost); err != nil { return err } if m.DefaultHostingCost != nil { if err := m.DefaultHostingCost.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("defaultHostingCost") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("defaultHostingCost") } return err } } return nil } func (m *IdentityDetail) validateDefaultHostingPrecedence(formats strfmt.Registry) error { if swag.IsZero(m.DefaultHostingPrecedence) { // not required return nil } if err := m.DefaultHostingPrecedence.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("defaultHostingPrecedence") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("defaultHostingPrecedence") } return err } return nil } func (m *IdentityDetail) validateDisabled(formats strfmt.Registry) error { if err := validate.Required("disabled", "body", m.Disabled); err != nil { return err } return nil } func (m *IdentityDetail) validateDisabledAt(formats strfmt.Registry) error { if swag.IsZero(m.DisabledAt) { // not required return nil } if err := validate.FormatOf("disabledAt", "body", "date-time", m.DisabledAt.String(), formats); err != nil { return err } return nil } func (m *IdentityDetail) validateDisabledUntil(formats strfmt.Registry) error { if swag.IsZero(m.DisabledUntil) { // not required return nil } if err := validate.FormatOf("disabledUntil", "body", "date-time", m.DisabledUntil.String(), formats); err != nil { return err } return nil } func (m *IdentityDetail) validateEnrollment(formats strfmt.Registry) error { if err := validate.Required("enrollment", "body", m.Enrollment); err != nil { return err } if m.Enrollment != nil { if err := m.Enrollment.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("enrollment") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("enrollment") } return err } } return nil } func (m *IdentityDetail) validateEnvInfo(formats strfmt.Registry) error { if err := validate.Required("envInfo", "body", m.EnvInfo); err != nil { return err } if m.EnvInfo != nil { if err := m.EnvInfo.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("envInfo") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("envInfo") } return err } } return nil } func (m *IdentityDetail) validateExternalID(formats strfmt.Registry) error { if err := validate.Required("externalId", "body", m.ExternalID); err != nil { return err } return nil } func (m *IdentityDetail) validateHasAPISession(formats strfmt.Registry) error { if err := validate.Required("hasApiSession", "body", m.HasAPISession); err != nil { return err } return nil } func (m *IdentityDetail) validateHasEdgeRouterConnection(formats strfmt.Registry) error { if err := validate.Required("hasEdgeRouterConnection", "body", m.HasEdgeRouterConnection); err != nil { return err } return nil } func (m *IdentityDetail) validateIsAdmin(formats strfmt.Registry) error { if err := validate.Required("isAdmin", "body", m.IsAdmin); err != nil { return err } return nil } func (m *IdentityDetail) validateIsDefaultAdmin(formats strfmt.Registry) error { if err := validate.Required("isDefaultAdmin", "body", m.IsDefaultAdmin); err != nil { return err } return nil } func (m *IdentityDetail) validateIsMfaEnabled(formats strfmt.Registry) error { if err := validate.Required("isMfaEnabled", "body", m.IsMfaEnabled); err != nil { return err } return nil } func (m *IdentityDetail) validateName(formats strfmt.Registry) error { if err := validate.Required("name", "body", m.Name); err != nil { return err } return nil } func (m *IdentityDetail) validateRoleAttributes(formats strfmt.Registry) error { if err := validate.Required("roleAttributes", "body", m.RoleAttributes); err != nil { return err } if m.RoleAttributes != nil { if err := m.RoleAttributes.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("roleAttributes") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("roleAttributes") } return err } } return nil } func (m *IdentityDetail) validateSdkInfo(formats strfmt.Registry) error { if err := validate.Required("sdkInfo", "body", m.SdkInfo); err != nil { return err } if m.SdkInfo != nil { if err := m.SdkInfo.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("sdkInfo") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("sdkInfo") } return err } } return nil } func (m *IdentityDetail) validateServiceHostingCosts(formats strfmt.Registry) error { if err := validate.Required("serviceHostingCosts", "body", m.ServiceHostingCosts); err != nil { return err } if m.ServiceHostingCosts != nil { if err := m.ServiceHostingCosts.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("serviceHostingCosts") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("serviceHostingCosts") } return err } } return nil } func (m *IdentityDetail) validateServiceHostingPrecedences(formats strfmt.Registry) error { if err := validate.Required("serviceHostingPrecedences", "body", m.ServiceHostingPrecedences); err != nil { return err } if m.ServiceHostingPrecedences != nil { if err := m.ServiceHostingPrecedences.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("serviceHostingPrecedences") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("serviceHostingPrecedences") } return err } } return nil } func (m *IdentityDetail) validateType(formats strfmt.Registry) error { if err := validate.Required("type", "body", m.Type); err != nil { return err } if m.Type != nil { if err := m.Type.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("type") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("type") } return err } } return nil } func (m *IdentityDetail) validateTypeID(formats strfmt.Registry) error { if err := validate.Required("typeId", "body", m.TypeID); err != nil { return err } return nil } // ContextValidate validate this identity detail based on the context it is used func (m *IdentityDetail) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error // validation for a type composition with BaseEntity if err := m.BaseEntity.ContextValidate(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateAppData(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateAuthenticators(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateDefaultHostingCost(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateDefaultHostingPrecedence(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateEnrollment(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateEnvInfo(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateRoleAttributes(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateSdkInfo(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateServiceHostingCosts(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateServiceHostingPrecedences(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateType(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *IdentityDetail) contextValidateAppData(ctx context.Context, formats strfmt.Registry) error { if m.AppData != nil { if err := m.AppData.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("appData") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("appData") } return err } } return nil } func (m *IdentityDetail) contextValidateAuthenticators(ctx context.Context, formats strfmt.Registry) error { if m.Authenticators != nil { if err := m.Authenticators.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("authenticators") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("authenticators") } return err } } return nil } func (m *IdentityDetail) contextValidateDefaultHostingCost(ctx context.Context, formats strfmt.Registry) error { if m.DefaultHostingCost != nil { if err := m.DefaultHostingCost.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("defaultHostingCost") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("defaultHostingCost") } return err } } return nil } func (m *IdentityDetail) contextValidateDefaultHostingPrecedence(ctx context.Context, formats strfmt.Registry) error { if err := m.DefaultHostingPrecedence.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("defaultHostingPrecedence") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("defaultHostingPrecedence") } return err } return nil } func (m *IdentityDetail) contextValidateEnrollment(ctx context.Context, formats strfmt.Registry) error { if m.Enrollment != nil { if err := m.Enrollment.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("enrollment") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("enrollment") } return err } } return nil } func (m *IdentityDetail) contextValidateEnvInfo(ctx context.Context, formats strfmt.Registry) error { if m.EnvInfo != nil { if err := m.EnvInfo.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("envInfo") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("envInfo") } return err } } return nil } func (m *IdentityDetail) contextValidateRoleAttributes(ctx context.Context, formats strfmt.Registry) error { if m.RoleAttributes != nil { if err := m.RoleAttributes.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("roleAttributes") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("roleAttributes") } return err } } return nil } func (m *IdentityDetail) contextValidateSdkInfo(ctx context.Context, formats strfmt.Registry) error { if m.SdkInfo != nil { if err := m.SdkInfo.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("sdkInfo") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("sdkInfo") } return err } } return nil } func (m *IdentityDetail) contextValidateServiceHostingCosts(ctx context.Context, formats strfmt.Registry) error { if err := m.ServiceHostingCosts.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("serviceHostingCosts") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("serviceHostingCosts") } return err } return nil } func (m *IdentityDetail) contextValidateServiceHostingPrecedences(ctx context.Context, formats strfmt.Registry) error { if err := m.ServiceHostingPrecedences.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("serviceHostingPrecedences") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("serviceHostingPrecedences") } return err } return nil } func (m *IdentityDetail) contextValidateType(ctx context.Context, formats strfmt.Registry) error { if m.Type != nil { if err := m.Type.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("type") } else if ce, ok := err.(*errors.CompositeError); ok { return ce.ValidateName("type") } return err } } return nil } // MarshalBinary interface implementation func (m *IdentityDetail) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *IdentityDetail) UnmarshalBinary(b []byte) error { var res IdentityDetail if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
rnn_decoder.py
import random from typing import Dict import torch from torch import Tensor, nn from torch.nn import functional as F class RNNDecoder(nn.Module): @property def max_gen_length(self) -> int: return self.hparams["dec_max_gen_length"] @property def EOS_idx(self) -> int: return self.hparams["dec_EOS_idx"] def __init__(self, hparams: dict) -> None: super().__init__() self.hparams = hparams self.embedding = nn.Embedding( hparams["dec_vocab_size"], hparams["dec_embedding_size"] ) self.unit = nn.RNN( hparams["dec_embedding_size"], hparams["dec_hidden_size"], num_layers=hparams["dec_num_layers"], batch_first=True, ) self.output = nn.Linear(hparams["dec_hidden_size"], hparams["dec_vocab_size"]) def forward_step(self, step_input: Dict[str, Tensor]) -> Dict[str, Tensor]: # Unsqueeze if only one batch is present no_squeeze = lambda a: a.unsqueeze(0) if a.shape == 2 else a # print("Step Input") # for key in step_input: # print(f"{key}: {step_input[key].shape}") h = no_squeeze(step_input["h"]) unit_input = no_squeeze(F.relu(self.embedding(step_input["x"]))) _, state = self.unit(unit_input, h) y = self.output(no_squeeze(state[-1, :, :])) # print(f"h: {h.shape}") # print(f"unit_input: {unit_input.shape}") # print(f"unk: {unk.shape}") # print(f"state: {state.shape}") # print(f"state[-1]: {state[-1].shape}") # print(f"y: {y.shape}") return {"y": y, "h": state} def
(self, dec_input: Dict[str, Tensor]) -> Dict[str, Tensor]: if "h" in dec_input: h = dec_input["h"] elif "encoder_last_state" in dec_input: h = torch.transpose(dec_input["encoder_last_state"], 0, 1) else: raise ValueError( f"You must provide a hidden input in dec_input '{dec_input}'" ) if "x" in dec_input: x = dec_input["x"] elif "transform" in dec_input: # print("No x found") # print(dec_input["transform"][:, 1:-1].shape) x = dec_input["transform"][:, 1:-1] else: raise ValueError( f"You must provide a step input in dec_input '{dec_input}'" ) step_input = {"x": x, "h": h} if "encoder_output" in dec_input: step_input["encoder_output"] = dec_input["encoder_output"] return step_input def forward(self, dec_input: Dict[str, Tensor], tf_ratio) -> Dict[str, Tensor]: is_teacher_forcing = random.random() < tf_ratio batch_size: int = dec_input["encoder_output"].shape[0] hidden_size: int = self.output.in_features vocab_size: int = self.output.out_features gen_length = ( dec_input["target"][0].shape[0] if is_teacher_forcing else self.max_gen_length ) dec_step_input = self.get_step_input(dec_input) has_finished = torch.zeros(batch_size, dtype=torch.bool) dec_output = torch.zeros(gen_length, batch_size, vocab_size) dec_hidden = torch.zeros(gen_length, batch_size, hidden_size) for i in range(gen_length): # print(f"STEP {i} (tf={is_teacher_forcing})") step_result = self.forward_step(dec_step_input) step_prediction = step_result["y"].argmax(dim=-1) # for key in step_result: # print(f"step_result[{key}]: {step_result[key].shape}") # print("dec_hidden: ", dec_hidden.shape) dec_output[i] = step_result["y"] dec_hidden[i] = step_result["h"] has_finished[step_prediction == self.EOS_idx] = True if all(has_finished): break else: x = dec_input["target"][:, i] if is_teacher_forcing else step_prediction step_result["x"] = x.unsqueeze(-1) step_result["encoder_output"] = dec_input["encoder_output"] dec_step_input = self.get_step_input(step_result) output = { "logits": torch.transpose(dec_output, 0, 1), "predictions": torch.transpose(dec_output, 0, 1).argmax(dim=-1), "decoder_hiddens": dec_hidden, } return output
get_step_input
egypt_model_test.py
import egypt_model import unittest class TestAggregateMethods(unittest.TestCase): def test_aggregates(self): model = egypt_model.EgyptModel(31, 30, starting_settlements=9, starting_households=5, starting_household_size=5, starting_grain=1000) self.assertEqual(egypt_model.compute_total_population(model), 9 * 5 * 5) self.assertEqual(egypt_model.compute_total_wealth(model), 9 * 5 * 1000) self.assertEqual(egypt_model.compute_mean_population(model), 5 * 5) self.assertEqual(egypt_model.compute_mean_wealth(model), 5 * 1000) model = egypt_model.EgyptModel(31, 30, starting_settlements=0, starting_households=5, starting_household_size=5, starting_grain=1000) self.assertEqual(egypt_model.compute_total_population(model), 0) self.assertEqual(egypt_model.compute_total_wealth(model), 0) self.assertEqual(egypt_model.compute_mean_population(model), 0) self.assertEqual(egypt_model.compute_mean_wealth(model), 0) model = egypt_model.EgyptModel(31, 30, starting_settlements=9, starting_households=0, starting_household_size=5, starting_grain=1000) self.assertEqual(egypt_model.compute_total_population(model), 0) self.assertEqual(egypt_model.compute_total_wealth(model), 0) self.assertEqual(egypt_model.compute_mean_population(model), 0) self.assertEqual(egypt_model.compute_mean_wealth(model), 0) model = egypt_model.EgyptModel(31, 30, starting_settlements=9, starting_households=5, starting_household_size=0, starting_grain=1000) self.assertEqual(egypt_model.compute_total_population(model), 0) self.assertEqual(egypt_model.compute_total_wealth(model), 9 * 5 * 1000) self.assertEqual(egypt_model.compute_mean_population(model), 0) self.assertEqual(egypt_model.compute_mean_wealth(model), 5 * 1000) class TestSettlementMethods(unittest.TestCase): def setUp(self): self.model = egypt_model.EgyptModel(31, 30, starting_settlements=9, starting_households=5, starting_household_size=5, starting_grain=1000) self.settlement = self.model.settlements[0] def test_settlement_workers(self): self.assertEqual(self.settlement.workers(), 5*5) for household in self.settlement.households: household.workers += 1 self.assertEqual(self.settlement.workers(), 5*6) self.settlement.households.remove(self.settlement.households[0]) self.assertEqual(self.settlement.workers(), 4*6) def test_settlement_grain(self): self.assertEqual(self.settlement.grain(), 5*1000) for household in self.settlement.households: household.grain += 1 self.assertEqual(self.settlement.grain(), 5*1001) self.settlement.households.remove(self.settlement.households[0]) self.assertEqual(self.settlement.grain(), 4*1001) class TestHouseholdMethods(unittest.TestCase): def setUp(self): self.model = egypt_model.EgyptModel(31, 30, starting_settlements=9, starting_households=5, starting_household_size=5, starting_grain=1000) self.household = self.model.households[0] self.assertEqual(self.household.grain, 1000) def test_workers(self): self.assertEqual(self.household.workers, 5) self.assertEqual(self.household.workers_worked, 0) def test_storage_loss(self): grain = 1000 self.household.grain = grain self.household.storage_loss() grain -= grain * 0.1 self.assertEqual(self.household.grain, grain) self.household.storage_loss() grain -= grain * 0.1 self.assertEqual(self.household.grain, grain) self.household.storage_loss() grain -= grain * 0.1 self.assertEqual(self.household.grain, grain) def test_consume_grain(self): workers = 5 grain = workers * egypt_model.ANNUAL_PER_PERSON_GRAIN_CONSUMPTION + 1 self.household.grain = grain self.household.workers = workers self.household.consume_grain() self.assertEqual(self.household.grain, grain - workers * egypt_model.ANNUAL_PER_PERSON_GRAIN_CONSUMPTION) self.assertEqual(self.household.workers, workers) grain = workers * egypt_model.ANNUAL_PER_PERSON_GRAIN_CONSUMPTION self.household.grain = grain self.household.workers = workers self.household.consume_grain() self.assertEqual(self.household.grain, 0) self.assertEqual(self.household.workers, workers - 1) workers = 5 grain = workers * egypt_model.ANNUAL_PER_PERSON_GRAIN_CONSUMPTION - 1 self.household.grain = grain self.household.workers = workers self.household.consume_grain() self.assertEqual(self.household.grain, 0) self.assertEqual(self.household.workers, workers - 1) def test_competency_increase(self): self.household.competency = 0.5 self.model.annual_competency_increase = 5 self.assertEqual(self.household.competency, 0.5) self.household.competency_increase() self.assertEqual(self.household.competency, 0.525) self.household.competency_increase() self.assertEqual(self.household.competency, 0.55125) self.model.annual_competency_increase = 0 self.household.competency_increase() self.assertEqual(self.household.competency, 0.55125) def test_generation_changeover(self):
class TestFieldMethods(unittest.TestCase): def setUp(self): self.model = egypt_model.EgyptModel(31, 30, starting_settlements=9, starting_households=5, starting_household_size=5, starting_grain=1000) self.model.fallow_limit = 10 self.household = self.model.households[0] self.field = egypt_model.FieldAgent(1, self.model, self.household) self.household.fields.append(self.field) self.model.fields.append(self.field) self.model.grid.position_agent(self.field, 0,0) self.assertEqual(self.field.unique_id, 1) self.assertEqual(self.field.years_fallowed,0) self.assertFalse(self.field.harvested) def test_changeover(self): for i in range(10): self.field.harvested = True self.field.changeover() self.assertEqual(self.field.years_fallowed, 0) self.assertEqual(self.household, self.field.household) for i in range(9): self.field.changeover() self.assertEqual(self.field.years_fallowed, 9) self.assertEqual(self.household, self.field.household) self.field.changeover() self.assertEqual(self.field.years_fallowed, self.model.fallow_limit) self.assertTrue(self.field not in self.household.fields) self.assertTrue(self.field not in self.model.fields) if __name__ == '__main__': unittest.main()
self.model.min_ambition = 0.2 self.model.min_competency = 0.5 self.household.generation_changeover_countdown = 3 self.household.competency = 0.8 self.household.ambition = 0.4 self.household.generation_changeover() self.assertEqual(self.household.competency, 0.8) self.assertEqual(self.household.ambition, 0.4) self.household.generation_changeover() self.assertEqual(self.household.competency, 0.8) self.assertEqual(self.household.ambition, 0.4) self.household.generation_changeover() self.assertNotEqual(self.household.competency, 0.8) self.assertNotEqual(self.household.competency, 0.4) self.assertTrue(self.household.competency >= 0.5 and self.household.competency <= 1) self.assertTrue(self.household.ambition >= 0.2and self.household.ambition <= 1)
to-have-been-warned.js
if (typeof console === 'undefined') { window.console = { warn: function () {}, error: function () {} } } function
(msg) { var count = console.error.calls.count() var args while (count--) { args = console.error.calls.argsFor(count) if (args.some(containsMsg)) { return true } } function containsMsg (arg) { if (arg instanceof Error) throw arg return typeof arg === 'string' && arg.indexOf(msg) > -1 } } // define custom matcher for warnings beforeEach(() => { spyOn(console, 'error') jasmine.addMatchers({ toHaveBeenWarned: () => { return { compare: msg => { var warned = Array.isArray(msg) ? msg.some(hasWarned) : hasWarned(msg) return { pass: warned, message: warned ? 'Expected message "' + msg + '" not to have been warned' : 'Expected message "' + msg + '" to have been warned' } } } } }) })
hasWarned
CustomPopover.tsx
import React from 'react'; import { Popover, Whisper } from 'rsuite'; import './CustomPopover.scss'; type Placement4 = 'top' | 'bottom' | 'right' | 'left'; type Placement8 = | 'bottomStart' | 'bottomEnd' | 'topStart' | 'topEnd' | 'leftStart' | 'rightStart' | 'leftEnd' | 'rightEnd'; type PlacementAuto = | 'auto' | 'autoVertical' | 'autoVerticalStart' | 'autoVerticalEnd' | 'autoHorizontal' | 'autoHorizontalStart' | 'autoHorizontalEnd';
type OverlayTrigger = 'click' | 'contextMenu' | 'hover' | 'focus' | 'active' | 'none'; type Props = { trigger?: OverlayTrigger; placement: Placement; title?: string; content: string; children: React.ReactElement; }; export const CustomPopover: React.FC<Props> = ({ trigger = 'hover', placement, title, content, children }) => { const speaker = ( <Popover className="custom-popover" title={title}> <p>{content}</p> </Popover> ); return ( <Whisper trigger={trigger} placement={placement} controlId={`control-id-${title}-${content}`} speaker={speaker}> {children} </Whisper> ); };
type Placement = Placement4 | Placement8 | PlacementAuto;
testsummaries_test.go
package testsummaries import ( "fmt" "reflect" "testing" "time" "github.com/bitrise-io/go-xcode/plistutil" "github.com/bitrise-steplib/steps-xcode-test/pretty" ) func TestTimestampToTime(t *testing.T) { time, err := TimestampStrToTime("522675441.31045401") wantErr := false if (err != nil) != wantErr { t.Errorf("TimestampStrToTime() wantErr: %v, got: %v", wantErr, err) } want := []int{ 2017, 7, 25, 11, 37, 21, } got := []int{ time.Year(), int(time.Month()), time.Day(), time.Hour(), time.Minute(), time.Second(), } if !reflect.DeepEqual(want, got) { t.Errorf("TimestampStrToTime() want: %v, got: %v", want, got) } } func Test_parseTestSummaries(t *testing.T) { const testID = "ios_simple_objcTests/testExample" const testStatus = "Success" type args struct { testSummariesContent plistutil.PlistData } tests := []struct { name string args args want []TestResult wantErr bool }{ { name: "Simple, single test result", args: args{ plistutil.PlistData{ "TestableSummaries": []interface{}{ map[string]interface{}{ "Tests": []interface{}{ map[string]interface{}{ "Subtests": []interface{}{ map[string]interface{}{ "TestIdentifier": testID, "TestStatus": testStatus, }, }, }, }, }, }, }, }, want: []TestResult{ { ID: testID, Status: testStatus, FailureInfo: nil, Activities: nil, }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := parseTestSummaries(tt.args.testSummariesContent) // t.Logf(pretty.Object(got)) if (err != nil) != tt.wantErr { t.Errorf("parseTestSummaries() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("parseTestSummaries() = %v, want %v", pretty.Object(got), pretty.Object(tt.want)) } }) } } func Test_parseFailureSummaries(t *testing.T) { type args struct { failureSummariesData []plistutil.PlistData } tests := []struct { name string args args want []FailureSummary wantErr bool }{ { name: "Ok case", args: args{[]plistutil.PlistData{{ "FileName": "/tmp/ios_simple_objcUITests.m", "LineNumber": uint64(64), "Message": "((NO) is true) failed", "PerformanceFailure": false, }}}, want: []FailureSummary{{ FileName: "/tmp/ios_simple_objcUITests.m", LineNumber: 64, Message: "((NO) is true) failed", IsPerformanceFailure: false, }}, wantErr: false, }, { name: "Key FileName not found", args: args{[]plistutil.PlistData{{ "LineNumber": uint64(64), "Message": "((NO) is true) failed", "PerformanceFailure": false, }}}, want: nil, wantErr: true, }, { name: "Key LineNumber not found", args: args{[]plistutil.PlistData{{ "FileName": "/tmp/ios_simple_objcUITests.m", "Message": "((NO) is true) failed", "PerformanceFailure": false, }}}, want: nil, wantErr: true, }, { name: "Key Message not found", args: args{[]plistutil.PlistData{{ "FileName": "/tmp/ios_simple_objcUITests.m", "LineNumber": uint64(64), "PerformanceFailure": false, }}}, want: nil, wantErr: true, }, { name: "Key PerformanceFailure not found", args: args{[]plistutil.PlistData{{ "FileName": "/tmp/ios_simple_objcUITests.m", "LineNumber": uint64(64), "Message": "((NO) is true) failed", }}}, want: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := parseFailureSummaries(tt.args.failureSummariesData) if (err != nil) != tt.wantErr { t.Errorf("parseFailureSummaries() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("parseFailureSummaries() = %v, want %v", pretty.Object(got), pretty.Object(tt.want)) } }) } } func Test_collectLastSubtests(t *testing.T) { type args struct { testsItem plistutil.PlistData } tests := []struct { name string args args want []plistutil.PlistData wantErr bool }{ { name: "Simple case", args: args{ map[string]interface{}{ "1": "", "Subtests": []interface{}{ map[string]interface{}{ "2": "", "Subtests": []interface{}{ map[string]interface{}{ "3": "", }}, }}, }, }, want: []plistutil.PlistData{map[string]interface{}{ "3": "", }}, wantErr: false, }, { name: "Multiple levels", args: args{ map[string]interface{}{ "1": "", "Subtests": []interface{}{ map[string]interface{}{ "2": "", "Subtests": []interface{}{ map[string]interface{}{ "3": "", }, }, }, map[string]interface{}{ "4": "", }, }, }, }, want: []plistutil.PlistData{ { "3": "", }, { "4": "", }}, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := collectLastSubtests(tt.args.testsItem) if (err != nil) != tt.wantErr { t.Errorf("collectLastSubtests() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("collectLastSubtests() = %v, want %v", got, tt.want) } }) } } func Test_parseActivites(t *testing.T) { type args struct { activitySummariesData []plistutil.PlistData } tests := []struct { name string args args want []Activity wantErr bool }{ { name: "Simple case", args: args{[]plistutil.PlistData{{ "Title": "Start Test", "UUID": "CE23D189-E75A-437D-A4B5-B97F1658FC98", "StartTimeInterval": 568123776.87169898, }}}, want: []Activity{{ Title: "Start Test", UUID: "CE23D189-E75A-437D-A4B5-B97F1658FC98", Screenshots: nil, SubActivities: nil, }}, wantErr: false, }, { name: "Subactivty case", args: args{[]plistutil.PlistData{{ "Title": "Start Test", "UUID": "CE23D189-E75A-437D-A4B5-B97F1658FC98", "StartTimeInterval": 568123776.87169898, "SubActivities": []interface{}{ map[string]interface{}{ "Title": "Launch", "UUID": "1D7E1C6A-D0A3-432F-819F-64BE07C30517", "StartTimeInterval": 568123780.54294205, }, }, }}}, want: []Activity{{ Title: "Start Test", UUID: "CE23D189-E75A-437D-A4B5-B97F1658FC98", Screenshots: nil, SubActivities: []Activity{{ Title: "Launch", UUID: "1D7E1C6A-D0A3-432F-819F-64BE07C30517", Screenshots: nil, SubActivities: nil, }}, }}, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := parseActivites(tt.args.activitySummariesData) if (err != nil) != tt.wantErr { t.Errorf("parseActivites() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("parseActivites() = %v, want %v", pretty.Object(got), pretty.Object(tt.want)) } }) } } func Test_parseSceenshots(t *testing.T)
{ const fileName = "Screenshot of main screen (ID 1)_1_A07C26DB-8E1E-46ED-90F2-981438BE0BBA.png" const attachmentTimeStampFloat = 568123782.31287897 const activityUUIDinLegacyScreenshotName = "C02EF626-0892-4B50-9B98-70D6F2C3EFE5" activityStartTimeForLegacyScreenshot := time.Now() type args struct { activitySummary plistutil.PlistData activityUUID string activityStartTime time.Time } tests := []struct { name string args args want []Screenshot wantErr bool }{ { name: "Attachments (new)", args: args{ activitySummary: plistutil.PlistData{ "Title": "Start Test", "UUID": "CE23D189-E75A-437D-A4B5-B97F1658FC98", "StartTimeInterval": 568123776.87169898, "Attachments": []interface{}{ map[string]interface{}{ "Filename": fileName, "Name": "Screenshot of main screen (ID 1)", "Timestamp": attachmentTimeStampFloat, }, }, }, activityUUID: "C02EF626-0892-4B50-9B98-70D6F2C3EFE5", activityStartTime: time.Time{}, }, want: []Screenshot{{ FileName: fileName, TimeCreated: TimestampToTime(attachmentTimeStampFloat), }}, wantErr: false, }, { name: "Screenhot data (legacy)", args: args{ activitySummary: plistutil.PlistData{ "Title": "Start Test", "UUID": "CE23D189-E75A-437D-A4B5-B97F1658FC98", "StartTimeInterval": 568123776.87169898, "HasScreenshotData": true, }, activityUUID: activityUUIDinLegacyScreenshotName, activityStartTime: activityStartTimeForLegacyScreenshot, }, want: []Screenshot{ { FileName: fmt.Sprintf("Screenshot_%s.%s", activityUUIDinLegacyScreenshotName, "png"), TimeCreated: activityStartTimeForLegacyScreenshot, }, { FileName: fmt.Sprintf("Screenshot_%s.%s", activityUUIDinLegacyScreenshotName, "jpg"), TimeCreated: activityStartTimeForLegacyScreenshot, }}, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := parseSceenshots(tt.args.activitySummary, tt.args.activityUUID, tt.args.activityStartTime) if (err != nil) != tt.wantErr { t.Errorf("parseSceenshots() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("parseSceenshots() = %v, want %v", pretty.Object(got), pretty.Object(tt.want)) } }) } }
randomdest.py
"""randomdest.py - dearpygui app to plot random destinations""" import math import os import random import requests from dotenv import load_dotenv from dearpygui.core import * from dearpygui.simple import * # globals/constants EARTH_RADIUS = 6378.1 MAX_DIST = 16 # destination radius in KM maps_key = "" BASE_URL = "https://dev.virtualearth.net/REST/v1/Imagery/Map/AerialWithLabels/" zoom = "18" distance = MAX_DIST img_size_x = 900 img_size_y = 900 img_file_name = "pic1.png" def plot_location(latitude, longitude, bearing, distance): """Plot a new location based on starting point, bearing and distance""" bearing_rad = math.radians(bearing) lat1 = math.radians(latitude) lon1 = math.radians(longitude) d_over_r = distance / EARTH_RADIUS lat2 = math.asin( math.sin(lat1) * math.cos(d_over_r) + math.cos(lat1) * math.sin(d_over_r) * math.cos(bearing_rad) ) lon2 = lon1 + math.atan2( math.sin(bearing_rad) * math.sin(d_over_r) * math.cos(lat1), math.cos(d_over_r) - math.sin(lat1) * math.sin(lat2), ) lat2 = round(math.degrees(lat2), 6) lon2 = round(math.degrees(lon2), 6) return [lat2, lon2] def get_random_location(latitude, longitude, radius_km): """Return coordinates for a random location based on starting point and radius""" global distance # update distance as a global - it will be used to calculate route zoom # get random destination and distance bearing = round(random.uniform(0, 360),3 ) distance = round(random.uniform(0, radius_km), 3) # set zoom based on distance # print(f"Bearing: {str(bearing)}, Distance (km): {str(distance_km)}") set_value("bearing_label", f"Bearing: {str(bearing)}°, Distance: {str(distance)} km") # calculate the new latitude and longitude return plot_location(latitude, longitude, bearing, distance) def get_image(coords): """Get a new Bing maps image for specified coordinates and save it as a PNG file""" pic_url = f"{BASE_URL}{coords}/{zoom}?mapSize={str(img_size_x)},{str(img_size_y)}&pp={coords};;1&dcl=1&key={maps_key}" image_data = requests.get(pic_url).content with open(img_file_name, "wb") as handler: handler.write(image_data) def get_route_image(coords1, coords2, zoom, midpoint): """Get a new Bing maps image for specified coordinates and save it as a PNG file""" pic_url = f"{BASE_URL}{midpoint}/{zoom}/Routes/Driving?waypoint.1={coords1}&waypoint.2={coords2}&mapSize={str(img_size_x)},{str(img_size_y)}&imagerySet=AerialWithLabels&key={maps_key}" image_data = requests.get(pic_url).content with open(img_file_name, "wb") as handler: handler.write(image_data) def get_midpoint(coord1, coord2): '''Get the midway point between 2 coordinates, input and output are strings''' coord1_list = coord1.split(',') coord2_list = coord2.split(',') lat1 = float(coord1_list[0]) lon1 = float(coord1_list[1]) lat2 = float(coord2_list[0]) lon2 = float(coord2_list[1]) midlat = lat1 + (lat2 - lat1)/2 midlon = lon1 + (lon2 - lon1)/2 return f"{str(midlat)},{str(midlon)}" def s
sender, callback): """Get the coordinates from the UI and get the Bing maps image for those coords""" coords = get_value("Coords") get_image(coords) # update canvas clear_drawing("canvas") draw_image("canvas", img_file_name, [0, 0], pmax=[img_size_x, img_size_y]) def show_destination(sender, callback): """Display a map image for the destination coordinates""" coords = get_value("destination_text") if len(coords) < 3: print("No destination") # to do: convert this message to a popup return get_image(coords) # update canvas clear_drawing("canvas") draw_image("canvas", img_file_name, [0, 0], pmax=[img_size_x, img_size_y]) def show_route(sender, callback): """Display a map image for the destination coordinates""" coords1 = get_value("Coords") coords2 = get_value("destination_text") if len(coords2) < 3: print("No destination") # to do: convert this message to a popup return midpoint = get_midpoint(coords1, coords2) # zoom of route map will be proportional to distance to make it fit on canvas if distance < 1.8: route_zoom = 16 elif distance < 3: route_zoom = 15 elif distance < 6.5: route_zoom = 14 elif distance < 12: route_zoom = 13 else: route_zoom = 12 get_route_image(coords1, coords2, route_zoom, midpoint) # update canvas clear_drawing("canvas") draw_image("canvas", img_file_name, [0, 0], pmax=[img_size_x, img_size_y]) def get_random_destination(sender, callback): """Get new random destination based on starting coordinates""" coords = get_value("Coords") # calculate new coords and write then in the destination text box coord_list = coords.split(",") latitude = float(coord_list[0]) longitude = float(coord_list[1]) new_coords = get_random_location(latitude, longitude, MAX_DIST) new_coords_str = f"{str(new_coords[0])},{str(new_coords[1])}" set_value("destination_text", new_coords_str) def main(): """main routine to draw the UI and start the GUI""" global maps_key load_dotenv() maps_key = os.environ.get("BING_MAPS_KEY") coords = os.environ.get("DEFAULT_COORDS") # set main window defaults set_main_window_size(img_size_x + 20, img_size_y + 130) set_main_window_pos(100, 25) set_main_window_title("Random destination app") with window("Main"): add_text("Coordinates: ") add_same_line() add_input_text( "Coords", label="", default_value=coords, width=170, callback=show_origin, on_enter=True, ) add_same_line() add_button("Show origin", callback=show_origin) add_text("Destination: ") add_same_line() add_input_text("destination_text", label="", width=170) add_same_line() add_button("Random destination", callback=get_random_destination) add_same_line() add_button("Show destination", callback=show_destination) add_same_line() add_button("Show route", callback=show_route) add_text("bearing_label", default_value=" ") add_spacing() add_separator() add_spacing() add_drawing("canvas", width=img_size_x, height=img_size_y) # if os.path.isfile(img_file_name): # draw_image("canvas", img_file_name, [0, 0], pmax=[img_size_x, img_size_y]) start_dearpygui(primary_window="Main") if __name__ == "__main__": main()
how_origin(
stream.rs
use super::split::{ split, split_mut, TcpStreamReadHalf, TcpStreamReadHalfMut, TcpStreamWriteHalf, TcpStreamWriteHalfMut, }; use crate::driver::Handle; use crate::util::PollEvented; use crate::ToSocketAddrs; use tokio_io::{AsyncRead, AsyncWrite}; use bytes::{Buf, BufMut}; use futures_core::ready; use futures_util::future::poll_fn; use iovec::IoVec; use mio; use std::convert::TryFrom; use std::fmt; use std::io::{self, Read, Write}; use std::net::{self, Shutdown, SocketAddr}; use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; /// An I/O object representing a TCP stream connected to a remote endpoint. /// /// A TCP stream can either be created by connecting to an endpoint, via the /// [`connect`] method, or by [accepting] a connection from a [listener]. /// /// [`connect`]: struct.TcpStream.html#method.connect /// [accepting]: struct.TcpListener.html#method.accept /// [listener]: struct.TcpListener.html /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// use tokio::prelude::*; /// use std::error::Error; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn Error>> { /// // Connect to a peer /// let mut stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// // Write some data. /// stream.write_all(b"hello world!").await?; /// /// Ok(()) /// } /// ``` pub struct TcpStream { io: PollEvented<mio::net::TcpStream>, } impl TcpStream { /// Opens a TCP connection to a remote host. /// /// `addr` is an address of the remote host. Anything which implements /// `ToSocketAddrs` trait can be supplied for the address. /// /// If `addr` yields multiple addresses, connect will be attempted with each /// of the addresses until a connection is successful. If none of the /// addresses result in a successful connection, the error returned from the /// last connection attempt (the last address) is returned. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// use tokio::prelude::*; /// use std::error::Error; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn Error>> { /// // Connect to a peer /// let mut stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// // Write some data. /// stream.write_all(b"hello world!").await?; /// /// Ok(()) /// } /// ``` pub async fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> { let addrs = addr.to_socket_addrs().await?; let mut last_err = None; for addr in addrs { match TcpStream::connect_addr(addr).await { Ok(stream) => return Ok(stream), Err(e) => last_err = Some(e), } } Err(last_err.unwrap_or_else(|| { io::Error::new( io::ErrorKind::InvalidInput, "could not resolve to any addresses", ) })) } /// Establish a connection to the specified `addr`. async fn connect_addr(addr: SocketAddr) -> io::Result<TcpStream> { let sys = mio::net::TcpStream::connect(&addr)?; let stream = TcpStream::new(sys); // Once we've connected, wait for the stream to be writable as // that's when the actual connection has been initiated. Once we're // writable we check for `take_socket_error` to see if the connect // actually hit an error or not. // // If all that succeeded then we ship everything on up. poll_fn(|cx| stream.io.poll_write_ready(cx)).await?; if let Some(e) = stream.io.get_ref().take_error()? { return Err(e); } Ok(stream) } pub(crate) fn new(connected: mio::net::TcpStream) -> TcpStream { let io = PollEvented::new(connected); TcpStream { io } } /// Create a new `TcpStream` from a `std::net::TcpStream`. /// /// This function will convert a TCP stream created by the standard library /// to a TCP stream ready to be used with the provided event loop handle. /// Use `Handle::default()` to lazily bind to an event loop, just like `connect` does. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// use tokio_net::driver::Handle; /// /// # fn dox() -> std::io::Result<()> { /// let std_stream = std::net::TcpStream::connect("127.0.0.1:34254")?; /// let stream = TcpStream::from_std(std_stream, &Handle::default())?; /// # Ok(()) /// # } /// ``` pub fn from_std(stream: net::TcpStream, handle: &Handle) -> io::Result<TcpStream> { let io = mio::net::TcpStream::from_stream(stream)?; let io = PollEvented::new_with_handle(io, handle)?; Ok(TcpStream { io }) } // Connect a TcpStream asynchronously that may be built with a net2 TcpBuilder. // // This should be removed in favor of some in-crate TcpSocket builder API. #[doc(hidden)] pub async fn connect_std( stream: net::TcpStream, addr: &SocketAddr, handle: &Handle, ) -> io::Result<TcpStream> { let io = mio::net::TcpStream::connect_stream(stream, addr)?; let io = PollEvented::new_with_handle(io, handle)?; let stream = TcpStream { io }; // Once we've connected, wait for the stream to be writable as // that's when the actual connection has been initiated. Once we're // writable we check for `take_socket_error` to see if the connect // actually hit an error or not. // // If all that succeeded then we ship everything on up. poll_fn(|cx| stream.io.poll_write_ready(cx)).await?; if let Some(e) = stream.io.get_ref().take_error()? { return Err(e); } Ok(stream) } /// Returns the local address that this stream is bound to. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// println!("{:?}", stream.local_addr()?); /// # Ok(()) /// # } /// ``` pub fn local_addr(&self) -> io::Result<SocketAddr> { self.io.get_ref().local_addr() } /// Returns the remote address that this stream is connected to. /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// println!("{:?}", stream.peer_addr()?); /// # Ok(()) /// # } /// ``` pub fn peer_addr(&self) -> io::Result<SocketAddr> { self.io.get_ref().peer_addr() } fn poll_peek(&mut self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> { ready!(self.io.poll_read_ready(cx, mio::Ready::readable()))?; match self.io.get_ref().peek(buf) { Ok(ret) => Poll::Ready(Ok(ret)), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { self.io.clear_read_ready(cx, mio::Ready::readable())?; Poll::Pending } Err(e) => Poll::Ready(Err(e)), } } /// Receives data on the socket from the remote address to which it is /// connected, without removing that data from the queue. On success, /// returns the number of bytes peeked. /// /// Successive calls return the same data. This is accomplished by passing /// `MSG_PEEK` as a flag to the underlying recv system call. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// use tokio::prelude::*; /// use std::error::Error; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn Error>> { /// // Connect to a peer /// let mut stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// let mut b1 = [0; 10]; /// let mut b2 = [0; 10]; /// /// // Peek at the data /// let n = stream.peek(&mut b1).await?; /// /// // Read the data /// assert_eq!(n, stream.read(&mut b2[..n]).await?); /// assert_eq!(&b1[..n], &b2[..n]); /// /// Ok(()) /// } /// ``` pub async fn peek(&mut self, buf: &mut [u8]) -> io::Result<usize> { poll_fn(|cx| self.poll_peek(cx, buf)).await } /// Shuts down the read, write, or both halves of this connection. /// /// This function will cause all pending and future I/O on the specified /// portions to return immediately with an appropriate value (see the /// documentation of `Shutdown`). /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// use tokio::prelude::*; /// use std::error::Error; /// use std::net::Shutdown; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn Error>> { /// // Connect to a peer /// let mut stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// // Shutdown the stream /// stream.shutdown(Shutdown::Write)?; /// /// Ok(()) /// } /// ``` pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { self.io.get_ref().shutdown(how) } /// Gets the value of the `TCP_NODELAY` option on this socket. /// /// For more information about this option, see [`set_nodelay`]. /// /// [`set_nodelay`]: #method.set_nodelay /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// println!("{:?}", stream.nodelay()?); /// # Ok(()) /// # } /// ``` pub fn nodelay(&self) -> io::Result<bool> { self.io.get_ref().nodelay() } /// Sets the value of the `TCP_NODELAY` option on this socket. /// /// If set, this option disables the Nagle algorithm. This means that /// segments are always sent as soon as possible, even if there is only a /// small amount of data. When not set, data is buffered until there is a /// sufficient amount to send out, thereby avoiding the frequent sending of /// small packets. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// stream.set_nodelay(true)?; /// # Ok(()) /// # } /// ``` pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { self.io.get_ref().set_nodelay(nodelay) } /// Gets the value of the `SO_RCVBUF` option on this socket. /// /// For more information about this option, see [`set_recv_buffer_size`]. /// /// [`set_recv_buffer_size`]: #tymethod.set_recv_buffer_size /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// println!("{:?}", stream.recv_buffer_size()?); /// # Ok(()) /// # } /// ``` pub fn recv_buffer_size(&self) -> io::Result<usize> { self.io.get_ref().recv_buffer_size() } /// Sets the value of the `SO_RCVBUF` option on this socket. /// /// Changes the size of the operating system's receive buffer associated /// with the socket. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// stream.set_recv_buffer_size(100)?; /// # Ok(()) /// # } /// ``` pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { self.io.get_ref().set_recv_buffer_size(size) } /// Gets the value of the `SO_SNDBUF` option on this socket. /// /// For more information about this option, see [`set_send_buffer`]. /// /// [`set_send_buffer`]: #tymethod.set_send_buffer /// /// # Examples /// /// Returns whether keepalive messages are enabled on this socket, and if so /// the duration of time between them. /// /// For more information about this option, see [`set_keepalive`]. /// /// [`set_keepalive`]: #tymethod.set_keepalive /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// println!("{:?}", stream.send_buffer_size()?); /// # Ok(()) /// # } /// ``` pub fn send_buffer_size(&self) -> io::Result<usize> { self.io.get_ref().send_buffer_size() } /// Sets the value of the `SO_SNDBUF` option on this socket. /// /// Changes the size of the operating system's send buffer associated with /// the socket. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// stream.set_send_buffer_size(100)?; /// # Ok(()) /// # } /// ``` pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { self.io.get_ref().set_send_buffer_size(size) } /// Returns whether keepalive messages are enabled on this socket, and if so /// the duration of time between them. /// /// For more information about this option, see [`set_keepalive`]. /// /// [`set_keepalive`]: #tymethod.set_keepalive /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// println!("{:?}", stream.keepalive()?); /// # Ok(()) /// # } /// ``` pub fn keepalive(&self) -> io::Result<Option<Duration>> { self.io.get_ref().keepalive() } /// Sets whether keepalive messages are enabled to be sent on this socket. /// /// On Unix, this option will set the `SO_KEEPALIVE` as well as the /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform). /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option. /// /// If `None` is specified then keepalive messages are disabled, otherwise /// the duration specified will be the time to remain idle before sending a /// TCP keepalive probe. /// /// Some platforms specify this value in seconds, so sub-second /// specifications may be omitted. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// stream.set_keepalive(None)?; /// # Ok(()) /// # } /// ``` pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { self.io.get_ref().set_keepalive(keepalive) } /// Gets the value of the `IP_TTL` option for this socket. /// /// For more information about this option, see [`set_ttl`]. /// /// [`set_ttl`]: #tymethod.set_ttl /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// println!("{:?}", stream.ttl()?); /// # Ok(()) /// # } /// ``` pub fn ttl(&self) -> io::Result<u32> { self.io.get_ref().ttl() } /// Sets the value for the `IP_TTL` option on this socket. /// /// This value sets the time-to-live field that is used in every packet sent /// from this socket. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// stream.set_ttl(123)?; /// # Ok(()) /// # } /// ``` pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.io.get_ref().set_ttl(ttl) } /// Reads the linger duration for this socket by getting the `SO_LINGER` /// option. /// /// For more information about this option, see [`set_linger`]. /// /// [`set_linger`]: #tymethod.set_linger /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// println!("{:?}", stream.linger()?); /// # Ok(()) /// # } /// ``` pub fn linger(&self) -> io::Result<Option<Duration>> { self.io.get_ref().linger() } /// Sets the linger duration of this socket by setting the `SO_LINGER` /// option. /// /// This option controls the action taken when a stream has unsent messages /// and the stream is closed. If `SO_LINGER` is set, the system /// shall block the process until it can transmit the data or until the /// time expires. /// /// If `SO_LINGER` is not specified, and the stream is closed, the system /// handles the call in a way that allows the process to continue as quickly /// as possible. /// /// # Examples /// /// ```no_run /// use tokio::net::TcpStream; /// /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { /// let stream = TcpStream::connect("127.0.0.1:8080").await?; /// /// stream.set_linger(None)?; /// # Ok(()) /// # } /// ``` pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { self.io.get_ref().set_linger(dur) } /// Split a `TcpStream` into a read half and a write half, which can be used /// to read and write the stream concurrently. /// /// See the module level documenation of [`split`](super::split) for more /// details. pub fn split(self) -> (TcpStreamReadHalf, TcpStreamWriteHalf) { split(self) } /// Split a `TcpStream` into a read half and a write half, which can be used /// to read and write the stream concurrently. /// /// See the module level documenation of [`split`](super::split) for more /// details. pub fn split_mut(&mut self) -> (TcpStreamReadHalfMut<'_>, TcpStreamWriteHalfMut<'_>) { split_mut(self) } // == Poll IO functions that takes `&self` == // // They are not public because (taken from the doc of `PollEvented`): // // While `PollEvented` is `Sync` (if the underlying I/O type is `Sync`), the // caller must ensure that there are at most two tasks that use a // `PollEvented` instance concurrently. One for reading and one for writing. // While violating this requirement is "safe" from a Rust memory model point // of view, it will result in unexpected behavior in the form of lost
// notifications and tasks hanging. pub(crate) fn poll_read_priv( &self, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { ready!(self.io.poll_read_ready(cx, mio::Ready::readable()))?; match self.io.get_ref().read(buf) { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { self.io.clear_read_ready(cx, mio::Ready::readable())?; Poll::Pending } x => Poll::Ready(x), } } pub(crate) fn poll_read_buf_priv<B: BufMut>( &self, cx: &mut Context<'_>, buf: &mut B, ) -> Poll<io::Result<usize>> { ready!(self.io.poll_read_ready(cx, mio::Ready::readable()))?; let r = unsafe { // The `IoVec` type can't have a 0-length size, so we create a bunch // of dummy versions on the stack with 1 length which we'll quickly // overwrite. let b1: &mut [u8] = &mut [0]; let b2: &mut [u8] = &mut [0]; let b3: &mut [u8] = &mut [0]; let b4: &mut [u8] = &mut [0]; let b5: &mut [u8] = &mut [0]; let b6: &mut [u8] = &mut [0]; let b7: &mut [u8] = &mut [0]; let b8: &mut [u8] = &mut [0]; let b9: &mut [u8] = &mut [0]; let b10: &mut [u8] = &mut [0]; let b11: &mut [u8] = &mut [0]; let b12: &mut [u8] = &mut [0]; let b13: &mut [u8] = &mut [0]; let b14: &mut [u8] = &mut [0]; let b15: &mut [u8] = &mut [0]; let b16: &mut [u8] = &mut [0]; let mut bufs: [&mut IoVec; 16] = [ b1.into(), b2.into(), b3.into(), b4.into(), b5.into(), b6.into(), b7.into(), b8.into(), b9.into(), b10.into(), b11.into(), b12.into(), b13.into(), b14.into(), b15.into(), b16.into(), ]; let n = buf.bytes_vec_mut(&mut bufs); self.io.get_ref().read_bufs(&mut bufs[..n]) }; match r { Ok(n) => { unsafe { buf.advance_mut(n); } trace!(tcp.written.bytes = n); Poll::Ready(Ok(n)) } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { self.io.clear_read_ready(cx, mio::Ready::readable())?; Poll::Pending } Err(e) => Poll::Ready(Err(e)), } } pub(crate) fn poll_write_priv( &self, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { ready!(self.io.poll_write_ready(cx))?; match self.io.get_ref().write(buf) { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { self.io.clear_write_ready(cx)?; Poll::Pending } x => Poll::Ready(x), } } pub(crate) fn poll_write_buf_priv<B: Buf>( &self, cx: &mut Context<'_>, buf: &mut B, ) -> Poll<io::Result<usize>> { ready!(self.io.poll_write_ready(cx))?; let r = { // The `IoVec` type can't have a zero-length size, so create a dummy // version from a 1-length slice which we'll overwrite with the // `bytes_vec` method. static DUMMY: &[u8] = &[0]; let iovec = <&IoVec>::from(DUMMY); let mut bufs = [iovec; 64]; let n = buf.bytes_vec(&mut bufs); self.io.get_ref().write_bufs(&bufs[..n]) }; match r { Ok(n) => { buf.advance(n); Poll::Ready(Ok(n)) } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { self.io.clear_write_ready(cx)?; Poll::Pending } Err(e) => Poll::Ready(Err(e)), } } } impl TryFrom<TcpStream> for mio::net::TcpStream { type Error = io::Error; /// Consumes value, returning the mio I/O object. /// /// See [`PollEvented::into_inner`] for more details about /// resource deregistration that happens during the call. /// /// [`PollEvented::into_inner`]: crate::util::PollEvented::into_inner fn try_from(value: TcpStream) -> Result<Self, Self::Error> { value.io.into_inner() } } impl TryFrom<net::TcpStream> for TcpStream { type Error = io::Error; /// Consumes stream, returning the tokio I/O object. /// /// This is equivalent to /// [`TcpStream::from_std(stream, &Handle::default())`](TcpStream::from_std). fn try_from(stream: net::TcpStream) -> Result<Self, Self::Error> { Self::from_std(stream, &Handle::default()) } } // ===== impl Read / Write ===== impl AsyncRead for TcpStream { unsafe fn prepare_uninitialized_buffer(&self, _: &mut [u8]) -> bool { false } fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { self.poll_read_priv(cx, buf) } fn poll_read_buf<B: BufMut>( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut B, ) -> Poll<io::Result<usize>> { self.poll_read_buf_priv(cx, buf) } } impl AsyncWrite for TcpStream { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { self.poll_write_priv(cx, buf) } #[inline] fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { // tcp flush is a no-op Poll::Ready(Ok(())) } fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { self.shutdown(std::net::Shutdown::Write)?; Poll::Ready(Ok(())) } fn poll_write_buf<B: Buf>( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut B, ) -> Poll<io::Result<usize>> { self.poll_write_buf_priv(cx, buf) } } impl fmt::Debug for TcpStream { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.io.get_ref().fmt(f) } } #[cfg(unix)] mod sys { use super::TcpStream; use std::os::unix::prelude::*; impl AsRawFd for TcpStream { fn as_raw_fd(&self) -> RawFd { self.io.get_ref().as_raw_fd() } } } #[cfg(windows)] mod sys { // TODO: let's land these upstream with mio and then we can add them here. // // use std::os::windows::prelude::*; // use super::TcpStream; // // impl AsRawHandle for TcpStream { // fn as_raw_handle(&self) -> RawHandle { // self.io.get_ref().as_raw_handle() // } // } }
completion.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package completion implements the `completion` command package completion
"sigs.k8s.io/kind/cmd/kind/completion/zsh" ) // NewCommand returns a new cobra.Command for cluster creation func NewCommand() *cobra.Command { cmd := &cobra.Command{ Args: cobra.NoArgs, Use: "completion", Short: "Output shell completion code for the specified shell (bash or zsh)", Long: longDescription, } cmd.AddCommand(zsh.NewCommand()) cmd.AddCommand(bash.NewCommand()) return cmd } const longDescription = ` Outputs kind shell completion for the given shell (bash or zsh) This depends on the bash-completion binary. Example installation instructions: # for bash users $ kind completion bash > ~/.kind-completion $ source ~/.kind-completion # for zsh users % kind completion zsh > /usr/local/share/zsh/site-functions/_kind % autoload -U compinit && compinit Additionally, you may want to output the completion to a file and source in your .bashrc Note for zsh users: [1] zsh completions are only supported in versions of zsh >= 5.2 `
import ( "github.com/spf13/cobra" "sigs.k8s.io/kind/cmd/kind/completion/bash"
kill.go
package cmd import ( "github.com/spf13/cobra" "github.com/whiteblock/cli/whiteblock/util" ) var killCmd = &cobra.Command{ Aliases: []string{}, Use: "kill <node>", Short: "Raise SIGINT to a node's main process and wait for it to die", Long: `Sends SIGINT to the node's main process, and continue to query the state of that process until it dies. `, Run: func(cmd *cobra.Command, args []string) { util.CheckArguments(cmd, args, 1, 1) testnetId, err := getPreviousBuildId() if err != nil
util.JsonRpcCallAndPrint("kill_node", []interface{}{testnetId, args[0]}) }, } func init() { RootCmd.AddCommand(killCmd) }
{ util.PrintErrorFatal(err) }
torch_ods_gen.py
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Also available under a BSD-style license. See LICENSE. """Queries the pytorch op registry and generates ODS and CC sources for the ops. """ from typing import List, Optional, TextIO import argparse import logging import os import sys from .utils import TextEmitter from .registry import Registry, JitOperator # Mapping from torch types to their corresponding ODS type predicates. # Use `get_ods_type` instead of using this directly. TORCH_TYPE_TO_ODS_TYPE = { "Tensor": "AnyTorchTensorType", "Tensor?": "AnyTorchOptionalTensorType", "Tensor?[]": "AnyTorchListOfOptionalTensorType", "Tensor[]": "AnyTorchListOfTensorType", "Scalar": "AnyTorchScalarType", "Scalar?": "AnyTorchOptionalScalarType", "int": "Torch_IntType", "int[]": "AnyTorchListOfTorchIntType", "int?": "AnyTorchOptionalIntType", "int[]?": "AnyTorchOptionalListOfTorchIntType", "bool": "Torch_BoolType", "bool[]": "AnyTorchListOfTorchBoolType", "bool?": "AnyTorchOptionalBoolType", "float": "Torch_FloatType", "float?": "AnyTorchOptionalFloatType", "t[]": "AnyTorchListType", "t": "AnyTorchType", "t1": "AnyTorchType", "t2": "AnyTorchType", "Any": "AnyTorchType", "Device": "Torch_DeviceType", "Device?": "AnyTorchOptionalDeviceType", "Generator": "Torch_GeneratorType", "Generator?": "AnyTorchOptionalGeneratorType", "str": "Torch_StringType", "str?": "AnyTorchOptionalStringType", "str[]": "AnyTorchListOfTorchStringType", "Dict": "Torch_DictType", "__torch__.torch.classes.quantized.LinearPackedParamsBase": "Torch_LinearParamsType", } def get_ods_type(type: str): # TODO: Increase precision on dict type modeling. if type.startswith("Dict("): type = "Dict" ods_type = TORCH_TYPE_TO_ODS_TYPE.get(type) if ods_type is None: raise Exception( f"{type!r} not in TORCH_TYPE_TO_ODS_TYPE mapping. Please add it!") return ods_type def _get_main_module_name() -> str: # pytype: disable=attribute-error return sys.modules["__main__"].__loader__.name # pytype: enable=attribute-error ODS_BANNER = f"""//===-------------------------------------------------------*- tablegen -*-===// // // This file is licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // Also available under a BSD-style license. See LICENSE. // // Operation summaries and descriptions were systematically derived from public // API docstrings and are licensed accordingly: // https://github.com/pytorch/pytorch/blob/master/LICENSE //===----------------------------------------------------------------------===// // // This file is automatically generated. Please do not edit. // Generated via: // ``` // python -m {_get_main_module_name()} // ``` // //===----------------------------------------------------------------------===// """ def raw_emit_op(operator: JitOperator, emitter_td: TextEmitter, *, traits: List[str], has_folder: bool, has_canonicalizer: bool): """Emit the ODS for a JitOperator to a textual file. This is the lowest level of emission and is responsible for low-level textual emission details. This function should not have any "smarts" for deducing traits/etc. You probably don't want to call this directly. """ p_td = lambda *args: emitter_td.print(*args) op_name, cpp_class_name = operator.get_mlir_names() # Generate unique result names for ops with nameless results multiple_results = len(operator.returns) > 1 def generic_result_name(i): return "result" + (str(i) if multiple_results else "") p_td( f"def Torch_{cpp_class_name} : Torch_Op<{emitter_td.quote(op_name)}, [") with emitter_td.indent(): with emitter_td.indent(): p_td(",\n".join(traits)) p_td("]> {") with emitter_td.indent(): summary = f"Generated op for `{operator.unique_key}`" p_td(f"let summary = {emitter_td.quote(summary)};") p_td(f"let arguments = (ins") with emitter_td.indent(): if operator.is_vararg: p_td("Variadic<AnyTorchType>:$operands") else: p_td(",\n".join([ f"""{get_ods_type(arg["type"])}:${arg["name"]}""" for arg in operator.arguments ])) p_td(");") p_td(f"let results = (outs") with emitter_td.indent(): if operator.is_varret: p_td("Variadic<AnyTorchType>:$results") else: p_td(",\n".join([ f"""{get_ods_type(ret["type"])}:${ret["name"] or generic_result_name(e)}""" for e, ret in enumerate(operator.returns) ])) p_td(");") if operator.is_vararg or operator.is_varret: if operator.is_vararg: assembly_operands = "`(` $operands `)`" assembly_operand_types = "qualified(type($operands))" else: assembly_operands = " `,` ".join("$" + arg["name"] for arg in operator.arguments) assembly_operand_types = " `,` ".join( f"""qualified(type(${arg["name"]}))""" for arg in operator.arguments) if operator.is_varret: assembly_result_types = "qualified(type($results))" else: assembly_result_types = " `,` ".join( f"""qualified(type(${ret["name"] or generic_result_name(e)}))""" for e, ret in enumerate(operator.returns)) if assembly_operand_types and assembly_result_types: maybe_arrow = " `->` " else: maybe_arrow = "" assembly_format = f"{assembly_operands} attr-dict `:` {assembly_operand_types}{maybe_arrow}{assembly_result_types}" p_td(f"let assemblyFormat = {emitter_td.quote(assembly_format)};") else: p_td(f"let hasCustomAssemblyFormat = 1;") p_td(f"""let extraClassDefinition = [{{ ParseResult {cpp_class_name}::parse(OpAsmParser &parser, OperationState &result) {{ return parseDefaultTorchOp(parser, result, {len(operator.arguments)}, {len(operator.returns)}); }} void {cpp_class_name}::print(OpAsmPrinter &printer) {{ printDefaultTorchOp(printer, *this, {len(operator.arguments)}, {len(operator.returns)}); }} }}]; """) if has_folder: p_td("let hasFolder = 1;") if has_canonicalizer: p_td("let hasCanonicalizer = 1;") p_td("}") p_td("\n") def emit_op(operator: JitOperator, emitter_td: TextEmitter, *, traits: Optional[List[str]] = None, has_folder: bool = False, has_canonicalizer: bool = False):
def emit_ops(emitter_td: TextEmitter, registry: Registry): def emit(key, **kwargs): emit_op(registry[key], emitter_td, **kwargs) def emit_with_mutating_variants(key, **kwargs): operator = registry[key] emit_op(operator, emitter_td, **kwargs) ns, unqual, overload = operator.triple emit_op(registry.get_by_triple((ns, unqual + "_", overload)), emitter_td, traits=["IsTrailingUnderscoreInplaceVariant"]) # ========================================================================== # `aten::` namespace. # ========================================================================== # Elementwise tensor compute ops for key in [ "aten::tanh : (Tensor) -> (Tensor)", "aten::hardtanh : (Tensor, Scalar, Scalar) -> (Tensor)", "aten::relu : (Tensor) -> (Tensor)", "aten::leaky_relu : (Tensor, Scalar) -> (Tensor)", "aten::log : (Tensor) -> (Tensor)", "aten::sigmoid : (Tensor) -> (Tensor)", "aten::hardsigmoid : (Tensor) -> (Tensor)", "aten::hardswish : (Tensor) -> (Tensor)", "aten::erf : (Tensor) -> (Tensor)", "aten::silu : (Tensor) -> (Tensor)", "aten::sin : (Tensor) -> (Tensor)", "aten::exp : (Tensor) -> (Tensor)", "aten::cos : (Tensor) -> (Tensor)", "aten::neg : (Tensor) -> (Tensor)", "aten::floor : (Tensor) -> (Tensor)", "aten::ceil : (Tensor) -> (Tensor)", "aten::bitwise_not : (Tensor) -> (Tensor)", "aten::add.Tensor : (Tensor, Tensor, Scalar) -> (Tensor)", "aten::sub.Tensor : (Tensor, Tensor, Scalar) -> (Tensor)", "aten::mul.Tensor : (Tensor, Tensor) -> (Tensor)", "aten::div.Tensor : (Tensor, Tensor) -> (Tensor)", "aten::lerp.Tensor : (Tensor, Tensor, Tensor) -> (Tensor)", "aten::eq.Tensor : (Tensor, Tensor) -> (Tensor)", "aten::gt.Tensor : (Tensor, Tensor) -> (Tensor)", "aten::lt.Tensor : (Tensor, Tensor) -> (Tensor)", "aten::ne.Tensor : (Tensor, Tensor) -> (Tensor)", "aten::add.Scalar : (Tensor, Scalar, Scalar) -> (Tensor)", "aten::sub.Scalar : (Tensor, Scalar, Scalar) -> (Tensor)", "aten::mul.Scalar : (Tensor, Scalar) -> (Tensor)", "aten::div.Scalar : (Tensor, Scalar) -> (Tensor)", "aten::ne.Scalar : (Tensor, Scalar) -> (Tensor)", "aten::eq.Scalar : (Tensor, Scalar) -> (Tensor)", "aten::gt.Scalar : (Tensor, Scalar) -> (Tensor)", "aten::ge.Scalar : (Tensor, Scalar) -> (Tensor)", "aten::lt.Scalar : (Tensor, Scalar) -> (Tensor)", "aten::le.Scalar : (Tensor, Scalar) -> (Tensor)", "aten::fmod.Scalar : (Tensor, Scalar) -> (Tensor)", "aten::masked_fill.Scalar : (Tensor, Tensor, Scalar) -> (Tensor)", "aten::clamp : (Tensor, Scalar?, Scalar?) -> (Tensor)", "aten::log2 : (Tensor) -> (Tensor)", "aten::rsqrt : (Tensor) -> (Tensor)", "aten::abs : (Tensor) -> (Tensor)", "aten::reciprocal : (Tensor) -> (Tensor)", "aten::bitwise_and.Tensor : (Tensor, Tensor) -> (Tensor)", "aten::threshold : (Tensor, Scalar, Scalar) -> (Tensor)", "aten::square : (Tensor) -> (Tensor)", ]: emit_with_mutating_variants(key) # Elementwise tensor compute ops that don't have the standard mutating # variants. emit("aten::addcmul : (Tensor, Tensor, Tensor, Scalar) -> (Tensor)") emit("aten::addcdiv : (Tensor, Tensor, Tensor, Scalar) -> (Tensor)") emit("aten::maximum : (Tensor, Tensor) -> (Tensor)") emit("aten::minimum : (Tensor, Tensor) -> (Tensor)") emit("aten::rsub.Scalar : (Tensor, Scalar, Scalar) -> (Tensor)") emit("aten::gelu : (Tensor, str) -> (Tensor)") emit("aten::pow.Tensor_Scalar : (Tensor, Scalar) -> (Tensor)") emit("aten::threshold_backward : (Tensor, Tensor, Scalar) -> (Tensor)") # Ops without value semantics but the corresponding without trailing # underscore variant doesn't exist. emit("aten::fill_.Scalar : (Tensor, Scalar) -> (Tensor)") emit("aten::uniform_ : (Tensor, float, float, Generator?) -> (Tensor)") emit("aten::rand_like : (Tensor, int?, int?, Device?, bool?, int?) -> (Tensor)") emit("aten::bernoulli : (Tensor, Generator?) -> (Tensor)") emit("aten::bernoulli_.float : (Tensor, float, Generator?) -> (Tensor)") emit("aten::bernoulli_.Tensor : (Tensor, Tensor, Generator?) -> (Tensor)") emit_with_mutating_variants("aten::triu : (Tensor, int) -> (Tensor)") emit_with_mutating_variants( "aten::index_put : (Tensor, Tensor?[], Tensor, bool) -> (Tensor)") emit_with_mutating_variants( "aten::index_put.hacked_twin : (Tensor, Tensor[], Tensor, bool) -> (Tensor)") # Non-elementwise tensor compute ops emit("aten::linear : (Tensor, Tensor, Tensor?) -> (Tensor)") emit("aten::mm : (Tensor, Tensor) -> (Tensor)") emit("aten::addmm : (Tensor, Tensor, Tensor, Scalar, Scalar) -> (Tensor)") emit("aten::matmul : (Tensor, Tensor) -> (Tensor)") emit( "aten::conv2d : (Tensor, Tensor, Tensor?, int[], int[], int[], int) -> (Tensor)" ) emit("aten::convolution : (Tensor, Tensor, Tensor?, int[], int[], int[], bool, int[], int) -> (Tensor)") emit("aten::convolution_overrideable : (Tensor, Tensor, Tensor?, int[], int[], int[], bool, int[], int) -> (Tensor)") emit("aten::flip : (Tensor, int[]) -> (Tensor)") emit( "aten::native_batch_norm : (Tensor, Tensor?, Tensor?, Tensor?, Tensor?, bool, float, float) -> (Tensor, Tensor, Tensor)" ) emit( "aten::batch_norm : (Tensor, Tensor?, Tensor?, Tensor?, Tensor?, bool, float, float, bool) -> (Tensor)" ) emit( "aten::layer_norm : (Tensor, int[], Tensor?, Tensor?, float, bool) -> (Tensor)" ) emit( "aten::native_layer_norm : (Tensor, int[], Tensor?, Tensor?, float) -> (Tensor, Tensor, Tensor)" ) emit( "aten::max_pool2d : (Tensor, int[], int[], int[], int[], bool) -> (Tensor)" ) emit( "aten::max_pool2d_with_indices : (Tensor, int[], int[], int[], int[], bool) -> (Tensor, Tensor)" ) emit( "aten::max_pool2d_with_indices_backward : (Tensor, Tensor, int[], int[], int[], int[], bool, Tensor) -> (Tensor)" ) emit( "aten::avg_pool2d : (Tensor, int[], int[], int[], bool, bool, int?) -> (Tensor)" ) emit( "aten::softmax.int : (Tensor, int, int?) -> (Tensor)" ) emit( "aten::log_softmax.int : (Tensor, int, int?) -> (Tensor)" ) emit( "aten::_log_softmax : (Tensor, int, bool) -> (Tensor)" ) emit("aten::adaptive_avg_pool2d : (Tensor, int[]) -> (Tensor)") emit("aten::topk : (Tensor, int, int, bool, bool) -> (Tensor, Tensor)") emit("aten::transpose.int : (Tensor, int, int) -> (Tensor)") emit("aten::permute : (Tensor, int[]) -> (Tensor)") emit("aten::bmm : (Tensor, Tensor) -> (Tensor)") emit("aten::cumsum : (Tensor, int, int?) -> (Tensor)") emit("aten::floor_divide.Scalar : (Tensor, Scalar) -> (Tensor)") emit("aten::logsumexp : (Tensor, int[], bool) -> (Tensor)") emit("aten::mean.dim : (Tensor, int[], bool, int?) -> (Tensor)") emit("aten::__and__.Tensor : (Tensor, Tensor) -> (Tensor)") emit("aten::sqrt : (Tensor) -> (Tensor)") emit("aten::_softmax : (Tensor, int, bool) -> (Tensor)") emit("aten::mean : (Tensor, int?) -> (Tensor)") emit("aten::std : (Tensor, bool) -> (Tensor)") emit("aten::var : (Tensor, bool) -> (Tensor)") emit("aten::nll_loss_forward : (Tensor, Tensor, Tensor?, int, int) -> (Tensor, Tensor)") emit("aten::nll_loss_backward : (Tensor, Tensor, Tensor, Tensor?, int, int, Tensor) -> (Tensor)") emit("aten::bincount : (Tensor, Tensor?, int) -> (Tensor)") # Misc tensor ops. emit("aten::constant_pad_nd : (Tensor, int[], Scalar) -> (Tensor)") emit("aten::pad : (Tensor, int[], str, float?) -> (Tensor)") emit("aten::squeeze.dim : (Tensor, int) -> (Tensor)", has_folder=True) emit("aten::unsqueeze : (Tensor, int) -> (Tensor)") emit("aten::squeeze : (Tensor) -> (Tensor)", has_folder=True) emit("aten::flatten.using_ints : (Tensor, int, int) -> (Tensor)") emit("aten::dim : (Tensor) -> (int)", has_folder=True) emit("aten::size : (Tensor) -> (int[])", has_canonicalizer=True) emit("aten::Bool.Tensor : (Tensor) -> (bool)") emit("aten::ones : (int[], int?, int?, Device?, bool?) -> (Tensor)") emit("aten::new_ones : (Tensor, int[], int?, int?, Device?, bool?) -> (Tensor)") emit("aten::zeros : (int[], int?, int?, Device?, bool?) -> (Tensor)") emit("aten::zero_ : (Tensor) -> (Tensor)") emit("aten::new_zeros : (Tensor, int[], int?, int?, Device?, bool?) -> (Tensor)") emit("aten::tensor : (t[], int?, Device?, bool) -> (Tensor)") emit("aten::tensor.bool : (bool, int?, Device?, bool) -> (Tensor)") emit("aten::tensor.int : (int, int?, Device?, bool) -> (Tensor)") emit("aten::_shape_as_tensor : (Tensor) -> (Tensor)") emit("aten::all : (Tensor) -> (Tensor)") emit("aten::any : (Tensor) -> (Tensor)") emit("aten::any.dim : (Tensor, int, bool) -> (Tensor)") emit("aten::arange : (Scalar, int?, int?, Device?, bool?) -> (Tensor)") emit("aten::arange.start : (Scalar, Scalar, int?, int?, Device?, bool?) -> (Tensor)") emit("aten::arange.start_step : (Scalar, Scalar, Scalar, int?, int?, Device?, bool?) -> (Tensor)") emit("aten::argmax : (Tensor, int?, bool) -> (Tensor)") emit("aten::bucketize.Tensor : (Tensor, Tensor, bool, bool) -> (Tensor)") emit("aten::clone : (Tensor, int?) -> (Tensor)") emit("aten::contiguous : (Tensor, int) -> (Tensor)") emit("aten::copy_ : (Tensor, Tensor, bool) -> (Tensor)") emit("aten::_to_copy : (Tensor, int?, int?, Device?, bool?, bool, int?) -> (Tensor)") emit("aten::detach : (Tensor) -> (Tensor)") emit("aten::embedding : (Tensor, Tensor, int, bool, bool) -> (Tensor)") emit("aten::empty_like : (Tensor, int?, int?, Device?, bool?, int?) -> (Tensor)") emit("aten::new_empty : (Tensor, int[], int?, int?, Device?, bool?) -> (Tensor)") emit("aten::zeros_like : (Tensor, int?, int?, Device?, bool?, int?) -> (Tensor)") emit("aten::ones_like : (Tensor, int?, int?, Device?, bool?, int?) -> (Tensor)") emit("aten::empty.memory_format : (int[], int?, int?, Device?, bool?, int?) -> (Tensor)") emit("aten::expand : (Tensor, int[], bool) -> (Tensor)") emit("aten::expand_as : (Tensor, Tensor) -> (Tensor)") emit("aten::broadcast_to : (Tensor, int[]) -> (Tensor)") emit("aten::index.Tensor : (Tensor, Tensor?[]) -> (Tensor)") emit("aten::index_select : (Tensor, int, Tensor) -> (Tensor)") emit("aten::_index_put_impl_ : (Tensor, Tensor?[], Tensor, bool, bool) -> (Tensor)") emit("aten::item : (Tensor) -> (Scalar)") emit("aten::masked_select : (Tensor, Tensor) -> (Tensor)") emit("aten::numel : (Tensor) -> (int)") emit("aten::repeat : (Tensor, int[]) -> (Tensor)") emit("aten::reshape : (Tensor, int[]) -> (Tensor)") emit("aten::_reshape_alias : (Tensor, int[], int[]) -> (Tensor)") emit("aten::resize_ : (Tensor, int[], int?) -> (Tensor)") emit("aten::select.int : (Tensor, int, int) -> (Tensor)") emit("aten::size.int : (Tensor, int) -> (int)", has_folder=True) emit("aten::stack : (Tensor[], int) -> (Tensor)") emit("aten::sum : (Tensor, int?) -> (Tensor)") emit("aten::sum.dim_IntList : (Tensor, int[], bool, int?) -> (Tensor)") emit("aten::max : (Tensor) -> (Tensor)") emit("aten::max.dim : (Tensor, int, bool) -> (Tensor, Tensor)") emit("aten::to.dtype : (Tensor, int, bool, bool, int?) -> (Tensor)", has_folder=True) emit("aten::to.dtype_layout : (Tensor, int?, int?, Device?, bool?, bool, bool, int?) -> (Tensor)", has_folder=True) emit("aten::to.other : (Tensor, Tensor, bool, bool, int?) -> (Tensor)") emit("aten::to.prim_Device : (Tensor, Device?, int?, bool, bool) -> (Tensor)") emit("aten::type_as : (Tensor, Tensor) -> (Tensor)") emit("aten::view : (Tensor, int[]) -> (Tensor)", has_folder=True) emit("aten::_unsafe_view : (Tensor, int[]) -> (Tensor)") emit("aten::where.self : (Tensor, Tensor, Tensor) -> (Tensor)") emit("aten::where.Scalar : (Tensor, Scalar, Scalar) -> (Tensor)") emit("aten::where.ScalarOther : (Tensor, Tensor, Scalar) -> (Tensor)") emit("aten::where.ScalarSelf : (Tensor, Scalar, Tensor) -> (Tensor)") emit("aten::slice.Tensor : (Tensor, int, int?, int?, int) -> (Tensor)") emit("aten::len.Tensor : (Tensor) -> (int)") emit("aten::cpu : (Tensor) -> (Tensor)") emit("aten::gather : (Tensor, int, Tensor, bool) -> (Tensor)") emit("aten::IntImplicit : (Tensor) -> (int)") emit("aten::tensor.float : (float, int?, Device?, bool) -> (Tensor)") emit("aten::Int.Tensor : (Tensor) -> (int)", has_folder=True) emit("aten::Float.Tensor : (Tensor) -> (float)", has_folder=True) emit_with_mutating_variants("aten::dropout : (Tensor, float, bool) -> (Tensor)") emit("aten::t : (Tensor) -> (Tensor)") emit("aten::full : (int[], Scalar, int?, int?, Device?, bool?) -> (Tensor)") emit("aten::full_like : (Tensor, Scalar, int?, int?, Device?, bool?, int?) -> (Tensor)") # Dict ops. emit("aten::__contains__.str : (Dict(str, t), str) -> (bool)", has_folder=True) emit("aten::__getitem__.Dict_str : (Dict(str, t), str) -> (t)", has_folder=True) emit("aten::_set_item.str : (Dict(str, t), str, t) -> ()") emit("aten::keys.str : (Dict(str, t)) -> (str[])") emit("aten::get.default_str : (Dict(str, t), str, t) -> (t)") emit("aten::Delete.Dict_str : (Dict(str, t), str) -> ()") # List ops. emit("aten::cat : (Tensor[], int) -> (Tensor)") emit("aten::append.t : (t[], t) -> (t[])") emit("aten::add.t : (t[], t[]) -> (t[])") emit("aten::eq.int_list : (int[], int[]) -> (bool)", has_folder=True) emit("aten::list.t : (t[]) -> (t[])") emit("aten::slice.t : (t[], int?, int?, int) -> (t[])") emit("aten::insert.t : (t[], int, t) -> ()") emit("aten::ne.int_list : (int[], int[]) -> (bool)") # Str ops. emit("aten::add.str : (str, str) -> (str)") emit("aten::eq.str : (str, str) -> (bool)", has_folder=True) emit("aten::str : (t) -> (str)") emit("aten::format : (...) -> (str)") emit("aten::join : (str, str[]) -> (str)") # Type conversion ops. emit("aten::Float.Scalar : (Scalar) -> (float)", has_folder=True) emit("aten::Float.str : (str) -> (float)") emit("aten::Int.float : (float) -> (int)") # Primitive ops emit("aten::__range_length : (int, int, int) -> (int)", has_folder=True) emit("aten::__derive_index : (int, int, int) -> (int)", has_folder=True) emit("aten::gt.int : (int, int) -> (bool)", has_folder=True) emit("aten::ge.int : (int, int) -> (bool)", has_folder=True) emit("aten::lt.int : (int, int) -> (bool)", has_folder=True) emit("aten::le.int : (int, int) -> (bool)", has_folder=True) emit("aten::ne.int : (int, int) -> (bool)", has_folder=True) emit("aten::eq.int : (int, int) -> (bool)", has_folder=True) emit("aten::floordiv.int : (int, int) -> (int)", has_folder=True) emit("aten::remainder.int : (int, int) -> (int)", has_folder=True) emit("aten::add.int : (int, int) -> (int)", has_folder=True) emit("aten::sub.int : (int, int) -> (int)", has_folder=True) emit("aten::mul.int : (int, int) -> (int)", has_folder=True) emit("aten::neg.int : (int) -> (int)", has_folder=True) emit("aten::log.int : (int) -> (float)") emit("aten::add.float_int : (float, int) -> (float)") emit("aten::sub.float : (float, float) -> (float)") emit("aten::mul.float : (float, float) -> (float)") emit("aten::div.float : (float, float) -> (float)", has_folder=True) emit("aten::neg.float : (float) -> (float)") emit("aten::eq.float : (float, float) -> (bool)", has_folder=True) emit("aten::gt.float : (float, float) -> (bool)", has_folder=True) emit("aten::ge.float : (float, float) -> (bool)", has_folder=True) emit("aten::lt.float : (float, float) -> (bool)", has_folder=True) emit("aten::lt.float_int : (float, int) -> (bool)") emit("aten::ge.float_int : (float, int) -> (bool)") emit("aten::ne.float_int : (float, int) -> (bool)") emit("aten::gt.float_int : (float, int) -> (bool)") emit("aten::__and__.bool : (bool, bool) -> (bool)") emit("aten::ne.bool : (bool, bool) -> (bool)", has_folder=True) emit("aten::__is__ : (t1, t2) -> (bool)", has_folder=True) emit("aten::__isnot__ : (t1, t2) -> (bool)", has_folder=True) emit("aten::__not__ : (bool) -> (bool)", has_folder=True) emit("aten::len.t : (t[]) -> (int)", has_folder=True, has_canonicalizer=True) emit("aten::__getitem__.t : (t[], int) -> (t)", has_canonicalizer=True) emit("aten::_set_item.t : (t[], int, t) -> (t[])") emit("aten::div : (Scalar, Scalar) -> (float)") emit("aten::add : (Scalar, Scalar) -> (Scalar)") emit("aten::eq.device : (Device, Device) -> (bool)") emit("aten::ceil.float : (float) -> (int)", has_folder=True) # backprop ops emit("aten::_softmax_backward_data : (Tensor, Tensor, int, int) -> (Tensor)") emit("aten::tanh_backward : (Tensor, Tensor) -> (Tensor)") emit("aten::gelu_backward : (Tensor, Tensor, str) -> (Tensor)") emit("aten::_log_softmax_backward_data : (Tensor, Tensor, int, int) -> (Tensor)") # ========================================================================== # `prim::` namespace. # ========================================================================== emit("prim::layout : (Tensor) -> (int)") emit("prim::TupleIndex : (Any, int) -> (Any)", has_canonicalizer=True) emit("prim::device : (Tensor) -> (Device)") emit("prim::dtype : (Tensor) -> (int)", has_folder=True) emit("prim::TupleUnpack : (Any) -> (...)", has_canonicalizer=True) emit("prim::NumToTensor.Scalar : (Scalar) -> (Tensor)") emit("prim::min.self_int : (int[]) -> (int)", has_folder=True) emit("prim::min.int : (int, int) -> (int)") emit("prim::max.self_int : (int[]) -> (int)") emit("prim::max.int : (int, int) -> (int)", has_folder=True) emit("prim::RaiseException : (str, str?) -> ()") emit("prim::Uninitialized : () -> (Any)", has_canonicalizer=True, traits=["NoSideEffect"]) emit("prim::unchecked_cast : (t) -> (t)", has_folder=True, traits=["DeclareOpInterfaceMethods<CastOpInterface>"]) emit("prim::Print : (...) -> ()") emit("prim::tolist : (...) -> (...)") emit("prim::abs.Scalar : (Scalar) -> (Scalar)") # ========================================================================== # `quantized::` namespace. # ========================================================================== emit( "quantized::linear : (Tensor, __torch__.torch.classes.quantized.LinearPackedParamsBase, float, int) -> (Tensor)", traits=["HasValueSemantics"]) def dump_registered_ops(outfile: TextIO, registry: Registry): for _, v in sorted(registry.by_unique_key.items()): outfile.write(repr(v)) def main(args: argparse.Namespace): registry = Registry.load() if args.debug_registry_dump: with open(args.debug_registry_dump, "w") as debug_registry_dump: dump_registered_ops(debug_registry_dump, registry) td_path = os.path.join(args.torch_ir_include_dir, "GeneratedTorchOps.td") with open(td_path, "w") as f_td: emitter_td = TextEmitter(f_td) emitter_td.print(ODS_BANNER) emit_ops(emitter_td, registry) def _create_argparse() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="generate_ods") parser.add_argument( "--torch_ir_include_dir", required=True, help="Directory in include/ containing the Torch dialect") parser.add_argument( "--debug_registry_dump", help="File to dump the the PyTorch JIT operator registry into") return parser if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) parser = _create_argparse() args = parser.parse_args() main(args)
"""Main entry point for op emission. Besides emitting the op, it deduces / adds traits based on the operator information. """ if traits is None: traits = [] # All Torch operators allow type refinement. traits += ["AllowsTypeRefinement"] if operator.has_value_semantics(): traits += ["HasValueSemantics"] if operator.is_readonly(): traits += ["ReadOnly"] raw_emit_op(operator, emitter_td, traits=traits, has_folder=has_folder, has_canonicalizer=has_canonicalizer)
m3_calling_functions_returning_values.py
""" This module demonstrates and practices: -- using ARGUMENTs in function CALLs, -- having PARAMETERs in function DEFINITIONs, and -- RETURNING a value from a function, possibly CAPTURING the RETURNED VALUE in a VARIABLE. -- UNIT TESTING. Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, their colleagues and PUT_YOUR_NAME_HERE. """ # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE. import m3t_tester def
(): """ Calls the TEST functions in this module. """ run_test_sum_of_digits() run_test_digits_in_cube() run_test_digits_in_power() run_test_fancy_sums_of_digits() # ------------------------------------------------------------------ # TODO: 9. DO THIS LAST! # -- Uncomment the line of code below to run the main function # in m3t_tester.py (do not make changes to it). # It runs OUR tests on your code. # -- Check to see whether all test cases indicate they # "COMPLETED SUCCESSFULLY!" # -- If your code fails any of OUR tests but passes YOUR tests, # then you are likely not TESTING the methods correctly. # ** Ask a TA or your professor for help in that case. ** # ------------------------------------------------------------------ # m3t_tester.main() def run_test_sum_of_digits(): """ Tests the sum_of_digits function. """ # ------------------------------------------------------------------ # TODO: 2. Implement this TEST function, as follows: # # Step 1: This TEST function tests the sum_of_digits function. # So read the doc-string of the sum_of_digits function # defined below. Be sure that you understand from the # doc-string what the sum_of_digits function SHOULD return. # # Step 2: Pick a test case: a number that you could send as # an actual argument to the sum_of_digits function. # - For example, you could pick the test case 826. # # Step 3: Figure out the CORRECT (EXPECTED) answer for your # test case. In the example of 826 the correct answer # for the sum of its digits is 8 + 2 + 6, which is 16. # # Step 4: Write code that prints both the EXPECTED answer # and the ACTUAL answer returned when you call the function. # See the example below. # ------------------------------------------------------------------ print() print('--------------------------------------------------') print('Testing the sum_of_digits function:') print('--------------------------------------------------') # Test 1: expected = 16 answer = sum_of_digits(826) print('Test 1 expected:', expected) print(' actual: ', answer) # ------------------------------------------------------------------ # TO DO: 2 (continued). # Below this comment, add 3 more test cases of your own choosing. # ------------------------------------------------------------------ def sum_of_digits(number): """ What comes in: An integer. What goes out: The sum of the digits in the given integer. Side effects: None. Example: If the integer is 83135, this function returns (8 + 3 + 1 + 3 + 5), which is 20. """ # ------------------------------------------------------------------ # Students: # Do NOT touch this function - it has no TO DO in it. # Do NOT copy code from this function. # # Instead, ** CALL ** this function as needed in the other problems. # # Ask for help if you are unsure what it means to CALL a function. # The ONLY part of this function that you need to understand is # the doc-string above. Treat this function as a black box. # ------------------------------------------------------------------ if number < 0: number = -number digit_sum = 0 while True: if number == 0: break digit_sum = digit_sum + (number % 10) number = number // 10 return digit_sum def run_test_digits_in_cube(): """ Tests the digits_in_cube function. """ # ------------------------------------------------------------------ # TODO: 3. Implement this function. # It TESTS the digits_in_cube function defined below. # Include at least ** 3 ** tests. # # To implement this TEST function, use the same 4 steps as above: # # Step 1: Read the doc-string of digits_in_cube below. # Understand what that function SHOULD return. # # Step 2: Pick a test case: a number(s) that you could send as # actual argument(s) to the digits_in_cube function. # # Step 3: Figure out the CORRECT (EXPECTED) answer for your test case. # # Step 4: Write code that prints both the EXPECTED answer # and the ACTUAL answer returned when you call the function. # Follow the same form as in previous examples. # # Include at least ** 3 ** tests. # ------------------------------------------------------------------ print() print('-----------------------------------------------------') print('Testing the digits_in_cube function:') print('-----------------------------------------------------') def digits_in_cube(n): """ What comes in: A positive integer. What goes out: The sum of the digits in the CUBE of the integer. Side effects: None. Example: If the integer (n) is 5 (so n cubed is 125), this function returns (1 + 2 + 5), which is 8. """ # ------------------------------------------------------------------ # TODO: 4. Implement and test this function. # Note that you should write its TEST function first (above). # That is called TEST-DRIVEN DEVELOPMENT (TDD). # #################################################################### # IMPORTANT: CALL, as many times as needed, # the sum_of_digits function that is DEFINED ABOVE. #################################################################### # ------------------------------------------------------------------ def run_test_digits_in_power(): """ Tests the digits_in_power function. """ # ------------------------------------------------------------------ # TODO: 5. Implement this function. # It TESTS the digits_in_power function defined below. # Include at least ** 3 ** tests. # # Use the same 4-step process as in implementing previous TEST functions. # ------------------------------------------------------------------ print() print('--------------------------------------------------') print('Testing the digits_in_power function:') print('--------------------------------------------------') def digits_in_power(n, k): """ What comes in: Two positive integers, n and k. What goes out: The sum of the digits in x, where x is n raised to the kth power. Side effects: None. Example: If the arguments are 12 and 3, respectively, this function returns 18 since 12 to the 3rd power is 1728 (whose digits sum to 18). """ # ------------------------------------------------------------------ # TODO: 6. Implement and test this function. # #################################################################### # IMPORTANT: CALL, as many times as needed, # the sum_of_digits function that is DEFINED ABOVE. #################################################################### # ------------------------------------------------------------------ def run_test_fancy_sums_of_digits(): """ Tests the fancy_sums_of_digits function. """ # ------------------------------------------------------------------ # TODO: 7. Implement this function. # It TESTS the fancy_sums_of_digits function defined below. # Include at least ** 3 ** tests. # # Use the same 4-step process as in implementing the previous # TEST functions. # ------------------------------------------------------------------ print() print('--------------------------------------------------') print('Testing the fancy_sums_of_digits function:') print('--------------------------------------------------') # ------------------------------------------------------------------ # HINT: For your 1st test, consider n=10. Figure out BY HAND # the correct (expected) answer for that test case. (It's easy.) # The doc-string below gives test cases you can use for # your 2nd and 3rd tests but READ THOSE TEST CASES CAREFULLY # in the doc-string to be sure that you understand the specification. # ------------------------------------------------------------------ def fancy_sums_of_digits(n): """ What comes in: A positive integer n. What goes out: -- Let X denote the sum of the digits in (n ** 1000). -- Let Y denote the sum of the digits in (n ** 999). This function RETURNs the sum of the digits in (X ** Y). Side effects: None. Examples: -- If n is 2, then: -- the sum of the digits in n ** 1000 is 1366 (trust me!). -- the sum of the digits in n ** 999 is 1367 (trust me!). -- so X ** Y is VERY LARGE in this case (don't try to print it!) -- the sum of the digits in (X ** Y) is 19084 (trust me!) -- so this function returns 19084. -- If n is 35, then: -- the sum of the digits in n ** 1000 is 7021 (trust me!). -- the sum of the digits in n ** 999 is 7145 (trust me!). -- so X ** Y is VERY LARGE in this case (don't try to print it!) -- the sum of the digits in (X ** Y) is 124309 (trust me!) -- so this function returns 124309. """ # ------------------------------------------------------------------ # TODO: 8. Implement and test this function. # #################################################################### # IMPORTANT: CALL, as many times as needed, # the sum_of_digits function that is DEFINED ABOVE. #################################################################### # ------------------------------------------------------------------ # ---------------------------------------------------------------------- # Calls main to start the ball rolling. # This unusual form is necessary for the special testing we provided. # ---------------------------------------------------------------------- if __name__ == '__main__': main()
main
main.js
import React, { Component, PropTypes } from 'react'; import { AppRegistry, StyleSheet, Text, TouchableOpacity, View, StatusBar, } from 'react-native'; import 'exponent'; import { NavigationProvider,
} from '@exponent/ex-navigation'; import AppRouter from 'AppRouter'; class AppContainer extends React.Component { render() { return ( <View style={{ flex: 1 }}> <StatusBar backgroundColor="#cccccc" barStyle="default" translucent={false} /> <NavigationProvider router={AppRouter}> <SharedElementOverlay> <StackNavigation id="root" initialRoute={AppRouter.getRoute('placesList')} /> </SharedElementOverlay> </NavigationProvider> </View> ); } } AppRegistry.registerComponent('main', () => AppContainer);
StackNavigation, SharedElementOverlay,
generate-root-readme.ts
import { generateRootReadmeBadges } from "./generate-root-readme-badges"; import { readReadmeContent } from "./read-readme-content"; import { generateRootReadmePackageTable } from "./generate-root-readme-package-table"; import { generateReadmeFooter } from "./generate-readme-footer"; import { getAllPackages } from "./get-all-packages"; export async function
(): Promise<string> { const packages = await getAllPackages(); const commandLineExecutables = packages.filter(({ name }) => name[name.length - 1].endsWith(`-cli`) ); const plugins = packages.filter(({ name }) => name[name.length - 1].endsWith(`-plugin`) ); const steps = packages.filter(({ name }) => name[name.length - 1].endsWith(`-step`) ); const inputs = packages.filter(({ name }) => name[name.length - 1].endsWith(`-input`) ); const outputs = packages.filter(({ name }) => name[name.length - 1].endsWith(`-output`) ); const stores = packages.filter(({ name }) => name[name.length - 1].endsWith(`-store`) ); const other = packages.filter( (step) => ![ ...commandLineExecutables, ...plugins, ...steps, ...inputs, ...outputs, ...stores, ].includes(step) ); return `# Shanzhai ${generateRootReadmeBadges()}${await readReadmeContent([])} A crude, plugin-based plugin system built upon NodeJS. ## NPM packages ### Plugins For the most part, software built using Shanzhai is configured simply by adding NPM dependencies upon plugins (e.g. \`npm install --save-dev @shanzhai/read-type-script-files-plugin\`). A plugin will typically read information from one or more files or stores, apply a transformation, then write the results to one or more files or stores. Take note of and install any peer dependencies recommended upon installation of these packages. ![Map](https://tinyurl.com/w799ywr9) ${await generateRootReadmePackageTable(plugins)} ### Command-Line Executables These command-line executables can be ran using [NPX](https://www.npmjs.com/package/npx) (e.g. \`npx @shanzhai/production-cli\`). ${await generateRootReadmePackageTable(commandLineExecutables)} ### For extending Shanzhai These packages are only needed should you wish to extend the Shanzhai itself. #### Steps Whenever a plugin is triggered, it generates a step. Most are "action steps", which perform a single operation such as reading a file, compiling script or minifying mark-up. Some are "aggregation steps", which allow multiple other steps to be executed in parallel or serial. ${await generateRootReadmePackageTable(steps)} #### Inputs An input provides a value to a step during its execution. While some perform transformations, most simply provide a value. Inputs should not be performing complex or potentially risky operations. ${await generateRootReadmePackageTable(inputs)} #### Outputs An output stores a value provided by a step during its execution. As with inputs, most simply store a value. Only simple and fast transformations should be performed in outputs, and preferably none should be made at all. ${await generateRootReadmePackageTable(outputs)} #### Stores Stores are peer dependencies of plugins, and are used to pass data between them. For example: - A plugin to read TypeScript files from disk might write the read TypeScript into a keyed ephemeral store. - A plugin might then read from that store to parse the files, writing the results to another keyed ephemeral store. - Then, another plugin might collect all those parsed files to compile them, writing the result to an unkeyed ephemeral store, ${await generateRootReadmePackageTable(stores)} #### Other These packages do not fall into any of the above categories. ${await generateRootReadmePackageTable(other)} ${generateReadmeFooter()} `; }
generateRootReadme
zh-cg.js
export default { devAuthConfig: { title: { list: '权限配置', record: '权限配置', code: '权限配置' }, route: { listTag: '权限配置', recordTag: '权限配置' }, field: {
id: '主键', roleId: '配置id', beginAt: '开始日期', endAt: '结束日期', startTime: '开始时间', endTime: '结束时间', onlyWorkDay: '仅工作日有效', auth: '权限' } } }
vsnp_statistics.py
#!/usr/bin/env python import argparse import csv import gzip import os from functools import partial import numpy import pandas from Bio import SeqIO def nice_size(size): # Returns a readably formatted string with the size words = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'] prefix = '' try: size = float(size) if size < 0: size = abs(size) prefix = '-' except Exception: return '??? bytes' for ind, word in enumerate(words): step = 1024 ** (ind + 1) if step > size: size = size / float(1024 ** ind) if word == 'bytes': # No decimals for bytes return "%s%d bytes" % (prefix, size) return "%s%.1f %s" % (prefix, size, word) return '??? bytes' def output_statistics(fastq_files, idxstats_files, metrics_files, output_file, gzipped, dbkey): # Produce an Excel spreadsheet that # contains a row for each sample. columns = ['Reference', 'File Size', 'Mean Read Length', 'Mean Read Quality', 'Reads Passing Q30', 'Total Reads', 'All Mapped Reads', 'Unmapped Reads', 'Unmapped Reads Percentage of Total', 'Reference with Coverage', 'Average Depth of Coverage', 'Good SNP Count'] data_frames = [] for i, fastq_file in enumerate(fastq_files): idxstats_file = idxstats_files[i] metrics_file = metrics_files[i] file_name_base = os.path.basename(fastq_file) # Read fastq_file into a data frame. _open = partial(gzip.open, mode='rt') if gzipped else open with _open(fastq_file) as fh: identifiers = [] seqs = [] letter_annotations = [] for seq_record in SeqIO.parse(fh, "fastq"): identifiers.append(seq_record.id) seqs.append(seq_record.seq) letter_annotations.append(seq_record.letter_annotations["phred_quality"]) # Convert lists to Pandas series. s1 = pandas.Series(identifiers, name='id') s2 = pandas.Series(seqs, name='seq') # Gather Series into a data frame. fastq_df = pandas.DataFrame(dict(id=s1, seq=s2)).set_index(['id']) total_reads = int(len(fastq_df.index) / 4) current_sample_df = pandas.DataFrame(index=[file_name_base], columns=columns) # Reference current_sample_df.at[file_name_base, 'Reference'] = dbkey # File Size current_sample_df.at[file_name_base, 'File Size'] = nice_size(os.path.getsize(fastq_file)) # Mean Read Length sampling_size = 10000 if sampling_size > total_reads: sampling_size = total_reads fastq_df = fastq_df.iloc[3::4].sample(sampling_size) dict_mean = {} list_length = [] i = 0 for id, seq, in fastq_df.iterrows(): dict_mean[id] = numpy.mean(letter_annotations[i]) list_length.append(len(seq.array[0])) i += 1 current_sample_df.at[file_name_base, 'Mean Read Length'] = '%.1f' % numpy.mean(list_length) # Mean Read Quality df_mean = pandas.DataFrame.from_dict(dict_mean, orient='index', columns=['ave']) current_sample_df.at[file_name_base, 'Mean Read Quality'] = '%.1f' % df_mean['ave'].mean() # Reads Passing Q30 reads_gt_q30 = len(df_mean[df_mean['ave'] >= 30]) reads_passing_q30 = '{:10.2f}'.format(reads_gt_q30 / sampling_size) current_sample_df.at[file_name_base, 'Reads Passing Q30'] = reads_passing_q30 # Total Reads current_sample_df.at[file_name_base, 'Total Reads'] = total_reads # All Mapped Reads all_mapped_reads, unmapped_reads = process_idxstats_file(idxstats_file) current_sample_df.at[file_name_base, 'All Mapped Reads'] = all_mapped_reads # Unmapped Reads current_sample_df.at[file_name_base, 'Unmapped Reads'] = unmapped_reads # Unmapped Reads Percentage of Total if unmapped_reads > 0: unmapped_reads_percentage = '{:10.2f}'.format(unmapped_reads / total_reads) else: unmapped_reads_percentage = 0 current_sample_df.at[file_name_base, 'Unmapped Reads Percentage of Total'] = unmapped_reads_percentage # Reference with Coverage ref_with_coverage, avg_depth_of_coverage, good_snp_count = process_metrics_file(metrics_file) current_sample_df.at[file_name_base, 'Reference with Coverage'] = ref_with_coverage # Average Depth of Coverage current_sample_df.at[file_name_base, 'Average Depth of Coverage'] = avg_depth_of_coverage # Good SNP Count current_sample_df.at[file_name_base, 'Good SNP Count'] = good_snp_count data_frames.append(current_sample_df) output_df = pandas.concat(data_frames) output_df.to_csv(output_file, sep='\t', quoting=csv.QUOTE_NONE, escapechar='\\') def process_idxstats_file(idxstats_file): all_mapped_reads = 0 unmapped_reads = 0 with open(idxstats_file, "r") as fh: for i, line in enumerate(fh): line = line.rstrip('\r\n') items = line.split("\t") if i == 0: # NC_002945.4 4349904 213570 4047 all_mapped_reads = int(items[2]) elif i == 1: # * 0 0 82774 unmapped_reads = int(items[3]) return all_mapped_reads, unmapped_reads def process_metrics_file(metrics_file): ref_with_coverage = '0%' avg_depth_of_coverage = 0 good_snp_count = 0 with open(metrics_file, "r") as ifh: for i, line in enumerate(ifh): if i == 0: # Skip comments. continue line = line.rstrip('\r\n') items = line.split("\t") if i == 1: # MarkDuplicates 10.338671 98.74% ref_with_coverage = items[3] avg_depth_of_coverage = items[2] elif i == 2: # VCFfilter 611 good_snp_count = items[1] return ref_with_coverage, avg_depth_of_coverage, good_snp_count parser = argparse.ArgumentParser() parser.add_argument('--dbkey', action='store', dest='dbkey', help='Reference dbkey') parser.add_argument('--gzipped', action='store_true', dest='gzipped', required=False, default=False, help='Input files are gzipped') parser.add_argument('--input_idxstats_dir', action='store', dest='input_idxstats_dir', required=False, default=None, help='Samtools idxstats input directory') parser.add_argument('--input_metrics_dir', action='store', dest='input_metrics_dir', required=False, default=None, help='vSNP add zero coverage metrics input directory') parser.add_argument('--input_reads_dir', action='store', dest='input_reads_dir', required=False, default=None, help='Samples input directory') parser.add_argument('--list_paired', action='store_true', dest='list_paired', required=False, default=False, help='Input samples is a list of paired reads') parser.add_argument('--output', action='store', dest='output', help='Output Excel statistics file') parser.add_argument('--read1', action='store', dest='read1', help='Required: single read') parser.add_argument('--read2', action='store', dest='read2', required=False, default=None, help='Optional: paired read') parser.add_argument('--samtools_idxstats', action='store', dest='samtools_idxstats', help='Output of samtools_idxstats') parser.add_argument('--vsnp_azc', action='store', dest='vsnp_azc', help='Output of vsnp_add_zero_coverage') args = parser.parse_args() fastq_files = [] idxstats_files = [] metrics_files = [] # Accumulate inputs. if args.read1 is not None: # The inputs are not dataset collections, so # read1, read2 (possibly) and vsnp_azc will also # not be None. fastq_files.append(args.read1) idxstats_files.append(args.samtools_idxstats) metrics_files.append(args.vsnp_azc) if args.read2 is not None: fastq_files.append(args.read2) idxstats_files.append(args.samtools_idxstats) metrics_files.append(args.vsnp_azc) else: for file_name in sorted(os.listdir(args.input_reads_dir)): fastq_files.append(os.path.join(args.input_reads_dir, file_name)) for file_name in sorted(os.listdir(args.input_idxstats_dir)): idxstats_files.append(os.path.join(args.input_idxstats_dir, file_name)) if args.list_paired: # Add the idxstats file for reverse. idxstats_files.append(os.path.join(args.input_idxstats_dir, file_name)) for file_name in sorted(os.listdir(args.input_metrics_dir)):
output_statistics(fastq_files, idxstats_files, metrics_files, args.output, args.gzipped, args.dbkey)
metrics_files.append(os.path.join(args.input_metrics_dir, file_name)) if args.list_paired: # Add the metrics file for reverse. metrics_files.append(os.path.join(args.input_metrics_dir, file_name))
map.rs
// Copyright 2017 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. use futures::prelude::*; use multiaddr::Multiaddr; use std::io::Error as IoError; use transport::Transport; use Endpoint; /// See `Transport::map`. #[derive(Debug, Copy, Clone)] pub struct Map<T, F> { transport: T, map: F, } impl<T, F> Map<T, F> { /// Internal function that builds a `Map`. #[inline] pub(crate) fn new(transport: T, map: F) -> Map<T, F> { Map { transport, map } } } impl<T, F, D> Transport for Map<T, F> where T: Transport + 'static, // TODO: 'static :-/ T::Dial: Send, T::Listener: Send, T::ListenerUpgrade: Send, F: FnOnce(T::Output, Endpoint) -> D + Clone + Send + 'static, // TODO: 'static :-/ { type Output = D; type Listener = Box<Stream<Item = (Self::ListenerUpgrade, Multiaddr), Error = IoError> + Send>; type ListenerUpgrade = Box<Future<Item = Self::Output, Error = IoError> + Send>; type Dial = Box<Future<Item = Self::Output, Error = IoError> + Send>; fn listen_on(self, addr: Multiaddr) -> Result<(Self::Listener, Multiaddr), (Self, Multiaddr)> { let map = self.map; match self.transport.listen_on(addr) { Ok((stream, listen_addr)) => { let stream = stream.map(move |(future, addr)| { let map = map.clone(); let future = future .into_future() .map(move |output| map(output, Endpoint::Listener)); (Box::new(future) as Box<_>, addr) });
} } fn dial(self, addr: Multiaddr) -> Result<Self::Dial, (Self, Multiaddr)> { let map = self.map; match self.transport.dial(addr) { Ok(future) => { let future = future .into_future() .map(move |output| map(output, Endpoint::Dialer)); Ok(Box::new(future)) } Err((transport, addr)) => Err((Map { transport, map }, addr)), } } #[inline] fn nat_traversal(&self, server: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr> { self.transport.nat_traversal(server, observed) } }
Ok((Box::new(stream), listen_addr)) } Err((transport, addr)) => Err((Map { transport, map }, addr)),
model_evaluate.py
# author: Carlina Kim, Karanpal Singh, Sukriti Trehan, Victor Cuspinera # date: 2020-06-21 '''This script will read the saved theme/subtheme model(s), padded validation sets and y validation sets for model evaluation, and will save the evaluation results in the specified directory. There are 2 parameters Input Path and Output Path where you want to save the evaluation results. Usage: model_evaluate.py --level='theme' --output_dir=<destination_dir_path> Example: python src/models/model_evaluate.py --level='theme' --output_dir=reports/ python src/models/model_evaluate.py --level='subtheme' --output_dir=reports/ Options: --input_dir=<input_dir_path> Directory name for the padded documents and embeddings --output_dir=<destination_dir_path> Directory for saving evaluated results ''' import pandas as pd import numpy as np from docopt import docopt from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score, precision_recall_curve import matplotlib.pyplot as plt import tensorflow.compat.v1 as tf tf.disable_v2_behavior() opt = docopt(__doc__) print("\n-----START: model_evaluate.py-----\n") def main(level, output_dir):
class model_evaluate: # Loads data and evaluates saved theme model and subtheme models on validation set def eval_metrics(self, model_name, x_valid, y_valid, level='theme'): """ Evaluates model results on different threshold levels and produces data table/ precision recall curves Parameters ----------- model_name: (TensforFlow Saved model) x_valid: (pandas dataframe) dataframe with validation comments y_valid: (numpy array) array with labels level: (string) Takes value 'theme' or 'subtheme' to evaluate accordingly Returns ------- Pandas DataFrame or matplotlib plot dataframe with evaluation metrics including precision, recall, f1 score at different threshold values """ pred_values = model_name.predict(x_valid) if level == 'theme': precision_dict = dict() recall_dict = dict() thresh_dict = dict() precision_dict["BiGRU + Fasttext"], recall_dict["BiGRU + Fasttext"], thresh_dict["BiGRU + Fasttext"] = precision_recall_curve(y_valid.ravel(), pred_values.ravel()) labels = [] labels = list(precision_dict.keys()) plt.figure() plt.step(recall_dict['BiGRU + Fasttext'], precision_dict['BiGRU + Fasttext'], where='post', color='orange') plt.xlabel('Recall', fontsize=18) plt.ylabel('Precision', fontsize=18) plt.axhline(y=0.743643, xmin=0, xmax=0.71, ls='--', color="cornflowerblue") plt.axvline(x=0.705382, ymin=0, ymax=0.71, ls='--', color="cornflowerblue") plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.legend(labels, loc=(1.01, .79), prop=dict(size=14)) plt.title('Precision Recall Curves for best performing model', fontsize = 18) plt.savefig('reports/figures/pr_curve_valid_theme.png') # PRECISION & RECALL predictions_results = [] thresholds=[0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] for val in thresholds: pred=pred_values.copy() pred[pred>=val]=1 pred[pred<val]=0 accuracy = accuracy_score(y_valid, pred, normalize=True, sample_weight=None) precision = precision_score(y_valid, pred, average='micro') recall = recall_score(y_valid, pred, average='micro') f1 = f1_score(y_valid, pred, average='micro') case= {'Threshold': val, 'Accuracy': accuracy, 'Precision': precision, 'Recall': recall, 'F1-measure': f1} predictions_results.append(case) return pd.DataFrame(predictions_results) def get_evaluations(self, level, output_dir): """ Evaluates models by using eval_metrics function """ if level == 'theme': print("**Loading data**") x_valid = np.load('data/interim/question1_models/advance/X_valid_padded.npy') y_valid = np.load('data/interim/question1_models/advance/y_valid.npy') print("**Loading the saved theme model**") model = tf.keras.models.load_model('models/Theme_Model/theme_model') print("**Predicting on validation set using saved model and evaluating metrics**") results = self.eval_metrics(model_name = model, x_valid = x_valid, y_valid = y_valid) print("**Saving results**") results.to_csv(output_dir + '/tables/theme_tables/theme_valid_eval.csv') print("Evaluations saved to reports/") else: print("Loading data and evaluating the subthemes model on validation set") themes = ['CPD', 'CB', 'EWC', 'Exec', 'FWE', 'SP', 'RE', 'Sup', 'SW', 'TEPE', 'VMG', 'OTH'] for label in themes: print("****Label:", label, "****") print("**Loading data**") x_valid = np.load('data/interim/subthemes/' + str(label) + '/X_valid_padded.npy') # self.x_valids.append(x_valid) y_valid = np.load('data/interim/subthemes/' + str(label) + '/y_valid.npy') # self.y_valids.append(y_valid) print("**Loading the saved subtheme model**") model = tf.keras.models.load_model('models/Subtheme_Models/' + str(label).lower() + '_model') # self.models.append(model) print("**Predicting on validation set using saved model and evaluating metrics**") results = self.eval_metrics(model_name = model, x_valid = x_valid, y_valid = y_valid, level = 'subtheme') print("**Saving results**") results.to_csv(output_dir + '/tables/subtheme_tables' + str(label).lower() + '_valid_eval.csv') print("Process of subtheme", label, "model completed\n") print("Evaluations saved to reports/tables") if __name__ == "__main__": main(opt["--level"], opt["--output_dir"])
""" Takes the input level and calls model_evaluate class with output_dir as argument """ me = model_evaluate() me.get_evaluations(level=level, output_dir=output_dir) print('Thanks for your patience, the evaluation process has finished!\n') print('----END: model_evaluate.py----\n') return
command_line.rs
use anyhow::Result; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; use std::path::PathBuf; use std::str::FromStr; use structopt::StructOpt; use url::Url; use crate::error::{usage_error, ShellError}; #[derive(Debug, StructOpt, Default)] /// A shell for interacting with Amazon QLDB. For more details, /// see the shell topic in the QLDB Developer Guide: https://docs.aws.amazon.com/qldb/latest/developerguide/data-shell.html #[structopt(name = "qldb")] pub struct Opt {
#[structopt(short, long = "--region")] pub region: Option<String>, /// The name of the ledger to connect to. If a ledger with this name is /// configured in the config file, then additional configuration (such as /// the region) may be applied. #[structopt(short, long = "--ledger")] pub ledger: Option<String>, /// Config file to load. By default, this file is in /// $XDG_CONFIG_HOME/qldbshell/config.ion #[structopt(short, long, parse(from_os_str))] pub config: Option<PathBuf>, /// The qldb-session API endpoint to connect to. /// For a complete list of available QLDB Regions and endpoints, see the shell guide. #[structopt(short = "-s", long = "--qldb-session-endpoint", parse(try_from_str = Url::try_from))] pub qldb_session_endpoint: Option<Url>, /// The location of your AWS credentials profile to use for authentication. /// By default, the shell will pick a default profile as described in the shell guide. #[structopt(short, long = "--profile")] pub profile: Option<String>, /// Configure verbosity of logging. By default, only errors will be logged. /// Repeated usages of this (e.g. `-vv`) will increase the level. The /// highest level is `-vvv` which corresponds to `trace`. #[structopt(short, long = "--verbose", parse(from_occurrences))] pub verbose: u8, /// The output format of your query results. By default, the format is ion. #[structopt(short, long = "--format")] pub format: Option<FormatMode>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum FormatMode { Ion, Table, // Removing a warning temporarily // Json, } impl Default for FormatMode { fn default() -> Self { FormatMode::Ion } } impl FromStr for FormatMode { type Err = ShellError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match &s.to_lowercase()[..] { "ion" | "ion-text" => FormatMode::Ion, "table" => FormatMode::Table, "json" => todo!("json is not yet supported"), _ => return Err(usage_error(format!("{} is not a valid format mode", s))), }) } }
/// The AWS Region code of the QLDB ledger to connect to. For example: us-east-1. /// By default, the shell will pick a default region as described in the shell guide.
_run.py
""" """ ## python imports from argparse import ArgumentParser from datetime import datetime, timedelta from enum import IntEnum from os.path import abspath, dirname, join ## internal imports from geodeconstructor.history.json import generate_location_history_json from geodeconstructor.history.locations import iter_unique_path_by_attribute ## Argument parsing argument_parser = ArgumentParser() argument_parser.add_argument( "filepath", help="The path to the `Location History.json` exported by Google Takeout.", type=str ) argument_parser.add_argument( "-a", "--attr", help="The attribute to diff upon when determining changes in position.", type=str, default="country" ) argument_parser.add_argument( "-e", "--export", help="The file type that should be exported (stdout/xml/csv/kml).", type=str, default="stdout" ) argument_parser.add_argument( "-f", "--filename", help="The name of the file that should be exported.", type=str, default="Location History" ) argument_parser.add_argument( "--startdate", help="The date of which to start parsing from; in ISO format.", type=str ) argument_parser.add_argument( "--enddate", help="The date of which to stop parsing at; in ISO format.", type=str ) ## Output handling class Action(IntEnum): ENTERING = 0 EXITING = 1 def print_node(action, node, timedelta): """Prints the state of the action and the location city/country.""" if action == Action.ENTERING: print(f"Entering {node.city}, {node.country} at {timedelta}.") elif action == Action.EXITING: print(f"Exiting {node.city}, {node.country} after {timedelta}.") def
(action, node, timedelta, filepointer): """Writes the state of the action and the location city/country to CSV.""" if action == Action.ENTERING: # Using '' instead of "" due to use of them within CSV output. filepointer.write( f'"Entering","{node.city}","{node.country}","{timedelta}",,\n' ) elif action == Action.EXITING: # Using '' instead of "" due to use of them within CSV output. filepointer.write( f'"Exiting","{node.city}","{node.country}","","{timedelta}",\n' ) def write_node_kml(action, node, timedelta, kml_doc, kml_styles): """Writes the state of the action and the location city/country to KML.""" if action == Action.ENTERING: # Ugly way of achieving this, however KML library doesn't support style # as kwargs... point = kml_doc.newpoint( name=f"Entering {node.city}, {node.country}", description=str(timedelta), coords=[node.as_tuple()] ) point.iconstyle = kml_styles[0] elif action == Action.EXITING: # Ugly way of achieving this, however KML library doesn't support style # as kwargs... point = kml_doc.newpoint( name=f"Exiting {node.city}, {node.country}", description=str(timedelta), coords=[node.as_tuple()] ) point.iconstyle = kml_styles[1] # Actually handling script usage. # Only run if directly run by user. if __name__ == "__main__": # Handle argument parsing. args = argument_parser.parse_args() # Validate the JSON provided is a Location History export. json = generate_location_history_json(args.filepath) if args.startdate and args.enddate: date1Ms = datetime.fromisoformat(args.startdate).timestamp() * 1000 date2Ms = datetime.fromisoformat(args.enddate).timestamp() * 1000 # Generate dynamic function to handle filtering upon timestamps by # milliseconds. def _new_filter(item): value = int(item.get("timestampMs", 0)) if value == 0 or value > date2Ms or value < date1Ms: return False return True # Start the iteration... and return in generator form. generator = iter_unique_path_by_attribute(args.attr, json["locations"], _new_filter) else: generator = iter_unique_path_by_attribute(args.attr, json["locations"]) # Upon requesting CSV, open the CSV file for writing. if args.export == "csv": csv = open( join(dirname(args.filepath), f"{args.filename}.csv"), "w+" ) # Using '' instead of "" due to use of them within CSV output. csv.write('"Action","City","Country","DateTime","TimeDelta",\n') elif args.export == "kml": try: from simplekml import Kml, Style, IconStyle, ItemIcon except ImportError: raise ImportError(f"To export as KML, use `pip install simplekml`.") kml = Kml(name=f"Location History {args.attr.capitalize()} Changes") kml_styles = [ IconStyle( color="#00FF00", # GREEN ), IconStyle( color="#FF0000", # RED ) ] # Start iterating over the generator. # The generator will output the previous and next node when detecting a change in # attribute, whether this be on city or country change. for prev_node, prev_timestampMs, next_node, next_timestampMs in generator: # Case when printing out first node. if prev_node is None: next_datetime = datetime.fromtimestamp(next_timestampMs / 1000) if args.export == "stdout": print_node(Action.ENTERING, next_node, next_datetime) elif args.export == "csv": write_node_csv(Action.ENTERING, next_node, next_datetime, csv) elif args.export == "kml": write_node_kml(Action.ENTERING, next_node, next_datetime, kml, kml_styles) else: time_spent = timedelta(milliseconds=next_timestampMs - prev_timestampMs) if args.export == "stdout": print_node(Action.EXITING, prev_node, time_spent) elif args.export == "csv": write_node_csv(Action.EXITING, prev_node, time_spent, csv) elif args.export == "kml": write_node_kml(Action.EXITING, prev_node, time_spent, kml, kml_styles) next_datetime = datetime.fromtimestamp(next_timestampMs / 1000) if args.export == "stdout": print_node(Action.ENTERING, next_node, next_datetime) elif args.export == "csv": write_node_csv(Action.ENTERING, next_node, next_datetime, csv) elif args.export == "kml": write_node_kml(Action.ENTERING, next_node, next_datetime, kml, kml_styles) # Close up any opened files. if args.export == "csv": csv.close() elif args.export == "kml": kml.save(join(dirname(args.filepath), f"{args.filename}.kml"))
write_node_csv
macros.rs
/// Return early with an error. /// /// This macro is equivalent to `return Err(From::from($err))`. /// /// # Example /// /// ``` /// # use eyre::{bail, Result}; /// # /// # fn has_permission(user: usize, resource: usize) -> bool { /// # true /// # } /// # /// # fn main() -> Result<()> { /// # let user = 0; /// # let resource = 0; /// # /// if !has_permission(user, resource) { /// bail!("permission denied for accessing {}", resource); /// } /// # Ok(()) /// # } /// ``` /// /// ``` /// # use eyre::{bail, Result}; /// # use thiserror::Error; /// # /// # const MAX_DEPTH: usize = 1; /// # /// #[derive(Error, Debug)] /// enum ScienceError { /// #[error("recursion limit exceeded")] /// RecursionLimitExceeded, /// # #[error("...")] /// # More = (stringify! { /// ... /// # }, 1).1, /// } /// /// # fn main() -> Result<()> { /// # let depth = 0; /// # let err: &'static dyn std::error::Error = &ScienceError::RecursionLimitExceeded; /// # /// if depth > MAX_DEPTH { /// bail!(ScienceError::RecursionLimitExceeded); /// } /// # Ok(()) /// # } /// ``` #[macro_export] macro_rules! bail { ($msg:literal $(,)?) => { return $crate::private::Err($crate::eyre!($msg)); }; ($err:expr $(,)?) => { return $crate::private::Err($crate::eyre!($err)); }; ($fmt:expr, $($arg:tt)*) => { return $crate::private::Err($crate::eyre!($fmt, $($arg)*)); }; } /// Return early with an error if a condition is not satisfied. /// /// This macro is equivalent to `if !$cond { return Err(From::from($err)); }`. /// /// Analogously to `assert!`, `ensure!` takes a condition and exits the function /// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error` /// rather than panicking. /// /// # Example /// /// ``` /// # use eyre::{ensure, Result}; /// # /// # fn main() -> Result<()> { /// # let user = 0; /// # /// ensure!(user == 0, "only user 0 is allowed"); /// # Ok(()) /// # } /// ``` /// /// ``` /// # use eyre::{ensure, Result}; /// # use thiserror::Error; /// # /// # const MAX_DEPTH: usize = 1; /// #
/// #[error("recursion limit exceeded")] /// RecursionLimitExceeded, /// # #[error("...")] /// # More = (stringify! { /// ... /// # }, 1).1, /// } /// /// # fn main() -> Result<()> { /// # let depth = 0; /// # /// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded); /// # Ok(()) /// # } /// ``` #[macro_export] macro_rules! ensure { ($cond:expr, $msg:literal $(,)?) => { if !$cond { return $crate::private::Err($crate::eyre!($msg)); } }; ($cond:expr, $err:expr $(,)?) => { if !$cond { return $crate::private::Err($crate::eyre!($err)); } }; ($cond:expr, $fmt:expr, $($arg:tt)*) => { if !$cond { return $crate::private::Err($crate::eyre!($fmt, $($arg)*)); } }; } /// Construct an ad-hoc error from a string. /// /// This evaluates to an `Error`. It can take either just a string, or a format /// string with arguments. It also can take any custom type which implements /// `Debug` and `Display`. /// /// # Example /// /// ``` /// # type V = (); /// # /// use eyre::{eyre, Result}; /// /// fn lookup(key: &str) -> Result<V> { /// if key.len() != 16 { /// return Err(eyre!("key length must be 16 characters, got {:?}", key)); /// } /// /// // ... /// # Ok(()) /// } /// ``` #[macro_export] macro_rules! eyre { ($msg:literal $(,)?) => ({ let error = $crate::private::format_err($crate::private::format_args!($msg)); error }); ($err:expr $(,)?) => ({ use $crate::private::kind::*; let error = match $err { error => (&error).eyre_kind().new(error), }; error }); ($fmt:expr, $($arg:tt)*) => { $crate::private::new_adhoc($crate::private::format!($fmt, $($arg)*)) }; }
/// #[derive(Error, Debug)] /// enum ScienceError {
coinsList.ts
import { JSON } from "@web3api/wasm-as"; import { COINGECKO_API_URL } from "../config"; import { getStringProperty } from "../utils"; import { CoinsList, HTTP_Query, HTTP_ResponseType, HTTP_UrlParam, Input_coinsList } from "../w3"; export function
(input: Input_coinsList): Array<CoinsList> { const urlParams: Array<HTTP_UrlParam> = [ { key: "include_platform", value: `${input.include_platform.value}` }, ]; const response = HTTP_Query.get({ url: COINGECKO_API_URL + "/coins/list", request: { headers: [], urlParams: urlParams, body: "", responseType: HTTP_ResponseType.TEXT, }, }).unwrap(); if (!response || response.status !== 200 || !response.body) { const errorMsg = response && response.statusText ? (response.statusText as string) : "An error occurred while fetching data from Coingecko API"; throw new Error(errorMsg); } const jsonArray = <JSON.Arr>JSON.parse(response.body); if (!jsonArray) { const message: string = response.body ? (response.body as string) : ""; throw new Error("Invalid response: " + message); } const valueArr = jsonArray.valueOf(); const coinsListArr: CoinsList[] = []; for (let i = 0; i < valueArr.length; i++) { const elem = valueArr[i]; if (!elem.isObj) { const message: string = response.body ? (response.body as string) : ""; throw new Error("Invalid response: " + message); } const coinObj = elem as JSON.Obj; coinsListArr.push({ id: getStringProperty(coinObj, "id"), symbol: getStringProperty(coinObj, "symbol"), name: getStringProperty(coinObj, "name"), }); } return coinsListArr; }
coinsList
helper.go
package pgxhelper import ( "github.com/apaxa-io/strconvhelper" "github.com/jackc/pgx" ) const stmtNamePrefix = "stmt" var stmtNum uint = 0 // PgxPreparer interface can hold any object that can prepare SQL statements. // Currently (and is primary used for) it can hold pgx.Conn & pgx.ConnPool. type PgxPreparer interface { Prepare(name, sql string) (*pgx.PreparedStatement, error) } // MustPrepare is like pgxConn[Pool].Prepare but panics if the SQL cannot be parsed. // It simplifies safe initialization of global variables holding prepared statements. // It also assign name to prepared statement (currently name is "stmt<number>"). func MustPrepare(p PgxPreparer, sql string) (stmtName string) { stmtName = stmtNamePrefix + strconvhelper.FormatUint(stmtNum) stmtNum++ if _, err := p.Prepare(stmtName, sql); err != nil { panic(`pgxhelper: Prepare(` + sql + `): ` + err.Error()) } return } // MustPrepareAll is like MustPrepare but accept multiple sql to prepare. // It return slice of statements names. func MustPrepareAll(p PgxPreparer, sqls ...string) (stmtNames []string) { stmtNames = make([]string, len(sqls)) for i, sql := range sqls { stmtNames[i] = MustPrepare(p, sql) } return } // MustPrepareInPlace is modification of MustPrepare with resulting statement name stored in original string with sql. func MustPrepareInPlace(p PgxPreparer, stmt *string) { *stmt = MustPrepare(p, *stmt) } // MustPrepareAllInPlace is modification of MustPrepareAll with resulting statements names stored in original strings with sql.
func MustPrepareAllInPlace(p PgxPreparer, stmts ...*string) { for _, stmt := range stmts { MustPrepareInPlace(p, stmt) } }
go.js
/* * GoJS v2.1.45 JavaScript Library for HTML Diagrams, https://gojs.net * GoJS and Northwoods Software are registered trademarks of Northwoods Software Corporation, https://www.nwoods.com. * Copyright (C) 1998-2021 by Northwoods Software Corporation. All Rights Reserved. * THIS SOFTWARE IS LICENSED. THE LICENSE AGREEMENT IS AT: https://gojs.net/2.1.45/license.html. * DO NOT MODIFY THIS FILE. DO NOT DISTRIBUTE A MODIFIED COPY OF THE CONTENTS OF THIS FILE. */ (function() { var t;function aa(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}}function ca(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):{next:aa(a)}}function da(a){for(var b,c=[];!(b=a.next()).done;)c.push(b.value);return c}var ea="function"==typeof Object.create?Object.create:function(a){function b(){}b.prototype=a;return new b},fa; if("function"==typeof Object.setPrototypeOf)fa=Object.setPrototypeOf;else{var ha;a:{var ia={a:!0},ja={};try{ja.__proto__=ia;ha=ja.a;break a}catch(a){}ha=!1}fa=ha?function(a,b){a.__proto__=b;if(a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null}var la=fa; function ma(a,b){a.prototype=ea(b.prototype);a.prototype.constructor=a;if(la)la(a,b);else for(var c in b)if("prototype"!=c)if(Object.defineProperties){var d=Object.getOwnPropertyDescriptor(b,c);d&&Object.defineProperty(a,c,d)}else a[c]=b[c];a.AB=b.prototype}var na="undefined"!=typeof window&&window===self?self:"undefined"!=typeof global&&null!=global?global:self,oa="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){a!=Array.prototype&&a!=Object.prototype&&(a[b]=c.value)}; function pa(a){if(a){for(var b=na,c=["Array","prototype","fill"],d=0;d<c.length-1;d++){var e=c[d];e in b||(b[e]={});b=b[e]}c=c[c.length-1];d=b[c];a=a(d);a!=d&&null!=a&&oa(b,c,{writable:!0,value:a})}}pa(function(a){return a?a:function(a,c,d){var b=this.length||0;0>c&&(c=Math.max(0,b+c));if(null==d||d>b)d=b;d=Number(d);0>d&&(d=Math.max(0,b+d));for(c=Number(c||0);c<d;c++)this[c]=a;return this}});var x="object"===typeof self&&self.self===self&&self||"object"===typeof global&&global.global===global&&global||"object"===typeof window&&window.window===window&&window||{};void 0===x.requestAnimationFrame&&(void 0===x.setImmediate?x.requestAnimationFrame=function(a){x.setTimeout(a,0)}:x.requestAnimationFrame=x.setImmediate);function ra(){}function sa(a,b){var c=-1;return function(){var d=this,e=arguments;-1!==c&&x.clearTimeout(c);c=ta(function(){c=-1;a.apply(d,e)},b)}} function ta(a,b){return x.setTimeout(a,b)}function ua(a){return x.document.createElement(a)}function B(a){throw Error(a);}function va(a,b){a="The object is frozen, so its properties cannot be set: "+a.toString();void 0!==b&&(a+=" to value: "+b);B(a)}function wa(a,b,c,d){c=null===c?"*":"string"===typeof c?c:"function"===typeof c&&"string"===typeof c.className?c.className:"";void 0!==d&&(c+="."+d);B(c+" is not in the range "+b+": "+a)}function xa(a){x.console&&x.console.log(a)} function ya(){x.console&&x.console.log("Warning: List/Map/Set constructors no longer take an argument that enforces type.Instead they take an optional collection of Values to add to the collection. See 2.0 changelog for details.")}function za(a){return"object"===typeof a&&null!==a}function Aa(a){return Array.isArray(a)||x.NodeList&&a instanceof x.NodeList||x.HTMLCollection&&a instanceof x.HTMLCollection}function Ba(a){return Array.prototype.slice.call(a)} function Ca(a,b,c){Array.isArray(a)?b>=a.length?a.push(c):a.splice(b,0,c):B("Cannot insert an object into an HTMLCollection or NodeList: "+c+" at "+b)}function Da(a,b){Array.isArray(a)?b>=a.length?a.pop():a.splice(b,1):B("Cannot remove an object from an HTMLCollection or NodeList at "+b)}function Ea(){var a=Fa.pop();return void 0===a?[]:a}function Ia(a){a.length=0;Fa.push(a)} function Ja(a){if("function"===typeof a){if(a.className)return a.className;if(a.name)return a.name;var b=a.toString();b=b.substring(9,b.indexOf("(")).trim();if(""!==b)return a._className=b}else if(za(a)&&a.constructor)return Ja(a.constructor);return typeof a} function Ka(a){var b=a;za(a)&&(a.text?b=a.text:a.name?b=a.name:void 0!==a.key?b=a.key:void 0!==a.id?b=a.id:a.constructor===Object&&(a.Text?b=a.Text:a.Name?b=a.Name:void 0!==a.Key?b=a.Key:void 0!==a.Id?b=a.Id:void 0!==a.ID&&(b=a.ID)));return void 0===b?"undefined":null===b?"null":b.toString()}function La(a,b){if(a.hasOwnProperty(b))return!0;for(a=Object.getPrototypeOf(a);a&&a!==Function;){if(a.hasOwnProperty(b))return!0;var c=a.lB;if(c&&c[b])return!0;a=Object.getPrototypeOf(a)}return!1} function Na(a,b,c){Object.defineProperty(Pa.prototype,a,{get:b,set:c})}function Qa(){var a=Ra;if(void 0===x.document)return a;if(0===a.length)for(var b=x.document.getElementsByTagName("canvas"),c=b.length,d=0;d<c;d++){var e=b[d];e.parentElement&&e.parentElement.B&&a.push(e.parentElement.B)}return a} function Sa(a){for(var b=[],c=0;256>c;c++)b["0123456789abcdef".charAt(c>>4)+"0123456789abcdef".charAt(c&15)]=String.fromCharCode(c);a.length%2&&(a="0"+a);c=[];for(var d=0,e=0;e<a.length;e+=2)c[d++]=b[a.substr(e,2)];a=c.join("");a=""===a?"0":a;b=[];for(c=0;256>c;c++)b[c]=c;for(c=d=0;256>c;c++)d=(d+b[c]+119)%256,e=b[c],b[c]=b[d],b[d]=e;d=c=0;for(var f="",g=0;g<a.length;g++)c=(c+1)%256,d=(d+b[c])%256,e=b[c],b[c]=b[d],b[d]=e,f+=String.fromCharCode(a.charCodeAt(g)^b[(b[c]+b[d])%256]);return f} var Ta=void 0!==x.navigator&&0<x.navigator.userAgent.indexOf("MSIE 9.0"),Ua=void 0!==x.navigator&&0<x.navigator.userAgent.indexOf("MSIE 10.0"),Va=void 0!==x.navigator&&0<x.navigator.userAgent.indexOf("Trident/7"),Wa=void 0!==x.navigator&&0<x.navigator.userAgent.indexOf("Edge/"),Xa=void 0!==x.navigator&&void 0!==x.navigator.platform&&0<=x.navigator.platform.toUpperCase().indexOf("MAC"),Ya=void 0!==x.navigator&&void 0!==x.navigator.platform&&null!==x.navigator.platform.match(/(iPhone|iPod|iPad)/i), Fa=[];Object.freeze([]);var Ra=[];ra.className="Util";ra.Dx="32ab5ff3b26f42dc0ed90f21452913b5";ra.adym="gojs.net";ra.vfo="28e647fdb763";ra.className="Util";function D(a,b,c){Za(this);this.l=a;this.Qa=b;this.v=c}D.prototype.toString=function(){return"EnumValue."+this.Qa};function $a(a,b){return void 0===b||null===b||""===b?null:a[b]} na.Object.defineProperties(D.prototype,{classType:{get:function(){return this.l}},name:{get:function(){return this.Qa}},value:{get:function(){return this.v}}});D.className="EnumValue";function bb(){this.sx=[]}bb.prototype.toString=function(){return this.sx.join("")};bb.prototype.add=function(a){""!==a&&this.sx.push(a)};bb.className="StringBuilder";function cb(){}cb.className="PropertyCollection"; var db={nB:!1,sB:!1,pB:!1,rB:!1,xB:!1,vB:!1,my:!1,oB:null,trace:function(a){x.console&&x.console.log(a)},qB:function(a,b,c,d){a.strokeStyle="red";a.fillStyle="red";a.font="8px sans-serif";a.beginPath();a.moveTo(-10,0);a.lineTo(10,0);a.moveTo(0,-10);a.lineTo(0,10);a.stroke();a.setTransform(1,0,0,1,0,0);a.scale(c,c);a.transform(b.m11,b.m12,b.m21,b.m22,b.dx,b.dy);a.lineWidth=2;a.beginPath();a.moveTo(d.left,d.top+20);a.lineTo(d.left,d.top);a.lineTo(d.left+20,d.top);a.moveTo(d.right,d.bottom-20);a.lineTo(d.right, d.bottom);a.lineTo(d.right-20,d.bottom);a.stroke();a.fillText("DB: "+Math.round(d.x)+", "+Math.round(d.y)+", "+Math.round(d.width)+", "+Math.round(d.height),d.left,d.top-5)},mB:function(a){var b={},c;for(c in a){b.x=c;if("licenseKey"!==b.x){var d=a[b.x];if(void 0!==d.prototype){b.Im=Object.getOwnPropertyNames(d.prototype);for(var e={zk:0};e.zk<b.Im.length;e={zk:e.zk},e.zk++){var f=Object.getOwnPropertyDescriptor(d.prototype,b.Im[e.zk]);void 0!==f.get&&void 0===f.set&&Object.defineProperty(d.prototype, b.Im[e.zk],{set:function(a,b){return function(){throw Error("Property "+a.Im[b.zk]+" of "+a.x+" is read-only.");}}(b,e)})}}}b={Im:b.Im,x:b.x}}}};function hb(){}hb.prototype.reset=function(){};hb.prototype.next=function(){return!1};hb.prototype.sd=function(){return!1};hb.prototype.first=function(){return null};hb.prototype.any=function(){return!1};hb.prototype.all=function(){return!0};hb.prototype.each=function(){return this};hb.prototype.map=function(){return this};hb.prototype.filter=function(){return this}; hb.prototype.Sd=function(){};hb.prototype.toString=function(){return"EmptyIterator"};na.Object.defineProperties(hb.prototype,{iterator:{get:function(){return this}},count:{get:function(){return 0}}});hb.prototype.first=hb.prototype.first;hb.prototype.hasNext=hb.prototype.sd;hb.prototype.next=hb.prototype.next;hb.prototype.reset=hb.prototype.reset;var ib=null;hb.className="EmptyIterator";ib=new hb;function jb(a){this.key=-1;this.value=a} jb.prototype.reset=function(){this.key=-1};jb.prototype.next=function(){return-1===this.key?(this.key=0,!0):!1};jb.prototype.sd=function(){return this.next()};jb.prototype.first=function(){this.key=0;return this.value};jb.prototype.any=function(a){this.key=-1;return a(this.value)};jb.prototype.all=function(a){this.key=-1;return a(this.value)};jb.prototype.each=function(a){this.key=-1;a(this.value);return this};jb.prototype.map=function(a){return new jb(a(this.value))}; jb.prototype.filter=function(a){return a(this.value)?new jb(this.value):ib};jb.prototype.Sd=function(){this.value=null};jb.prototype.toString=function(){return"SingletonIterator("+this.value+")"};na.Object.defineProperties(jb.prototype,{iterator:{get:function(){return this}},count:{get:function(){return 1}}});jb.prototype.first=jb.prototype.first;jb.prototype.hasNext=jb.prototype.sd;jb.prototype.next=jb.prototype.next; jb.prototype.reset=jb.prototype.reset;jb.className="SingletonIterator";function kb(a){this.tb=a;this.gf=null;a.Ha=null;this.ia=a.Aa;this.Pa=-1}kb.prototype.reset=function(){var a=this.tb;a.Ha=null;this.ia=a.Aa;this.Pa=-1};kb.prototype.next=function(){var a=this.tb;if(a.Aa!==this.ia&&0>this.key)return!1;a=a.j;var b=a.length,c=++this.Pa,d=this.gf;if(null!==d)for(;c<b;){var e=a[c];if(d(e))return this.key=this.Pa=c,this.value=e,!0;c++}else{if(c<b)return this.key=c,this.value=a[c],!0;this.Sd()}return!1}; kb.prototype.sd=function(){return this.next()};kb.prototype.first=function(){var a=this.tb;this.ia=a.Aa;this.Pa=0;a=a.j;var b=a.length,c=this.gf;if(null!==c){for(var d=0;d<b;){var e=a[d];if(c(e))return this.key=this.Pa=d,this.value=e;d++}return null}return 0<b?(a=a[0],this.key=0,this.value=a):null};kb.prototype.any=function(a){var b=this.tb;b.Ha=null;this.Pa=-1;b=b.j;for(var c=b.length,d=this.gf,e=0;e<c;e++){var f=b[e];if((null===d||d(f))&&a(f))return!0}return!1}; kb.prototype.all=function(a){var b=this.tb;b.Ha=null;this.Pa=-1;b=b.j;for(var c=b.length,d=this.gf,e=0;e<c;e++){var f=b[e];if((null===d||d(f))&&!a(f))return!1}return!0};kb.prototype.each=function(a){var b=this.tb;b.Ha=null;this.Pa=-1;b=b.j;for(var c=b.length,d=this.gf,e=0;e<c;e++){var f=b[e];(null===d||d(f))&&a(f)}return this}; kb.prototype.map=function(a){var b=this.tb;b.Ha=null;this.Pa=-1;var c=[];b=b.j;for(var d=b.length,e=this.gf,f=0;f<d;f++){var g=b[f];(null===e||e(g))&&c.push(a(g))}a=new E;a.j=c;a.ob();return a.iterator};kb.prototype.filter=function(a){var b=this.tb;b.Ha=null;this.Pa=-1;var c=[];b=b.j;for(var d=b.length,e=this.gf,f=0;f<d;f++){var g=b[f];(null===e||e(g))&&a(g)&&c.push(g)}a=new E;a.j=c;a.ob();return a.iterator}; kb.prototype.Sd=function(){this.key=-1;this.value=null;this.ia=-1;this.gf=null;this.tb.Ha=this};kb.prototype.toString=function(){return"ListIterator@"+this.Pa+"/"+this.tb.count}; na.Object.defineProperties(kb.prototype,{iterator:{get:function(){return this}},predicate:{get:function(){return this.gf},set:function(a){this.gf=a}},count:{get:function(){var a=this.gf;if(null!==a){for(var b=0,c=this.tb.j,d=c.length,e=0;e<d;e++)a(c[e])&&b++;return b}return this.tb.j.length}}});kb.prototype.first=kb.prototype.first;kb.prototype.hasNext=kb.prototype.sd;kb.prototype.next=kb.prototype.next; kb.prototype.reset=kb.prototype.reset;kb.className="ListIterator";function lb(a){this.tb=a;a.gh=null;this.ia=a.Aa;this.Pa=a.j.length}lb.prototype.reset=function(){var a=this.tb;a.gh=null;this.ia=a.Aa;this.Pa=a.j.length};lb.prototype.next=function(){var a=this.tb;if(a.Aa!==this.ia&&0>this.key)return!1;var b=--this.Pa;if(0<=b)return this.key=b,this.value=a.j[b],!0;this.Sd();return!1};lb.prototype.sd=function(){return this.next()}; lb.prototype.first=function(){var a=this.tb;this.ia=a.Aa;var b=a.j;this.Pa=a=b.length-1;return 0<=a?(b=b[a],this.key=a,this.value=b):null};lb.prototype.any=function(a){var b=this.tb;b.gh=null;b=b.j;var c=b.length;this.Pa=c;for(--c;0<=c;c--)if(a(b[c]))return!0;return!1};lb.prototype.all=function(a){var b=this.tb;b.gh=null;b=b.j;var c=b.length;this.Pa=c;for(--c;0<=c;c--)if(!a(b[c]))return!1;return!0}; lb.prototype.each=function(a){var b=this.tb;b.gh=null;b=b.j;var c=b.length;this.Pa=c;for(--c;0<=c;c--)a(b[c]);return this};lb.prototype.map=function(a){var b=this.tb;b.gh=null;var c=[];b=b.j;var d=b.length;this.Pa=d;for(--d;0<=d;d--)c.push(a(b[d]));a=new E;a.j=c;a.ob();return a.iterator};lb.prototype.filter=function(a){var b=this.tb;b.gh=null;var c=[];b=b.j;var d=b.length;this.Pa=d;for(--d;0<=d;d--){var e=b[d];a(e)&&c.push(e)}a=new E;a.j=c;a.ob();return a.iterator}; lb.prototype.Sd=function(){this.key=-1;this.value=null;this.ia=-1;this.tb.gh=this};lb.prototype.toString=function(){return"ListIteratorBackwards("+this.Pa+"/"+this.tb.count+")"};na.Object.defineProperties(lb.prototype,{iterator:{get:function(){return this}},count:{get:function(){return this.tb.j.length}}});lb.prototype.first=lb.prototype.first;lb.prototype.hasNext=lb.prototype.sd;lb.prototype.next=lb.prototype.next;lb.prototype.reset=lb.prototype.reset; lb.className="ListIteratorBackwards";function E(a){Za(this);this.u=!1;this.j=[];this.Aa=0;this.gh=this.Ha=null;void 0!==a&&("function"===typeof a||"string"===typeof a?ya():this.addAll(a))}t=E.prototype;t.ob=function(){var a=this.Aa;a++;999999999<a&&(a=0);this.Aa=a};t.freeze=function(){this.u=!0;return this};t.ea=function(){this.u=!1;return this};t.toString=function(){return"List()#"+mb(this)};t.add=function(a){if(null===a)return this;this.u&&va(this,a);this.j.push(a);this.ob();return this}; t.push=function(a){this.add(a)};t.addAll=function(a){if(null===a)return this;this.u&&va(this);var b=this.j;if(Aa(a))for(var c=a.length,d=0;d<c;d++)b.push(a[d]);else for(a=a.iterator;a.next();)b.push(a.value);this.ob();return this};t.clear=function(){this.u&&va(this);this.j.length=0;this.ob()};t.contains=function(a){return null===a?!1:-1!==this.j.indexOf(a)};t.has=function(a){return this.contains(a)};t.indexOf=function(a){return null===a?-1:this.j.indexOf(a)}; t.J=function(a){var b=this.j;(0>a||a>=b.length)&&wa(a,"0 <= i < length",E,"elt:i");return b[a]};t.get=function(a){return this.J(a)};t.Rc=function(a,b){var c=this.j;(0>a||a>=c.length)&&wa(a,"0 <= i < length",E,"setElt:i");this.u&&va(this,a);c[a]=b};t.set=function(a,b){this.Rc(a,b)};t.first=function(){var a=this.j;return 0===a.length?null:a[0]};t.Xb=function(){var a=this.j,b=a.length;return 0<b?a[b-1]:null};t.pop=function(){this.u&&va(this);var a=this.j;return 0<a.length?a.pop():null}; E.prototype.any=function(a){for(var b=this.j,c=b.length,d=0;d<c;d++)if(a(b[d]))return!0;return!1};E.prototype.all=function(a){for(var b=this.j,c=b.length,d=0;d<c;d++)if(!a(b[d]))return!1;return!0};E.prototype.each=function(a){for(var b=this.j,c=b.length,d=0;d<c;d++)a(b[d]);return this};E.prototype.map=function(a){for(var b=new E,c=[],d=this.j,e=d.length,f=0;f<e;f++)c.push(a(d[f]));b.j=c;b.ob();return b}; E.prototype.filter=function(a){for(var b=new E,c=[],d=this.j,e=d.length,f=0;f<e;f++){var g=d[f];a(g)&&c.push(g)}b.j=c;b.ob();return b};t=E.prototype;t.wb=function(a,b){0>a&&wa(a,">= 0",E,"insertAt:i");this.u&&va(this,a);var c=this.j;a>=c.length?c.push(b):c.splice(a,0,b);this.ob()};t.remove=function(a){if(null===a)return!1;this.u&&va(this,a);var b=this.j;a=b.indexOf(a);if(-1===a)return!1;a===b.length-1?b.pop():b.splice(a,1);this.ob();return!0};t.delete=function(a){return this.remove(a)}; t.cb=function(a){var b=this.j;(0>a||a>=b.length)&&wa(a,"0 <= i < length",E,"removeAt:i");this.u&&va(this,a);a===b.length-1?b.pop():b.splice(a,1);this.ob()};t.removeRange=function(a,b){var c=this.j,d=c.length;if(0>a)a=0;else if(a>=d)return this;if(0>b)return this;b>=d&&(b=d-1);if(a>b)return this;this.u&&va(this);for(var e=a,f=b+1;f<d;)c[e++]=c[f++];c.length=d-(b-a+1);this.ob();return this};E.prototype.copy=function(){var a=new E,b=this.j;0<b.length&&(a.j=Array.prototype.slice.call(b));return a}; t=E.prototype;t.ma=function(){for(var a=this.j,b=this.count,c=Array(b),d=0;d<b;d++)c[d]=a[d];return c};t.Mw=function(){for(var a=new G,b=this.j,c=this.count,d=0;d<c;d++)a.add(b[d]);return a};t.sort=function(a){this.u&&va(this);this.j.sort(a);this.ob();return this}; t.uj=function(a,b,c){var d=this.j,e=d.length;void 0===b&&(b=0);void 0===c&&(c=e);this.u&&va(this);var f=c-b;if(1>=f)return this;(0>b||b>=e-1)&&wa(b,"0 <= from < length",E,"sortRange:from");if(2===f)return c=d[b],e=d[b+1],0<a(c,e)&&(d[b]=e,d[b+1]=c,this.ob()),this;if(0===b)if(c>=e)d.sort(a);else for(b=d.slice(0,c),b.sort(a),a=0;a<c;a++)d[a]=b[a];else if(c>=e)for(c=d.slice(b),c.sort(a),a=b;a<e;a++)d[a]=c[a-b];else for(e=d.slice(b,c),e.sort(a),a=b;a<c;a++)d[a]=e[a-b];this.ob();return this}; t.reverse=function(){this.u&&va(this);this.j.reverse();this.ob();return this}; na.Object.defineProperties(E.prototype,{_dataArray:{get:function(){return this.j}},count:{get:function(){return this.j.length}},size:{get:function(){return this.j.length}},length:{get:function(){return this.j.length}},iterator:{get:function(){if(0>=this.j.length)return ib;var a=this.Ha;return null!==a?(a.reset(),a):new kb(this)}},iteratorBackwards:{ get:function(){if(0>=this.j.length)return ib;var a=this.gh;return null!==a?(a.reset(),a):new lb(this)}}});E.prototype.reverse=E.prototype.reverse;E.prototype.sortRange=E.prototype.uj;E.prototype.sort=E.prototype.sort;E.prototype.toSet=E.prototype.Mw;E.prototype.toArray=E.prototype.ma;E.prototype.removeRange=E.prototype.removeRange;E.prototype.removeAt=E.prototype.cb;E.prototype["delete"]=E.prototype.delete;E.prototype.remove=E.prototype.remove;E.prototype.insertAt=E.prototype.wb; E.prototype.pop=E.prototype.pop;E.prototype.last=E.prototype.Xb;E.prototype.first=E.prototype.first;E.prototype.set=E.prototype.set;E.prototype.setElt=E.prototype.Rc;E.prototype.get=E.prototype.get;E.prototype.elt=E.prototype.J;E.prototype.indexOf=E.prototype.indexOf;E.prototype.has=E.prototype.has;E.prototype.contains=E.prototype.contains;E.prototype.clear=E.prototype.clear;E.prototype.addAll=E.prototype.addAll;E.prototype.push=E.prototype.push;E.prototype.add=E.prototype.add;E.prototype.thaw=E.prototype.ea; E.prototype.freeze=E.prototype.freeze;E.className="List";function nb(a){this.vg=a;a.Ha=null;this.ia=a.Aa;this.ka=null}nb.prototype.reset=function(){var a=this.vg;a.Ha=null;this.ia=a.Aa;this.ka=null};nb.prototype.next=function(){var a=this.vg;if(a.Aa!==this.ia&&null===this.key)return!1;var b=this.ka;b=null===b?a.ba:b.oa;if(null!==b)return this.ka=b,this.value=b.value,this.key=b.key,!0;this.Sd();return!1};nb.prototype.sd=function(){return this.next()}; nb.prototype.first=function(){var a=this.vg;this.ia=a.Aa;a=a.ba;if(null!==a){this.ka=a;var b=a.value;this.key=a.key;return this.value=b}return null};nb.prototype.any=function(a){var b=this.vg;this.ka=b.Ha=null;for(b=b.ba;null!==b;){if(a(b.value))return!0;b=b.oa}return!1};nb.prototype.all=function(a){var b=this.vg;this.ka=b.Ha=null;for(b=b.ba;null!==b;){if(!a(b.value))return!1;b=b.oa}return!0};nb.prototype.each=function(a){var b=this.vg;this.ka=b.Ha=null;for(b=b.ba;null!==b;)a(b.value),b=b.oa;return this}; nb.prototype.map=function(a){var b=this.vg;b.Ha=null;var c=new E;for(b=b.ba;null!==b;)c.add(a(b.value)),b=b.oa;return c.iterator};nb.prototype.filter=function(a){var b=this.vg;b.Ha=null;var c=new E;for(b=b.ba;null!==b;){var d=b.value;a(d)&&c.add(d);b=b.oa}return c.iterator};nb.prototype.Sd=function(){this.value=this.key=null;this.ia=-1;this.vg.Ha=this};nb.prototype.toString=function(){return null!==this.ka?"SetIterator@"+this.ka.value:"SetIterator"}; na.Object.defineProperties(nb.prototype,{iterator:{get:function(){return this}},count:{get:function(){return this.vg.Gb}}});nb.prototype.first=nb.prototype.first;nb.prototype.hasNext=nb.prototype.sd;nb.prototype.next=nb.prototype.next;nb.prototype.reset=nb.prototype.reset;nb.className="SetIterator"; function G(a){Za(this);this.u=!1;this.Ib={};this.Gb=0;this.Ha=null;this.Aa=0;this.af=this.ba=null;void 0!==a&&("function"===typeof a||"string"===typeof a?ya():this.addAll(a))}t=G.prototype;t.ob=function(){var a=this.Aa;a++;999999999<a&&(a=0);this.Aa=a};t.freeze=function(){this.u=!0;return this};t.ea=function(){this.u=!1;return this};t.toString=function(){return"Set()#"+mb(this)}; t.add=function(a){if(null===a)return this;this.u&&va(this,a);var b=a;za(a)&&(b=ob(a));void 0===this.Ib[b]&&(this.Gb++,a=new pb(a,a),this.Ib[b]=a,b=this.af,null===b?this.ba=a:(a.Xl=b,b.oa=a),this.af=a,this.ob());return this};t.addAll=function(a){if(null===a)return this;this.u&&va(this);if(Aa(a))for(var b=a.length,c=0;c<b;c++)this.add(a[c]);else for(a=a.iterator;a.next();)this.add(a.value);return this}; t.contains=function(a){if(null===a)return!1;var b=a;return za(a)&&(b=mb(a),void 0===b)?!1:void 0!==this.Ib[b]};t.has=function(a){return this.contains(a)};t.Ez=function(a){if(null===a)return!0;for(a=a.iterator;a.next();)if(!this.contains(a.value))return!1;return!0};t.Fz=function(a){if(null===a)return!0;for(a=a.iterator;a.next();)if(this.contains(a.value))return!0;return!1};t.first=function(){var a=this.ba;return null===a?null:a.value}; G.prototype.any=function(a){for(var b=this.ba;null!==b;){if(a(b.value))return!0;b=b.oa}return!1};G.prototype.all=function(a){for(var b=this.ba;null!==b;){if(!a(b.value))return!1;b=b.oa}return!0};G.prototype.each=function(a){for(var b=this.ba;null!==b;)a(b.value),b=b.oa;return this};G.prototype.map=function(a){for(var b=new G,c=this.ba;null!==c;)b.add(a(c.value)),c=c.oa;return b};G.prototype.filter=function(a){for(var b=new G,c=this.ba;null!==c;){var d=c.value;a(d)&&b.add(d);c=c.oa}return b};t=G.prototype; t.remove=function(a){if(null===a)return!1;this.u&&va(this,a);var b=a;if(za(a)&&(b=mb(a),void 0===b))return!1;a=this.Ib[b];if(void 0===a)return!1;var c=a.oa,d=a.Xl;null!==c&&(c.Xl=d);null!==d&&(d.oa=c);this.ba===a&&(this.ba=c);this.af===a&&(this.af=d);delete this.Ib[b];this.Gb--;this.ob();return!0};t.delete=function(a){return this.remove(a)}; t.Zq=function(a){if(null===a)return this;this.u&&va(this);if(Aa(a))for(var b=a.length,c=0;c<b;c++)this.remove(a[c]);else for(a=a.iterator;a.next();)this.remove(a.value);return this};t.WA=function(a){if(null===a||0===this.count)return this;this.u&&va(this);var b=new G;b.addAll(a);a=[];for(var c=this.iterator;c.next();){var d=c.value;b.contains(d)||a.push(d)}this.Zq(a);return this};t.clear=function(){this.u&&va(this);this.Ib={};this.Gb=0;null!==this.Ha&&this.Ha.reset();this.af=this.ba=null;this.ob()}; G.prototype.copy=function(){var a=new G,b=this.Ib,c;for(c in b)a.add(b[c].value);return a};G.prototype.ma=function(){var a=Array(this.Gb),b=this.Ib,c=0,d;for(d in b)a[c]=b[d].value,c++;return a};G.prototype.Lw=function(){var a=new E,b=this.Ib,c;for(c in b)a.add(b[c].value);return a};function Za(a){a.__gohashid=qb++}function ob(a){var b=a.__gohashid;void 0===b&&(b=qb++,a.__gohashid=b);return b}function mb(a){return a.__gohashid} na.Object.defineProperties(G.prototype,{count:{get:function(){return this.Gb}},size:{get:function(){return this.Gb}},iterator:{get:function(){if(0>=this.Gb)return ib;var a=this.Ha;return null!==a?(a.reset(),a):new nb(this)}}});G.prototype.toList=G.prototype.Lw;G.prototype.toArray=G.prototype.ma;G.prototype.clear=G.prototype.clear;G.prototype.retainAll=G.prototype.WA;G.prototype.removeAll=G.prototype.Zq; G.prototype["delete"]=G.prototype.delete;G.prototype.remove=G.prototype.remove;G.prototype.first=G.prototype.first;G.prototype.containsAny=G.prototype.Fz;G.prototype.containsAll=G.prototype.Ez;G.prototype.has=G.prototype.has;G.prototype.contains=G.prototype.contains;G.prototype.addAll=G.prototype.addAll;G.prototype.add=G.prototype.add;G.prototype.thaw=G.prototype.ea;G.prototype.freeze=G.prototype.freeze;var qb=1;G.className="Set";G.uniqueHash=Za;G.hashIdUnique=ob;G.hashId=mb; function rb(a){this.ga=a;this.ia=a.Aa;this.ka=null}rb.prototype.reset=function(){this.ia=this.ga.Aa;this.ka=null};rb.prototype.next=function(){var a=this.ga;if(a.Aa!==this.ia&&null===this.key)return!1;var b=this.ka;b=null===b?a.ba:b.oa;if(null!==b)return this.ka=b,this.value=this.key=a=b.key,!0;this.Sd();return!1};rb.prototype.sd=function(){return this.next()};rb.prototype.first=function(){var a=this.ga;this.ia=a.Aa;a=a.ba;return null!==a?(this.ka=a,this.value=this.key=a=a.key):null}; rb.prototype.any=function(a){var b=this.ga;this.ka=null;for(b=b.ba;null!==b;){if(a(b.key))return!0;b=b.oa}return!1};rb.prototype.all=function(a){var b=this.ga;this.ka=null;for(b=b.ba;null!==b;){if(!a(b.key))return!1;b=b.oa}return!0};rb.prototype.each=function(a){var b=this.ga;this.ka=null;for(b=b.ba;null!==b;)a(b.key),b=b.oa;return this};rb.prototype.map=function(a){var b=this.ga;this.ka=null;var c=new E;for(b=b.ba;null!==b;)c.add(a(b.key)),b=b.oa;return c.iterator}; rb.prototype.filter=function(a){var b=this.ga;this.ka=null;var c=new E;for(b=b.ba;null!==b;){var d=b.key;a(d)&&c.add(d);b=b.oa}return c.iterator};rb.prototype.Sd=function(){this.value=this.key=null;this.ia=-1};rb.prototype.toString=function(){return null!==this.ka?"MapKeySetIterator@"+this.ka.value:"MapKeySetIterator"};na.Object.defineProperties(rb.prototype,{iterator:{get:function(){return this}},count:{get:function(){return this.ga.Gb}}}); rb.prototype.first=rb.prototype.first;rb.prototype.hasNext=rb.prototype.sd;rb.prototype.next=rb.prototype.next;rb.prototype.reset=rb.prototype.reset;rb.className="MapKeySetIterator";function sb(a){G.call(this);Za(this);this.u=!0;this.ga=a}ma(sb,G);t=sb.prototype;t.freeze=function(){return this};t.ea=function(){return this};t.toString=function(){return"MapKeySet("+this.ga.toString()+")"};t.add=function(){B("This Set is read-only: "+this.toString());return this};t.contains=function(a){return this.ga.contains(a)}; t.has=function(a){return this.contains(a)};t.remove=function(){B("This Set is read-only: "+this.toString());return!1};t.delete=function(a){return this.remove(a)};t.clear=function(){B("This Set is read-only: "+this.toString())};t.first=function(){var a=this.ga.ba;return null!==a?a.key:null};sb.prototype.any=function(a){for(var b=this.ga.ba;null!==b;){if(a(b.key))return!0;b=b.oa}return!1};sb.prototype.all=function(a){for(var b=this.ga.ba;null!==b;){if(!a(b.key))return!1;b=b.oa}return!0}; sb.prototype.each=function(a){for(var b=this.ga.ba;null!==b;)a(b.key),b=b.oa;return this};sb.prototype.map=function(a){for(var b=new G,c=this.ga.ba;null!==c;)b.add(a(c.key)),c=c.oa;return b};sb.prototype.filter=function(a){for(var b=new G,c=this.ga.ba;null!==c;){var d=c.key;a(d)&&b.add(d);c=c.oa}return b};sb.prototype.copy=function(){return new sb(this.ga)};sb.prototype.Mw=function(){var a=new G,b=this.ga.Ib,c;for(c in b)a.add(b[c].key);return a}; sb.prototype.ma=function(){var a=this.ga.Ib,b=Array(this.ga.Gb),c=0,d;for(d in a)b[c]=a[d].key,c++;return b};sb.prototype.Lw=function(){var a=new E,b=this.ga.Ib,c;for(c in b)a.add(b[c].key);return a};na.Object.defineProperties(sb.prototype,{count:{get:function(){return this.ga.Gb}},size:{get:function(){return this.ga.Gb}},iterator:{get:function(){return 0>=this.ga.Gb?ib:new rb(this.ga)}}}); sb.prototype.toList=sb.prototype.Lw;sb.prototype.toArray=sb.prototype.ma;sb.prototype.toSet=sb.prototype.Mw;sb.prototype.first=sb.prototype.first;sb.prototype.clear=sb.prototype.clear;sb.prototype["delete"]=sb.prototype.delete;sb.prototype.remove=sb.prototype.remove;sb.prototype.has=sb.prototype.has;sb.prototype.contains=sb.prototype.contains;sb.prototype.add=sb.prototype.add;sb.prototype.thaw=sb.prototype.ea;sb.prototype.freeze=sb.prototype.freeze;sb.className="MapKeySet"; function tb(a){this.ga=a;a.$e=null;this.ia=a.Aa;this.ka=null}tb.prototype.reset=function(){var a=this.ga;a.$e=null;this.ia=a.Aa;this.ka=null};tb.prototype.next=function(){var a=this.ga;if(a.Aa!==this.ia&&null===this.key)return!1;var b=this.ka;b=null===b?a.ba:b.oa;if(null!==b)return this.ka=b,this.value=b.value,this.key=b.key,!0;this.Sd();return!1};tb.prototype.sd=function(){return this.next()}; tb.prototype.first=function(){var a=this.ga;this.ia=a.Aa;a=a.ba;if(null!==a){this.ka=a;var b=a.value;this.key=a.key;return this.value=b}return null};tb.prototype.any=function(a){var b=this.ga;this.ka=b.$e=null;for(b=b.ba;null!==b;){if(a(b.value))return!0;b=b.oa}return!1};tb.prototype.all=function(a){var b=this.ga;this.ka=b.$e=null;for(b=b.ba;null!==b;){if(!a(b.value))return!1;b=b.oa}return!0};tb.prototype.each=function(a){var b=this.ga;this.ka=b.$e=null;for(b=b.ba;null!==b;)a(b.value),b=b.oa;return this}; tb.prototype.map=function(a){var b=this.ga;this.ka=b.$e=null;var c=new E;for(b=b.ba;null!==b;)c.add(a(b.value)),b=b.oa;return c.iterator};tb.prototype.filter=function(a){var b=this.ga;this.ka=b.$e=null;var c=new E;for(b=b.ba;null!==b;){var d=b.value;a(d)&&c.add(d);b=b.oa}return c.iterator};tb.prototype.Sd=function(){this.value=this.key=null;this.ia=-1;this.ga.$e=this};tb.prototype.toString=function(){return null!==this.ka?"MapValueSetIterator@"+this.ka.value:"MapValueSetIterator"}; na.Object.defineProperties(tb.prototype,{iterator:{get:function(){return this}},count:{get:function(){return this.ga.Gb}}});tb.prototype.first=tb.prototype.first;tb.prototype.hasNext=tb.prototype.sd;tb.prototype.next=tb.prototype.next;tb.prototype.reset=tb.prototype.reset;tb.className="MapValueSetIterator";function pb(a,b){this.key=a;this.value=b;this.Xl=this.oa=null}pb.prototype.toString=function(){return"{"+this.key+":"+this.value+"}"}; pb.className="KeyValuePair";function ub(a){this.ga=a;a.Ha=null;this.ia=a.Aa;this.ka=null}ub.prototype.reset=function(){var a=this.ga;a.Ha=null;this.ia=a.Aa;this.ka=null};ub.prototype.next=function(){var a=this.ga;if(a.Aa!==this.ia&&null===this.key)return!1;var b=this.ka;b=null===b?a.ba:b.oa;if(null!==b)return this.ka=b,this.key=b.key,this.value=b.value,!0;this.Sd();return!1};ub.prototype.sd=function(){return this.next()}; ub.prototype.first=function(){var a=this.ga;this.ia=a.Aa;a=a.ba;return null!==a?(this.ka=a,this.key=a.key,this.value=a.value,a):null};ub.prototype.any=function(a){var b=this.ga;this.ka=b.Ha=null;for(b=b.ba;null!==b;){if(a(b))return!0;b=b.oa}return!1};ub.prototype.all=function(a){var b=this.ga;this.ka=b.Ha=null;for(b=b.ba;null!==b;){if(!a(b))return!1;b=b.oa}return!0};ub.prototype.each=function(a){var b=this.ga;this.ka=b.Ha=null;for(b=b.ba;null!==b;)a(b),b=b.oa;return this}; ub.prototype.map=function(a){var b=this.ga;this.ka=b.Ha=null;var c=new E;for(b=b.ba;null!==b;)c.add(a(b)),b=b.oa;return c.iterator};ub.prototype.filter=function(a){var b=this.ga;this.ka=b.Ha=null;var c=new E;for(b=b.ba;null!==b;)a(b)&&c.add(b),b=b.oa;return c.iterator};ub.prototype.Sd=function(){this.value=this.key=null;this.ia=-1;this.ga.Ha=this};ub.prototype.toString=function(){return null!==this.ka?"MapIterator@"+this.ka:"MapIterator"}; na.Object.defineProperties(ub.prototype,{iterator:{get:function(){return this}},count:{get:function(){return this.ga.Gb}}});ub.prototype.first=ub.prototype.first;ub.prototype.hasNext=ub.prototype.sd;ub.prototype.next=ub.prototype.next;ub.prototype.reset=ub.prototype.reset;ub.className="MapIterator"; function H(a){Za(this);this.u=!1;this.Ib={};this.Gb=0;this.$e=this.Ha=null;this.Aa=0;this.af=this.ba=null;void 0!==a&&("function"===typeof a||"string"===typeof a?ya():this.addAll(a))}t=H.prototype;t.ob=function(){var a=this.Aa;a++;999999999<a&&(a=0);this.Aa=a};t.freeze=function(){this.u=!0;return this};t.ea=function(){this.u=!1;return this};t.toString=function(){return"Map()#"+mb(this)}; t.add=function(a,b){this.u&&va(this,a);var c=a;za(a)&&(c=ob(a));var d=this.Ib[c];void 0===d?(this.Gb++,a=new pb(a,b),this.Ib[c]=a,c=this.af,null===c?this.ba=a:(a.Xl=c,c.oa=a),this.af=a,this.ob()):d.value=b;return this};t.set=function(a,b){return this.add(a,b)}; t.addAll=function(a){if(null===a)return this;if(Aa(a))for(var b=a.length,c=0;c<b;c++){var d=a[c];this.add(d.key,d.value)}else if(a instanceof H)for(a=a.iterator;a.next();)this.add(a.key,a.value);else for(a=a.iterator;a.next();)b=a.value,this.add(b.key,b.value);return this};t.first=function(){return this.ba};H.prototype.any=function(a){for(var b=this.ba;null!==b;){if(a(b))return!0;b=b.oa}return!1};H.prototype.all=function(a){for(var b=this.ba;null!==b;){if(!a(b))return!1;b=b.oa}return!0}; H.prototype.each=function(a){for(var b=this.ba;null!==b;)a(b),b=b.oa;return this};H.prototype.map=function(a){for(var b=new H,c=this.ba;null!==c;)b.add(c.key,a(c)),c=c.oa;return b};H.prototype.filter=function(a){for(var b=new H,c=this.ba;null!==c;)a(c)&&b.add(c.key,c.value),c=c.oa;return b};t=H.prototype;t.contains=function(a){var b=a;return za(a)&&(b=mb(a),void 0===b)?!1:void 0!==this.Ib[b]};t.has=function(a){return this.contains(a)}; t.H=function(a){var b=a;if(za(a)&&(b=mb(a),void 0===b))return null;a=this.Ib[b];return void 0===a?null:a.value};t.get=function(a){return this.H(a)};t.remove=function(a){if(null===a)return!1;this.u&&va(this,a);var b=a;if(za(a)&&(b=mb(a),void 0===b))return!1;a=this.Ib[b];if(void 0===a)return!1;var c=a.oa,d=a.Xl;null!==c&&(c.Xl=d);null!==d&&(d.oa=c);this.ba===a&&(this.ba=c);this.af===a&&(this.af=d);delete this.Ib[b];this.Gb--;this.ob();return!0};t.delete=function(a){return this.remove(a)}; t.clear=function(){this.u&&va(this);this.Ib={};this.Gb=0;null!==this.Ha&&this.Ha.reset();null!==this.$e&&this.$e.reset();this.af=this.ba=null;this.ob()};H.prototype.copy=function(){var a=new H,b=this.Ib,c;for(c in b){var d=b[c];a.add(d.key,d.value)}return a};H.prototype.ma=function(){var a=this.Ib,b=Array(this.Gb),c=0,d;for(d in a){var e=a[d];b[c]=new pb(e.key,e.value);c++}return b};H.prototype.Mf=function(){return new sb(this)}; na.Object.defineProperties(H.prototype,{count:{get:function(){return this.Gb}},size:{get:function(){return this.Gb}},iterator:{get:function(){if(0>=this.count)return ib;var a=this.Ha;return null!==a?(a.reset(),a):new ub(this)}},iteratorKeys:{get:function(){return 0>=this.count?ib:new rb(this)}},iteratorValues:{get:function(){if(0>=this.count)return ib; var a=this.$e;return null!==a?(a.reset(),a):new tb(this)}}});H.prototype.toKeySet=H.prototype.Mf;H.prototype.toArray=H.prototype.ma;H.prototype.clear=H.prototype.clear;H.prototype["delete"]=H.prototype.delete;H.prototype.remove=H.prototype.remove;H.prototype.get=H.prototype.get;H.prototype.getValue=H.prototype.H;H.prototype.has=H.prototype.has;H.prototype.contains=H.prototype.contains;H.prototype.first=H.prototype.first;H.prototype.addAll=H.prototype.addAll;H.prototype.set=H.prototype.set; H.prototype.add=H.prototype.add;H.prototype.thaw=H.prototype.ea;H.prototype.freeze=H.prototype.freeze;H.className="Map";function I(a,b){void 0===a?this.y=this.x=0:"number"===typeof a&&"number"===typeof b?(this.x=a,this.y=b):B("Invalid arguments to Point constructor: "+a+", "+b);this.u=!1}I.prototype.assign=function(a){this.x=a.x;this.y=a.y;return this};I.prototype.h=function(a,b){this.x=a;this.y=b;return this};I.prototype.Jg=function(a,b){this.x=a;this.y=b;return this}; I.prototype.set=function(a){this.x=a.x;this.y=a.y;return this};I.prototype.copy=function(){var a=new I;a.x=this.x;a.y=this.y;return a};t=I.prototype;t.ca=function(){this.u=!0;Object.freeze(this);return this};t.G=function(){return this.u||Object.isFrozen(this)?this:this.copy().freeze()};t.freeze=function(){this.u=!0;return this};t.ea=function(){Object.isFrozen(this)&&B("cannot thaw constant: "+this);this.u=!1;return this}; function vb(a){if("string"===typeof a){a=a.split(" ");for(var b=0,c=0;""===a[b];)b++;var d=a[b++];d&&(c=parseFloat(d));for(var e=0;""===a[b];)b++;(d=a[b++])&&(e=parseFloat(d));return new I(c,e)}return new I}function wb(a){return a.x.toString()+" "+a.y.toString()}t.toString=function(){return"Point("+this.x+","+this.y+")"};t.w=function(a){return a instanceof I?this.x===a.x&&this.y===a.y:!1};t.fj=function(a,b){return this.x===a&&this.y===b};t.Na=function(a){return L.A(this.x,a.x)&&L.A(this.y,a.y)}; t.add=function(a){this.x+=a.x;this.y+=a.y;return this};t.he=function(a){this.x-=a.x;this.y-=a.y;return this};t.offset=function(a,b){this.x+=a;this.y+=b;return this};I.prototype.rotate=function(a){if(0===a)return this;var b=this.x,c=this.y;if(0===b&&0===c)return this;360<=a?a-=360:0>a&&(a+=360);if(90===a){a=0;var d=1}else 180===a?(a=-1,d=0):270===a?(a=0,d=-1):(d=a*Math.PI/180,a=Math.cos(d),d=Math.sin(d));this.x=a*b-d*c;this.y=d*b+a*c;return this};t=I.prototype; t.scale=function(a,b){this.x*=a;this.y*=b;return this};t.Ie=function(a){var b=a.x-this.x;a=a.y-this.y;return b*b+a*a};t.rd=function(a,b){a-=this.x;b-=this.y;return a*a+b*b};t.normalize=function(){var a=this.x,b=this.y,c=Math.sqrt(a*a+b*b);0<c&&(this.x=a/c,this.y=b/c);return this};t.Sa=function(a){return xb(a.x-this.x,a.y-this.y)};t.direction=function(a,b){return xb(a-this.x,b-this.y)}; function xb(a,b){if(0===a)return 0<b?90:0>b?270:0;if(0===b)return 0<a?0:180;if(isNaN(a)||isNaN(b))return 0;var c=180*Math.atan(Math.abs(b/a))/Math.PI;0>a?c=0>b?c+180:180-c:0>b&&(c=360-c);return c}t.OA=function(a,b,c,d){L.Ph(a,b,c,d,this.x,this.y,this);return this};t.PA=function(a,b){L.Ph(a.x,a.y,b.x,b.y,this.x,this.y,this);return this};t.aB=function(a,b,c,d){L.Dq(this.x,this.y,a,b,c,d,this);return this};t.bB=function(a,b){L.Dq(this.x,this.y,a.x,a.y,b.width,b.height,this);return this}; t.tj=function(a,b){this.x=a.x+b.x*a.width+b.offsetX;this.y=a.y+b.y*a.height+b.offsetY;return this};t.Tk=function(a,b,c,d,e){this.x=a+e.x*c+e.offsetX;this.y=b+e.y*d+e.offsetY;return this};t.transform=function(a){a.sa(this);return this};function yb(a,b){b.Jd(a);return a}function zb(a,b,c,d,e,f){var g=e-c,h=f-d,k=g*g+h*h;c-=a;d-=b;var l=-c*g-d*h;if(0>=l||l>=k)return g=e-a,h=f-b,Math.min(c*c+d*d,g*g+h*h);a=g*d-h*c;return a*a/k}function Ab(a,b,c,d){a=c-a;b=d-b;return a*a+b*b} function Bb(a,b,c,d){a=c-a;b=d-b;if(0===a)return 0<b?90:0>b?270:0;if(0===b)return 0<a?0:180;if(isNaN(a)||isNaN(b))return 0;d=180*Math.atan(Math.abs(b/a))/Math.PI;0>a?d=0>b?d+180:180-d:0>b&&(d=360-d);return d}t.s=function(){return isFinite(this.x)&&isFinite(this.y)};I.alloc=function(){var a=Cb.pop();return void 0===a?new I:a};I.allocAt=function(a,b){var c=Cb.pop();if(void 0===c)return new I(a,b);c.x=a;c.y=b;return c};I.free=function(a){Cb.push(a)};I.prototype.isReal=I.prototype.s; I.prototype.setSpot=I.prototype.Tk;I.prototype.setRectSpot=I.prototype.tj;I.prototype.snapToGridPoint=I.prototype.bB;I.prototype.snapToGrid=I.prototype.aB;I.prototype.projectOntoLineSegmentPoint=I.prototype.PA;I.prototype.projectOntoLineSegment=I.prototype.OA;I.intersectingLineSegments=function(a,b,c,d,e,f,g,h){return L.Lq(a,b,c,d,e,f,g,h)};I.prototype.direction=I.prototype.direction;I.prototype.directionPoint=I.prototype.Sa;I.prototype.normalize=I.prototype.normalize; I.prototype.distanceSquared=I.prototype.rd;I.prototype.distanceSquaredPoint=I.prototype.Ie;I.prototype.scale=I.prototype.scale;I.prototype.rotate=I.prototype.rotate;I.prototype.offset=I.prototype.offset;I.prototype.subtract=I.prototype.he;I.prototype.add=I.prototype.add;I.prototype.equalsApprox=I.prototype.Na;I.prototype.equalTo=I.prototype.fj;I.prototype.equals=I.prototype.w;I.prototype.set=I.prototype.set;I.prototype.setTo=I.prototype.Jg;var Fb=null,Gb=null,Hb=null,Ib=null,Jb=null,Cb=[]; I.className="Point";I.parse=vb;I.stringify=wb;I.distanceLineSegmentSquared=zb;I.distanceSquared=Ab;I.direction=Bb;I.Origin=Fb=(new I(0,0)).ca();I.InfiniteTopLeft=Gb=(new I(-Infinity,-Infinity)).ca();I.InfiniteBottomRight=Hb=(new I(Infinity,Infinity)).ca();I.SixPoint=Ib=(new I(6,6)).ca();I.NoPoint=Jb=(new I(NaN,NaN)).ca();I.parse=vb;I.stringify=wb;I.distanceLineSegmentSquared=zb;I.distanceSquared=Ab;I.direction=Bb; function M(a,b){void 0===a?this.height=this.width=0:"number"===typeof a&&(0<=a||isNaN(a))&&"number"===typeof b&&(0<=b||isNaN(b))?(this.width=a,this.height=b):B("Invalid arguments to Size constructor: "+a+", "+b);this.u=!1}var Kb,Lb,Mb,Nb,Ob,Pb,Qb;M.prototype.assign=function(a){this.width=a.width;this.height=a.height;return this};M.prototype.h=function(a,b){this.width=a;this.height=b;return this};M.prototype.Jg=function(a,b){this.width=a;this.height=b;return this}; M.prototype.set=function(a){this.width=a.width;this.height=a.height;return this};M.prototype.copy=function(){var a=new M;a.width=this.width;a.height=this.height;return a};t=M.prototype;t.ca=function(){this.u=!0;Object.freeze(this);return this};t.G=function(){return this.u||Object.isFrozen(this)?this:this.copy().freeze()};t.freeze=function(){this.u=!0;return this};t.ea=function(){Object.isFrozen(this)&&B("cannot thaw constant: "+this);this.u=!1;return this}; function Rb(a){if("string"===typeof a){a=a.split(" ");for(var b=0,c=0;""===a[b];)b++;var d=a[b++];d&&(c=parseFloat(d));for(var e=0;""===a[b];)b++;(d=a[b++])&&(e=parseFloat(d));return new M(c,e)}return new M}function Sb(a){return a.width.toString()+" "+a.height.toString()}t.toString=function(){return"Size("+this.width+","+this.height+")"};t.w=function(a){return a instanceof M?this.width===a.width&&this.height===a.height:!1};t.fj=function(a,b){return this.width===a&&this.height===b}; t.Na=function(a){return L.A(this.width,a.width)&&L.A(this.height,a.height)};t.s=function(){return isFinite(this.width)&&isFinite(this.height)};M.alloc=function(){var a=Tb.pop();return void 0===a?new M:a};M.free=function(a){Tb.push(a)};M.prototype.isReal=M.prototype.s;M.prototype.equalsApprox=M.prototype.Na;M.prototype.equalTo=M.prototype.fj;M.prototype.equals=M.prototype.w;M.prototype.set=M.prototype.set;M.prototype.setTo=M.prototype.Jg;var Tb=[];M.className="Size";M.parse=Rb;M.stringify=Sb; M.ZeroSize=Kb=(new M(0,0)).ca();M.OneSize=Lb=(new M(1,1)).ca();M.SixSize=Mb=(new M(6,6)).ca();M.EightSize=Nb=(new M(8,8)).ca();M.TenSize=Ob=(new M(10,10)).ca();M.InfiniteSize=Pb=(new M(Infinity,Infinity)).ca();M.NoSize=Qb=(new M(NaN,NaN)).ca();M.parse=Rb;M.stringify=Sb; function N(a,b,c,d){void 0===a?this.height=this.width=this.y=this.x=0:a instanceof I?(c=a.x,a=a.y,b instanceof I?(d=b.x,b=b.y,this.x=Math.min(c,d),this.y=Math.min(a,b),this.width=Math.abs(c-d),this.height=Math.abs(a-b)):b instanceof M?(this.x=c,this.y=a,this.width=b.width,this.height=b.height):B("Incorrect arguments supplied to Rect constructor")):"number"===typeof a&&"number"===typeof b&&"number"===typeof c&&(0<=c||isNaN(c))&&"number"===typeof d&&(0<=d||isNaN(d))?(this.x=a,this.y=b,this.width=c, this.height=d):B("Invalid arguments to Rect constructor: "+a+", "+b+", "+c+", "+d);this.u=!1}t=N.prototype;t.assign=function(a){this.x=a.x;this.y=a.y;this.width=a.width;this.height=a.height;return this};t.h=function(a,b,c,d){this.x=a;this.y=b;this.width=c;this.height=d;return this};function Ub(a,b,c){a.width=b;a.height=c}t.Jg=function(a,b,c,d){this.x=a;this.y=b;this.width=c;this.height=d;return this};t.set=function(a){this.x=a.x;this.y=a.y;this.width=a.width;this.height=a.height;return this}; t.Sc=function(a){this.x=a.x;this.y=a.y;return this};t.$A=function(a){this.width=a.width;this.height=a.height;return this};N.prototype.copy=function(){var a=new N;a.x=this.x;a.y=this.y;a.width=this.width;a.height=this.height;return a};t=N.prototype;t.ca=function(){this.u=!0;Object.freeze(this);return this};t.G=function(){return this.u||Object.isFrozen(this)?this:this.copy().freeze()};t.freeze=function(){this.u=!0;return this}; t.ea=function(){Object.isFrozen(this)&&B("cannot thaw constant: "+this);this.u=!1;return this};function Vb(a){if("string"===typeof a){a=a.split(" ");for(var b=0,c=0;""===a[b];)b++;var d=a[b++];d&&(c=parseFloat(d));for(var e=0;""===a[b];)b++;(d=a[b++])&&(e=parseFloat(d));for(var f=0;""===a[b];)b++;(d=a[b++])&&(f=parseFloat(d));for(var g=0;""===a[b];)b++;(d=a[b++])&&(g=parseFloat(d));return new N(c,e,f,g)}return new N} function Wb(a){return a.x.toString()+" "+a.y.toString()+" "+a.width.toString()+" "+a.height.toString()}t.toString=function(){return"Rect("+this.x+","+this.y+","+this.width+","+this.height+")"};t.w=function(a){return a instanceof N?this.x===a.x&&this.y===a.y&&this.width===a.width&&this.height===a.height:!1};t.fj=function(a,b,c,d){return this.x===a&&this.y===b&&this.width===c&&this.height===d};t.Na=function(a){return L.A(this.x,a.x)&&L.A(this.y,a.y)&&L.A(this.width,a.width)&&L.A(this.height,a.height)}; function $b(a,b){return L.aa(a.x,b.x)&&L.aa(a.y,b.y)&&L.aa(a.width,b.width)&&L.aa(a.height,b.height)}t.$=function(a){return this.x<=a.x&&this.x+this.width>=a.x&&this.y<=a.y&&this.y+this.height>=a.y};t.He=function(a){return this.x<=a.x&&a.x+a.width<=this.x+this.width&&this.y<=a.y&&a.y+a.height<=this.y+this.height};t.contains=function(a,b,c,d){void 0===c&&(c=0);void 0===d&&(d=0);return this.x<=a&&a+c<=this.x+this.width&&this.y<=b&&b+d<=this.y+this.height}; t.offset=function(a,b){this.x+=a;this.y+=b;return this};t.Lc=function(a,b){return ac(this,b,a,b,a)};t.rq=function(a){return ac(this,a.top,a.right,a.bottom,a.left)};t.Kw=function(a){return ac(this,-a.top,-a.right,-a.bottom,-a.left)};t.sA=function(a,b,c,d){return ac(this,a,b,c,d)};function ac(a,b,c,d,e){var f=a.width;c+e<=-f?(a.x+=f/2,a.width=0):(a.x-=e,a.width+=c+e);c=a.height;b+d<=-c?(a.y+=c/2,a.height=0):(a.y-=b,a.height+=b+d);return a}t.Dy=function(a){return bc(this,a.x,a.y,a.width,a.height)}; t.aw=function(a,b,c,d){return bc(this,a,b,c,d)};function bc(a,b,c,d,e){var f=Math.max(a.x,b),g=Math.max(a.y,c);b=Math.min(a.x+a.width,b+d);c=Math.min(a.y+a.height,c+e);a.x=f;a.y=g;a.width=Math.max(0,b-f);a.height=Math.max(0,c-g);return a}t.Oc=function(a){return this.bw(a.x,a.y,a.width,a.height)}; t.bw=function(a,b,c,d){var e=this.width,f=this.x;if(Infinity!==e&&Infinity!==c&&(e+=f,c+=a,isNaN(c)||isNaN(e)||f>c||a>e))return!1;a=this.height;c=this.y;return Infinity!==a&&Infinity!==d&&(a+=c,d+=b,isNaN(d)||isNaN(a)||c>d||b>a)?!1:!0};function cc(a,b){var c=a.width,d=a.x,e=b.x-10;if(d>b.width+10+10+e||e>c+d)return!1;c=a.height;a=a.y;d=b.y-10;return a>b.height+10+10+d||d>c+a?!1:!0}t.Pe=function(a){return gc(this,a.x,a.y,0,0)};t.Tc=function(a){return gc(this,a.x,a.y,a.width,a.height)}; t.Sw=function(a,b,c,d){void 0===c&&(c=0);void 0===d&&(d=0);return gc(this,a,b,c,d)};function gc(a,b,c,d,e){var f=Math.min(a.x,b),g=Math.min(a.y,c);b=Math.max(a.x+a.width,b+d);c=Math.max(a.y+a.height,c+e);a.x=f;a.y=g;a.width=b-f;a.height=c-g;return a}t.Tk=function(a,b,c){this.x=a-c.offsetX-c.x*this.width;this.y=b-c.offsetY-c.y*this.height;return this};function hc(a,b,c,d,e,f,g,h){void 0===g&&(g=0);void 0===h&&(h=0);return a<=e&&e+g<=a+c&&b<=f&&f+h<=b+d} function ic(a,b,c,d,e,f,g,h){return a>g+e||e>c+a?!1:b>h+f||f>d+b?!1:!0}t.s=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)};t.yA=function(){return 0===this.width&&0===this.height};N.alloc=function(){var a=jc.pop();return void 0===a?new N:a};N.allocAt=function(a,b,c,d){var e=jc.pop();return void 0===e?new N(a,b,c,d):e.h(a,b,c,d)};N.free=function(a){jc.push(a)}; na.Object.defineProperties(N.prototype,{left:{get:function(){return this.x},set:function(a){this.x=a}},top:{get:function(){return this.y},set:function(a){this.y=a}},right:{get:function(){return this.x+this.width},set:function(a){this.x+=a-(this.x+this.width)}},bottom:{get:function(){return this.y+this.height},set:function(a){this.y+=a-(this.y+this.height)}},position:{ get:function(){return new I(this.x,this.y)},set:function(a){this.x=a.x;this.y=a.y}},size:{get:function(){return new M(this.width,this.height)},set:function(a){this.width=a.width;this.height=a.height}},center:{get:function(){return new I(this.x+this.width/2,this.y+this.height/2)},set:function(a){this.x=a.x-this.width/2;this.y=a.y-this.height/2}},centerX:{get:function(){return this.x+this.width/2}, set:function(a){this.x=a-this.width/2}},centerY:{get:function(){return this.y+this.height/2},set:function(a){this.y=a-this.height/2}}});N.prototype.isEmpty=N.prototype.yA;N.prototype.isReal=N.prototype.s;N.intersectsLineSegment=function(a,b,c,d,e,f,g,h){return L.Ey(a,b,c,d,e,f,g,h)};N.prototype.setSpot=N.prototype.Tk;N.prototype.union=N.prototype.Sw;N.prototype.unionRect=N.prototype.Tc;N.prototype.unionPoint=N.prototype.Pe;N.prototype.intersects=N.prototype.bw; N.prototype.intersectsRect=N.prototype.Oc;N.prototype.intersect=N.prototype.aw;N.prototype.intersectRect=N.prototype.Dy;N.prototype.grow=N.prototype.sA;N.prototype.subtractMargin=N.prototype.Kw;N.prototype.addMargin=N.prototype.rq;N.prototype.inflate=N.prototype.Lc;N.prototype.offset=N.prototype.offset;N.prototype.contains=N.prototype.contains;N.prototype.containsRect=N.prototype.He;N.prototype.containsPoint=N.prototype.$;N.prototype.equalsApprox=N.prototype.Na;N.prototype.equalTo=N.prototype.fj; N.prototype.equals=N.prototype.w;N.prototype.setSize=N.prototype.$A;N.prototype.setPoint=N.prototype.Sc;N.prototype.set=N.prototype.set;N.prototype.setTo=N.prototype.Jg;var kc=null,lc=null,jc=[];N.className="Rect";N.parse=Vb;N.stringify=Wb;N.contains=hc;N.intersects=ic;N.ZeroRect=kc=(new N(0,0,0,0)).ca();N.NoRect=lc=(new N(NaN,NaN,NaN,NaN)).ca();N.parse=Vb;N.stringify=Wb;N.contains=hc;N.intersects=ic; function oc(a,b,c,d){void 0===a?this.left=this.bottom=this.right=this.top=0:void 0===b?this.left=this.bottom=this.right=this.top=a:void 0===c?(this.top=a,this.right=b,this.bottom=a,this.left=b):void 0!==d?(this.top=a,this.right=b,this.bottom=c,this.left=d):B("Invalid arguments to Margin constructor: "+a+", "+b+", "+c+", "+d);this.u=!1}oc.prototype.assign=function(a){this.top=a.top;this.right=a.right;this.bottom=a.bottom;this.left=a.left;return this}; oc.prototype.Jg=function(a,b,c,d){this.top=a;this.right=b;this.bottom=c;this.left=d;return this};oc.prototype.set=function(a){this.top=a.top;this.right=a.right;this.bottom=a.bottom;this.left=a.left;return this};oc.prototype.copy=function(){var a=new oc;a.top=this.top;a.right=this.right;a.bottom=this.bottom;a.left=this.left;return a};t=oc.prototype;t.ca=function(){this.u=!0;Object.freeze(this);return this};t.G=function(){return this.u||Object.isFrozen(this)?this:this.copy().freeze()}; t.freeze=function(){this.u=!0;return this};t.ea=function(){Object.isFrozen(this)&&B("cannot thaw constant: "+this);this.u=!1;return this}; function pc(a){if("string"===typeof a){a=a.split(" ");for(var b=0,c=NaN;""===a[b];)b++;var d=a[b++];d&&(c=parseFloat(d));if(isNaN(c))return new oc;for(var e=NaN;""===a[b];)b++;(d=a[b++])&&(e=parseFloat(d));if(isNaN(e))return new oc(c);for(var f=NaN;""===a[b];)b++;(d=a[b++])&&(f=parseFloat(d));if(isNaN(f))return new oc(c,e);for(var g=NaN;""===a[b];)b++;(d=a[b++])&&(g=parseFloat(d));return isNaN(g)?new oc(c,e):new oc(c,e,f,g)}return new oc} function qc(a){return a.top.toString()+" "+a.right.toString()+" "+a.bottom.toString()+" "+a.left.toString()}t.toString=function(){return"Margin("+this.top+","+this.right+","+this.bottom+","+this.left+")"};t.w=function(a){return a instanceof oc?this.top===a.top&&this.right===a.right&&this.bottom===a.bottom&&this.left===a.left:!1};t.fj=function(a,b,c,d){return this.top===a&&this.right===b&&this.bottom===c&&this.left===d}; t.Na=function(a){return L.A(this.top,a.top)&&L.A(this.right,a.right)&&L.A(this.bottom,a.bottom)&&L.A(this.left,a.left)};t.s=function(){return isFinite(this.top)&&isFinite(this.right)&&isFinite(this.bottom)&&isFinite(this.left)};oc.alloc=function(){var a=rc.pop();return void 0===a?new oc:a};oc.free=function(a){rc.push(a)};oc.prototype.isReal=oc.prototype.s;oc.prototype.equalsApprox=oc.prototype.Na;oc.prototype.equalTo=oc.prototype.fj;oc.prototype.equals=oc.prototype.w;oc.prototype.set=oc.prototype.set; oc.prototype.setTo=oc.prototype.Jg;var sc=null,tc=null,rc=[];oc.className="Margin";oc.parse=pc;oc.stringify=qc;oc.ZeroMargin=sc=(new oc(0,0,0,0)).ca();oc.TwoMargin=tc=(new oc(2,2,2,2)).ca();oc.parse=pc;oc.stringify=qc;function O(a,b,c,d){void 0===a?this.offsetY=this.offsetX=this.y=this.x=0:(void 0===b&&(b=0),void 0===c&&(c=0),void 0===d&&(d=0),this.x=a,this.y=b,this.offsetX=c,this.offsetY=d);this.u=!1} var uc,vc,yc,zc,Ac,Bc,Cc,Dc,Fc,Gc,Hc,Ic,Jc,Kc,Lc,Mc,Nc,Pc,Qc,Rc,Sc,Tc,Uc,Vc,Yc,Zc,$c,ad,bd,cd,dd,ed,fd,gd,hd,id;O.prototype.assign=function(a){this.x=a.x;this.y=a.y;this.offsetX=a.offsetX;this.offsetY=a.offsetY;return this};O.prototype.Jg=function(a,b,c,d){this.x=a;this.y=b;this.offsetX=c;this.offsetY=d;return this};O.prototype.set=function(a){this.x=a.x;this.y=a.y;this.offsetX=a.offsetX;this.offsetY=a.offsetY;return this}; O.prototype.copy=function(){var a=new O;a.x=this.x;a.y=this.y;a.offsetX=this.offsetX;a.offsetY=this.offsetY;return a};t=O.prototype;t.ca=function(){this.u=!0;Object.freeze(this);return this};t.G=function(){return this.u||Object.isFrozen(this)?this:this.copy().freeze()};t.freeze=function(){this.u=!0;return this};t.ea=function(){Object.isFrozen(this)&&B("cannot thaw constant: "+this);this.u=!1;return this};function jd(a,b){a.x=NaN;a.y=NaN;a.offsetX=b;return a} function kd(a){if("string"===typeof a){a=a.trim();if("None"===a)return uc;if("TopLeft"===a)return vc;if("Top"===a||"TopCenter"===a||"MiddleTop"===a)return yc;if("TopRight"===a)return zc;if("Left"===a||"LeftCenter"===a||"MiddleLeft"===a)return Ac;if("Center"===a)return Bc;if("Right"===a||"RightCenter"===a||"MiddleRight"===a)return Cc;if("BottomLeft"===a)return Dc;if("Bottom"===a||"BottomCenter"===a||"MiddleBottom"===a)return Fc;if("BottomRight"===a)return Gc;if("TopSide"===a)return Hc;if("LeftSide"=== a)return Ic;if("RightSide"===a)return Jc;if("BottomSide"===a)return Kc;if("TopBottomSides"===a)return Lc;if("LeftRightSides"===a)return Mc;if("TopLeftSides"===a)return Nc;if("TopRightSides"===a)return Pc;if("BottomLeftSides"===a)return Qc;if("BottomRightSides"===a)return Rc;if("NotTopSide"===a)return Sc;if("NotLeftSide"===a)return Tc;if("NotRightSide"===a)return Uc;if("NotBottomSide"===a)return Vc;if("AllSides"===a)return Yc;if("Default"===a)return Zc;a=a.split(" ");for(var b=0,c=0;""===a[b];)b++; var d=a[b++];void 0!==d&&0<d.length&&(c=parseFloat(d));for(var e=0;""===a[b];)b++;d=a[b++];void 0!==d&&0<d.length&&(e=parseFloat(d));for(var f=0;""===a[b];)b++;d=a[b++];void 0!==d&&0<d.length&&(f=parseFloat(d));for(var g=0;""===a[b];)b++;d=a[b++];void 0!==d&&0<d.length&&(g=parseFloat(d));return new O(c,e,f,g)}return new O}function ld(a){return a.kb()?a.x.toString()+" "+a.y.toString()+" "+a.offsetX.toString()+" "+a.offsetY.toString():a.toString()} t.toString=function(){return this.kb()?0===this.offsetX&&0===this.offsetY?"Spot("+this.x+","+this.y+")":"Spot("+this.x+","+this.y+","+this.offsetX+","+this.offsetY+")":this.w(uc)?"None":this.w(vc)?"TopLeft":this.w(yc)?"Top":this.w(zc)?"TopRight":this.w(Ac)?"Left":this.w(Bc)?"Center":this.w(Cc)?"Right":this.w(Dc)?"BottomLeft":this.w(Fc)?"Bottom":this.w(Gc)?"BottomRight":this.w(Hc)?"TopSide":this.w(Ic)?"LeftSide":this.w(Jc)?"RightSide":this.w(Kc)?"BottomSide":this.w(Lc)?"TopBottomSides":this.w(Mc)? "LeftRightSides":this.w(Nc)?"TopLeftSides":this.w(Pc)?"TopRightSides":this.w(Qc)?"BottomLeftSides":this.w(Rc)?"BottomRightSides":this.w(Sc)?"NotTopSide":this.w(Tc)?"NotLeftSide":this.w(Uc)?"NotRightSide":this.w(Vc)?"NotBottomSide":this.w(Yc)?"AllSides":this.w(Zc)?"Default":"None"};t.w=function(a){return a instanceof O?(this.x===a.x||isNaN(this.x)&&isNaN(a.x))&&(this.y===a.y||isNaN(this.y)&&isNaN(a.y))&&this.offsetX===a.offsetX&&this.offsetY===a.offsetY:!1}; t.lw=function(){return new O(.5-(this.x-.5),.5-(this.y-.5),-this.offsetX,-this.offsetY)};t.Gf=function(a){if(!this.Qc())return!1;if(!a.Qc())if(a.w($c))a=Ic;else if(a.w(ad))a=Jc;else if(a.w(bd))a=Hc;else if(a.w(cd))a=Kc;else return!1;a=a.offsetY;return(this.offsetY&a)===a};t.kb=function(){return!isNaN(this.x)&&!isNaN(this.y)};t.nc=function(){return isNaN(this.x)||isNaN(this.y)};t.Qc=function(){return isNaN(this.x)&&isNaN(this.y)&&1===this.offsetX&&0!==this.offsetY}; t.Wt=function(){return isNaN(this.x)&&isNaN(this.y)&&0===this.offsetX&&0===this.offsetY};t.Nb=function(){return isNaN(this.x)&&isNaN(this.y)&&-1===this.offsetX&&0===this.offsetY};O.alloc=function(){var a=qd.pop();return void 0===a?new O:a};O.free=function(a){qd.push(a)};O.prototype.isDefault=O.prototype.Nb;O.prototype.isNone=O.prototype.Wt;O.prototype.isSide=O.prototype.Qc;O.prototype.isNoSpot=O.prototype.nc;O.prototype.isSpot=O.prototype.kb;O.prototype.includesSide=O.prototype.Gf; O.prototype.opposite=O.prototype.lw;O.prototype.equals=O.prototype.w;O.prototype.set=O.prototype.set;O.prototype.setTo=O.prototype.Jg;var qd=[];O.className="Spot";O.parse=kd;O.stringify=ld;O.None=uc=jd(new O(0,0,0,0),0).ca();O.Default=Zc=jd(new O(0,0,-1,0),-1).ca();O.TopLeft=vc=(new O(0,0,0,0)).ca();O.TopCenter=yc=(new O(.5,0,0,0)).ca();O.TopRight=zc=(new O(1,0,0,0)).ca();O.LeftCenter=Ac=(new O(0,.5,0,0)).ca();O.Center=Bc=(new O(.5,.5,0,0)).ca();O.RightCenter=Cc=(new O(1,.5,0,0)).ca(); O.BottomLeft=Dc=(new O(0,1,0,0)).ca();O.BottomCenter=Fc=(new O(.5,1,0,0)).ca();O.BottomRight=Gc=(new O(1,1,0,0)).ca();O.MiddleTop=dd=yc;O.MiddleLeft=ed=Ac;O.MiddleRight=fd=Cc;O.MiddleBottom=gd=Fc;O.Top=bd=yc;O.Left=$c=Ac;O.Right=ad=Cc;O.Bottom=cd=Fc;O.TopSide=Hc=jd(new O(0,0,1,1),1).ca();O.LeftSide=Ic=jd(new O(0,0,1,2),1).ca();O.RightSide=Jc=jd(new O(0,0,1,4),1).ca();O.BottomSide=Kc=jd(new O(0,0,1,8),1).ca();O.TopBottomSides=Lc=jd(new O(0,0,1,9),1).ca();O.LeftRightSides=Mc=jd(new O(0,0,1,6),1).ca(); O.TopLeftSides=Nc=jd(new O(0,0,1,3),1).ca();O.TopRightSides=Pc=jd(new O(0,0,1,5),1).ca();O.BottomLeftSides=Qc=jd(new O(0,0,1,10),1).ca();O.BottomRightSides=Rc=jd(new O(0,0,1,12),1).ca();O.NotTopSide=Sc=jd(new O(0,0,1,14),1).ca();O.NotLeftSide=Tc=jd(new O(0,0,1,13),1).ca();O.NotRightSide=Uc=jd(new O(0,0,1,11),1).ca();O.NotBottomSide=Vc=jd(new O(0,0,1,7),1).ca();O.AllSides=Yc=jd(new O(0,0,1,15),1).ca();hd=(new O(.156,.156)).ca();id=(new O(.844,.844)).ca();O.parse=kd;O.stringify=ld; function rd(){this.m11=1;this.m21=this.m12=0;this.m22=1;this.dy=this.dx=0}rd.prototype.set=function(a){this.m11=a.m11;this.m12=a.m12;this.m21=a.m21;this.m22=a.m22;this.dx=a.dx;this.dy=a.dy;return this};rd.prototype.copy=function(){var a=new rd;a.m11=this.m11;a.m12=this.m12;a.m21=this.m21;a.m22=this.m22;a.dx=this.dx;a.dy=this.dy;return a};t=rd.prototype;t.toString=function(){return"Transform("+this.m11+","+this.m12+","+this.m21+","+this.m22+","+this.dx+","+this.dy+")"}; t.w=function(a){return this.m11===a.m11&&this.m12===a.m12&&this.m21===a.m21&&this.m22===a.m22&&this.dx===a.dx&&this.dy===a.dy};t.Ut=function(){return 0===this.dx&&0===this.dy&&1===this.m11&&0===this.m12&&0===this.m21&&1===this.m22};t.reset=function(){this.m11=1;this.m21=this.m12=0;this.m22=1;this.dy=this.dx=0;return this}; t.multiply=function(a){var b=this.m11*a.m11+this.m21*a.m12,c=this.m12*a.m11+this.m22*a.m12,d=this.m11*a.m21+this.m21*a.m22,e=this.m12*a.m21+this.m22*a.m22;this.dx=this.m11*a.dx+this.m21*a.dy+this.dx;this.dy=this.m12*a.dx+this.m22*a.dy+this.dy;this.m11=b;this.m12=c;this.m21=d;this.m22=e;return this}; t.iw=function(a){var b=1/(a.m11*a.m22-a.m12*a.m21),c=a.m22*b,d=-a.m12*b,e=-a.m21*b,f=a.m11*b,g=b*(a.m21*a.dy-a.m22*a.dx);a=b*(a.m12*a.dx-a.m11*a.dy);b=this.m11*c+this.m21*d;c=this.m12*c+this.m22*d;d=this.m11*e+this.m21*f;e=this.m12*e+this.m22*f;this.dx=this.m11*g+this.m21*a+this.dx;this.dy=this.m12*g+this.m22*a+this.dy;this.m11=b;this.m12=c;this.m21=d;this.m22=e;return this}; t.Tt=function(){var a=1/(this.m11*this.m22-this.m12*this.m21),b=-this.m12*a,c=-this.m21*a,d=this.m11*a,e=a*(this.m21*this.dy-this.m22*this.dx),f=a*(this.m12*this.dx-this.m11*this.dy);this.m11=this.m22*a;this.m12=b;this.m21=c;this.m22=d;this.dx=e;this.dy=f;return this}; rd.prototype.rotate=function(a,b,c){360<=a?a-=360:0>a&&(a+=360);if(0===a)return this;this.translate(b,c);if(90===a){a=0;var d=1}else 180===a?(a=-1,d=0):270===a?(a=0,d=-1):(d=a*Math.PI/180,a=Math.cos(d),d=Math.sin(d));var e=this.m12*a+this.m22*d,f=this.m11*-d+this.m21*a,g=this.m12*-d+this.m22*a;this.m11=this.m11*a+this.m21*d;this.m12=e;this.m21=f;this.m22=g;this.translate(-b,-c);return this};t=rd.prototype;t.translate=function(a,b){this.dx+=this.m11*a+this.m21*b;this.dy+=this.m12*a+this.m22*b;return this}; t.scale=function(a,b){void 0===b&&(b=a);this.m11*=a;this.m12*=a;this.m21*=b;this.m22*=b;return this};t.sa=function(a){var b=a.x,c=a.y;return a.h(b*this.m11+c*this.m21+this.dx,b*this.m12+c*this.m22+this.dy)};t.Jd=function(a){var b=1/(this.m11*this.m22-this.m12*this.m21),c=a.x,d=a.y;return a.h(c*this.m22*b+d*-this.m21*b+b*(this.m21*this.dy-this.m22*this.dx),c*-this.m12*b+d*this.m11*b+b*(this.m12*this.dx-this.m11*this.dy))}; t.$x=function(a){var b=1/(this.m11*this.m22-this.m12*this.m21),c=1.25*a.x,d=1.2*a.y;return a.h(c*this.m22*b+d*-this.m21*b+b*(this.m21*this.dy-this.m22*this.dx),c*-this.m12*b+d*this.m11*b+b*(this.m12*this.dx-this.m11*this.dy))}; t.Qw=function(a){var b=a.x,c=a.y,d=b+a.width,e=c+a.height,f=this.m11,g=this.m12,h=this.m21,k=this.m22,l=this.dx,m=this.dy,n=b*f+c*h+l,p=b*g+c*k+m,r=d*f+c*h+l,q=d*g+c*k+m;c=b*f+e*h+l;b=b*g+e*k+m;f=d*f+e*h+l;d=d*g+e*k+m;e=Math.min(n,r);n=Math.max(n,r);r=Math.min(p,q);p=Math.max(p,q);e=Math.min(e,c);n=Math.max(n,c);r=Math.min(r,b);p=Math.max(p,b);e=Math.min(e,f);n=Math.max(n,f);r=Math.min(r,d);p=Math.max(p,d);a.h(e,r,n-e,p-r);return a};rd.alloc=function(){var a=sd.pop();return void 0===a?new rd:a}; rd.free=function(a){sd.push(a)};rd.prototype.transformRect=rd.prototype.Qw;rd.prototype.transformPoint=rd.prototype.sa;rd.prototype.scale=rd.prototype.scale;rd.prototype.translate=rd.prototype.translate;rd.prototype.rotate=rd.prototype.rotate;rd.prototype.invert=rd.prototype.Tt;rd.prototype.multiplyInverted=rd.prototype.iw;rd.prototype.multiply=rd.prototype.multiply;rd.prototype.reset=rd.prototype.reset;rd.prototype.isIdentity=rd.prototype.Ut;rd.prototype.equals=rd.prototype.w;rd.prototype.set=rd.prototype.set; var sd=[];rd.className="Transform";rd.xF="54a702f3e53909c447824c6706603faf4c"; var L={jB:"7da71ca0ad381e90",Lg:(Math.sqrt(2)-1)/3*4,kx:null,sqrt:function(a){if(0>=a)return 0;var b=L.kx;if(null===b){b=[];for(var c=0;2E3>=c;c++)b[c]=Math.sqrt(c);L.kx=b}return 1>a?(c=1/a,2E3>=c?1/b[c|0]:Math.sqrt(a)):2E3>=a?b[a|0]:Math.sqrt(a)},A:function(a,b){a-=b;return.5>a&&-.5<a},aa:function(a,b){a-=b;return 5E-8>a&&-5E-8<a},Ob:function(a,b,c,d,e,f,g){0>=e&&(e=1E-6);if(a<c){var h=a;var k=c}else h=c,k=a;if(b<d){var l=b;var m=d}else l=d,m=b;if(a===c)return l<=g&&g<=m&&a-e<=f&&f<=a+e;if(b===d)return h<= f&&f<=k&&b-e<=g&&g<=b+e;k+=e;h-=e;if(h<=f&&f<=k&&(m+=e,l-=e,l<=g&&g<=m))if(k-h>m-l)if(a-c>e||c-a>e){if(f=(d-b)/(c-a)*(f-a)+b,f-e<=g&&g<=f+e)return!0}else return!0;else if(b-d>e||d-b>e){if(g=(c-a)/(d-b)*(g-b)+a,g-e<=f&&f<=g+e)return!0}else return!0;return!1},yt:function(a,b,c,d,e,f,g,h,k,l,m,n){if(L.Ob(a,b,g,h,n,c,d)&&L.Ob(a,b,g,h,n,e,f))return L.Ob(a,b,g,h,n,l,m);var p=(a+c)/2,r=(b+d)/2,q=(c+e)/2,u=(d+f)/2;e=(e+g)/2;f=(f+h)/2;d=(p+q)/2;c=(r+u)/2;q=(q+e)/2;u=(u+f)/2;var v=(d+q)/2,w=(c+u)/2;return L.yt(a, b,p,r,d,c,v,w,k,l,m,n)||L.yt(v,w,q,u,e,f,g,h,k,l,m,n)},yz:function(a,b,c,d,e,f,g,h,k){var l=(c+e)/2,m=(d+f)/2;k.h((((a+c)/2+l)/2+(l+(e+g)/2)/2)/2,(((b+d)/2+m)/2+(m+(f+h)/2)/2)/2);return k},xz:function(a,b,c,d,e,f,g,h){var k=(c+e)/2,l=(d+f)/2;return Bb(((a+c)/2+k)/2,((b+d)/2+l)/2,(k+(e+g)/2)/2,(l+(f+h)/2)/2)},um:function(a,b,c,d,e,f,g,h,k,l){if(L.Ob(a,b,g,h,k,c,d)&&L.Ob(a,b,g,h,k,e,f))gc(l,a,b,0,0),gc(l,g,h,0,0);else{var m=(a+c)/2,n=(b+d)/2,p=(c+e)/2,r=(d+f)/2;e=(e+g)/2;f=(f+h)/2;d=(m+p)/2;c=(n+r)/ 2;p=(p+e)/2;r=(r+f)/2;var q=(d+p)/2,u=(c+r)/2;L.um(a,b,m,n,d,c,q,u,k,l);L.um(q,u,p,r,e,f,g,h,k,l)}return l},Ge:function(a,b,c,d,e,f,g,h,k,l){if(L.Ob(a,b,g,h,k,c,d)&&L.Ob(a,b,g,h,k,e,f))0===l.length&&(l.push(a),l.push(b)),l.push(g),l.push(h);else{var m=(a+c)/2,n=(b+d)/2,p=(c+e)/2,r=(d+f)/2;e=(e+g)/2;f=(f+h)/2;d=(m+p)/2;c=(n+r)/2;p=(p+e)/2;r=(r+f)/2;var q=(d+p)/2,u=(c+r)/2;L.Ge(a,b,m,n,d,c,q,u,k,l);L.Ge(q,u,p,r,e,f,g,h,k,l)}return l},pw:function(a,b,c,d,e,f,g,h,k,l){if(L.Ob(a,b,e,f,l,c,d))return L.Ob(a, b,e,f,l,h,k);var m=(a+c)/2,n=(b+d)/2;c=(c+e)/2;d=(d+f)/2;var p=(m+c)/2,r=(n+d)/2;return L.pw(a,b,m,n,p,r,g,h,k,l)||L.pw(p,r,c,d,e,f,g,h,k,l)},yB:function(a,b,c,d,e,f,g){g.h(((a+c)/2+(c+e)/2)/2,((b+d)/2+(d+f)/2)/2);return g},ow:function(a,b,c,d,e,f,g,h){if(L.Ob(a,b,e,f,g,c,d))gc(h,a,b,0,0),gc(h,e,f,0,0);else{var k=(a+c)/2,l=(b+d)/2;c=(c+e)/2;d=(d+f)/2;var m=(k+c)/2,n=(l+d)/2;L.ow(a,b,k,l,m,n,g,h);L.ow(m,n,c,d,e,f,g,h)}return h},Vq:function(a,b,c,d,e,f,g,h){if(L.Ob(a,b,e,f,g,c,d))0===h.length&&(h.push(a), h.push(b)),h.push(e),h.push(f);else{var k=(a+c)/2,l=(b+d)/2;c=(c+e)/2;d=(d+f)/2;var m=(k+c)/2,n=(l+d)/2;L.Vq(a,b,k,l,m,n,g,h);L.Vq(m,n,c,d,e,f,g,h)}return h},tq:function(a,b,c,d,e,f,g,h,k,l,m,n,p,r){if(L.Ob(a,b,g,h,p,c,d)&&L.Ob(a,b,g,h,p,e,f)){if(a<k&&g<k&&a<m&&g<m||a>k&&g>k&&a>m&&g>m||b<l&&h<l&&b<n&&h<n||b>l&&h>l&&b>n&&h>n)return!1;var q=(a-g)*(l-n)-(b-h)*(k-m);if(0===q)return!1;p=((a*h-b*g)*(k-m)-(a-g)*(k*n-l*m))/q;q=((a*h-b*g)*(l-n)-(b-h)*(k*n-l*m))/q;if((k>m?k-m:m-k)<(l>n?l-n:n-l)){if(b<h?g=b: (g=h,h=b),1E-5+q<g||q>h+1E-5)return!1}else if(a<g?h=a:(h=g,g=a),1E-5+p<h||p>g+1E-5)return!1;r.h(p,q);return!0}q=(a+c)/2;var u=(b+d)/2,v=(c+e)/2,w=(d+f)/2;e=(e+g)/2;f=(f+h)/2;d=(q+v)/2;c=(u+w)/2;v=(v+e)/2;w=(w+f)/2;var y=(d+v)/2,z=(c+w)/2,A=Infinity,C=!1,F=0,Q=0;L.tq(a,b,q,u,d,c,y,z,k,l,m,n,p,r)&&(a=(r.x-k)*(r.x-k)+(r.y-l)*(r.y-l),a<A&&(A=a,C=!0,F=r.x,Q=r.y));L.tq(y,z,v,w,e,f,g,h,k,l,m,n,p,r)&&(r.x-k)*(r.x-k)+(r.y-l)*(r.y-l)<A&&(C=!0,F=r.x,Q=r.y);C&&(r.x=F,r.y=Q);return C},uq:function(a,b,c,d,e,f, g,h,k,l,m,n,p){var r=0;if(L.Ob(a,b,g,h,p,c,d)&&L.Ob(a,b,g,h,p,e,f)){p=(a-g)*(l-n)-(b-h)*(k-m);if(0===p)return r;var q=((a*h-b*g)*(k-m)-(a-g)*(k*n-l*m))/p,u=((a*h-b*g)*(l-n)-(b-h)*(k*n-l*m))/p;if(q>=m)return r;if((k>m?k-m:m-k)<(l>n?l-n:n-l)){if(b<h?(a=b,b=h):a=h,u<a||u>b)return r}else if(a<g?(b=a,a=g):b=g,q<b||q>a)return r;0<p?r++:0>p&&r--}else{q=(a+c)/2;u=(b+d)/2;var v=(c+e)/2,w=(d+f)/2;e=(e+g)/2;f=(f+h)/2;d=(q+v)/2;c=(u+w)/2;v=(v+e)/2;w=(w+f)/2;var y=(d+v)/2,z=(c+w)/2;r+=L.uq(a,b,q,u,d,c,y,z,k,l, m,n,p);r+=L.uq(y,z,v,w,e,f,g,h,k,l,m,n,p)}return r},Ph:function(a,b,c,d,e,f,g){if(L.aa(a,c)){b<d?(c=b,b=d):c=d;if(f<c)return g.h(a,c),!1;if(f>b)return g.h(a,b),!1;g.h(a,f);return!0}if(L.aa(b,d)){a<c?(d=a,a=c):d=c;if(e<d)return g.h(d,b),!1;if(e>a)return g.h(a,b),!1;g.h(e,b);return!0}e=((a-e)*(a-c)+(b-f)*(b-d))/((c-a)*(c-a)+(d-b)*(d-b));if(-5E-6>e)return g.h(a,b),!1;if(1.000005<e)return g.h(c,d),!1;g.h(a+e*(c-a),b+e*(d-b));return!0},Me:function(a,b,c,d,e,f,g,h,k){if(L.A(a,c)&&L.A(b,d))return k.h(a, b),!1;if(L.aa(e,g))return L.aa(a,c)?(L.Ph(a,b,c,d,e,f,k),!1):L.Ph(a,b,c,d,e,(d-b)/(c-a)*(e-a)+b,k);h=(h-f)/(g-e);if(L.aa(a,c)){c=h*(a-e)+f;b<d?(e=b,b=d):e=d;if(c<e)return k.h(a,e),!1;if(c>b)return k.h(a,b),!1;k.h(a,c);return!0}g=(d-b)/(c-a);if(L.aa(h,g))return L.Ph(a,b,c,d,e,f,k),!1;e=(g*a-h*e+f-b)/(g-h);if(L.aa(g,0)){a<c?(d=a,a=c):d=c;if(e<d)return k.h(d,b),!1;if(e>a)return k.h(a,b),!1;k.h(e,b);return!0}return L.Ph(a,b,c,d,e,g*(e-a)+b,k)},wB:function(a,b,c,d,e){return L.Me(c.x,c.y,d.x,d.y,a.x,a.y, b.x,b.y,e)},uB:function(a,b,c,d,e,f,g,h,k,l){function m(c,d){var e=(c-a)*(c-a)+(d-b)*(d-b);e<n&&(n=e,k.h(c,d))}var n=Infinity;m(k.x,k.y);var p=0,r=0,q=0,u=0;e<g?(p=e,r=g):(p=g,r=e);f<h?(q=e,u=g):(q=g,u=e);p=(r-p)/2+l;l=(u-q)/2+l;e=(e+g)/2;f=(f+h)/2;if(0===p||0===l)return k;if(.5>(c>a?c-a:a-c)){p=1-(c-e)*(c-e)/(p*p);if(0>p)return k;p=Math.sqrt(p);d=-l*p+f;m(c,l*p+f);m(c,d)}else{c=(d-b)/(c-a);d=1/(p*p)+c*c/(l*l);h=2*c*(b-c*a)/(l*l)-2*c*f/(l*l)-2*e/(p*p);p=h*h-4*d*(2*c*a*f/(l*l)-2*b*f/(l*l)+f*f/(l*l)+ e*e/(p*p)-1+(b-c*a)*(b-c*a)/(l*l));if(0>p)return k;p=Math.sqrt(p);l=(-h+p)/(2*d);m(l,c*l-c*a+b);p=(-h-p)/(2*d);m(p,c*p-c*a+b)}return k},Ef:function(a,b,c,d,e,f,g,h,k){var l=1E21,m=a,n=b;if(L.Me(a,b,a,d,e,f,g,h,k)){var p=(k.x-e)*(k.x-e)+(k.y-f)*(k.y-f);p<l&&(l=p,m=k.x,n=k.y)}L.Me(c,b,c,d,e,f,g,h,k)&&(p=(k.x-e)*(k.x-e)+(k.y-f)*(k.y-f),p<l&&(l=p,m=k.x,n=k.y));L.Me(a,b,c,b,e,f,g,h,k)&&(b=(k.x-e)*(k.x-e)+(k.y-f)*(k.y-f),b<l&&(l=b,m=k.x,n=k.y));L.Me(a,d,c,d,e,f,g,h,k)&&(a=(k.x-e)*(k.x-e)+(k.y-f)*(k.y-f), a<l&&(l=a,m=k.x,n=k.y));k.h(m,n);return 1E21>l},tB:function(a,b,c,d,e,f,g,h,k){c=a-c;g=e-g;0===c||0===g?0===c?(b=(f-h)/g,h=a,e=b*h+(f-b*e)):(f=(b-d)/c,h=e,e=f*h+(b-f*a)):(d=(b-d)/c,h=(f-h)/g,a=b-d*a,h=(f-h*e-a)/(d-h),e=d*h+a);k.h(h,e);return k},Rt:function(a,b,c){return L.Ey(a.x,a.y,a.width,a.height,b.x,b.y,c.x,c.y)},Ey:function(a,b,c,d,e,f,g,h){var k=a+c,l=b+d;return e===g?(f<h?(g=f,f=h):g=h,a<=e&&e<=k&&g<=l&&f>=b):f===h?(e<g?(h=e,e=g):h=g,b<=f&&f<=l&&h<=k&&e>=a):hc(a,b,c,d,e,f)||hc(a,b,c,d,g,h)|| L.Lq(a,b,k,b,e,f,g,h)||L.Lq(k,b,k,l,e,f,g,h)||L.Lq(k,l,a,l,e,f,g,h)||L.Lq(a,l,a,b,e,f,g,h)?!0:!1},Lq:function(a,b,c,d,e,f,g,h){return 0>=L.Bt(a,b,c,d,e,f)*L.Bt(a,b,c,d,g,h)&&0>=L.Bt(e,f,g,h,a,b)*L.Bt(e,f,g,h,c,d)},Bt:function(a,b,c,d,e,f){c-=a;d-=b;a=e-a;b=f-b;f=a*d-b*c;0===f&&(f=a*c+b*d,0<f&&(f=(a-c)*c+(b-d)*d,0>f&&(f=0)));return 0>f?-1:0<f?1:0},Sq:function(a){0>a&&(a+=360);360<=a&&(a-=360);return a},hy:function(a,b,c,d,e,f){var g=Math.PI;f||(d*=g/180,e*=g/180);var h=d>e?-1:1;f=[];var k=g/2,l=d; d=Math.min(2*g,Math.abs(e-d));if(1E-5>d)return k=l+h*Math.min(d,k),h=a+c*Math.cos(l),l=b+c*Math.sin(l),a+=c*Math.cos(k),b+=c*Math.sin(k),c=(h+a)/2,k=(l+b)/2,f.push([h,l,c,k,c,k,a,b]),f;for(;1E-5<d;)e=l+h*Math.min(d,k),f.push(L.Hz(c,l,e,a,b)),d-=Math.abs(e-l),l=e;return f},Hz:function(a,b,c,d,e){var f=(c-b)/2,g=a*Math.cos(f),h=a*Math.sin(f),k=-h,l=g*g+k*k,m=l+g*g+k*h;l=4/3*(Math.sqrt(2*l*m)-m)/(g*h-k*g);h=g-l*k;g=k+l*g;k=-g;l=f+b;f=Math.cos(l);l=Math.sin(l);return[d+a*Math.cos(b),e+a*Math.sin(b),d+ h*f-g*l,e+h*l+g*f,d+h*f-k*l,e+h*l+k*f,d+a*Math.cos(c),e+a*Math.sin(c)]},Dq:function(a,b,c,d,e,f,g){c=Math.floor((a-c)/e)*e+c;d=Math.floor((b-d)/f)*f+d;var h=c;c+e-a<e/2&&(h=c+e);a=d;d+f-b<f/2&&(a=d+f);g.h(h,a);return g},uy:function(a,b){var c=Math.max(a,b);a=Math.min(a,b);var d;do b=c%a,c=d=a,a=b;while(0<b);return d},Mz:function(a,b,c,d){var e=0>c,f=0>d;if(a<b){var g=1;var h=0}else g=0,h=1;var k=0===g?a:b;var l=0===g?c:d;if(0===g?e:f)l=-l;g=h;c=0===g?c:d;if(0===g?e:f)c=-c;return L.Nz(k,0===g?a:b, l,c,0,0)},Nz:function(a,b,c,d,e,f){if(0<d)if(0<c){e=a*a;f=b*b;a*=c;var g=b*d,h=-f+g,k=-f+Math.sqrt(a*a+g*g);b=h;for(var l=0;9999999999>l;++l){b=.5*(h+k);if(b===h||b===k)break;var m=a/(b+e),n=g/(b+f);m=m*m+n*n-1;if(0<m)h=b;else if(0>m)k=b;else break}c=e*c/(b+e)-c;d=f*d/(b+f)-d;c=Math.sqrt(c*c+d*d)}else c=Math.abs(d-b);else d=a*a-b*b,f=a*c,f<d?(d=f/d,f=b*Math.sqrt(Math.abs(1-d*d)),c=a*d-c,c=Math.sqrt(c*c+f*f)):c=Math.abs(c-a);return c},Re:new cb,bn:new cb,Th:new cb,Uh:0};L.za=L.jB; function td(a){Za(this);this.u=!1;void 0===a&&(a=ud);this.pa=a;this.oc=this.hc=this.fd=this.ed=0;this.Jj=new E;this.Yr=this.Jj.Aa;this.Gr=(new N).freeze();this.qa=!0;this.jn=this.al=null;this.kn=NaN;this.qf=vc;this.rf=Gc;this.Dl=this.El=NaN;this.Uf=vd} td.prototype.copy=function(){var a=new td;a.pa=this.pa;a.ed=this.ed;a.fd=this.fd;a.hc=this.hc;a.oc=this.oc;for(var b=this.Jj.j,c=b.length,d=a.Jj,e=0;e<c;e++){var f=b[e].copy();d.add(f)}a.Yr=this.Yr;a.Gr.assign(this.Gr);a.qa=this.qa;a.al=this.al;a.jn=this.jn;a.kn=this.kn;a.qf=this.qf.G();a.rf=this.rf.G();a.El=this.El;a.Dl=this.Dl;a.Uf=this.Uf;return a};t=td.prototype;t.ca=function(){this.freeze();Object.freeze(this);return this}; t.freeze=function(){this.u=!0;var a=this.figures;a.freeze();a=a.j;for(var b=a.length,c=0;c<b;c++)a[c].freeze();return this};t.ea=function(){Object.isFrozen(this)&&B("cannot thaw constant: "+this);this.u=!1;var a=this.figures;a.ea();a=a.j;for(var b=a.length,c=0;c<b;c++)a[c].ea();return this}; t.Na=function(a){if(!(a instanceof td))return!1;if(this.type!==a.type)return this.type===wd&&a.type===ud?xd(this,a):a.type===wd&&this.type===ud?xd(a,this):!1;if(this.type===ud){var b=this.figures.j;a=a.figures.j;var c=b.length;if(c!==a.length)return!1;for(var d=0;d<c;d++)if(!b[d].Na(a[d]))return!1;return!0}return L.A(this.startX,a.startX)&&L.A(this.startY,a.startY)&&L.A(this.endX,a.endX)&&L.A(this.endY,a.endY)}; function xd(a,b){return a.type!==wd||b.type!==ud?!1:1===b.figures.count&&(b=b.figures.J(0),1===b.segments.count&&L.A(a.startX,b.startX)&&L.A(a.startY,b.startY)&&(b=b.segments.J(0),b.type===yd&&L.A(a.endX,b.endX)&&L.A(a.endY,b.endY)))?!0:!1}function zd(a){return a.toString()}t.jb=function(a){a.classType===td&&(this.type=a)}; t.toString=function(a){void 0===a&&(a=-1);switch(this.type){case wd:return 0>a?"M"+this.startX.toString()+" "+this.startY.toString()+"L"+this.endX.toString()+" "+this.endY.toString():"M"+this.startX.toFixed(a)+" "+this.startY.toFixed(a)+"L"+this.endX.toFixed(a)+" "+this.endY.toFixed(a);case Dd:var b=new N(this.startX,this.startY,0,0);b.Sw(this.endX,this.endY,0,0);return 0>a?"M"+b.x.toString()+" "+b.y.toString()+"H"+b.right.toString()+"V"+b.bottom.toString()+"H"+b.left.toString()+"z":"M"+b.x.toFixed(a)+ " "+b.y.toFixed(a)+"H"+b.right.toFixed(a)+"V"+b.bottom.toFixed(a)+"H"+b.left.toFixed(a)+"z";case Ed:b=new N(this.startX,this.startY,0,0);b.Sw(this.endX,this.endY,0,0);if(0>a)return a=b.left.toString()+" "+(b.y+b.height/2).toString(),"M"+a+"A"+(b.width/2).toString()+" "+(b.height/2).toString()+" 0 0 1 "+(b.right.toString()+" "+(b.y+b.height/2).toString())+"A"+(b.width/2).toString()+" "+(b.height/2).toString()+" 0 0 1 "+a;var c=b.left.toFixed(a)+" "+(b.y+b.height/2).toFixed(a);return"M"+c+"A"+(b.width/ 2).toFixed(a)+" "+(b.height/2).toFixed(a)+" 0 0 1 "+(b.right.toFixed(a)+" "+(b.y+b.height/2).toFixed(a))+"A"+(b.width/2).toFixed(a)+" "+(b.height/2).toFixed(a)+" 0 0 1 "+c;case ud:b="";c=this.figures.j;for(var d=c.length,e=0;e<d;e++){var f=c[e];0<e&&(b+=" x ");f.isFilled&&(b+="F ");b+=f.toString(a)}return b;default:return this.type.toString()}}; function Fd(a,b){function c(){return u>=A-1?!0:null!==n[u+1].match(C)}function d(){u++;return n[u]}function e(a){var b=parseFloat(d()),c=parseFloat(d());v===v.toLowerCase()&&(b=z.x+b,c=z.y+c);a.h(b,c)}function f(){e(z);return z}function g(){e(y);return y}function h(){var a=w.toLowerCase();return"c"!==a&&"s"!==a&&"q"!==a&&"t"!==a?z:new I(2*z.x-y.x,2*z.y-y.y)}void 0===b&&(b=!1);var k=new RegExp("(["+Gd+"])(["+Gd+"])","gm"),l=new RegExp("(["+Gd+"])([^s])","gm"),m=new RegExp("([^s])(["+Gd+"])","gm"); a=a.replace(/,/gm," ");a=a.replace(k,"$1 $2");a=a.replace(k,"$1 $2");a=a.replace(l,"$1 $2");a=a.replace(m,"$1 $2");a=a.replace(/([0-9])([+\-])/gm,"$1 $2");a=a.replace(/[\s\r\t\n]+/gm," ");a=a.replace(/^\s+|\s+$/g,"");var n=a.split(" ");for(a=0;a<n.length;a++)if(l=n[a],null!==l.match(/(\.[0-9]*)(\.)/gm)){k=Ea();m="";for(var p=!1,r=0;r<l.length;r++){var q=l[r];"."!==q||p?"."===q?(k.push(m),m="."):m+=q:(p=!0,m+=q)}k.push(m);n.splice(a,1);for(l=0;l<k.length;l++)n.splice(a+l,0,k[l]);a+=k.length-1;Ia(k)}var u= -1,v="",w="";k=new I(0,0);var y=new I(0,0),z=new I(0,0),A=n.length;a=Hd(null);m=l=!1;p=!0;r=null;for(var C=new RegExp("["+Gd+"]");!(u>=A-1);)if(w=v,v=d(),""!==v)switch(v.toUpperCase()){case "X":p=!0;m=l=!1;break;case "M":r=f();null===a.ic||!0===p?(Id(a,r.x,r.y,l,!m),p=!1):a.moveTo(r.x,r.y);for(k.assign(z);!c();)r=f(),a.lineTo(r.x,r.y);break;case "L":for(;!c();)r=f(),a.lineTo(r.x,r.y);break;case "H":for(;!c();)z=new I((v===v.toLowerCase()?z.x:0)+parseFloat(d()),z.y),a.lineTo(z.x,z.y);break;case "V":for(;!c();)z= new I(z.x,(v===v.toLowerCase()?z.y:0)+parseFloat(d())),a.lineTo(z.x,z.y);break;case "C":for(;!c();){r=new I;e(r);q=g();var F=f();Ud(a,r.x,r.y,q.x,q.y,F.x,F.y)}break;case "S":for(;!c();)r=h(),q=g(),F=f(),Ud(a,r.x,r.y,q.x,q.y,F.x,F.y);break;case "Q":for(;!c();)r=g(),q=f(),Vd(a,r.x,r.y,q.x,q.y);break;case "T":for(;!c();)y=r=h(),q=f(),Vd(a,r.x,r.y,q.x,q.y);break;case "B":for(;!c();){r=parseFloat(d());q=parseFloat(d());F=parseFloat(d());var Q=parseFloat(d()),K=parseFloat(d()),T=K,P=!1;c()||(T=parseFloat(d()), c()||(P=0!==parseFloat(d())));v===v.toLowerCase()&&(F+=z.x,Q+=z.y);a.arcTo(r,q,F,Q,K,T,P)}break;case "A":for(;!c();)r=Math.abs(parseFloat(d())),q=Math.abs(parseFloat(d())),F=parseFloat(d()),K=Q=!1,P=T=0,T=d(),1===T.length?(Q=!!parseFloat(T),K=!!parseFloat(d()),T=parseFloat(d())):2===T.length?(Q=!!parseFloat(T[0]),K=!!parseFloat(T[1]),T=parseFloat(d())):(Q=!!parseFloat(T[0]),K=!!parseFloat(T[1]),T=parseFloat(T.slice(2))),P=parseFloat(d()),v===v.toLowerCase()&&(T=z.x+T,P=z.y+P),z.h(T,P),Wd(a,r,q,F, Q,K,T,P);break;case "Z":Xd(a);z.assign(k);break;case "F":r="";for(q=1;n[u+q];)if(null!==n[u+q].match(/[Uu]/))q++;else if(null===n[u+q].match(C))q++;else{r=n[u+q];break}r.match(/[Mm]/)?l=!0:0<a.ic.segments.length&&(a.ic.isFilled=!0);break;case "U":r="";for(q=1;n[u+q];)if(null!==n[u+q].match(/[Ff]/))q++;else if(null===n[u+q].match(C))q++;else{r=n[u+q];break}r.match(/[Mm]/)?m=!0:a.fr(!1)}k=a.Lt;Yd=a;if(b)for(b=k.figures.iterator;b.next();)b.value.isFilled=!0;return k} function Zd(a,b){for(var c=a.length,d=I.alloc(),e=0;e<c;e++){var f=a[e];d.x=f[0];d.y=f[1];b.sa(d);f[0]=d.x;f[1]=d.y;d.x=f[2];d.y=f[3];b.sa(d);f[2]=d.x;f[3]=d.y;d.x=f[4];d.y=f[5];b.sa(d);f[4]=d.x;f[5]=d.y;d.x=f[6];d.y=f[7];b.sa(d);f[6]=d.x;f[7]=d.y}I.free(d)}t.fw=function(){if(this.qa||this.Yr!==this.figures.Aa)return!0;for(var a=this.figures.j,b=a.length,c=0;c<b;c++)if(a[c].fw())return!0;return!1}; td.prototype.computeBounds=function(){this.qa=!1;this.jn=this.al=null;this.kn=NaN;this.Yr=this.figures.Aa;for(var a=this.figures.j,b=a.length,c=0;c<b;c++){var d=a[c];d.qa=!1;var e=d.segments;d.dt=e.Aa;d=e.j;e=d.length;for(var f=0;f<e;f++){var g=d[f];g.qa=!1;g.Qd=null}}a=this.Gr;a.ea();isNaN(this.El)||isNaN(this.Dl)?a.h(0,0,0,0):a.h(0,0,this.El,this.Dl);$d(this,a,!1);gc(a,0,0,0,0);a.freeze()};td.prototype.gy=function(){var a=new N;$d(this,a,!0);return a}; function $d(a,b,c){switch(a.type){case wd:case Dd:case Ed:c?b.h(a.ed,a.fd,0,0):gc(b,a.ed,a.fd,0,0);gc(b,a.hc,a.oc,0,0);break;case ud:var d=a.figures;a=d.j;d=d.length;for(var e=0;e<d;e++){var f=a[e];c&&0===e?b.h(f.startX,f.startY,0,0):gc(b,f.startX,f.startY,0,0);for(var g=f.segments.j,h=g.length,k=f.startX,l=f.startY,m=0;m<h;m++){var n=g[m];switch(n.type){case yd:case ae:k=n.endX;l=n.endY;gc(b,k,l,0,0);break;case be:L.um(k,l,n.point1X,n.point1Y,n.point2X,n.point2Y,n.endX,n.endY,.5,b);k=n.endX;l=n.endY; break;case ce:L.ow(k,l,n.point1X,n.point1Y,n.endX,n.endY,.5,b);k=n.endX;l=n.endY;break;case de:case ee:var p=n.type===de?fe(n,f):ge(n,f,k,l),r=p.length;if(0===r){k=n.type===de?n.centerX:n.endX;l=n.type===de?n.centerY:n.endY;gc(b,k,l,0,0);break}n=null;for(var q=0;q<r;q++)n=p[q],L.um(n[0],n[1],n[2],n[3],n[4],n[5],n[6],n[7],.5,b);null!==n&&(k=n[6],l=n[7]);break;default:B("Unknown Segment type: "+n.type)}}}break;default:B("Unknown Geometry type: "+a.type)}} td.prototype.normalize=function(){this.u&&va(this);var a=this.gy();this.offset(-a.x,-a.y);return new I(-a.x,-a.y)};td.prototype.offset=function(a,b){this.u&&va(this);this.transform(1,0,0,1,a,b);return this};td.prototype.scale=function(a,b){this.u&&va(this);this.transform(a,0,0,b,0,0);return this};td.prototype.rotate=function(a,b,c){this.u&&va(this);void 0===b&&(b=0);void 0===c&&(c=0);var d=rd.alloc();d.reset();d.rotate(a,b,c);this.transform(d.m11,d.m12,d.m21,d.m22,d.dx,d.dy);rd.free(d);return this}; t=td.prototype; t.transform=function(a,b,c,d,e,f){switch(this.type){case wd:case Dd:case Ed:var g=this.ed;var h=this.fd;this.ed=g*a+h*c+e;this.fd=g*b+h*d+f;g=this.hc;h=this.oc;this.hc=g*a+h*c+e;this.oc=g*b+h*d+f;break;case ud:for(var k=this.figures.j,l=k.length,m=0;m<l;m++){var n=k[m];g=n.startX;h=n.startY;n.startX=g*a+h*c+e;n.startY=g*b+h*d+f;n=n.segments.j;for(var p=n.length,r=0;r<p;r++){var q=n[r];switch(q.type){case yd:case ae:g=q.endX;h=q.endY;q.endX=g*a+h*c+e;q.endY=g*b+h*d+f;break;case be:g=q.point1X;h=q.point1Y; q.point1X=g*a+h*c+e;q.point1Y=g*b+h*d+f;g=q.point2X;h=q.point2Y;q.point2X=g*a+h*c+e;q.point2Y=g*b+h*d+f;g=q.endX;h=q.endY;q.endX=g*a+h*c+e;q.endY=g*b+h*d+f;break;case ce:g=q.point1X;h=q.point1Y;q.point1X=g*a+h*c+e;q.point1Y=g*b+h*d+f;g=q.endX;h=q.endY;q.endX=g*a+h*c+e;q.endY=g*b+h*d+f;break;case de:g=q.centerX;h=q.centerY;q.centerX=g*a+h*c+e;q.centerY=g*b+h*d+f;0!==b&&(g=180*Math.atan2(b,a)/Math.PI,0>g&&(g+=360),q.startAngle+=g);0>a&&(q.startAngle=180-q.startAngle,q.sweepAngle=-q.sweepAngle);0>d&& (q.startAngle=-q.startAngle,q.sweepAngle=-q.sweepAngle);q.radiusX*=Math.sqrt(a*a+c*c);void 0!==q.radiusY&&(q.radiusY*=Math.sqrt(b*b+d*d));break;case ee:g=q.endX;h=q.endY;q.endX=g*a+h*c+e;q.endY=g*b+h*d+f;if(0===q.radiusX||0===q.radiusY)break;0!==b&&(g=180*Math.atan2(b,a)/Math.PI,0>g&&(g+=360),q.xAxisRotation+=g);0>a&&(q.xAxisRotation=180-q.xAxisRotation,q.isClockwiseArc=!q.isClockwiseArc);0>d&&(q.xAxisRotation=-q.xAxisRotation,q.isClockwiseArc=!q.isClockwiseArc);q.radiusX*=Math.sqrt(a*a+c*c);q.radiusY*= Math.sqrt(b*b+d*d);break;default:B("Unknown Segment type: "+q.type)}}}}this.qa=!0;return this}; t.$=function(a,b){void 0===b&&(b=0);var c=this.ed,d=this.fd,e=this.hc,f=this.oc;switch(this.type){case wd:return L.Ob(c,d,e,f,b,a.x,a.y);case Dd:var g=N.allocAt(Math.min(c,e)-b,Math.min(d,f)-b,Math.abs(e-c)+2*b,Math.abs(f-d)+2*b);a=g.$(a);N.free(g);return a;case Ed:g=Math.min(c,e)-b;var h=Math.min(d,f)-b;c=(Math.abs(e-c)+2*b)/2;b=(Math.abs(f-d)+2*b)/2;if(0>=c||0>=b)return!1;g=a.x-(g+c);h=a.y-(h+b);return 1>=g*g/(c*c)+h*h/(b*b);case ud:return he(this,a,b,!0,!1);default:return!1}}; function he(a,b,c,d,e){var f=b.x;b=b.y;for(var g=a.bounds.x-20,h=0,k,l,m,n,p=a.figures.j,r=p.length,q=0;q<r;q++){var u=p[q];if(u.isFilled){if(d&&u.$(f,b,c))return!0;var v=u.segments;k=u.startX;l=u.startY;for(var w=k,y=l,z=v.j,A=0;A<=v.length;A++){var C=void 0;if(A!==v.length){C=z[A];var F=C.type;a=C.endX;n=C.endY}else F=yd,a=w,n=y;switch(F){case ae:w=ie(f,b,g,b,k,l,w,y);if(isNaN(w))return!0;h+=w;w=a;y=n;break;case yd:k=ie(f,b,g,b,k,l,a,n);if(isNaN(k))return!0;h+=k;break;case be:m=L.uq(k,l,C.point1X, C.point1Y,C.point2X,C.point2Y,a,n,g,b,f,b,.5);h+=m;break;case ce:m=L.uq(k,l,(k+2*C.point1X)/3,(l+2*C.point1Y)/3,(2*C.point1X+a)/3,(2*C.point1Y+n)/3,a,n,g,b,f,b,.5);h+=m;break;case de:case ee:F=C.type===de?fe(C,u):ge(C,u,k,l);var Q=F.length;if(0===Q){k=ie(f,b,g,b,k,l,C.type===de?C.centerX:C.endX,C.type===de?C.centerY:C.endY);if(isNaN(k))return!0;h+=k;break}C=null;for(var K=0;K<Q;K++){C=F[K];if(0===K){m=ie(f,b,g,b,k,l,C[0],C[1]);if(isNaN(m))return!0;h+=m}m=L.uq(C[0],C[1],C[2],C[3],C[4],C[5],C[6],C[7], g,b,f,b,.5);h+=m}null!==C&&(a=C[6],n=C[7]);break;default:B("Unknown Segment type: "+C.type)}k=a;l=n}if(0!==h)return!0;h=0}else if(u.$(f,b,e?c:c+2))return!0}return 0!==h} function ie(a,b,c,d,e,f,g,h){if(L.Ob(e,f,g,h,.05,a,b))return NaN;var k=(a-c)*(f-h);if(0===k)return 0;var l=((a*d-b*c)*(e-g)-(a-c)*(e*h-f*g))/k;b=(a*d-b*c)*(f-h)/k;if(l>=a)return 0;if((e>g?e-g:g-e)<(f>h?f-h:h-f))if(f<h){if(b<f||b>h)return 0}else{if(b<h||b>f)return 0}else if(e<g){if(l<e||l>g)return 0}else if(l<g||l>e)return 0;return 0<k?1:-1}function je(a,b,c,d){a=a.figures.j;for(var e=a.length,f=0;f<e;f++)if(a[f].$(b,c,d))return!0;return!1} t.Wv=function(a,b){0>a?a=0:1<a&&(a=1);void 0===b&&(b=new I);if(this.type===wd)return b.h(this.startX+a*(this.endX-this.startX),this.startY+a*(this.endY-this.startY)),b;for(var c=this.flattenedSegments,d=this.flattenedLengths,e=c.length,f=this.flattenedTotalLength*a,g=0,h=0;h<e;h++){var k=d[h],l=k.length;for(a=0;a<l;a++){var m=k[a];if(g+m>=f)return d=f-g,d=0===m?0:d/m,c=c[h],h=c[2*a],e=c[2*a+1],b.h(h+(c[2*a+2]-h)*d,e+(c[2*a+3]-e)*d),b;g+=m}}return b}; t.vy=function(a){0>a?a=0:1<a&&(a=1);if(this.type===wd)return 180*Math.atan2(this.endY-this.startY,this.endX-this.startX)/Math.PI;for(var b=this.flattenedSegments,c=this.flattenedLengths,d=b.length,e=this.flattenedTotalLength*a,f=0,g=0;g<d;g++){var h=c[g],k=h.length;for(a=0;a<k;a++){var l=h[a];if(f+l>=e)return e=b[g],b=e[2*a],c=e[2*a+1],d=e[2*a+2],a=e[2*a+3],1>Math.abs(d-b)&&1>Math.abs(a-c)?0:1>Math.abs(d-b)?0<=a-c?90:270:1>Math.abs(a-c)?0<=d-b?0:180:180*Math.atan2(a-c,d-b)/Math.PI;f+=l}}return NaN}; t.Xv=function(a,b){0>a?a=0:1<a&&(a=1);void 0===b&&(b=[]);b.length=3;if(this.type===wd)return b[0]=this.startX+a*(this.endX-this.startX),b[1]=this.startY+a*(this.endY-this.startY),b[2]=180*Math.atan2(this.endY-this.startY,this.endX-this.startX)/Math.PI,b;for(var c=this.flattenedSegments,d=this.flattenedLengths,e=c.length,f=this.flattenedTotalLength*a,g=0,h=0;h<e;h++){var k=d[h],l=k.length;for(a=0;a<l;a++){var m=k[a];if(g+m>=f)return d=f-g,d=0===m?0:d/m,m=c[h],c=m[2*a],h=m[2*a+1],e=m[2*a+2],a=m[2*a+ 3],b[0]=c+(e-c)*d,b[1]=h+(a-h)*d,b[2]=1>Math.abs(e-c)&&1>Math.abs(a-h)?0:1>Math.abs(e-c)?0<=a-h?90:270:1>Math.abs(a-h)?0<=e-c?0:180:180*Math.atan2(a-h,e-c)/Math.PI,b;g+=m}}return b}; t.wy=function(a){if(this.type===wd){var b=this.startX,c=this.startY,d=this.endX,e=this.endY;if(b!==d||c!==e){var f=a.x;a=a.y;if(b===d){if(c<e){var g=c;d=e}else g=e,d=c;return a<=g?g===c?0:1:a>=d?d===c?0:1:Math.abs(a-c)/(d-g)}if(c===e)return b<d?g=b:(g=d,d=b),f<=g?g===b?0:1:f>=d?d===b?0:1:Math.abs(f-b)/(d-g);g=(d-b)*(d-b)+(e-c)*(e-c);var h=I.alloc();L.Ph(b,c,d,e,f,a,h);a=h.x;f=h.y;I.free(h);return Math.sqrt(((a-b)*(a-b)+(f-c)*(f-c))/g)}}else if(this.type===Dd){g=this.startX;h=this.startY;var k=this.endX; e=this.endY;if(g!==k||h!==e){b=k-g;c=e-h;f=2*b+2*c;d=a.x;a=a.y;d=Math.min(Math.max(d,g),k);a=Math.min(Math.max(a,h),e);g=Math.abs(d-g);k=Math.abs(d-k);h=Math.abs(a-h);e=Math.abs(a-e);var l=Math.min(g,k,h,e);if(l===h)return d/f;if(l===k)return(b+a)/f;if(l===e)return(2*b+c-d)/f;if(l===g)return(2*b+2*c-a)/f}}else{b=this.flattenedSegments;c=this.flattenedLengths;f=this.flattenedTotalLength;d=I.alloc();e=Infinity;h=g=0;k=b.length;for(var m=l=0,n=0;n<k;n++)for(var p=b[n],r=c[n],q=p.length,u=0;u<q;u+=2){var v= p[u],w=p[u+1];if(0!==u){L.Ph(l,m,v,w,a.x,a.y,d);var y=(d.x-a.x)*(d.x-a.x)+(d.y-a.y)*(d.y-a.y);y<e&&(e=y,g=h,g+=Math.sqrt((d.x-l)*(d.x-l)+(d.y-m)*(d.y-m)));h+=r[(u-2)/2]}l=v;m=w}I.free(d);a=g/f;return 0>a?0:1<a?1:a}return 0}; function ke(a){if(null===a.al){var b=a.al=[],c=a.jn=[],d=[],e=[];if(a.type===wd)d.push(a.startX),d.push(a.startY),d.push(a.endX),d.push(a.endY),b.push(d),e.push(Math.sqrt((a.startX-a.endX)*(a.startX-a.endX)+(a.startY-a.endY)*(a.startY-a.endY))),c.push(e);else if(a.type===Dd)d.push(a.startX),d.push(a.startY),d.push(a.endX),d.push(a.startY),d.push(a.endX),d.push(a.endY),d.push(a.startX),d.push(a.endY),d.push(a.startX),d.push(a.startY),b.push(d),e.push(Math.abs(a.startX-a.endX)),e.push(Math.abs(a.startY- a.endY)),e.push(Math.abs(a.startX-a.endX)),e.push(Math.abs(a.startY-a.endY)),c.push(e);else if(a.type===Ed){var f=new se;f.startX=a.endX;f.startY=(a.startY+a.endY)/2;var g=new te(de);g.startAngle=0;g.sweepAngle=360;g.centerX=(a.startX+a.endX)/2;g.centerY=(a.startY+a.endY)/2;g.radiusX=Math.abs(a.startX-a.endX)/2;g.radiusY=Math.abs(a.startY-a.endY)/2;f.add(g);a=fe(g,f);e=a.length;if(0===e)d.push(g.centerX),d.push(g.centerY);else{g=f.startX;f=f.startY;for(var h=0;h<e;h++){var k=a[h];L.Ge(g,f,k[2],k[3], k[4],k[5],k[6],k[7],.5,d);g=k[6];f=k[7]}}b.push(d);c.push(ue(d))}else for(a=a.figures.iterator;a.next();){e=a.value;d=[];d.push(e.startX);d.push(e.startY);g=e.startX;f=e.startY;h=g;k=f;for(var l=e.segments.j,m=l.length,n=0;n<m;n++){var p=l[n];switch(p.type){case ae:4<=d.length&&(b.push(d),c.push(ue(d)));d=[];d.push(p.endX);d.push(p.endY);g=p.endX;f=p.endY;h=g;k=f;break;case yd:d.push(p.endX);d.push(p.endY);g=p.endX;f=p.endY;break;case be:L.Ge(g,f,p.point1X,p.point1Y,p.point2X,p.point2Y,p.endX,p.endY, .5,d);g=p.endX;f=p.endY;break;case ce:L.Vq(g,f,p.point1X,p.point1Y,p.endX,p.endY,.5,d);g=p.endX;f=p.endY;break;case de:var r=fe(p,e),q=r.length;if(0===q){d.push(p.centerX);d.push(p.centerY);g=p.centerX;f=p.centerY;break}for(var u=0;u<q;u++){var v=r[u];L.Ge(g,f,v[2],v[3],v[4],v[5],v[6],v[7],.5,d);g=v[6];f=v[7]}break;case ee:r=ge(p,e,g,f);q=r.length;u=p.endX;v=p.endY;if(0===q){d.push(u);d.push(v);g=u;f=v;break}for(u=0;u<q;u++)v=r[u],L.Ge(g,f,v[2],v[3],v[4],v[5],v[6],v[7],.5,d),g=v[6],f=v[7];break;default:B("Segment not of valid type: "+ p.type)}p.isClosed&&(d.push(h),d.push(k))}4<=d.length&&(b.push(d),c.push(ue(d)))}}}function ue(a){for(var b=[],c=0,d=0,e=a.length,f=0;f<e;f+=2){var g=a[f],h=a[f+1];0!==f&&b.push(Math.sqrt(Ab(c,d,g,h)));c=g;d=h}return b}t.add=function(a){this.Jj.add(a);return this};t.Xm=function(a,b,c,d,e,f,g,h){this.u&&va(this);this.qf=(new O(a,b,e,f)).freeze();this.rf=(new O(c,d,g,h)).freeze();return this}; na.Object.defineProperties(td.prototype,{flattenedSegments:{get:function(){ke(this);return this.al}},flattenedLengths:{get:function(){ke(this);return this.jn}},flattenedTotalLength:{get:function(){var a=this.kn;if(isNaN(a)){if(this.type===wd){a=Math.abs(this.endX-this.startX);var b=Math.abs(this.endY-this.startY);a=Math.sqrt(a*a+b*b)}else if(this.type===Dd)a=2*Math.abs(this.endX-this.startX)+2*Math.abs(this.endY- this.startY);else{b=this.flattenedLengths;for(var c=b.length,d=a=0;d<c;d++)for(var e=b[d],f=e.length,g=0;g<f;g++)a+=e[g]}this.kn=a}return a}},type:{get:function(){return this.pa},set:function(a){this.pa!==a&&(this.u&&va(this,a),this.pa=a,this.qa=!0)}},startX:{get:function(){return this.ed},set:function(a){this.ed!==a&&(this.u&&va(this,a),this.ed=a,this.qa=!0)}},startY:{get:function(){return this.fd},set:function(a){this.fd!== a&&(this.u&&va(this,a),this.fd=a,this.qa=!0)}},endX:{get:function(){return this.hc},set:function(a){this.hc!==a&&(this.u&&va(this,a),this.hc=a,this.qa=!0)}},endY:{get:function(){return this.oc},set:function(a){this.oc!==a&&(this.u&&va(this,a),this.oc=a,this.qa=!0)}},figures:{get:function(){return this.Jj},set:function(a){this.Jj!==a&&(this.u&&va(this,a),this.Jj=a,this.qa=!0)}},spot1:{ get:function(){return this.qf},set:function(a){this.u&&va(this,a);this.qf=a.G()}},spot2:{get:function(){return this.rf},set:function(a){this.u&&va(this,a);this.rf=a.G()}},defaultStretch:{get:function(){return this.Uf},set:function(a){this.u&&va(this,a);this.Uf=a}},bounds:{get:function(){this.fw()&&this.computeBounds();return this.Gr}}});td.prototype.setSpots=td.prototype.Xm;td.prototype.add=td.prototype.add; td.prototype.getFractionForPoint=td.prototype.wy;td.prototype.getPointAndAngleAlongPath=td.prototype.Xv;td.prototype.getAngleAlongPath=td.prototype.vy;td.prototype.getPointAlongPath=td.prototype.Wv;td.prototype.containsPoint=td.prototype.$;td.prototype.transform=td.prototype.transform;td.prototype.rotate=td.prototype.rotate;td.prototype.scale=td.prototype.scale;td.prototype.offset=td.prototype.offset;td.prototype.normalize=td.prototype.normalize;td.prototype.computeBoundsWithoutOrigin=td.prototype.gy; td.prototype.equalsApprox=td.prototype.Na;var wd=new D(td,"Line",0),Dd=new D(td,"Rectangle",1),Ed=new D(td,"Ellipse",2),ud=new D(td,"Path",3),Gd="UuBbMmZzLlHhVvCcSsQqTtAaFfXx";td.className="Geometry";td.stringify=zd;td.fillPath=function(a){a=a.split(/[Xx]/);for(var b=a.length,c="",d=0;d<b;d++){var e=a[d];c=null!==e.match(/[Ff]/)?0===d?c+e:c+("X"+(" "===e[0]?"":" ")+e):c+((0===d?"":"X ")+"F"+(" "===e[0]?"":" ")+e)}return c};td.parse=Fd;td.Line=wd;td.Rectangle=Dd;td.Ellipse=Ed;td.Path=ud; function se(a,b,c,d){Za(this);this.tx=null;this.u=!1;void 0===c&&(c=!0);this.ks=c;void 0===d&&(d=!0);this.ps=d;void 0!==a?this.ed=a:this.ed=0;void 0!==b?this.fd=b:this.fd=0;this.cm=new E;this.dt=this.cm.Aa;this.qa=!0}se.prototype.copy=function(){var a=new se;a.ks=this.ks;a.ps=this.ps;a.ed=this.ed;a.fd=this.fd;for(var b=this.cm.j,c=b.length,d=a.cm,e=0;e<c;e++){var f=b[e].copy();d.add(f)}a.dt=this.dt;a.qa=this.qa;a.tx=this.tx;return a};t=se.prototype; t.Na=function(a){if(!(a instanceof se&&L.A(this.startX,a.startX)&&L.A(this.startY,a.startY)))return!1;var b=this.segments.j;a=a.segments.j;var c=b.length;if(c!==a.length)return!1;for(var d=0;d<c;d++)if(!b[d].Na(a[d]))return!1;return!0};t.toString=function(a){void 0===a&&(a=-1);var b=0>a?"M"+this.startX.toString()+" "+this.startY.toString():"M"+this.startX.toFixed(a)+" "+this.startY.toFixed(a);for(var c=this.segments.j,d=c.length,e=0;e<d;e++)b+=" "+c[e].toString(a);return b}; t.freeze=function(){this.u=!0;var a=this.segments;a.freeze();var b=a.j;a=a.length;for(var c=0;c<a;c++)b[c].freeze();return this};t.ea=function(){this.u=!1;var a=this.segments;a.ea();a=a.j;for(var b=a.length,c=0;c<b;c++)a[c].ea();return this};t.fw=function(){if(this.qa)return!0;var a=this.segments;if(this.dt!==a.Aa)return!0;a=a.j;for(var b=a.length,c=0;c<b;c++)if(a[c].qa)return!0;return!1};t.add=function(a){this.cm.add(a);return this}; t.$=function(a,b,c){for(var d=this.startX,e=this.startY,f=d,g=e,h=this.segments.j,k=h.length,l=0;l<k;l++){var m=h[l];switch(m.type){case ae:f=m.endX;g=m.endY;d=m.endX;e=m.endY;break;case yd:if(L.Ob(d,e,m.endX,m.endY,c,a,b))return!0;d=m.endX;e=m.endY;break;case be:if(L.yt(d,e,m.point1X,m.point1Y,m.point2X,m.point2Y,m.endX,m.endY,.5,a,b,c))return!0;d=m.endX;e=m.endY;break;case ce:if(L.pw(d,e,m.point1X,m.point1Y,m.endX,m.endY,.5,a,b,c))return!0;d=m.endX;e=m.endY;break;case de:case ee:var n=m.type=== de?fe(m,this):ge(m,this,d,e),p=n.length,r=m.type===de?m.centerX:m.endX,q=m.type===de?m.centerY:m.endY;if(0===p){if(L.Ob(d,e,r,q,c,a,b))return!0;d=r;e=q;break}r=null;for(q=0;q<p;q++)if(r=n[q],0===q&&L.Ob(d,e,r[0],r[1],c,a,b)||L.yt(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],.5,a,b,c))return!0;null!==r&&(d=r[6],e=r[7]);break;default:B("Unknown Segment type: "+m.type)}if(m.isClosed&&(d!==f||e!==g)&&L.Ob(d,e,f,g,c,a,b))return!0}return!1}; na.Object.defineProperties(se.prototype,{isFilled:{get:function(){return this.ks},set:function(a){this.u&&va(this,a);this.ks=a}},isShadowed:{get:function(){return this.ps},set:function(a){this.u&&va(this,a);this.ps=a}},startX:{get:function(){return this.ed},set:function(a){this.u&&va(this,a);this.ed=a;this.qa=!0}},startY:{get:function(){return this.fd},set:function(a){this.u&&va(this, a);this.fd=a;this.qa=!0}},segments:{get:function(){return this.cm},set:function(a){this.u&&va(this,a);this.cm=a;this.qa=!0}}});se.prototype.add=se.prototype.add;se.prototype.equalsApprox=se.prototype.Na;se.className="PathFigure"; function te(a,b,c,d,e,f,g,h){Za(this);this.u=!1;void 0===a&&(a=yd);this.pa=a;void 0!==b?this.hc=b:this.hc=0;void 0!==c?this.oc=c:this.oc=0;void 0===d&&(d=0);void 0===e&&(e=0);void 0===f&&(f=0);void 0===g&&(g=0);a===ee?(a=f%360,0>a&&(a+=360),this.De=a,this.Qi=0,this.Ri=Math.max(d,0),this.qh=Math.max(e,0),this.Ml="boolean"===typeof g?g:"number"===typeof g?!!g:!1,this.el=!!h):(this.De=d,this.Qi=e,a===de&&(f=Math.max(f,0)),this.Ri=f,"number"===typeof g?(a===de&&(g=Math.max(g,0)),this.qh=g):this.qh=0, this.el=this.Ml=!1);this.Oj=!1;this.qa=!0;this.Qd=null}te.prototype.copy=function(){var a=new te;a.pa=this.pa;a.hc=this.hc;a.oc=this.oc;a.De=this.De;a.Qi=this.Qi;a.Ri=this.Ri;a.qh=this.qh;a.Ml=this.Ml;a.el=this.el;a.Oj=this.Oj;a.qa=this.qa;return a};t=te.prototype; t.Na=function(a){if(!(a instanceof te)||this.type!==a.type||this.isClosed!==a.isClosed)return!1;switch(this.type){case ae:case yd:return L.A(this.endX,a.endX)&&L.A(this.endY,a.endY);case be:return L.A(this.endX,a.endX)&&L.A(this.endY,a.endY)&&L.A(this.point1X,a.point1X)&&L.A(this.point1Y,a.point1Y)&&L.A(this.point2X,a.point2X)&&L.A(this.point2Y,a.point2Y);case ce:return L.A(this.endX,a.endX)&&L.A(this.endY,a.endY)&&L.A(this.point1X,a.point1X)&&L.A(this.point1Y,a.point1Y);case de:return L.A(this.startAngle, a.startAngle)&&L.A(this.sweepAngle,a.sweepAngle)&&L.A(this.centerX,a.centerX)&&L.A(this.centerY,a.centerY)&&L.A(this.radiusX,a.radiusX)&&L.A(this.radiusY,a.radiusY);case ee:return this.isClockwiseArc===a.isClockwiseArc&&this.isLargeArc===a.isLargeArc&&L.A(this.xAxisRotation,a.xAxisRotation)&&L.A(this.endX,a.endX)&&L.A(this.endY,a.endY)&&L.A(this.radiusX,a.radiusX)&&L.A(this.radiusY,a.radiusY);default:return!1}};t.jb=function(a){a.classType===te&&(this.type=a)}; t.toString=function(a){void 0===a&&(a=-1);switch(this.type){case ae:a=0>a?"M"+this.endX.toString()+" "+this.endY.toString():"M"+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case yd:a=0>a?"L"+this.endX.toString()+" "+this.endY.toString():"L"+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case be:a=0>a?"C"+this.point1X.toString()+" "+this.point1Y.toString()+" "+this.point2X.toString()+" "+this.point2Y.toString()+" "+this.endX.toString()+" "+this.endY.toString():"C"+this.point1X.toFixed(a)+ " "+this.point1Y.toFixed(a)+" "+this.point2X.toFixed(a)+" "+this.point2Y.toFixed(a)+" "+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case ce:a=0>a?"Q"+this.point1X.toString()+" "+this.point1Y.toString()+" "+this.endX.toString()+" "+this.endY.toString():"Q"+this.point1X.toFixed(a)+" "+this.point1Y.toFixed(a)+" "+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case de:a=0>a?"B"+this.startAngle.toString()+" "+this.sweepAngle.toString()+" "+this.centerX.toString()+" "+this.centerY.toString()+ " "+this.radiusX.toString()+" "+this.radiusY.toString():"B"+this.startAngle.toFixed(a)+" "+this.sweepAngle.toFixed(a)+" "+this.centerX.toFixed(a)+" "+this.centerY.toFixed(a)+" "+this.radiusX.toFixed(a)+" "+this.radiusY.toFixed(a);break;case ee:a=0>a?"A"+this.radiusX.toString()+" "+this.radiusY.toString()+" "+this.xAxisRotation.toString()+" "+(this.isLargeArc?1:0)+" "+(this.isClockwiseArc?1:0)+" "+this.endX.toString()+" "+this.endY.toString():"A"+this.radiusX.toFixed(a)+" "+this.radiusY.toFixed(a)+ " "+this.xAxisRotation.toFixed(a)+" "+(this.isLargeArc?1:0)+" "+(this.isClockwiseArc?1:0)+" "+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;default:a=this.type.toString()}return a+(this.Oj?"z":"")};t.freeze=function(){this.u=!0;return this};t.ea=function(){this.u=!1;return this};t.close=function(){this.Oj=!0;return this}; function fe(a,b){if(null!==a.Qd&&!1===b.qa)return a.Qd;var c=a.radiusX,d=a.radiusY;void 0===d&&(d=c);if(0===c||0===d)return a.Qd=[],a.Qd;b=a.De;var e=a.Qi,f=L.hy(0,0,c<d?c:d,a.startAngle,a.startAngle+a.sweepAngle,!1);if(c!==d){var g=rd.alloc();g.reset();c<d?g.scale(1,d/c):g.scale(c/d,1);Zd(f,g);rd.free(g)}c=f.length;for(d=0;d<c;d++)g=f[d],g[0]+=b,g[1]+=e,g[2]+=b,g[3]+=e,g[4]+=b,g[5]+=e,g[6]+=b,g[7]+=e;a.Qd=f;return a.Qd} function ge(a,b,c,d){function e(a,b,c,d){return(a*d<b*c?-1:1)*Math.acos((a*c+b*d)/(Math.sqrt(a*a+b*b)*Math.sqrt(c*c+d*d)))}if(null!==a.Qd&&!1===b.qa)return a.Qd;if(0===a.radiusX||0===a.radiusY)return a.Qd=[],a.Qd;b=a.Ri;var f=a.qh;0===b&&(b=1E-4);0===f&&(f=1E-4);var g=Math.PI/180*a.De,h=a.Ml,k=a.el,l=a.hc,m=a.oc,n=Math.cos(g),p=Math.sin(g),r=n*(c-l)/2+p*(d-m)/2;g=-p*(c-l)/2+n*(d-m)/2;var q=r*r/(b*b)+g*g/(f*f);1<q&&(b*=Math.sqrt(q),f*=Math.sqrt(q));q=(h===k?-1:1)*Math.sqrt((b*b*f*f-b*b*g*g-f*f*r*r)/ (b*b*g*g+f*f*r*r));isNaN(q)&&(q=0);h=q*b*g/f;q=q*-f*r/b;isNaN(h)&&(h=0);isNaN(q)&&(q=0);c=(c+l)/2+n*h-p*q;d=(d+m)/2+p*h+n*q;m=e(1,0,(r-h)/b,(g-q)/f);n=(r-h)/b;l=(g-q)/f;r=(-r-h)/b;h=(-g-q)/f;g=e(n,l,r,h);r=(n*r+l*h)/(Math.sqrt(n*n+l*l)*Math.sqrt(r*r+h*h));-1>=r?g=Math.PI:1<=r&&(g=0);!k&&0<g&&(g-=2*Math.PI);k&&0>g&&(g+=2*Math.PI);k=b>f?1:b/f;r=b>f?f/b:1;b=L.hy(0,0,b>f?b:f,m,m+g,!0);f=rd.alloc();f.reset();f.translate(c,d);f.rotate(a.De,0,0);f.scale(k,r);Zd(b,f);rd.free(f);a.Qd=b;return a.Qd} na.Object.defineProperties(te.prototype,{isClosed:{get:function(){return this.Oj},set:function(a){this.Oj!==a&&(this.Oj=a,this.qa=!0)}},type:{get:function(){return this.pa},set:function(a){this.u&&va(this,a);this.pa=a;this.qa=!0}},endX:{get:function(){return this.hc},set:function(a){this.u&&va(this,a);this.hc=a;this.qa=!0}},endY:{get:function(){return this.oc},set:function(a){this.u&& va(this,a);this.oc=a;this.qa=!0}},point1X:{get:function(){return this.De},set:function(a){this.u&&va(this,a);this.De=a;this.qa=!0}},point1Y:{get:function(){return this.Qi},set:function(a){this.u&&va(this,a);this.Qi=a;this.qa=!0}},point2X:{get:function(){return this.Ri},set:function(a){this.u&&va(this,a);this.Ri=a;this.qa=!0}},point2Y:{get:function(){return this.qh},set:function(a){this.u&& va(this,a);this.qh=a;this.qa=!0}},centerX:{get:function(){return this.De},set:function(a){this.u&&va(this,a);this.De=a;this.qa=!0}},centerY:{get:function(){return this.Qi},set:function(a){this.u&&va(this,a);this.Qi=a;this.qa=!0}},radiusX:{get:function(){return this.Ri},set:function(a){0>a&&wa(a,">= zero",te,"radiusX");this.u&&va(this,a);this.Ri=a;this.qa=!0}},radiusY:{get:function(){return this.qh}, set:function(a){0>a&&wa(a,">= zero",te,"radiusY");this.u&&va(this,a);this.qh=a;this.qa=!0}},startAngle:{get:function(){return this.hc},set:function(a){this.hc!==a&&(this.u&&va(this,a),a%=360,0>a&&(a+=360),this.hc=a,this.qa=!0)}},sweepAngle:{get:function(){return this.oc},set:function(a){this.u&&va(this,a);360<a&&(a=360);-360>a&&(a=-360);this.oc=a;this.qa=!0}},isClockwiseArc:{get:function(){return this.el},set:function(a){this.u&& va(this,a);this.el=a;this.qa=!0}},isLargeArc:{get:function(){return this.Ml},set:function(a){this.u&&va(this,a);this.Ml=a;this.qa=!0}},xAxisRotation:{get:function(){return this.De},set:function(a){a%=360;0>a&&(a+=360);this.u&&va(this,a);this.De=a;this.qa=!0}}});te.prototype.equalsApprox=te.prototype.Na; var ae=new D(te,"Move",0),yd=new D(te,"Line",1),be=new D(te,"Bezier",2),ce=new D(te,"QuadraticBezier",3),de=new D(te,"Arc",4),ee=new D(te,"SvgArc",4);te.className="PathSegment";te.Move=ae;te.Line=yd;te.Bezier=be;te.QuadraticBezier=ce;te.Arc=de;te.SvgArc=ee;function ve(){this.B=null;this.xv=(new I(0,0)).freeze();this.Hu=(new I(0,0)).freeze();this.yr=this.As=0;this.zr=1;this.Ci="";this.st=this.Sr=!1;this.Pr=this.Br=0;this.Qg=this.cs=this.ns=!1;this.Xr=null;this.nt=0;this.qd=this.mt=null} ve.prototype.copy=function(){var a=new ve;return this.clone(a)};ve.prototype.clone=function(a){a.B=this.B;a.xv.assign(this.viewPoint);a.Hu.assign(this.documentPoint);a.As=this.As;a.yr=this.yr;a.zr=this.zr;a.Ci=this.Ci;a.Sr=this.Sr;a.st=this.st;a.Br=this.Br;a.Pr=this.Pr;a.ns=this.ns;a.cs=this.cs;a.Qg=this.Qg;a.Xr=this.Xr;a.nt=this.nt;a.mt=this.mt;a.qd=this.qd;return a}; ve.prototype.toString=function(){var a="^";0!==this.modifiers&&(a+="M:"+this.modifiers);0!==this.button&&(a+="B:"+this.button);""!==this.key&&(a+="K:"+this.key);0!==this.clickCount&&(a+="C:"+this.clickCount);0!==this.delta&&(a+="D:"+this.delta);this.handled&&(a+="h");this.bubbles&&(a+="b");null!==this.documentPoint&&(a+="@"+this.documentPoint.toString());return a};ve.prototype.Gq=function(a,b){var c=this.diagram;if(null===c)return b;we(c,this.event,a,b);return b}; ve.prototype.mA=function(a,b){var c=this.diagram;if(null===c)return b;we(c,this.event,a,b);b.assign(c.nu(b));return b}; na.Object.defineProperties(ve.prototype,{diagram:{get:function(){return this.B},set:function(a){this.B=a}},viewPoint:{get:function(){return this.xv},set:function(a){this.xv.assign(a)}},documentPoint:{get:function(){return this.Hu},set:function(a){this.Hu.assign(a)}},modifiers:{get:function(){return this.As},set:function(a){this.As=a}},button:{get:function(){return this.yr}, set:function(a){this.yr=a;if(null===this.event)switch(a){case 0:this.buttons=1;break;case 1:this.buttons=4;break;case 2:this.buttons=2}}},buttons:{get:function(){return this.zr},set:function(a){this.zr=a}},key:{get:function(){return this.Ci},set:function(a){this.Ci=a}},down:{get:function(){return this.Sr},set:function(a){this.Sr=a}},up:{get:function(){return this.st},set:function(a){this.st= a}},clickCount:{get:function(){return this.Br},set:function(a){this.Br=a}},delta:{get:function(){return this.Pr},set:function(a){this.Pr=a}},isMultiTouch:{get:function(){return this.ns},set:function(a){this.ns=a}},handled:{get:function(){return this.cs},set:function(a){this.cs=a}},bubbles:{get:function(){return this.Qg},set:function(a){this.Qg=a}},event:{ get:function(){return this.Xr},set:function(a){this.Xr=a}},isTouchEvent:{get:function(){var a=x.TouchEvent,b=this.event;return a&&b instanceof a?!0:(a=x.PointerEvent)&&b instanceof a&&("touch"===b.pointerType||"pen"===b.pointerType)}},timestamp:{get:function(){return this.nt},set:function(a){this.nt=a}},targetDiagram:{get:function(){return this.mt},set:function(a){this.mt=a}},targetObject:{ get:function(){return this.qd},set:function(a){this.qd=a}},control:{get:function(){return 0!==(this.modifiers&1)},set:function(a){this.modifiers=a?this.modifiers|1:this.modifiers&-2}},shift:{get:function(){return 0!==(this.modifiers&4)},set:function(a){this.modifiers=a?this.modifiers|4:this.modifiers&-5}},alt:{get:function(){return 0!==(this.modifiers&2)},set:function(a){this.modifiers=a?this.modifiers| 2:this.modifiers&-3}},meta:{get:function(){return 0!==(this.modifiers&8)},set:function(a){this.modifiers=a?this.modifiers|8:this.modifiers&-9}},left:{get:function(){var a=this.event;return null===a||"mousedown"!==a.type&&"mouseup"!==a.type&&"pointerdown"!==a.type&&"pointerup"!==a.type?0!==(this.buttons&1):0===this.button},set:function(a){this.buttons=a?this.buttons|1:this.buttons&-2}},right:{get:function(){var a= this.event;return null===a||"mousedown"!==a.type&&"mouseup"!==a.type&&"pointerdown"!==a.type&&"pointerup"!==a.type?0!==(this.buttons&2):2===this.button},set:function(a){this.buttons=a?this.buttons|2:this.buttons&-3}},middle:{get:function(){var a=this.event;return null===a||"mousedown"!==a.type&&"mouseup"!==a.type&&"pointerdown"!==a.type&&"pointerup"!==a.type?0!==(this.buttons&4):1===this.button},set:function(a){this.buttons=a?this.buttons|4:this.buttons&-5}}}); ve.prototype.getMultiTouchDocumentPoint=ve.prototype.mA;ve.prototype.getMultiTouchViewPoint=ve.prototype.Gq;ve.className="InputEvent";function xe(){this.B=null;this.Qa="";this.Ks=this.kt=null}xe.prototype.copy=function(){var a=new xe;a.B=this.B;a.Qa=this.Qa;a.kt=this.kt;a.Ks=this.Ks;return a};xe.prototype.toString=function(){var a="*"+this.name;null!==this.subject&&(a+=":"+this.subject.toString());null!==this.parameter&&(a+="("+this.parameter.toString()+")");return a}; na.Object.defineProperties(xe.prototype,{diagram:{get:function(){return this.B},set:function(a){this.B=a}},name:{get:function(){return this.Qa},set:function(a){this.Qa=a}},subject:{get:function(){return this.kt},set:function(a){this.kt=a}},parameter:{get:function(){return this.Ks},set:function(a){this.Ks=a}}});xe.className="DiagramEvent"; function ye(){this.un=ze;this.hf=this.zs="";this.bp=this.cp=this.jp=this.kp=this.ip=this.B=this.bc=null}ye.prototype.clear=function(){this.bp=this.cp=this.jp=this.kp=this.ip=this.B=this.bc=null}; ye.prototype.copy=function(){var a=new ye;a.un=this.un;a.zs=this.zs;a.hf=this.hf;a.bc=this.bc;a.B=this.B;a.ip=this.ip;var b=this.kp;a.kp=za(b)&&"function"===typeof b.G?b.G():b;b=this.jp;a.jp=za(b)&&"function"===typeof b.G?b.G():b;b=this.cp;a.cp=za(b)&&"function"===typeof b.G?b.G():b;b=this.bp;a.bp=za(b)&&"function"===typeof b.G?b.G():b;return a};ye.prototype.jb=function(a){a.classType===ye&&(this.change=a)}; ye.prototype.toString=function(){var a="";a=this.change===Ae?a+"* ":this.change===ze?a+(null!==this.model?"!m":"!d"):a+((null!==this.model?"!m":"!d")+this.change);this.propertyName&&"string"===typeof this.propertyName&&(a+=" "+this.propertyName);this.modelChange&&this.modelChange!==this.propertyName&&(a+=" "+this.modelChange);a+=": ";this.change===Ae?null!==this.oldValue&&(a+=" "+this.oldValue):(null!==this.object&&(a+=Ka(this.object)),null!==this.oldValue&&(a+=" old: "+Ka(this.oldValue)),null!== this.oldParam&&(a+=" "+this.oldParam),null!==this.newValue&&(a+=" new: "+Ka(this.newValue)),null!==this.newParam&&(a+=" "+this.newParam));return a};ye.prototype.H=function(a){return a?this.oldValue:this.newValue};ye.prototype.oA=function(a){return a?this.oldParam:this.newParam};ye.prototype.canUndo=function(){return null!==this.model||null!==this.diagram?!0:!1}; ye.prototype.undo=function(){this.canUndo()&&(null!==this.model?this.model.changeState(this,!0):null!==this.diagram&&this.diagram.changeState(this,!0))};ye.prototype.canRedo=function(){return null!==this.model||null!==this.diagram?!0:!1};ye.prototype.redo=function(){this.canRedo()&&(null!==this.model?this.model.changeState(this,!1):null!==this.diagram&&this.diagram.changeState(this,!1))}; na.Object.defineProperties(ye.prototype,{model:{get:function(){return this.bc},set:function(a){this.bc=a}},diagram:{get:function(){return this.B},set:function(a){this.B=a}},change:{get:function(){return this.un},set:function(a){this.un=a}},modelChange:{get:function(){return this.zs},set:function(a){this.zs=a}},propertyName:{get:function(){return this.hf}, set:function(a){this.hf=a}},isTransactionFinished:{get:function(){return this.un===Ae&&("CommittedTransaction"===this.hf||"FinishedUndo"===this.hf||"FinishedRedo"===this.hf)}},object:{get:function(){return this.ip},set:function(a){this.ip=a}},oldValue:{get:function(){return this.kp},set:function(a){this.kp=a}},oldParam:{get:function(){return this.jp},set:function(a){this.jp=a}}, newValue:{get:function(){return this.cp},set:function(a){this.cp=a}},newParam:{get:function(){return this.bp},set:function(a){this.bp=a}}});ye.prototype.redo=ye.prototype.redo;ye.prototype.canRedo=ye.prototype.canRedo;ye.prototype.undo=ye.prototype.undo;ye.prototype.canUndo=ye.prototype.canUndo;ye.prototype.getParam=ye.prototype.oA;ye.prototype.getValue=ye.prototype.H;ye.prototype.clear=ye.prototype.clear; var Ae=new D(ye,"Transaction",-1),ze=new D(ye,"Property",0),Be=new D(ye,"Insert",1),Ce=new D(ye,"Remove",2);ye.className="ChangedEvent";ye.Transaction=Ae;ye.Property=ze;ye.Insert=Be;ye.Remove=Ce;function De(){this.v=(new E).freeze();this.Qa="";this.l=!1}De.prototype.toString=function(a){var b="Transaction: "+this.name+" "+this.changes.count.toString()+(this.isComplete?"":", incomplete");if(void 0!==a&&0<a){a=this.changes.count;for(var c=0;c<a;c++){var d=this.changes.J(c);null!==d&&(b+="\n "+d.toString())}}return b}; De.prototype.clear=function(){var a=this.changes;a.ea();for(var b=a.count-1;0<=b;b--){var c=a.J(b);null!==c&&c.clear()}a.clear();a.freeze()};De.prototype.canUndo=function(){return this.isComplete};De.prototype.undo=function(){if(this.canUndo())for(var a=this.changes.count-1;0<=a;a--){var b=this.changes.J(a);null!==b&&b.undo()}};De.prototype.canRedo=function(){return this.isComplete}; De.prototype.redo=function(){if(this.canRedo())for(var a=this.changes.count,b=0;b<a;b++){var c=this.changes.J(b);null!==c&&c.redo()}}; De.prototype.mw=function(){if(this.isComplete){var a=this.changes;a.ea();for(var b=new H,c=0;c<a.count;c++){var d=a.J(c);if(null!==d&&d.change===ze&&d.object){var e=b.get(d.object);e||(e=new H,b.set(d.object,e));var f=e.get(d.propertyName);null===f?e.set(d.propertyName,-1):(0<f&&a.Rc(f,null),e.set(d.propertyName,c))}}for(c=b=0;c<a.count;c++)d=a.J(c),null!==d&&(c>b&&a.Rc(b,d),b++);for(;a.length>b;)a.pop();a.freeze()}}; na.Object.defineProperties(De.prototype,{changes:{get:function(){return this.v}},name:{get:function(){return this.Qa},set:function(a){this.Qa=a}},isComplete:{get:function(){return this.l},set:function(a){this.l=a}}});De.prototype.optimize=De.prototype.mw;De.prototype.redo=De.prototype.redo;De.prototype.canRedo=De.prototype.canRedo;De.prototype.undo=De.prototype.undo;De.prototype.canUndo=De.prototype.canUndo; De.prototype.clear=De.prototype.clear;De.className="Transaction";function Ee(){this.fv=new G;this.nd=!1;this.I=(new E).freeze();this.Xd=-1;this.v=999;this.te=!1;this.Mr=null;this.Yi=0;this.l=!1;this.ze=(new E).freeze();this.Ul=new E;this.Ou=!0;this.Vu=this.ls=this.Zu=this.Yu=!1} Ee.prototype.toString=function(a){var b="UndoManager "+this.historyIndex+"<"+this.history.count+"<="+this.maxHistoryLength;b+="[";for(var c=this.nestedTransactionNames.count,d=0;d<c;d++)0<d&&(b+=" "),b+=this.nestedTransactionNames.J(d);b+="]";if(void 0!==a&&0<a)for(c=this.history.count,d=0;d<c;d++)b+="\n "+this.history.J(d).toString(a-1);return b}; Ee.prototype.clear=function(){var a=this.history;a.ea();for(var b=a.count-1;0<=b;b--){var c=a.J(b);null!==c&&c.clear()}a.clear();this.Xd=-1;a.freeze();this.te=!1;this.Mr=null;this.Yi=0;this.ze.ea();this.ze.clear();this.ze.freeze();this.Ul.clear();this.Vu=this.ls=this.Zu=this.Yu=!1};Ee.prototype.copyProperties=function(a){this.isEnabled=a.isEnabled;this.maxHistoryLength=a.maxHistoryLength;this.checksTransactionLevel=a.checksTransactionLevel};t=Ee.prototype;t.Wx=function(a){this.fv.add(a)};t.Qy=function(a){this.fv.remove(a)}; t.xa=function(a){void 0===a&&(a="");null===a&&(a="");if(this.isUndoingRedoing)return!1;!0===this.Ou&&(this.Ou=!1,this.Yi++,this.isInternalTransaction||this.Cb("StartingFirstTransaction",a,this.currentTransaction),0<this.Yi&&this.Yi--);this.isEnabled&&(this.ze.ea(),this.ze.add(a),this.ze.freeze(),null===this.currentTransaction?this.Ul.add(0):this.Ul.add(this.currentTransaction.changes.count));this.Yi++;var b=1===this.transactionLevel;b&&(this.isInternalTransaction||this.Cb("StartedTransaction",a,this.currentTransaction)); return b};t.Wa=function(a){void 0===a&&(a="");return Fe(this,!0,a)};t.Kf=function(){return Fe(this,!1,"")}; function Fe(a,b,c){if(a.isUndoingRedoing)return!1;a.checksTransactionLevel&&1>a.transactionLevel&&xa("Ending transaction without having started a transaction: "+c);var d=1===a.transactionLevel,e=a.currentTransaction;d&&b&&(a.isInternalTransaction||a.Cb("CommittingTransaction",c,e));var f=0;if(0<a.transactionLevel&&(a.Yi--,a.isEnabled)){var g=a.ze.count;0<g&&(""===c&&(c=a.ze.J(0)),a.ze.ea(),a.ze.cb(g-1),a.ze.freeze());g=a.Ul.count;0<g&&(f=a.Ul.J(g-1),a.Ul.cb(g-1))}if(d){if(b){a.ls=!1;null===e&&""!== c&&(e=a.currentTransaction);if(a.isEnabled&&null!==e){e.isComplete||(e.isComplete=!0,e.name=c);b=a.history;b.ea();for(d=b.count-1;d>a.historyIndex;d--)f=b.J(d),null!==f&&f.clear(),b.cb(d),a.ls=!0;d=a.maxHistoryLength;0<=d&&(0===d?b.clear():b.count>=d&&(f=b.J(0),null!==f&&f.clear(),b.cb(0),a.Xd--));0===d||0!==b.count&&b.get(b.count-1)===e||(b.add(e),a.Xd++);b.freeze()}a.isInternalTransaction||a.Cb("CommittedTransaction",c,e)}else{a.te=!0;try{a.isEnabled&&null!==e&&(e.isComplete=!0,e.undo())}finally{a.isInternalTransaction|| a.Cb("RolledBackTransaction",c,e),a.te=!1}null!==e&&e.clear()}a.Mr=null;a.isPendingClear&&a.clear();a.isPendingClear=!1;a.isPendingUnmodified=!1;return!0}if(a.isEnabled&&!b&&null!==e){a=f;c=e.changes;for(e=c.count-1;e>=a;e--)b=c.J(e),null!==b&&b.undo(),c.ea(),c.cb(e);c.freeze()}return!1}Ee.prototype.canUndo=function(){if(!this.isEnabled||0<this.transactionLevel)return!1;var a=this.transactionToUndo;return null!==a&&a.canUndo()?!0:!1}; Ee.prototype.undo=function(){if(this.canUndo()){var a=this.transactionToUndo;try{this.te=!0,this.Cb("StartingUndo","Undo",a),this.Xd--,a.undo()}catch(b){xa("undo error: "+b.toString())}finally{this.Cb("FinishedUndo","Undo",a),this.te=!1}}};Ee.prototype.canRedo=function(){if(!this.isEnabled||0<this.transactionLevel)return!1;var a=this.transactionToRedo;return null!==a&&a.canRedo()?!0:!1}; Ee.prototype.redo=function(){if(this.canRedo()){var a=this.transactionToRedo;try{this.te=!0,this.Cb("StartingRedo","Redo",a),this.Xd++,a.redo()}catch(b){xa("redo error: "+b.toString())}finally{this.Cb("FinishedRedo","Redo",a),this.te=!1}}};Ee.prototype.Cb=function(a,b,c){void 0===c&&(c=null);var d=new ye;d.change=Ae;d.propertyName=a;d.object=c;d.oldValue=b;for(a=this.models;a.next();)b=a.value,d.model=b,b.zt(d)}; Ee.prototype.$v=function(a){if(this.isEnabled&&!this.isUndoingRedoing&&!this.skipsEvent(a)){var b=this.currentTransaction;null===b&&(this.Mr=b=new De);var c=a.copy();b=b.changes;b.ea();b.add(c);b.freeze();this.checksTransactionLevel&&0>=this.transactionLevel&&!this.Ou&&(a=a.diagram,null!==a&&!1===a.pj||xa("Change not within a transaction: "+c.toString()))}}; Ee.prototype.skipsEvent=function(a){if(null===a||0>a.change.value)return!0;a=a.object;if(null===a)return!1;if(void 0!==a.layer){if(a=a.layer,null!==a&&a.isTemporary)return!0}else if(a.isTemporary)return!0;return!1}; na.Object.defineProperties(Ee.prototype,{models:{get:function(){return this.fv.iterator}},isEnabled:{get:function(){return this.nd},set:function(a){this.nd=a}},transactionToUndo:{get:function(){return 0<=this.historyIndex&&this.historyIndex<=this.history.count-1?this.history.J(this.historyIndex):null}},transactionToRedo:{get:function(){return this.historyIndex<this.history.count- 1?this.history.J(this.historyIndex+1):null}},isUndoingRedoing:{get:function(){return this.te}},history:{get:function(){return this.I}},maxHistoryLength:{get:function(){return this.v},set:function(a){this.v=a}},historyIndex:{get:function(){return this.Xd}},currentTransaction:{get:function(){return this.Mr}},transactionLevel:{ get:function(){return this.Yi}},isInTransaction:{get:function(){return 0<this.Yi}},checksTransactionLevel:{get:function(){return this.l},set:function(a){this.l=a}},nestedTransactionNames:{get:function(){return this.ze}},isPendingClear:{get:function(){return this.Yu},set:function(a){this.Yu=a}},isPendingUnmodified:{get:function(){return this.Zu},set:function(a){this.Zu= a}},isInternalTransaction:{get:function(){return this.Vu},set:function(a){this.Vu=a}},isJustDiscarded:{get:function(){return this.ls}}});Ee.prototype.handleChanged=Ee.prototype.$v;Ee.prototype.redo=Ee.prototype.redo;Ee.prototype.undo=Ee.prototype.undo;Ee.prototype.canUndo=Ee.prototype.canUndo;Ee.prototype.rollbackTransaction=Ee.prototype.Kf;Ee.prototype.commitTransaction=Ee.prototype.Wa;Ee.prototype.startTransaction=Ee.prototype.xa; Ee.prototype.removeModel=Ee.prototype.Qy;Ee.prototype.addModel=Ee.prototype.Wx;Ee.prototype.clear=Ee.prototype.clear;Ee.className="UndoManager";function Ge(){Za(this);this.B=He;this.Qa="";this.nd=!0;this.Uc=!1;this.jx=null;this.lz=new ve;this.vt=-1}Ge.prototype.toString=function(){return""!==this.name?this.name+" Tool":Ja(this.constructor)};Ge.prototype.updateAdornments=function(){};Ge.prototype.canStart=function(){return this.isEnabled};Ge.prototype.doStart=function(){}; Ge.prototype.doActivate=function(){this.isActive=!0};Ge.prototype.doDeactivate=function(){this.isActive=!1};Ge.prototype.doStop=function(){};Ge.prototype.doCancel=function(){this.transactionResult=null;this.stopTool()};Ge.prototype.stopTool=function(){var a=this.diagram;a.currentTool===this&&(a.currentTool=null,a.currentCursor="")};Ge.prototype.doMouseDown=function(){!this.isActive&&this.canStart()&&this.doActivate()};Ge.prototype.doMouseMove=function(){};Ge.prototype.doMouseUp=function(){this.stopTool()}; Ge.prototype.doMouseWheel=function(){};Ge.prototype.canStartMultiTouch=function(){return!0};Ge.prototype.standardPinchZoomStart=function(){var a=this.diagram,b=a.lastInput,c=b.Gq(0,I.allocAt(NaN,NaN)),d=b.Gq(1,I.allocAt(NaN,NaN));if(c.s()&&d.s()&&(this.doCancel(),a.Bm("hasGestureZoom"))){a.Wl=a.scale;var e=d.x-c.x,f=d.y-c.y;a.rv=Math.sqrt(e*e+f*f);b.bubbles=!1}I.free(c);I.free(d)}; Ge.prototype.standardPinchZoomMove=function(){var a=this.diagram,b=a.lastInput,c=b.Gq(0,I.allocAt(NaN,NaN)),d=b.Gq(1,I.allocAt(NaN,NaN));if(c.s()&&d.s()&&(this.doCancel(),a.Bm("hasGestureZoom"))){var e=d.x-c.x,f=d.y-c.y;f=Math.sqrt(e*e+f*f)/a.rv;e=new I((Math.min(d.x,c.x)+Math.max(d.x,c.x))/2,(Math.min(d.y,c.y)+Math.max(d.y,c.y))/2);f*=a.Wl;var g=a.commandHandler;if(f!==a.scale&&g.canResetZoom(f)){var h=a.zoomPoint;a.zoomPoint=e;g.resetZoom(f);a.zoomPoint=h}b.bubbles=!1}I.free(c);I.free(d)}; Ge.prototype.doKeyDown=function(){"Esc"===this.diagram.lastInput.key&&this.doCancel()};Ge.prototype.doKeyUp=function(){};Ge.prototype.xa=function(a){void 0===a&&(a=this.name);this.transactionResult=null;return this.diagram.xa(a)};Ge.prototype.Kg=function(){var a=this.diagram;return null===this.transactionResult?a.Kf():a.Wa(this.transactionResult)}; Ge.prototype.standardMouseSelect=function(){var a=this.diagram;if(a.allowSelect){var b=a.lastInput,c=a.zm(b.documentPoint,!1);if(null!==c)if(Xa?b.meta:b.control){a.R("ChangingSelection",a.selection);for(b=c;null!==b&&!b.canSelect();)b=b.containingGroup;null!==b&&(b.isSelected=!b.isSelected);a.R("ChangedSelection",a.selection)}else if(b.shift){if(!c.isSelected){a.R("ChangingSelection",a.selection);for(b=c;null!==b&&!b.canSelect();)b=b.containingGroup;null!==b&&(b.isSelected=!0);a.R("ChangedSelection", a.selection)}}else{if(!c.isSelected){for(b=c;null!==b&&!b.canSelect();)b=b.containingGroup;null!==b&&a.select(b)}}else!b.left||(Xa?b.meta:b.control)||b.shift||a.clearSelection()}};Ge.prototype.standardMouseClick=function(a,b){void 0===a&&(a=null);void 0===b&&(b=function(a){return!a.layer.isTemporary});var c=this.diagram,d=c.lastInput;a=c.Vb(d.documentPoint,a,b);d.targetObject=a;Ie(a,d,c);return d.handled}; function Ie(a,b,c){b.handled=!1;if(null===a||a.Ig()){var d=0;b.left?d=1===b.clickCount?1:2===b.clickCount?2:1:b.right&&1===b.clickCount&&(d=3);var e="ObjectSingleClicked";if(null!==a){switch(d){case 1:e="ObjectSingleClicked";break;case 2:e="ObjectDoubleClicked";break;case 3:e="ObjectContextClicked"}0!==d&&c.R(e,a)}else{switch(d){case 1:e="BackgroundSingleClicked";break;case 2:e="BackgroundDoubleClicked";break;case 3:e="BackgroundContextClicked"}0!==d&&c.R(e)}if(null!==a)for(;null!==a;){c=null;switch(d){case 1:c= a.click;break;case 2:c=a.doubleClick?a.doubleClick:a.click;break;case 3:c=a.contextClick}if(null!==c&&(c(b,a),b.handled))break;a=a.panel}else{a=null;switch(d){case 1:a=c.click;break;case 2:a=c.doubleClick?c.doubleClick:c.click;break;case 3:a=c.contextClick}null!==a&&a(b)}}} Ge.prototype.standardMouseOver=function(){var a=this.diagram,b=a.lastInput;if(!0!==a.animationManager.sc){var c=a.skipsUndoManager;a.skipsUndoManager=!0;var d=a.viewportBounds.$(b.documentPoint)?a.Vb(b.documentPoint,null,null):null;b.targetObject=d;var e=!1;if(d!==a.Ej){var f=a.Ej,g=f;a.Ej=d;this.doCurrentObjectChanged(f,d);for(b.handled=!1;null!==f;){var h=f.mouseLeave;if(null!==h){if(d===f)break;if(null!==d&&d.Hg(f))break;h(b,f,d);e=!0;if(b.handled)break}f=f.panel}f=g;for(b.handled=!1;null!==d;){g= d.mouseEnter;if(null!==g){if(f===d)break;if(null!==f&&f.Hg(d))break;g(b,d,f);e=!0;if(b.handled)break}d=d.panel}d=a.Ej}if(null!==d){f=d;for(g="";null!==f;){g=f.cursor;if(""!==g)break;f=f.panel}a.currentCursor=g;b.handled=!1;for(f=d;null!==f;){d=f.mouseOver;if(null!==d&&(d(b,f),e=!0,b.handled))break;f=f.panel}}else a.currentCursor="",d=a.mouseOver,null!==d&&(d(b),e=!0);e&&a.Eb();a.skipsUndoManager=c}};Ge.prototype.doCurrentObjectChanged=function(){}; Ge.prototype.standardMouseWheel=function(){var a=this.diagram,b=a.lastInput,c=b.delta;if(0!==c&&a.documentBounds.s()){var d=a.commandHandler,e=a.toolManager.mouseWheelBehavior;if(null!==d&&(e===Je&&!b.shift||e===Ke&&b.control)){if(0<c?d.canIncreaseZoom():d.canDecreaseZoom())e=a.zoomPoint,a.zoomPoint=b.viewPoint,0<c?d.increaseZoom():d.decreaseZoom(),a.zoomPoint=e;b.bubbles=!1}else if(e===Je&&b.shift||e===Ke&&!b.control){d=a.position.copy();var f=0<c?c:-c,g=b.event,h=g.deltaMode;e=g.deltaX;g=g.deltaY; if(Ua||Va||Wa)h=1,0<e&&(e=3),0>e&&(e=-3),0<g&&(g=3),0>g&&(g=-3);if(void 0===h||void 0===e||void 0===g||0===e&&0===g||b.shift)!b.shift&&a.allowVerticalScroll?(f=3*f*a.scrollVerticalLineChange,0<c?a.scroll("pixel","up",f):a.scroll("pixel","down",f)):b.shift&&a.allowHorizontalScroll&&(f=3*f*a.scrollHorizontalLineChange,0<c?a.scroll("pixel","left",f):a.scroll("pixel","right",f));else{switch(h){case 0:c="pixel";break;case 1:c="line";break;case 2:c="page";break;default:c="pixel"}0!==e&&a.allowHorizontalScroll&& (e*=a.scrollHorizontalLineChange/16,0<e?a.scroll(c,"left",-e):a.scroll(c,"right",e));0!==g&&a.allowVerticalScroll&&(g*=a.scrollVerticalLineChange/16,0<g?a.scroll(c,"up",-g):a.scroll(c,"down",g))}a.position.w(d)||(b.bubbles=!1)}}};Ge.prototype.standardWaitAfter=function(a,b){void 0===b&&(b=this.diagram.lastInput);this.cancelWaitAfter();var c=this,d=b.clone(this.lz);this.vt=ta(function(){c.doWaitAfter(d)},a)};Ge.prototype.cancelWaitAfter=function(){-1!==this.vt&&x.clearTimeout(this.vt);this.vt=-1}; Ge.prototype.doWaitAfter=function(){};Ge.prototype.findToolHandleAt=function(a,b){a=this.diagram.Vb(a,function(a){for(;null!==a&&!(a.panel instanceof Qe);)a=a.panel;return a});return null===a?null:a.part.category===b?a:null};Ge.prototype.isBeyondDragSize=function(a,b){var c=this.diagram;void 0===a&&(a=c.firstInput.viewPoint);void 0===b&&(b=c.lastInput.viewPoint);var d=c.toolManager.dragSize,e=d.width;d=d.height;c.firstInput.isTouchEvent&&(e+=6,d+=6);return Math.abs(b.x-a.x)>e||Math.abs(b.y-a.y)>d}; na.Object.defineProperties(Ge.prototype,{diagram:{get:function(){return this.B},set:function(a){a instanceof R&&(this.B=a)}},name:{get:function(){return this.Qa},set:function(a){this.Qa=a}},isEnabled:{get:function(){return this.nd},set:function(a){this.nd=a}},isActive:{get:function(){return this.Uc},set:function(a){this.Uc=a}},transactionResult:{get:function(){return this.jx}, set:function(a){this.jx=a}}});Ge.prototype.stopTransaction=Ge.prototype.Kg;Ge.prototype.startTransaction=Ge.prototype.xa;Ge.className="Tool";function Pa(){Ge.call(this);this.name="ToolManager";this.Dc=new E;this.Vc=new E;this.Od=new E;this.T=this.Ja=850;this.v=(new M(2,2)).ca();this.eb=5E3;this.Ka=Ke;this.I=Re;this.Lr=this.l=null;this.ik=-1}ma(Pa,Ge);Pa.prototype.initializeStandardTools=function(){}; Pa.prototype.updateAdornments=function(a){var b=this.currentToolTip;if(b instanceof Qe&&this.Lr===a){var c=b.adornedObject;(null!==a?c.part===a:null===c)?this.showToolTip(b,c):this.hideToolTip()}}; Pa.prototype.doMouseDown=function(){var a=this.diagram,b=a.lastInput;b.isTouchEvent&&this.gestureBehavior===Se&&(b.bubbles=!1);if(b.isMultiTouch){this.cancelWaitAfter();if(this.gestureBehavior===Te){b.bubbles=!0;return}if(this.gestureBehavior===Se)return;if(a.currentTool.canStartMultiTouch()){a.currentTool.standardPinchZoomStart();return}}for(var c=this.mouseDownTools.length,d=0;d<c;d++){var e=this.mouseDownTools.J(d);e.diagram=this.diagram;if(e.canStart()){a.doFocus();a.currentTool=e;a.currentTool=== e&&(e.isActive||e.doActivate(),e.doMouseDown());return}}1===a.lastInput.button&&(this.mouseWheelBehavior===Ke?this.mouseWheelBehavior=Je:this.mouseWheelBehavior===Je&&(this.mouseWheelBehavior=Ke));this.doActivate();this.standardWaitAfter(this.holdDelay,b)}; Pa.prototype.doMouseMove=function(){var a=this.diagram,b=a.lastInput;if(b.isMultiTouch){if(this.gestureBehavior===Te){b.bubbles=!0;return}if(this.gestureBehavior===Se)return;if(a.currentTool.canStartMultiTouch()){a.currentTool.standardPinchZoomMove();return}}if(this.isActive)for(var c=this.mouseMoveTools.length,d=0;d<c;d++){var e=this.mouseMoveTools.J(d);e.diagram=this.diagram;if(e.canStart()){a.doFocus();a.currentTool=e;a.currentTool===e&&(e.isActive||e.doActivate(),e.doMouseMove());return}}Ue(this, a);a=b.event;null===a||"mousemove"!==a.type&&"pointermove"!==a.type&&a.cancelable||(b.bubbles=!0)};function Ue(a,b){a.standardMouseOver();a.isBeyondDragSize()&&a.standardWaitAfter(a.isActive?a.holdDelay:a.hoverDelay,b.lastInput)}Pa.prototype.doCurrentObjectChanged=function(a,b){a=this.currentToolTip;null===a||null!==b&&a instanceof Qe&&(b===a||b.Hg(a))||this.hideToolTip()}; Pa.prototype.doWaitAfter=function(a){var b=this.diagram;b.ta&&(this.doMouseHover(),this.isActive||this.doToolTip(),a.isTouchEvent&&!b.lastInput.handled&&(a=a.copy(),a.button=2,a.buttons=2,b.lastInput=a,b.hk=!0,b.doMouseUp()))}; Pa.prototype.doMouseHover=function(){var a=this.diagram,b=a.lastInput;null===b.targetObject&&(b.targetObject=a.Vb(b.documentPoint,null,null));var c=b.targetObject;if(null!==c)for(b.handled=!1;null!==c;){a=this.isActive?c.mouseHold:c.mouseHover;if(null!==a&&(a(b,c),b.handled))break;c=c.panel}else c=this.isActive?a.mouseHold:a.mouseHover,null!==c&&c(b)}; Pa.prototype.doToolTip=function(){var a=this.diagram,b=a.lastInput;null===b.targetObject&&(b.targetObject=a.Vb(b.documentPoint,null,null));b=b.targetObject;if(null!==b){if(a=this.currentToolTip,!(a instanceof Qe)||b!==a&&!b.Hg(a)){for(;null!==b;){a=b.toolTip;if(null!==a){this.showToolTip(a,b);return}b=b.panel}this.hideToolTip()}}else b=a.toolTip,null!==b?this.showToolTip(b,null):this.hideToolTip()}; Pa.prototype.showToolTip=function(a,b){var c=this.diagram;a!==this.currentToolTip&&this.hideToolTip();if(a instanceof Qe){a.layerName="Tool";a.selectable=!1;a.scale=1/c.scale;a.category="ToolTip";null!==a.placeholder&&(a.placeholder.scale=c.scale);var d=a.diagram;null!==d&&d!==c&&d.remove(a);c.add(a);null!==b?a.adornedObject=b:a.data=c.model;a.Ta();this.positionToolTip(a,b)}else a instanceof Ve&&a!==this.currentToolTip&&a.show(b,c,this);this.currentToolTip=a;-1!==this.ik&&(x.clearTimeout(this.ik), this.ik=-1);a=this.toolTipDuration;if(0<a&&Infinity!==a){var e=this;this.ik=ta(function(){e.hideToolTip()},a)}};Pa.prototype.positionToolTip=function(a){if(null===a.placeholder){var b=this.diagram,c=b.lastInput.documentPoint.copy(),d=a.measuredBounds,e=b.viewportBounds;b.lastInput.isTouchEvent&&(c.x-=d.width);c.x+d.width>e.right&&(c.x-=d.width+5/b.scale);c.x<e.x&&(c.x=e.x);c.y=c.y+20/b.scale+d.height>e.bottom?c.y-(d.height+5/b.scale):c.y+20/b.scale;c.y<e.y&&(c.y=e.y);a.position=c}}; Pa.prototype.hideToolTip=function(){-1!==this.ik&&(x.clearTimeout(this.ik),this.ik=-1);var a=this.diagram,b=this.currentToolTip;null!==b&&(b instanceof Qe?(a.remove(b),null!==this.Lr&&this.Lr.Jf(b.category),b.data=null,b.adornedObject=null):b instanceof Ve&&null!==b.hide&&b.hide(a,this),this.currentToolTip=null)}; Pa.prototype.doMouseUp=function(){this.cancelWaitAfter();var a=this.diagram;if(this.isActive)for(var b=this.mouseUpTools.length,c=0;c<b;c++){var d=this.mouseUpTools.J(c);d.diagram=this.diagram;if(d.canStart()){a.doFocus();a.currentTool=d;a.currentTool===d&&(d.isActive||d.doActivate(),d.doMouseUp());return}}a.doFocus();this.doDeactivate()};Pa.prototype.doMouseWheel=function(){this.standardMouseWheel()};Pa.prototype.doKeyDown=function(){var a=this.diagram;null!==a.commandHandler&&a.commandHandler.doKeyDown()}; Pa.prototype.doKeyUp=function(){var a=this.diagram;null!==a.commandHandler&&a.commandHandler.doKeyUp()};Pa.prototype.findTool=function(a){for(var b=this.mouseDownTools.length,c=0;c<b;c++){var d=this.mouseDownTools.J(c);if(d.name===a)return d}b=this.mouseMoveTools.length;for(c=0;c<b;c++)if(d=this.mouseMoveTools.J(c),d.name===a)return d;b=this.mouseUpTools.length;for(c=0;c<b;c++)if(d=this.mouseUpTools.J(c),d.name===a)return d;return null}; Pa.prototype.replaceTool=function(a,b){null!==b&&(b.diagram=this.diagram);for(var c=this.mouseDownTools.length,d=0;d<c;d++){var e=this.mouseDownTools.J(d);if(e.name===a)return null!==b?this.mouseDownTools.Rc(d,b):this.mouseDownTools.cb(d),e}c=this.mouseMoveTools.length;for(d=0;d<c;d++)if(e=this.mouseMoveTools.J(d),e.name===a)return null!==b?this.mouseMoveTools.Rc(d,b):this.mouseMoveTools.cb(d),e;c=this.mouseUpTools.length;for(d=0;d<c;d++)if(e=this.mouseUpTools.J(d),e.name===a)return null!==b?this.mouseUpTools.Rc(d, b):this.mouseUpTools.cb(d),e;return null};Pa.prototype.Xa=function(a,b,c){null!==b&&(b.name=a,b.diagram=this.diagram);this.findTool(a)?this.replaceTool(a,b):null!==b&&c.add(b)}; na.Object.defineProperties(Pa.prototype,{mouseWheelBehavior:{get:function(){return this.Ka},set:function(a){this.Ka=a}},gestureBehavior:{get:function(){return this.I},set:function(a){this.I=a}},currentToolTip:{get:function(){return this.l},set:function(a){this.l=a;this.Lr=null!==a&&a instanceof Qe?a.adornedPart:null}},mouseDownTools:{get:function(){return this.Dc}},mouseMoveTools:{ get:function(){return this.Vc}},mouseUpTools:{get:function(){return this.Od}},hoverDelay:{get:function(){return this.Ja},set:function(a){this.Ja=a}},holdDelay:{get:function(){return this.T},set:function(a){this.T=a}},dragSize:{get:function(){return this.v},set:function(a){this.v=a.G()}},toolTipDuration:{get:function(){return this.eb},set:function(a){this.eb= a}}});Pa.prototype.replaceStandardTool=Pa.prototype.Xa;var Ke=new D(Pa,"WheelScroll",0),Je=new D(Pa,"WheelZoom",1),We=new D(Pa,"WheelNone",2),Re=new D(Pa,"GestureZoom",3),Se=new D(Pa,"GestureCancel",4),Te=new D(Pa,"GestureNone",5);Pa.className="ToolManager";Pa.WheelScroll=Ke;Pa.WheelZoom=Je;Pa.WheelNone=We;Pa.GestureZoom=Re;Pa.GestureCancel=Se;Pa.GestureNone=Te; function Xe(){Ge.call(this);this.name="Dragging";this.I=this.Vc=!0;this.v=this.eb=this.Ja=this.rg=null;this.Rn=this.Od=!1;this.im=new I(NaN,NaN);this.it=new I;this.Dc=!0;this.pl=100;this.Xg=[];this.mr=(new G).freeze();this.Ka=new Ye;this.Ao=null;this.T="copy";this.Vh="";this.Wh="no-drop"}ma(Xe,Ge); Xe.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(a.isReadOnly&&!a.allowDragOut||!a.allowMove&&!a.allowCopy&&!a.allowDragOut||!a.allowSelect)return!1;var b=a.lastInput;return!b.left||a.currentTool!==this&&(!this.isBeyondDragSize()||b.isTouchEvent&&b.timestamp-a.firstInput.timestamp<this.pl)?!1:null!==this.findDraggablePart()}; Xe.prototype.findDraggablePart=function(){var a=this.diagram;a=a.zm(a.firstInput.documentPoint,!1);if(null===a)return null;for(;null!==a&&!a.canSelect();)a=a.containingGroup;return null!==a&&(a.canMove()||a.canCopy())?a:null}; Xe.prototype.standardMouseSelect=function(){var a=this.diagram;if(a.allowSelect){var b=a.zm(a.firstInput.documentPoint,!1);if(null!==b){for(;null!==b&&!b.canSelect();)b=b.containingGroup;this.currentPart=b;null===this.currentPart||this.currentPart.isSelected||(a.R("ChangingSelection",a.selection),b=a.lastInput,(Xa?b.meta:b.control)||b.shift||a.clearSelection(!0),this.currentPart.isSelected=!0,a.R("ChangedSelection",a.selection))}}}; Xe.prototype.doActivate=function(){var a=this.diagram;this.Ao=null;null===this.currentPart&&this.standardMouseSelect();var b=this.currentPart;null!==b&&(b.canMove()||b.canCopy())&&(Ze=null,this.isActive=!0,this.im.set(a.position),$e(this,a.selection),this.Xg.length=0,a.animationManager.Cc(),this.draggedParts=this.computeEffectiveCollection(a.selection,this.dragOptions),a.mu=!0,!0===a.Ke("temporaryPixelRatio")&&30<a.Zx&&af(a),bf(a,this.draggedParts),this.xa("Drag"),this.startPoint=a.firstInput.documentPoint, a.isMouseCaptured=!0,a.allowDragOut&&(this.isDragOutStarted=!0,this.Rn=!1,Ze=this,cf=this.diagram,this.doSimulatedDragOut()))};function $e(a,b){if(a.dragsLink){var c=a.diagram;c.allowRelink&&(c.model.Bk()&&1===b.count&&b.first()instanceof S?(a.draggedLink=b.first(),a.draggedLink.canRelinkFrom()&&a.draggedLink.canRelinkTo()&&a.draggedLink.nk(),a.rg=c.toolManager.findTool("Relinking"),null===a.rg&&(a.rg=new df,a.rg.diagram=c)):(a.draggedLink=null,a.rg=null))}} Xe.prototype.computeEffectiveCollection=function(a,b){return this.diagram.commandHandler.computeEffectiveCollection(a,b)};Xe.prototype.Cd=function(a){return void 0===a?new ef(Fb):this.isGridSnapEnabled?new ef(new I(Math.round(1E3*a.x)/1E3,Math.round(1E3*a.y)/1E3)):new ef(a.copy())}; Xe.prototype.doDeactivate=function(){this.isActive=!1;var a=this.diagram;a.Lf();jf(this);kf(a,this.draggedParts);this.draggedParts=this.currentPart=this.Ao=null;this.Rn=this.isDragOutStarted=!1;if(0<lf.count){for(var b=lf,c=b.length,d=0;d<c;d++){var e=b.J(d);mf(e);nf(e);jf(e);e.diagram.Lf()}b.clear()}mf(this);this.im.h(NaN,NaN);Ze=cf=null;nf(this);a.isMouseCaptured=!1;a.currentCursor="";a.mu=!1;this.Kg();of(a,!0)}; function jf(a){var b=a.diagram,c=b.skipsUndoManager;b.skipsUndoManager=!0;pf(a,b.lastInput,null);b.skipsUndoManager=c;a.Xg.length=0}function qf(){var a=Ze;nf(a);rf(a);var b=a.diagram;a.im.s()&&(b.position=a.im);b.Lf()}Xe.prototype.doCancel=function(){nf(this);rf(this);var a=this.diagram;this.im.s()&&(a.position=this.im);this.stopTool()};Xe.prototype.doKeyDown=function(){var a=this.diagram,b=a.lastInput;this.isActive&&("Esc"===b.key?this.doCancel():b.key!==a.previousInput.key&&this.doMouseMove())}; Xe.prototype.doKeyUp=function(){this.isActive&&this.doMouseMove()}; function sf(a,b){if(null===a.copiedParts){var c=a.diagram;if((!b||!c.isReadOnly&&!c.isModelReadOnly)&&null!==a.draggedParts){var d=c.undoManager;d.isEnabled&&d.isInTransaction?null!==d.currentTransaction&&0<d.currentTransaction.changes.count&&(c.undoManager.Kf(),c.xa("Drag")):rf(a);c.skipsUndoManager=!b;c.partManager.addsToTemporaryLayer=!b;a.startPoint=c.firstInput.documentPoint;b=a.copiesEffectiveCollection?a.draggedParts.Mf():c.selection;b=c.tk(b,c,!0);c=new H;for(d=a.draggedParts.iterator;d.next();){var e= d.key;if(e.Pc()&&e.canCopy()){var f=b.H(e);null!==f&&(f.location=e.location,f.Ta(),c.add(f,a.Cd(f.location)))}}for(b=b.iterator;b.next();)d=b.value,d instanceof S&&d.canCopy()&&c.add(d,a.Cd());a.copiedParts=c;$e(a,c.Mf());null!==a.draggedLink&&(c=a.draggedLink,b=c.routeBounds,tf(c,a.startPoint.x-(b.x+b.width/2),a.startPoint.y-(b.y+b.height/2)))}}} function nf(a){var b=a.diagram;if(null!==a.copiedParts&&(b.gu(a.copiedParts.Mf(),!1),a.copiedParts=null,null!==a.draggedParts))for(var c=a.draggedParts.iterator;c.next();)c.key instanceof S&&(c.value.point=new I(0,0));b.skipsUndoManager=!1;b.partManager.addsToTemporaryLayer=!1;a.startPoint=b.firstInput.documentPoint} function mf(a){if(null!==a.draggedLink){if(a.dragsLink&&null!==a.rg){var b=a.rg;b.diagram.remove(b.temporaryFromNode);b.diagram.remove(b.temporaryToNode)}a.draggedLink=null;a.rg=null}}function uf(a,b,c){var d=a.diagram,e=a.startPoint,f=I.alloc();f.assign(d.lastInput.documentPoint);a.moveParts(b,f.he(e),c);I.free(f);!0===d.Ke("temporaryPixelRatio")&&null===d.xh&&30<d.Zx&&(af(d),d.Yq())} Xe.prototype.moveParts=function(a,b,c){void 0===c&&(c=!1);var d=this.diagram;null!==d&&vf(d,a,b,this.dragOptions,c)};function rf(a){if(null!==a.draggedParts){for(var b=a.diagram,c=a.draggedParts.iterator;c.next();){var d=c.key;d.Pc()&&(d.location=c.value.point)}for(c=a.draggedParts.iterator;c.next();)if(d=c.key,d instanceof S&&d.suspendsRouting){var e=c.value.point;a.draggedParts.add(d,a.Cd());tf(d,-e.x,-e.y)}b.jd()}} function wf(a,b){var c=a.diagram;a.dragsLink&&(null!==a.draggedLink&&(a.draggedLink.fromNode=null,a.draggedLink.toNode=null),xf(a,!1));var d=a.findDragOverObject(b),e=c.lastInput;e.targetObject=d;a.doUpdateCursor(d);var f=c.skipsUndoManager,g=!1;try{c.skipsUndoManager=!0;g=pf(a,e,d);if(!a.isActive&&null===Ze)return;var h=null!==d?d.part:null;if(null===h||c.handlesDragDropForTopLevelParts&&h.isTopLevel&&!(h instanceof U)){var k=c.mouseDragOver;null!==k&&(k(e),g=!0)}if(!a.isActive&&null===Ze)return; a.doDragOver(b,d);if(!a.isActive&&null===Ze)return}finally{c.skipsUndoManager=f,g&&c.jd()}a.Ao=d;c.isReadOnly||!c.allowMove&&!c.allowCopy||!c.allowHorizontalScroll&&!c.allowVerticalScroll||c.Ft(e.viewPoint)}Xe.prototype.findDragOverObject=function(a){var b=this;return yf(this.diagram,a,null,function(a){null===a?a=!0:(a=a.part,a=null===a||a instanceof Qe||a.layer.isTemporary||b.draggedParts&&b.draggedParts.contains(a)||b.copiedParts&&b.copiedParts.contains(a)?!0:!1);return!a})}; Xe.prototype.doUpdateCursor=function(a){var b=this.diagram;this.Ao!==a&&(!this.diagram.currentTool.isActive||this.mayCopy()?b.currentCursor=this.copyCursor:this.mayMove()?b.currentCursor=this.moveCursor:this.mayDragOut()&&(b.currentCursor=this.nodropCursor))}; function pf(a,b,c){var d=!1,e=a.Xg.length,f=0<e?a.Xg[0]:null;if(c===f)return!1;b.handled=!1;for(var g=0;g<e;g++){var h=a.Xg[g],k=h.mouseDragLeave;if(null!==k&&(k(b,h,c),d=!0,b.handled))break}a.Xg.length=0;if(!a.isActive&&null===Ze||null===c)return d;b.handled=!1;for(e=c;null!==e;)a.Xg.push(e),e=zf(e);e=a.Xg.length;for(c=0;c<e&&(g=a.Xg[c],h=g.mouseDragEnter,null===h||(h(b,g,f),d=!0,!b.handled));c++);return d} function zf(a){var b=a.panel;return null!==b?b:a instanceof V&&!(a instanceof U)&&(a=a.containingGroup,null!==a&&a.handlesDragDropForMembers)?a:null}function Af(a,b,c){var d=a.rg;if(null===d)return null;var e=a.diagram.Fg(b,d.portGravity,function(a){return d.findValidLinkablePort(a,c)});a=I.alloc();var f=Infinity,g=null;for(e=e.iterator;e.next();){var h=e.value;if(null!==h.part){var k=h.da(Bc,a);k=b.Ie(k);k<f&&(g=h,f=k)}}I.free(a);return g} function xf(a,b){var c=a.draggedLink;if(null!==c&&!(2>c.pointsCount)){var d=a.diagram;if(!d.isReadOnly){var e=a.rg;if(null!==e){var f=null,g=null;null===c.fromNode&&(f=Af(a,c.i(0),!1),null!==f&&(g=f.part));var h=null,k=null;null===c.toNode&&(h=Af(a,c.i(c.pointsCount-1),!0),null!==h&&(k=h.part));e.isValidLink(g,f,k,h)?b?(c.defaultFromPoint=c.i(0),c.defaultToPoint=c.i(c.pointsCount-1),c.suspendsRouting=!1,c.fromNode=g,null!==f&&(c.fromPortId=f.portId),c.toNode=k,null!==h&&(c.toPortId=h.portId),c.fromPort!== d.Ly&&d.R("LinkRelinked",c,d.Ly),c.toPort!==d.My&&d.R("LinkRelinked",c,d.My)):Bf(e,g,f,k,h):Bf(e,null,null,null,null)}}}}Xe.prototype.doDragOver=function(){}; function Cf(a,b){var c=a.diagram;a.dragsLink&&xf(a,!0);jf(a);var d=a.findDragOverObject(b),e=c.lastInput;e.targetObject=d;if(null!==d){e.handled=!1;for(var f=d;null!==f;){var g=f.mouseDrop;if(null!==g&&(g(e,f),e.handled))break;Df(a,e,f);f=zf(f)}}else f=c.mouseDrop,null!==f&&f(e);if(a.isActive||null!==Ze){for(e=(a.copiedParts||a.draggedParts).iterator;e.next();)f=e.key,f instanceof W&&f.linksConnected.each(function(a){a.suspendsRouting=!1});a.doDropOnto(b,d);if(a.isActive||null!==Ze){a=N.alloc();for(b= c.selection.iterator;b.next();)d=b.value,d instanceof W&&Hf(c,d,a);N.free(a)}}}function Df(a,b,c){a=a.diagram;c=c.part;!a.handlesDragDropForTopLevelParts||!c.isTopLevel||c instanceof U||(c=a.mouseDrop,null!==c&&c(b))}function Hf(a,b,c){var d=!1;b.getAvoidableRect(c);a.viewportBounds.He(c)&&(d=!0);a=a.Uv(c,function(a){return a.part},function(a){return a instanceof S},!0,function(a){return a instanceof S},d);if(0!==a.count)for(a=a.iterator;a.next();)c=a.value,!c.Kd(b)&&c.isAvoiding&&c.Ua()} Xe.prototype.doDropOnto=function(){};Xe.prototype.doMouseMove=function(){if(this.isActive){var a=this.diagram,b=a.lastInput;this.simulatedMouseMove(b.event,b.documentPoint,b.targetDiagram)||null===this.currentPart||null===this.draggedParts||(this.mayCopy()?(sf(this,!1),bf(a,this.copiedParts),uf(this,this.copiedParts,!1),kf(a,this.copiedParts)):this.mayMove()?(nf(this),uf(this,this.draggedParts,!0)):this.mayDragOut()?(sf(this,!1),uf(this,this.copiedParts,!1)):nf(this),wf(this,a.lastInput.documentPoint))}}; Xe.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram,b=a.lastInput;if(!this.simulatedMouseUp(b.event,b.documentPoint,b.targetDiagram)){b=!1;var c=this.mayCopy();c&&null!==this.copiedParts?(nf(this),sf(this,!0),bf(a,this.copiedParts),uf(this,this.copiedParts,!1),kf(a,this.copiedParts),null!==this.copiedParts&&(a.R("ChangingSelection",a.selection),a.clearSelection(!0),this.copiedParts.iteratorKeys.each(function(a){a.isSelected=!0}))):(b=!0,nf(this),this.mayMove()&&(uf(this,this.draggedParts, !0),wf(this,a.lastInput.documentPoint)));this.Rn=!0;Cf(this,a.lastInput.documentPoint);if(this.isActive){var d=c?this.copiedParts.Mf():this.draggedParts.Mf();this.copiedParts=null;b&&If(this);a.Oa();kf(a,this.draggedParts);this.transactionResult=c?"Copy":"Move";a.R(c?"SelectionCopied":"SelectionMoved",d)}this.stopTool();c&&a.R("ChangedSelection",a.selection)}}}; Xe.prototype.simulatedMouseMove=function(a,b,c){if(null===Ze)return!1;var d=Ze.diagram;c instanceof R||(c=null);var e=cf;c!==e&&(null!==e&&e!==d&&(e.Lf(),Ze.isDragOutStarted=!1,e=e.toolManager.findTool("Dragging"),null!==e&&e.doSimulatedDragLeave()),cf=c,null!==c&&c!==d&&(qf(),e=c.toolManager.findTool("Dragging"),null!==e&&(lf.contains(e)||lf.add(e),e.doSimulatedDragEnter())));if(null===c||c===d||!c.allowDrop||c.isReadOnly||!c.allowInsert)return!1;d=c.toolManager.findTool("Dragging");null!==d&&(null!== a&&(void 0!==a.targetTouches&&(0<a.targetTouches.length?a=a.targetTouches[0]:0<a.changedTouches.length&&(a=a.changedTouches[0])),b=c.getMouse(a)),c.lastInput.documentPoint=b,c.lastInput.viewPoint=c.hr(b),c.lastInput.down=!1,c.lastInput.up=!1,d.doSimulatedDragOver());return!0}; Xe.prototype.simulatedMouseUp=function(a,b,c){if(null===Ze)return!1;var d=cf,e=Ze.diagram;if(null===c)return Ze.doCancel(),!0;if(c!==d){var f=d.toolManager.findTool("Dragging");if(null!==d&&d!==e&&null!==f)return d.Lf(),Ze.isDragOutStarted=!1,f.doSimulatedDragLeave(),!1;cf=c;d=c.toolManager.findTool("Dragging");null!==d&&(qf(),lf.contains(d)||lf.add(d),d.doSimulatedDragEnter())}return c!==this.diagram?(null!==a?(void 0!==a.targetTouches&&(0<a.targetTouches.length?a=a.targetTouches[0]:0<a.changedTouches.length&& (a=a.changedTouches[0])),b=c.getMouse(a)):null===b&&(b=new I),c.lastInput.documentPoint=b,c.lastInput.viewPoint=c.hr(b),c.lastInput.down=!1,c.lastInput.up=!0,a=c.toolManager.findTool("Dragging"),null!==a&&a.doSimulatedDrop(),a=Ze,null!==a&&(c=a.mayCopy(),a.transactionResult=c?"Copy":"Move",a.stopTool()),!0):!1}; function If(a){if(null!==a.draggedParts)for(var b=a.draggedParts.iterator;b.next();){var c=b.key;c instanceof W&&(c=c.containingGroup,null===c||null===c.placeholder||a.draggedParts.contains(c)||c.placeholder.o())}} Xe.prototype.mayCopy=function(){if(!this.isCopyEnabled)return!1;var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.allowCopy||(Xa?!a.lastInput.alt:!a.lastInput.control))return!1;for(a=a.selection.iterator;a.next();)if(a.value.canCopy())return!0;return null!==this.draggedLink&&this.dragsLink&&this.draggedLink.canCopy()?!0:!1}; Xe.prototype.mayDragOut=function(){if(!this.isCopyEnabled)return!1;var a=this.diagram;if(!a.allowDragOut||!a.allowCopy||a.allowMove)return!1;for(a=a.selection.iterator;a.next();)if(a.value.canCopy())return!0;return null!==this.draggedLink&&this.dragsLink&&this.draggedLink.canCopy()?!0:!1}; Xe.prototype.mayMove=function(){var a=this.diagram;if(a.isReadOnly||!a.allowMove)return!1;for(a=a.selection.iterator;a.next();)if(a.value.canMove())return!0;return null!==this.draggedLink&&this.dragsLink&&this.draggedLink.canMove()?!0:!1};Xe.prototype.computeBorder=function(a,b,c){return this.Rn||null===this.draggedParts||this.draggedParts.contains(a)?null:c.assign(b)};Xe.prototype.lA=function(){return Ze}; Xe.prototype.mayDragIn=function(){var a=this.diagram;if(!a.allowDrop||a.isReadOnly||a.isModelReadOnly||!a.allowInsert)return!1;var b=Ze;return null===b||b.diagram.model.dataFormat!==a.model.dataFormat?!1:!0};Xe.prototype.doSimulatedDragEnter=function(){if(this.mayDragIn()){var a=this.diagram;a.animationManager.Cc();Jf(a);a.animationManager.Cc();var b=Ze;null!==b&&(b.diagram.mu=!1);this.doUpdateCursor(a.grid)}}; Xe.prototype.doSimulatedDragLeave=function(){var a=Ze;null!==a&&a.doSimulatedDragOut();this.doCancel()};Xe.prototype.doSimulatedDragOver=function(){var a=this.diagram;a.animationManager.rn=!0;var b=Ze;if(null!==b&&null!==b.draggedParts){if(!this.mayDragIn())return;Kf(this,b.draggedParts.Mf(),!1,a.firstInput);uf(this,this.copiedParts,!1);wf(this,a.lastInput.documentPoint)}a.animationManager.rn=!1}; Xe.prototype.doSimulatedDrop=function(){var a=this.diagram,b=Ze;if(null!==b){var c=b.diagram;b.Rn=!0;nf(this);if(!this.mayDragIn())return;a.animationManager.rn=!0;a.R("ChangingSelection",a.selection);this.xa("Drop");Kf(this,b.draggedParts.Mf(),!0,a.lastInput);uf(this,this.copiedParts,!1);null!==this.copiedParts&&(a.clearSelection(!0),this.copiedParts.iteratorKeys.each(function(a){a.isSelected=!0}));Cf(this,a.lastInput.documentPoint);a.Oa();b=a.selection;null!==this.copiedParts?this.transactionResult= "ExternalCopy":b=new G;this.copiedParts=null;a.doFocus();a.R("ExternalObjectsDropped",b,c);this.Kg();a.R("ChangedSelection",a.selection)}a.animationManager.rn=!1}; function Kf(a,b,c,d){if(null===a.copiedParts){var e=a.diagram;if(!e.isReadOnly&&!e.isModelReadOnly){e.skipsUndoManager=!c;e.partManager.addsToTemporaryLayer=!c;a.startPoint=d.documentPoint;c=e.tk(b,e,!0);var f=N.alloc();e=d=Infinity;for(var g=-Infinity,h=-Infinity,k=b.iterator;k.next();){var l=k.value;if(l.isVisible()){var m=l.location;l=m.x;m=m.y;isNaN(l)||isNaN(m)||(l<d&&(d=l),m<e&&(e=m),l>g&&(g=l),m>h&&(h=m))}}Infinity===d?f.h(0,0,0,0):f.h(d,e,g-d,h-e);d=f.x+f.width/2;e=f.y+f.height/2;N.free(f); f=a.it;g=new H;h=I.alloc();for(k=b.iterator;k.next();)l=k.value,l instanceof S&&l.canCopy()&&(m=c.H(l),null!==m&&(m.points=l.points,tf(m,f.x-d,f.y-e),m.suspendsRouting=!0,g.add(m,a.Cd())));for(b=b.iterator;b.next();)l=b.value,l.Pc()&&l.canCopy()&&(k=c.H(l),null!==k&&(l=l.location,h.h(f.x-(d-l.x),f.y-(e-l.y)),k.location=h,k.Ta(),g.add(k,a.Cd(h))));I.free(h);a.copiedParts=g;$e(a,g.Mf());null!==a.draggedLink&&(c=a.draggedLink,b=c.routeBounds,tf(c,a.startPoint.x-(b.x+b.width/2),a.startPoint.y-(b.y+b.height/ 2)))}}}Xe.prototype.doSimulatedDragOut=function(){var a=this.diagram;a.mu=!1;this.mayCopy()||this.mayMove()?a.currentCursor="":a.currentCursor=this.nodropCursor;this.Ao=null};Xe.prototype.computeMove=function(a,b,c,d){c=this.diagram;return null!==c?c.computeMove(a,b,this.dragOptions,d):new I}; na.Object.defineProperties(Xe.prototype,{isCopyEnabled:{get:function(){return this.Vc},set:function(a){this.Vc=a}},copiesEffectiveCollection:{get:function(){return this.I},set:function(a){this.I=a}},dragOptions:{get:function(){return this.Ka},set:function(a){this.Ka=a}},isGridSnapEnabled:{get:function(){return this.dragOptions.isGridSnapEnabled},set:function(a){this.dragOptions.isGridSnapEnabled= a}},isComplexRoutingRealtime:{get:function(){return this.Dc},set:function(a){this.Dc=a}},isGridSnapRealtime:{get:function(){return this.dragOptions.isGridSnapRealtime},set:function(a){this.dragOptions.isGridSnapRealtime=a}},gridSnapCellSize:{get:function(){return this.dragOptions.gridSnapCellSize},set:function(a){this.dragOptions.gridSnapCellSize.w(a)||(a=a.G(),this.dragOptions.gridSnapCellSize=a)}},gridSnapCellSpot:{ get:function(){return this.dragOptions.gridSnapCellSpot},set:function(a){this.dragOptions.gridSnapCellSpot.w(a)||(a=a.G(),this.dragOptions.gridSnapCellSpot=a)}},gridSnapOrigin:{get:function(){return this.dragOptions.gridSnapOrigin},set:function(a){this.dragOptions.gridSnapOrigin.w(a)||(a=a.G(),this.dragOptions.gridSnapOrigin=a)}},dragsLink:{get:function(){return this.dragOptions.dragsLink},set:function(a){this.dragOptions.dragsLink= a}},dragsTree:{get:function(){return this.dragOptions.dragsTree},set:function(a){this.dragOptions.dragsTree=a}},copyCursor:{get:function(){return this.T},set:function(a){this.T=a}},moveCursor:{get:function(){return this.Vh},set:function(a){this.Vh=a}},nodropCursor:{get:function(){return this.Wh},set:function(a){this.Wh=a}},currentPart:{get:function(){return this.Ja}, set:function(a){this.Ja=a}},copiedParts:{get:function(){return this.v},set:function(a){this.v=a}},draggedParts:{get:function(){return this.eb},set:function(a){this.eb=a}},draggingParts:{get:function(){return null!==this.copiedParts?this.copiedParts.Mf():null!==this.draggedParts?this.draggedParts.Mf():this.mr}},draggedLink:{get:function(){return this.diagram.draggedLink},set:function(a){this.diagram.draggedLink= a}},isDragOutStarted:{get:function(){return this.Od},set:function(a){this.Od=a}},startPoint:{get:function(){return this.it},set:function(a){this.it.w(a)||this.it.assign(a)}},delay:{get:function(){return this.pl},set:function(a){this.pl=a}}});Xe.prototype.getDraggingSource=Xe.prototype.lA;var lf=null,Ze=null,cf=null;Xe.className="DraggingTool";lf=new E; Na("draggingTool",function(){return this.findTool("Dragging")},function(a){this.Xa("Dragging",a,this.mouseMoveTools)});Pa.prototype.doCancel=function(){null!==Ze&&Ze.doCancel();Ge.prototype.doCancel.call(this)}; function Lf(){Ge.call(this);this.Wh=100;this.Ka=!1;this.ni="pointer";var a=new S,b=new Mf;b.isPanelMain=!0;b.stroke="blue";a.add(b);b=new Mf;b.toArrow="Standard";b.fill="blue";b.stroke="blue";a.add(b);a.layerName="Tool";this.hx=a;a=new W;b=new Mf;b.portId="";b.figure="Rectangle";b.fill=null;b.stroke="magenta";b.strokeWidth=2;b.desiredSize=Lb;a.add(b);a.selectable=!1;a.layerName="Tool";this.gx=a;this.l=b;a=new W;b=new Mf;b.portId="";b.figure="Rectangle";b.fill=null;b.stroke="magenta";b.strokeWidth= 2;b.desiredSize=Lb;a.add(b);a.selectable=!1;a.layerName="Tool";this.ix=a;this.v=b;this.Vh=this.Od=this.Dc=this.eb=this.Vc=null;this.Ja=!0;this.dz=new H;this.mr=this.Hi=this.ex=null}ma(Lf,Ge);Lf.prototype.doStop=function(){this.diagram.Lf();this.originalToPort=this.originalToNode=this.originalFromPort=this.originalFromNode=this.originalLink=null;this.validPortsCache.clear();this.targetPort=null}; Lf.prototype.copyPortProperties=function(a,b,c,d,e){if(null!==a&&null!==b&&null!==c&&null!==d){var f=b.Cf(),g=M.alloc();g.width=b.naturalBounds.width*f;g.height=b.naturalBounds.height*f;d.desiredSize=g;M.free(g);e?(d.toSpot=b.toSpot,d.toEndSegmentLength=b.toEndSegmentLength):(d.fromSpot=b.fromSpot,d.fromEndSegmentLength=b.fromEndSegmentLength);c.locationSpot=Bc;f=I.alloc();c.location=b.da(Bc,f);I.free(f);d.angle=b.lj();null!==this.portTargeted&&this.portTargeted(a,b,c,d,e)}}; Lf.prototype.setNoTargetPortProperties=function(a,b,c){null!==b&&(b.desiredSize=Lb,b.fromSpot=uc,b.toSpot=uc);null!==a&&(a.location=this.diagram.lastInput.documentPoint);null!==this.portTargeted&&this.portTargeted(null,null,a,b,c)};Lf.prototype.doMouseDown=function(){this.isActive&&this.doMouseMove()}; Lf.prototype.doMouseMove=function(){if(this.isActive){var a=this.diagram;this.targetPort=this.findTargetPort(this.isForwards);if(null!==this.targetPort&&this.targetPort.part instanceof W){var b=this.targetPort.part;this.isForwards?this.copyPortProperties(b,this.targetPort,this.temporaryToNode,this.temporaryToPort,!0):this.copyPortProperties(b,this.targetPort,this.temporaryFromNode,this.temporaryFromPort,!1)}else this.isForwards?this.setNoTargetPortProperties(this.temporaryToNode,this.temporaryToPort, !0):this.setNoTargetPortProperties(this.temporaryFromNode,this.temporaryFromPort,!1);(a.allowHorizontalScroll||a.allowVerticalScroll)&&a.Ft(a.lastInput.viewPoint)}};Lf.prototype.findValidLinkablePort=function(a,b){if(null===a)return null;var c=a.part;if(!(c instanceof W))return null;for(;null!==a;){var d=b?a.toLinkable:a.fromLinkable;if(!0===d&&(null!==a.portId||a instanceof W)&&(b?this.isValidTo(c,a):this.isValidFrom(c,a)))return a;if(!1===d)break;a=a.panel}return null}; Lf.prototype.findTargetPort=function(a){var b=this.diagram,c=b.lastInput.documentPoint,d=this.portGravity;0>=d&&(d=.1);var e=this,f=b.Fg(c,d,function(b){return e.findValidLinkablePort(b,a)},null,!0);d=Infinity;b=null;for(f=f.iterator;f.next();){var g=f.value,h=g.part;if(h instanceof W){var k=g.da(Bc,I.alloc()),l=c.x-k.x,m=c.y-k.y;I.free(k);k=l*l+m*m;k<d&&(l=this.validPortsCache.H(g),null!==l?l&&(b=g,d=k):a&&this.isValidLink(this.originalFromNode,this.originalFromPort,h,g)||!a&&this.isValidLink(h, g,this.originalToNode,this.originalToPort)?(this.validPortsCache.add(g,!0),b=g,d=k):this.validPortsCache.add(g,!1))}}return null!==b&&(c=b.part,c instanceof W&&(null===c.layer||c.layer.allowLink))?b:null}; Lf.prototype.isValidFrom=function(a,b){if(null===a||null===b)return this.isUnconnectedLinkValid;if(this.diagram.currentTool===this&&(null!==a.layer&&!a.layer.allowLink||!0!==b.fromLinkable))return!1;var c=b.fromMaxLinks;if(Infinity>c){if(null!==this.originalLink&&a===this.originalFromNode&&b===this.originalFromPort)return!0;b=b.portId;null===b&&(b="");if(a.Cq(b).count>=c)return!1}return!0}; Lf.prototype.isValidTo=function(a,b){if(null===a||null===b)return this.isUnconnectedLinkValid;if(this.diagram.currentTool===this&&(null!==a.layer&&!a.layer.allowLink||!0!==b.toLinkable))return!1;var c=b.toMaxLinks;if(Infinity>c){if(null!==this.originalLink&&a===this.originalToNode&&b===this.originalToPort)return!0;b=b.portId;null===b&&(b="");if(a.Hd(b).count>=c)return!1}return!0}; Lf.prototype.isInSameNode=function(a,b){if(null===a||null===b)return!1;if(a===b)return!0;a=a.part;b=b.part;return null!==a&&a===b};Lf.prototype.isLinked=function(a,b){if(null===a||null===b)return!1;var c=a.part;if(!(c instanceof W))return!1;a=a.portId;null===a&&(a="");var d=b.part;if(!(d instanceof W))return!1;b=b.portId;null===b&&(b="");for(b=d.Hd(b);b.next();)if(d=b.value,d.fromNode===c&&d.fromPortId===a)return!0;return!1}; Lf.prototype.isValidLink=function(a,b,c,d){if(!this.isValidFrom(a,b)||!this.isValidTo(c,d)||!(null===b||null===d||(b.fromLinkableSelfNode&&d.toLinkableSelfNode||!this.isInSameNode(b,d))&&(b.fromLinkableDuplicates&&d.toLinkableDuplicates||!this.isLinked(b,d)))||null!==this.originalLink&&(null!==a&&this.isLabelDependentOnLink(a,this.originalLink)||null!==c&&this.isLabelDependentOnLink(c,this.originalLink))||null!==a&&null!==c&&(null===a.data&&null!==c.data||null!==a.data&&null===c.data)||!this.isValidCycle(a, c,this.originalLink))return!1;if(null!==a){var e=a.linkValidation;if(null!==e&&!e(a,b,c,d,this.originalLink))return!1}if(null!==c&&(e=c.linkValidation,null!==e&&!e(a,b,c,d,this.originalLink)))return!1;e=this.linkValidation;return null!==e?e(a,b,c,d,this.originalLink):!0};Lf.prototype.isLabelDependentOnLink=function(a,b){if(null===a)return!1;var c=a.labeledLink;if(null===c)return!1;if(c===b)return!0;var d=new G;d.add(a);return Nf(this,c,b,d)}; function Nf(a,b,c,d){if(b===c)return!0;var e=b.fromNode;if(null!==e&&e.isLinkLabel&&(d.add(e),Nf(a,e.labeledLink,c,d)))return!0;b=b.toNode;return null!==b&&b.isLinkLabel&&(d.add(b),Nf(a,b.labeledLink,c,d))?!0:!1} Lf.prototype.isValidCycle=function(a,b,c){void 0===c&&(c=null);if(null===a||null===b)return this.isUnconnectedLinkValid;var d=this.diagram.validCycle;if(d!==Of){if(d===Pf){d=c||this.temporaryLink;if(null!==d&&!d.isTreeLink)return!0;for(d=b.linksConnected;d.next();){var e=d.value;if(e!==c&&e.isTreeLink&&e.toNode===b)return!1}return!Qf(this,a,b,c,!0)}if(d===Rf){d=c||this.temporaryLink;if(null!==d&&!d.isTreeLink)return!0;for(d=a.linksConnected;d.next();)if(e=d.value,e!==c&&e.isTreeLink&&e.fromNode=== a)return!1;return!Qf(this,a,b,c,!0)}if(d===Sf)return a===b?a=!0:(d=new G,d.add(b),a=Tf(this,d,a,b,c)),!a;if(d===Uf)return!Qf(this,a,b,c,!1);if(d===Vf)return a===b?a=!0:(d=new G,d.add(b),a=Wf(this,d,a,b,c)),!a}return!0};function Qf(a,b,c,d,e){if(b===c)return!0;if(null===b||null===c)return!1;for(var f=b.linksConnected;f.next();){var g=f.value;if(g!==d&&(!e||g.isTreeLink)&&g.toNode===b&&(g=g.fromNode,g!==b&&Qf(a,g,c,d,e)))return!0}return!1} function Tf(a,b,c,d,e){if(c===d)return!0;if(null===c||null===d||b.contains(c))return!1;b.add(c);for(var f=c.linksConnected;f.next();){var g=f.value;if(g!==e&&g.toNode===c&&(g=g.fromNode,g!==c&&Tf(a,b,g,d,e)))return!0}return!1}function Wf(a,b,c,d,e){if(c===d)return!0;if(null===c||null===d||b.contains(c))return!1;b.add(c);for(var f=c.linksConnected;f.next();){var g=f.value;if(g!==e){var h=g.fromNode;g=g.toNode;h=h===c?g:h;if(h!==c&&Wf(a,b,h,d,e))return!0}}return!1} na.Object.defineProperties(Lf.prototype,{portGravity:{get:function(){return this.Wh},set:function(a){0<=a&&(this.Wh=a)}},isUnconnectedLinkValid:{get:function(){return this.Ka},set:function(a){this.Ka=a}},linkingCursor:{get:function(){return this.ni},set:function(a){this.ni=a}},temporaryLink:{get:function(){return this.hx},set:function(a){this.hx=a}},temporaryFromNode:{ get:function(){return this.gx},set:function(a){if(this.gx=a)this.l=a.port}},temporaryFromPort:{get:function(){return this.l},set:function(a){if(null!==this.l){var b=this.l.panel;if(null!==b){var c=b.W.indexOf(this.l);b.cb(c);b.wb(c,a)}}this.l=a}},temporaryToNode:{get:function(){return this.ix},set:function(a){if(this.ix=a)this.v=a.port}},temporaryToPort:{get:function(){return this.v},set:function(a){if(null!== this.v){var b=this.v.panel;if(null!==b){var c=b.W.indexOf(this.v);b.cb(c);b.wb(c,a)}}this.v=a}},originalLink:{get:function(){return this.Vc},set:function(a){this.Vc=a}},originalFromNode:{get:function(){return this.eb},set:function(a){this.eb=a}},originalFromPort:{get:function(){return this.Dc},set:function(a){this.Dc=a}},originalToNode:{get:function(){return this.Od},set:function(a){this.Od= a}},originalToPort:{get:function(){return this.Vh},set:function(a){this.Vh=a}},isForwards:{get:function(){return this.Ja},set:function(a){this.Ja=a}},validPortsCache:{get:function(){return this.dz}},targetPort:{get:function(){return this.ex},set:function(a){this.ex=a}},linkValidation:{get:function(){return this.Hi},set:function(a){this.Hi=a}},portTargeted:{ get:function(){return this.mr},set:function(a){this.mr=a}}});Lf.className="LinkingBaseTool";function Xf(){Lf.call(this);this.name="Linking";this.T={};this.I=null;this.K=Yf;this.cn=null}ma(Xf,Lf);Xf.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return a.isReadOnly||a.isModelReadOnly||!a.allowLink||!a.model.Vt()||!a.lastInput.left||a.currentTool!==this&&!this.isBeyondDragSize()?!1:null!==this.findLinkablePort()}; Xf.prototype.findLinkablePort=function(){var a=this.diagram,b=this.startObject;null===b&&(b=a.Vb(a.firstInput.documentPoint,null,null));if(null===b)return null;a=b.part;if(!(a instanceof W))return null;var c=this.direction;if(c===Yf||c===Zf){var d=this.findValidLinkablePort(b,!1);if(null!==d||this.startObject===a&&(d=a.port,this.findValidLinkablePort(d,!1)))return this.isForwards=!0,d}if(c===Yf||c===$f)if(b=this.findValidLinkablePort(b,!0),null!==b||this.startObject===a&&(b=a.port,this.findValidLinkablePort(b, !0)))return this.isForwards=!1,b;return null}; Xf.prototype.doActivate=function(){var a=this.diagram,b=this.findLinkablePort();null===b?this.stopTool():(this.xa(this.name),a.isMouseCaptured=!0,a.currentCursor=this.linkingCursor,this.isForwards?(null===this.temporaryToNode||this.temporaryToNode.location.s()||(this.temporaryToNode.location=a.lastInput.documentPoint),this.originalFromPort=b,b=this.originalFromPort.part,b instanceof W&&(this.originalFromNode=b),this.copyPortProperties(this.originalFromNode,this.originalFromPort,this.temporaryFromNode, this.temporaryFromPort,!1)):(null===this.temporaryFromNode||this.temporaryFromNode.location.s()||(this.temporaryFromNode.location=a.lastInput.documentPoint),this.originalToPort=b,b=this.originalToPort.part,b instanceof W&&(this.originalToNode=b),this.copyPortProperties(this.originalToNode,this.originalToPort,this.temporaryToNode,this.temporaryToPort,!0)),a.add(this.temporaryFromNode),a.add(this.temporaryToNode),null!==this.temporaryLink&&(null!==this.temporaryFromNode&&(this.temporaryLink.fromNode= this.temporaryFromNode),null!==this.temporaryToNode&&(this.temporaryLink.toNode=this.temporaryToNode),this.temporaryLink.isTreeLink=this.isNewTreeLink(),this.temporaryLink.Ua(),a.add(this.temporaryLink)),this.isActive=!0)};Xf.prototype.doDeactivate=function(){this.isActive=!1;var a=this.diagram;a.remove(this.temporaryLink);a.remove(this.temporaryFromNode);a.remove(this.temporaryToNode);a.isMouseCaptured=!1;a.currentCursor="";this.Kg()}; Xf.prototype.doStop=function(){Lf.prototype.doStop.call(this);this.startObject=null}; Xf.prototype.doMouseUp=function(){var a=this.diagram;if(this.isActive){var b=this.transactionResult=null,c=null,d=null,e=null,f=null;try{var g=this.targetPort=this.findTargetPort(this.isForwards);if(null!==g){var h=g.part;h instanceof W&&(this.isForwards?(null!==this.originalFromNode&&(b=this.originalFromNode,c=this.originalFromPort),d=h,e=g):(b=h,c=g,null!==this.originalToNode&&(d=this.originalToNode,e=this.originalToPort)))}else this.isForwards?null!==this.originalFromNode&&this.isUnconnectedLinkValid&& (b=this.originalFromNode,c=this.originalFromPort):null!==this.originalToNode&&this.isUnconnectedLinkValid&&(d=this.originalToNode,e=this.originalToPort);null!==b||null!==d?(f=this.insertLink(b,c,d,e),null!==f?(null===g&&(this.isForwards?f.defaultToPoint=a.lastInput.documentPoint.copy():f.defaultFromPoint=a.lastInput.documentPoint.copy()),a.allowSelect&&(a.R("ChangingSelection",a.selection),a.clearSelection(!0),f.isSelected=!0),this.transactionResult=this.name,a.R("LinkDrawn",f)):this.doNoLink(b,c, d,e)):this.isForwards?this.doNoLink(this.originalFromNode,this.originalFromPort,null,null):this.doNoLink(null,null,this.originalToNode,this.originalToPort)}finally{this.stopTool(),f&&a.allowSelect&&a.R("ChangedSelection",a.selection)}}}; Xf.prototype.isNewTreeLink=function(){var a=this.archetypeLinkData;if(null===a)return!0;if(a instanceof S)return a.isTreeLink;var b=this.diagram;if(null===b)return!0;a=b.partManager.getLinkCategoryForData(a);b=b.partManager.findLinkTemplateForCategory(a);return null!==b?b.isTreeLink:!0};Xf.prototype.insertLink=function(a,b,c,d){return this.diagram.partManager.insertLink(a,b,c,d)};Xf.prototype.doNoLink=function(){}; na.Object.defineProperties(Xf.prototype,{archetypeLinkData:{get:function(){return this.T},set:function(a){this.T=a}},archetypeLabelNodeData:{get:function(){return this.I},set:function(a){this.I=a}},direction:{get:function(){return this.K},set:function(a){this.K=a}},startObject:{get:function(){return this.cn},set:function(a){this.cn=a}}}); var Yf=new D(Xf,"Either",0),Zf=new D(Xf,"ForwardsOnly",0),$f=new D(Xf,"BackwardsOnly",0);Xf.className="LinkingTool";Xf.Either=Yf;Xf.ForwardsOnly=Zf;Xf.BackwardsOnly=$f; function df(){Lf.call(this);this.name="Relinking";var a=new Mf;a.figure="Diamond";a.desiredSize=Nb;a.fill="lightblue";a.stroke="dodgerblue";a.cursor=this.linkingCursor;a.segmentIndex=0;this.T=a;a=new Mf;a.figure="Diamond";a.desiredSize=Nb;a.fill="lightblue";a.stroke="dodgerblue";a.cursor=this.linkingCursor;a.segmentIndex=-1;this.cn=a;this.I=null;this.Ix=new N}ma(df,Lf); df.prototype.updateAdornments=function(a){if(null!==a&&a instanceof S){var b="RelinkFrom",c=null;if(a.isSelected&&!this.diagram.isReadOnly){var d=a.selectionObject;null!==d&&a.canRelinkFrom()&&a.actualBounds.s()&&a.isVisible()&&d.actualBounds.s()&&d.If()&&(c=a.wk(b),null===c&&(c=this.makeAdornment(d,!1),a.Fh(b,c)))}null===c&&a.Jf(b);b="RelinkTo";c=null;a.isSelected&&!this.diagram.isReadOnly&&(d=a.selectionObject,null!==d&&a.canRelinkTo()&&a.actualBounds.s()&&a.isVisible()&&d.actualBounds.s()&&d.If()&& (c=a.wk(b),null===c?(c=this.makeAdornment(d,!0),a.Fh(b,c)):c.o()));null===c&&a.Jf(b)}};df.prototype.makeAdornment=function(a,b){var c=new Qe;c.type=X.Link;b=b?this.toHandleArchetype:this.fromHandleArchetype;null!==b&&c.add(b.copy());c.adornedObject=a;return c}; df.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowRelink||!a.model.Vt()||!a.lastInput.left)return!1;var b=this.findToolHandleAt(a.firstInput.documentPoint,"RelinkFrom");null===b&&(b=this.findToolHandleAt(a.firstInput.documentPoint,"RelinkTo"));return null!==b}; df.prototype.doActivate=function(){var a=this.diagram;if(null===this.originalLink){var b=this.handle;null===b&&(b=this.findToolHandleAt(a.firstInput.documentPoint,"RelinkFrom"),null===b&&(b=this.findToolHandleAt(a.firstInput.documentPoint,"RelinkTo")));if(null===b)return;var c=b.part;if(!(c instanceof Qe&&c.adornedPart instanceof S))return;this.handle=b;this.isForwards=null===c||"RelinkTo"===c.category;this.originalLink=c.adornedPart}this.xa(this.name);a.isMouseCaptured=!0;a.currentCursor=this.linkingCursor; this.originalFromPort=this.originalLink.fromPort;this.originalFromNode=this.originalLink.fromNode;this.originalToPort=this.originalLink.toPort;this.originalToNode=this.originalLink.toNode;this.Ix.set(this.originalLink.actualBounds);null!==this.originalLink&&0<this.originalLink.pointsCount&&(null===this.originalLink.fromNode&&(null!==this.temporaryFromPort&&(this.temporaryFromPort.desiredSize=Kb),null!==this.temporaryFromNode&&(this.temporaryFromNode.location=this.originalLink.i(0))),null===this.originalLink.toNode&& (null!==this.temporaryToPort&&(this.temporaryToPort.desiredSize=Kb),null!==this.temporaryToNode&&(this.temporaryToNode.location=this.originalLink.i(this.originalLink.pointsCount-1))));this.copyPortProperties(this.originalFromNode,this.originalFromPort,this.temporaryFromNode,this.temporaryFromPort,!1);this.copyPortProperties(this.originalToNode,this.originalToPort,this.temporaryToNode,this.temporaryToPort,!0);a.add(this.temporaryFromNode);a.add(this.temporaryToNode);null!==this.temporaryLink&&(null!== this.temporaryFromNode&&(this.temporaryLink.fromNode=this.temporaryFromNode),null!==this.temporaryToNode&&(this.temporaryLink.toNode=this.temporaryToNode),this.copyLinkProperties(this.originalLink,this.temporaryLink),this.temporaryLink.Ua(),a.add(this.temporaryLink));this.isActive=!0}; df.prototype.copyLinkProperties=function(a,b){if(null!==a&&null!==b){b.adjusting=a.adjusting;b.corner=a.corner;var c=a.curve;if(c===ag||c===bg)c=cg;b.curve=c;b.curviness=a.curviness;b.isTreeLink=a.isTreeLink;b.points=a.points;b.routing=a.routing;b.smoothness=a.smoothness;b.fromSpot=a.fromSpot;b.fromEndSegmentLength=a.fromEndSegmentLength;b.fromShortLength=a.fromShortLength;b.toSpot=a.toSpot;b.toEndSegmentLength=a.toEndSegmentLength;b.toShortLength=a.toShortLength}}; df.prototype.doDeactivate=function(){this.isActive=!1;var a=this.diagram;a.remove(this.temporaryLink);a.remove(this.temporaryFromNode);a.remove(this.temporaryToNode);a.isMouseCaptured=!1;a.currentCursor="";this.Kg()};df.prototype.doStop=function(){Lf.prototype.doStop.call(this);this.handle=null}; df.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram;this.transactionResult=null;var b=this.originalFromNode,c=this.originalFromPort,d=this.originalToNode,e=this.originalToPort,f=this.originalLink;this.targetPort=this.findTargetPort(this.isForwards);if(null!==this.targetPort){var g=this.targetPort.part;g instanceof W&&(this.isForwards?(d=g,e=this.targetPort):(b=g,c=this.targetPort))}else this.isUnconnectedLinkValid?this.isForwards?e=d=null:c=b=null:f=null;null!==f?(this.reconnectLink(f, this.isForwards?d:b,this.isForwards?e:c,this.isForwards),null===this.targetPort&&(this.isForwards?f.defaultToPoint=a.lastInput.documentPoint.copy():f.defaultFromPoint=a.lastInput.documentPoint.copy(),f.Ua()),a.allowSelect&&(f.isSelected=!0),this.transactionResult=this.name,a.R("LinkRelinked",f,this.isForwards?this.originalToPort:this.originalFromPort)):this.doNoRelink(this.originalLink,this.isForwards);this.originalLink.Mq(this.Ix)}this.stopTool()}; df.prototype.reconnectLink=function(a,b,c,d){c=null!==c&&null!==c.portId?c.portId:"";d?(a.toNode=b,a.toPortId=c):(a.fromNode=b,a.fromPortId=c);return!0};df.prototype.doNoRelink=function(){}; function Bf(a,b,c,d,e){null!==b?(a.copyPortProperties(b,c,a.temporaryFromNode,a.temporaryFromPort,!1),a.diagram.add(a.temporaryFromNode)):a.diagram.remove(a.temporaryFromNode);null!==d?(a.copyPortProperties(d,e,a.temporaryToNode,a.temporaryToPort,!0),a.diagram.add(a.temporaryToNode)):a.diagram.remove(a.temporaryToNode)} na.Object.defineProperties(df.prototype,{fromHandleArchetype:{get:function(){return this.T},set:function(a){this.T=a}},toHandleArchetype:{get:function(){return this.cn},set:function(a){this.cn=a}},handle:{get:function(){return this.I},set:function(a){if(null!==a&&!(a.part instanceof Qe))throw Error("new handle is not in an Adornment: "+a);this.I=a}}});df.className="RelinkingTool"; Na("linkingTool",function(){return this.findTool("Linking")},function(a){this.Xa("Linking",a,this.mouseMoveTools)});Na("relinkingTool",function(){return this.findTool("Relinking")},function(a){this.Xa("Relinking",a,this.mouseDownTools)}); function dg(){Ge.call(this);this.name="LinkReshaping";var a=new Mf;a.figure="Rectangle";a.desiredSize=Mb;a.fill="lightblue";a.stroke="dodgerblue";this.v=a;a=new Mf;a.figure="Diamond";a.desiredSize=Nb;a.fill="lightblue";a.stroke="dodgerblue";a.cursor="move";this.I=a;this.T=3;this.vu=this.l=null;this.Jx=new I;this.Js=new E}ma(dg,Ge);dg.prototype.Yv=function(a){return a&&a.Qs&&0!==a.Qs.value?a.Qs:rg};dg.prototype.Wm=function(a,b){a.Qs=b}; dg.prototype.updateAdornments=function(a){if(null!==a&&a instanceof S){var b=null;if(a.isSelected&&!this.diagram.isReadOnly){var c=a.path;null!==c&&a.canReshape()&&a.actualBounds.s()&&a.isVisible()&&c.actualBounds.s()&&c.If()&&(b=a.wk(this.name),null===b||b.Fx!==a.pointsCount||b.Tx!==a.resegmentable)&&(b=this.makeAdornment(c),null!==b&&(b.Fx=a.pointsCount,b.Tx=a.resegmentable,a.Fh(this.name,b)))}null===b&&a.Jf(this.name)}}; dg.prototype.makeAdornment=function(a){var b=a.part,c=b.pointsCount,d=b.isOrthogonal,e=null;if(null!==b.points&&1<c){e=new Qe;e.type=X.Link;c=b.firstPickIndex;var f=b.lastPickIndex,g=d?1:0;if(b.resegmentable&&b.computeCurve()!==sg)for(var h=c+g;h<f-g;h++){var k=this.makeResegmentHandle(a,h);null!==k&&(k.segmentIndex=h,k.segmentFraction=.5,k.fromMaxLinks=999,e.add(k))}for(g=c+1;g<f;g++)if(h=this.makeHandle(a,g),null!==h){h.segmentIndex=g;if(g!==c)if(g===c+1&&d){k=b.i(c);var l=b.i(c+1);L.A(k.x,l.x)&& L.A(k.y,l.y)&&(l=b.i(c-1));L.A(k.x,l.x)?(this.Wm(h,tg),h.cursor="n-resize"):L.A(k.y,l.y)&&(this.Wm(h,ug),h.cursor="w-resize")}else g===f-1&&d?(k=b.i(f-1),l=b.i(f),L.A(k.x,l.x)&&L.A(k.y,l.y)&&(k=b.i(f+1)),L.A(k.x,l.x)?(this.Wm(h,tg),h.cursor="n-resize"):L.A(k.y,l.y)&&(this.Wm(h,ug),h.cursor="w-resize")):g!==f&&(this.Wm(h,vg),h.cursor="move");e.add(h)}e.adornedObject=a}return e};dg.prototype.makeHandle=function(){var a=this.handleArchetype;return null===a?null:a.copy()}; dg.prototype.makeResegmentHandle=function(){var a=this.midHandleArchetype;return null===a?null:a.copy()};dg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return!a.isReadOnly&&a.allowReshape&&a.lastInput.left?null!==this.findToolHandleAt(a.firstInput.documentPoint,this.name):!1}; dg.prototype.doActivate=function(){var a=this.diagram;null===this.handle&&(this.handle=this.findToolHandleAt(a.firstInput.documentPoint,this.name));if(null!==this.handle){var b=this.handle.part.adornedPart;if(b instanceof S){this.vu=b;a.isMouseCaptured=!0;this.xa(this.name);if(b.resegmentable&&999===this.handle.fromMaxLinks){var c=b.points.copy(),d=this.getResegmentingPoint();c.wb(this.handle.segmentIndex+1,d);b.isOrthogonal&&c.wb(this.handle.segmentIndex+1,d);b.points=c;b.Mb();b.updateAdornments(); this.handle=this.findToolHandleAt(a.firstInput.documentPoint,this.name);if(null===this.handle){this.doDeactivate();return}}this.Jx=b.i(this.handle.segmentIndex);this.Js=b.points.copy();this.isActive=!0}}};dg.prototype.doDeactivate=function(){this.Kg();this.vu=this.handle=null;this.isActive=this.diagram.isMouseCaptured=!1};dg.prototype.doCancel=function(){var a=this.adornedLink;null!==a&&(a.points=this.Js);this.stopTool()};dg.prototype.getResegmentingPoint=function(){return this.handle.da(Bc)}; dg.prototype.doMouseMove=function(){var a=this.diagram;this.isActive&&(a=this.computeReshape(a.lastInput.documentPoint),this.reshape(a))}; dg.prototype.doMouseUp=function(){var a=this.diagram;if(this.isActive){var b=this.computeReshape(a.lastInput.documentPoint);this.reshape(b);b=this.adornedLink;if(null!==b&&b.resegmentable){var c=this.handle.segmentIndex,d=b.i(c-1),e=b.i(c),f=b.i(c+1);if(b.isOrthogonal){if(c>b.firstPickIndex+1&&c<b.lastPickIndex-1){var g=b.i(c-2);if(Math.abs(d.x-e.x)<this.resegmentingDistance&&Math.abs(d.y-e.y)<this.resegmentingDistance&&(wg(this,g,d,e,f,!0)||wg(this,g,d,e,f,!1))){var h=b.points.copy();wg(this,g,d, e,f,!0)?(h.Rc(c-2,new I(g.x,(f.y+g.y)/2)),h.Rc(c+1,new I(f.x,(f.y+g.y)/2))):(h.Rc(c-2,new I((f.x+g.x)/2,g.y)),h.Rc(c+1,new I((f.x+g.x)/2,f.y)));h.cb(c);h.cb(c-1);b.points=h;b.Mb()}else g=b.i(c+2),Math.abs(e.x-f.x)<this.resegmentingDistance&&Math.abs(e.y-f.y)<this.resegmentingDistance&&(wg(this,d,e,f,g,!0)||wg(this,d,e,f,g,!1))&&(h=b.points.copy(),wg(this,d,e,f,g,!0)?(h.Rc(c-1,new I(d.x,(d.y+g.y)/2)),h.Rc(c+2,new I(g.x,(d.y+g.y)/2))):(h.Rc(c-1,new I((d.x+g.x)/2,d.y)),h.Rc(c+2,new I((d.x+g.x)/2,g.y))), h.cb(c+1),h.cb(c),b.points=h,b.Mb())}}else g=I.alloc(),L.Ph(d.x,d.y,f.x,f.y,e.x,e.y,g)&&g.Ie(e)<this.resegmentingDistance*this.resegmentingDistance&&(d=b.points.copy(),d.cb(c),b.points=d,b.Mb()),I.free(g)}a.Oa();this.transactionResult=this.name;a.R("LinkReshaped",this.adornedLink,this.Js)}this.stopTool()}; function wg(a,b,c,d,e,f){return f?Math.abs(b.y-c.y)<a.resegmentingDistance&&Math.abs(c.y-d.y)<a.resegmentingDistance&&Math.abs(d.y-e.y)<a.resegmentingDistance:Math.abs(b.x-c.x)<a.resegmentingDistance&&Math.abs(c.x-d.x)<a.resegmentingDistance&&Math.abs(d.x-e.x)<a.resegmentingDistance} dg.prototype.reshape=function(a){var b=this.adornedLink;b.Sh();var c=this.handle.segmentIndex,d=this.Yv(this.handle);if(b.isOrthogonal)if(c===b.firstPickIndex+1)c=b.firstPickIndex+1,d===tg?(b.L(c,b.i(c-1).x,a.y),b.L(c+1,b.i(c+2).x,a.y)):d===ug&&(b.L(c,a.x,b.i(c-1).y),b.L(c+1,a.x,b.i(c+2).y));else if(c===b.lastPickIndex-1)c=b.lastPickIndex-1,d===tg?(b.L(c-1,b.i(c-2).x,a.y),b.L(c,b.i(c+1).x,a.y)):d===ug&&(b.L(c-1,a.x,b.i(c-2).y),b.L(c,a.x,b.i(c+1).y));else{d=c;var e=b.i(d),f=b.i(d-1),g=b.i(d+1);L.A(f.x, e.x)&&L.A(e.y,g.y)?(L.A(f.x,b.i(d-2).x)&&!L.A(f.y,b.i(d-2).y)?(b.m(d,a.x,f.y),c++,d++):b.L(d-1,a.x,f.y),L.A(g.y,b.i(d+2).y)&&!L.A(g.x,b.i(d+2).x)?b.m(d+1,g.x,a.y):b.L(d+1,g.x,a.y)):L.A(f.y,e.y)&&L.A(e.x,g.x)?(L.A(f.y,b.i(d-2).y)&&!L.A(f.x,b.i(d-2).x)?(b.m(d,f.x,a.y),c++,d++):b.L(d-1,f.x,a.y),L.A(g.x,b.i(d+2).x)&&!L.A(g.y,b.i(d+2).y)?b.m(d+1,a.x,g.y):b.L(d+1,a.x,g.y)):L.A(f.x,e.x)&&L.A(e.x,g.x)?(L.A(f.x,b.i(d-2).x)&&!L.A(f.y,b.i(d-2).y)?(b.m(d,a.x,f.y),c++,d++):b.L(d-1,a.x,f.y),L.A(g.x,b.i(d+2).x)&& !L.A(g.y,b.i(d+2).y)?b.m(d+1,a.x,g.y):b.L(d+1,a.x,g.y)):L.A(f.y,e.y)&&L.A(e.y,g.y)&&(L.A(f.y,b.i(d-2).y)&&!L.A(f.x,b.i(d-2).x)?(b.m(d,f.x,a.y),c++,d++):b.L(d-1,f.x,a.y),L.A(g.y,b.i(d+2).y)&&!L.A(g.x,b.i(d+2).x)?b.m(d+1,g.x,a.y):b.L(d+1,g.x,a.y));b.L(c,a.x,a.y)}else b.L(c,a.x,a.y),d=b.fromNode,e=b.fromPort,null!==d&&(f=d.findVisibleNode(),null!==f&&f!==d&&(d=f,e=d.port)),1===c&&b.computeSpot(!0,e).nc()&&(f=e.da(Bc,I.alloc()),d=b.getLinkPointFromPoint(d,e,f,a,!0,I.alloc()),b.L(0,d.x,d.y),I.free(f), I.free(d)),d=b.toNode,e=b.toPort,null!==d&&(f=d.findVisibleNode(),null!==f&&f!==d&&(d=f,e=d.port)),c===b.pointsCount-2&&b.computeSpot(!1,e).nc()&&(c=e.da(Bc,I.alloc()),a=b.getLinkPointFromPoint(d,e,c,a,!1,I.alloc()),b.L(b.pointsCount-1,a.x,a.y),I.free(c),I.free(a));b.zf()};dg.prototype.computeReshape=function(a){var b=this.adornedLink,c=this.handle.segmentIndex;switch(this.Yv(this.handle)){case vg:return a;case tg:return new I(b.i(c).x,a.y);case ug:return new I(a.x,b.i(c).y);default:case rg:return b.i(c)}}; na.Object.defineProperties(dg.prototype,{handleArchetype:{get:function(){return this.v},set:function(a){this.v=a}},midHandleArchetype:{get:function(){return this.I},set:function(a){this.I=a}},handle:{get:function(){return this.l},set:function(a){if(null!==a&&!(a.part instanceof Qe))throw Error("new handle is not in an Adornment: "+a);this.l=a}},adornedLink:{get:function(){return this.vu}}, resegmentingDistance:{get:function(){return this.T},set:function(a){this.T=a}},originalPoint:{get:function(){return this.Jx}},originalPoints:{get:function(){return this.Js}}});dg.prototype.setReshapingBehavior=dg.prototype.Wm;dg.prototype.getReshapingBehavior=dg.prototype.Yv;var rg=new D(dg,"None",0),ug=new D(dg,"Horizontal",1),tg=new D(dg,"Vertical",2),vg=new D(dg,"All",3);dg.className="LinkReshapingTool"; dg.None=rg;dg.Horizontal=ug;dg.Vertical=tg;dg.All=vg;Na("linkReshapingTool",function(){return this.findTool("LinkReshaping")},function(a){this.Xa("LinkReshaping",a,this.mouseDownTools)}); function xg(){Ge.call(this);this.name="Resizing";this.hg=(new M(1,1)).freeze();this.gg=(new M(9999,9999)).freeze();this.Rg=(new M(NaN,NaN)).freeze();this.I=!1;this.T=!0;this.je=null;var a=new Mf;a.alignmentFocus=Bc;a.figure="Rectangle";a.desiredSize=Mb;a.fill="lightblue";a.stroke="dodgerblue";a.strokeWidth=1;a.cursor="pointer";this.v=a;this.l=null;this.Is=new I;this.Hx=new M;this.lp=new I;this.Mu=new M(0,0);this.Lu=new M(Infinity,Infinity);this.Ku=new M(1,1)}ma(xg,Ge); xg.prototype.updateAdornments=function(a){if(!(null===a||a instanceof S)){if(a.isSelected&&!this.diagram.isReadOnly){var b=a.resizeObject,c=a.wk(this.name);if(null!==b&&a.canResize()&&a.actualBounds.s()&&a.isVisible()&&b.actualBounds.s()&&b.If()){if(null===c||c.adornedObject!==b)c=this.makeAdornment(b);if(null!==c){b=b.lj();yg(a)&&this.updateResizeHandles(c,b);a.Fh(this.name,c);return}}}a.Jf(this.name)}}; xg.prototype.makeAdornment=function(a){var b=a.part.resizeAdornmentTemplate;if(null===b){b=new Qe;b.type=X.Spot;b.locationSpot=Bc;var c=new zg;c.isPanelMain=!0;b.add(c);b.add(this.makeHandle(a,vc));b.add(this.makeHandle(a,zc));b.add(this.makeHandle(a,Gc));b.add(this.makeHandle(a,Dc));b.add(this.makeHandle(a,dd));b.add(this.makeHandle(a,fd));b.add(this.makeHandle(a,gd));b.add(this.makeHandle(a,ed))}else if(Ag(b),b=b.copy(),null===b)return null;b.adornedObject=a;return b}; xg.prototype.makeHandle=function(a,b){a=this.handleArchetype;if(null===a)return null;a=a.copy();a.alignment=b;return a}; xg.prototype.updateResizeHandles=function(a,b){if(null!==a)if(!a.alignment.Nb()&&("pointer"===a.cursor||0<a.cursor.indexOf("resize")))a:{var c=a.alignment;c.nc()&&(c=Bc);if(0>=c.x)b=0>=c.y?b+225:1<=c.y?b+135:b+180;else if(1<=c.x)0>=c.y?b+=315:1<=c.y&&(b+=45);else if(0>=c.y)b+=270;else if(1<=c.y)b+=90;else break a;0>b?b+=360:360<=b&&(b-=360);a.cursor=22.5>b?"e-resize":67.5>b?"se-resize":112.5>b?"s-resize":157.5>b?"sw-resize":202.5>b?"w-resize":247.5>b?"nw-resize":292.5>b?"n-resize":337.5>b?"ne-resize": "e-resize"}else if(a instanceof X)for(a=a.elements;a.next();)this.updateResizeHandles(a.value,b)};xg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return!a.isReadOnly&&a.allowResize&&a.lastInput.left?null!==this.findToolHandleAt(a.firstInput.documentPoint,this.name):!1}; xg.prototype.doActivate=function(){var a=this.diagram;null===this.handle&&(this.handle=this.findToolHandleAt(a.firstInput.documentPoint,this.name));null!==this.handle&&(this.adornedObject=this.handle.part.adornedObject,null!==this.adornedObject&&(a.isMouseCaptured=!0,a.animationManager.Cc(),this.xa(this.name),this.Is.set(this.adornedObject.da(this.handle.alignment.lw())),this.lp.set(this.adornedObject.part.location),this.Hx.set(this.adornedObject.desiredSize),this.Ku=this.computeCellSize(),this.Mu= this.computeMinSize(),this.Lu=this.computeMaxSize(),this.isActive=!0))};xg.prototype.doDeactivate=function(){var a=this.diagram;this.Kg();this.je=this.handle=null;this.isActive=a.isMouseCaptured=!1};xg.prototype.doCancel=function(){null!==this.adornedObject&&(this.adornedObject.desiredSize=this.originalDesiredSize,this.adornedObject.part.location=this.originalLocation);this.stopTool()}; xg.prototype.doMouseMove=function(){var a=this.diagram;if(this.isActive){var b=this.Mu,c=this.Lu,d=this.Ku,e=this.adornedObject.Nt(a.lastInput.documentPoint,I.alloc()),f=this.computeReshape();b=this.computeResize(e,this.handle.alignment,b,c,d,f);this.resize(b);a.jd();I.free(e)}}; xg.prototype.doMouseUp=function(){var a=this.diagram;if(this.isActive){var b=this.Mu,c=this.Lu,d=this.Ku,e=this.adornedObject.Nt(a.lastInput.documentPoint,I.alloc()),f=this.computeReshape();b=this.computeResize(e,this.handle.alignment,b,c,d,f);this.resize(b);I.free(e);a.Oa();this.transactionResult=this.name;a.R("PartResized",this.adornedObject,this.originalDesiredSize)}this.stopTool()}; xg.prototype.resize=function(a){var b=this.diagram,c=this.adornedObject;if(null!==c){c.desiredSize=a.size;a=c.part;a.Ta();c=c.da(this.handle.alignment.lw());if(a instanceof U){var d=new E;d.add(a);if(!this.dragsMembers&&null===a.placeholder){var e=new Ye;e.dragsMembers=!1}b.moveParts(d,this.oppositePoint.copy().he(c),!0,e)}else a.location=a.location.copy().he(c).add(this.oppositePoint);b.jd()}}; xg.prototype.computeResize=function(a,b,c,d,e,f){b.nc()&&(b=Bc);var g=this.adornedObject.naturalBounds,h=g.x,k=g.y,l=g.x+g.width,m=g.y+g.height,n=1;if(!f){n=g.width;var p=g.height;0>=n&&(n=1);0>=p&&(p=1);n=p/n}p=I.alloc();L.Dq(a.x,a.y,h,k,e.width,e.height,p);a=g.copy();0>=b.x?0>=b.y?(a.x=Math.max(p.x,l-d.width),a.x=Math.min(a.x,l-c.width),a.width=Math.max(l-a.x,c.width),a.y=Math.max(p.y,m-d.height),a.y=Math.min(a.y,m-c.height),a.height=Math.max(m-a.y,c.height),f||(1<=a.height/a.width?(a.height=Math.max(Math.min(n* a.width,d.height),c.height),a.width=a.height/n):(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width),a.x=l-a.width,a.y=m-a.height)):1<=b.y?(a.x=Math.max(p.x,l-d.width),a.x=Math.min(a.x,l-c.width),a.width=Math.max(l-a.x,c.width),a.height=Math.max(Math.min(p.y-k,d.height),c.height),f||(1<=a.height/a.width?(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n):(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width),a.x=l-a.width)):(a.x= Math.max(p.x,l-d.width),a.x=Math.min(a.x,l-c.width),a.width=l-a.x,f||(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n,a.y=k+.5*(m-k-a.height))):1<=b.x?0>=b.y?(a.width=Math.max(Math.min(p.x-h,d.width),c.width),a.y=Math.max(p.y,m-d.height),a.y=Math.min(a.y,m-c.height),a.height=Math.max(m-a.y,c.height),f||(1<=a.height/a.width?(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n):(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width), a.y=m-a.height)):1<=b.y?(a.width=Math.max(Math.min(p.x-h,d.width),c.width),a.height=Math.max(Math.min(p.y-k,d.height),c.height),f||(1<=a.height/a.width?(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n):(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width))):(a.width=Math.max(Math.min(p.x-h,d.width),c.width),f||(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n,a.y=k+.5*(m-k-a.height))):0>=b.y?(a.y=Math.max(p.y,m-d.height), a.y=Math.min(a.y,m-c.height),a.height=m-a.y,f||(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width,a.x=h+.5*(l-h-a.width))):1<=b.y&&(a.height=Math.max(Math.min(p.y-k,d.height),c.height),f||(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width,a.x=h+.5*(l-h-a.width)));I.free(p);return a};xg.prototype.computeReshape=function(){var a=Bg;this.adornedObject instanceof Mf&&(a=Cg(this.adornedObject));return!(a===Dg||this.diagram.lastInput.shift)}; xg.prototype.computeMinSize=function(){var a=this.adornedObject.minSize.copy(),b=this.minSize;!isNaN(b.width)&&b.width>a.width&&(a.width=b.width);!isNaN(b.height)&&b.height>a.height&&(a.height=b.height);return a};xg.prototype.computeMaxSize=function(){var a=this.adornedObject.maxSize.copy(),b=this.maxSize;!isNaN(b.width)&&b.width<a.width&&(a.width=b.width);!isNaN(b.height)&&b.height<a.height&&(a.height=b.height);return a}; xg.prototype.computeCellSize=function(){var a=new M(NaN,NaN),b=this.adornedObject.part;null!==b&&(b=b.resizeCellSize,!isNaN(b.width)&&0<b.width&&(a.width=b.width),!isNaN(b.height)&&0<b.height&&(a.height=b.height));b=this.cellSize;isNaN(a.width)&&!isNaN(b.width)&&0<b.width&&(a.width=b.width);isNaN(a.height)&&!isNaN(b.height)&&0<b.height&&(a.height=b.height);b=this.diagram;(isNaN(a.width)||isNaN(a.height))&&b&&(b=b.grid,null!==b&&b.visible&&this.isGridSnapEnabled&&(b=b.gridCellSize,isNaN(a.width)&& !isNaN(b.width)&&0<b.width&&(a.width=b.width),isNaN(a.height)&&!isNaN(b.height)&&0<b.height&&(a.height=b.height)));if(isNaN(a.width)||0===a.width||Infinity===a.width)a.width=1;if(isNaN(a.height)||0===a.height||Infinity===a.height)a.height=1;return a}; na.Object.defineProperties(xg.prototype,{handleArchetype:{get:function(){return this.v},set:function(a){this.v=a}},handle:{get:function(){return this.l},set:function(a){if(null!==a&&!(a.part instanceof Qe))throw Error("new handle is not in an Adornment: "+a);this.l=a}},adornedObject:{get:function(){return this.je},set:function(a){if(null!==a&&a.part instanceof Qe)throw Error("new handle must not be in an Adornment: "+ a);this.je=a}},minSize:{get:function(){return this.hg},set:function(a){if(!this.hg.w(a)){var b=a.width;isNaN(b)&&(b=0);a=a.height;isNaN(a)&&(a=0);this.hg.h(b,a)}}},maxSize:{get:function(){return this.gg},set:function(a){if(!this.gg.w(a)){var b=a.width;isNaN(b)&&(b=Infinity);a=a.height;isNaN(a)&&(a=Infinity);this.gg.h(b,a)}}},cellSize:{get:function(){return this.Rg},set:function(a){this.Rg.w(a)||this.Rg.assign(a)}}, isGridSnapEnabled:{get:function(){return this.I},set:function(a){this.I=a}},dragsMembers:{get:function(){return this.T},set:function(a){this.T=a}},oppositePoint:{get:function(){return this.Is},set:function(a){this.Is.w(a)||this.Is.assign(a)}},originalDesiredSize:{get:function(){return this.Hx}},originalLocation:{get:function(){return this.lp}}}); xg.className="ResizingTool";Na("resizingTool",function(){return this.findTool("Resizing")},function(a){this.Xa("Resizing",a,this.mouseDownTools)});function Eg(){Ge.call(this);this.name="Rotating";this.Ka=45;this.Ja=2;this.lp=new I;this.je=null;var a=new Mf;a.figure="Ellipse";a.desiredSize=Nb;a.fill="lightblue";a.stroke="dodgerblue";a.strokeWidth=1;a.cursor="pointer";this.v=a;this.l=null;this.Gx=0;this.Rs=new I(NaN,NaN);this.I=0;this.T=50}ma(Eg,Ge); Eg.prototype.updateAdornments=function(a){if(null!==a){if(a.Oh()){var b=a.rotateObject;if(b===a||b===a.path||b.isPanelMain)return}if(a.isSelected&&!this.diagram.isReadOnly&&(b=a.rotateObject,null!==b&&a.canRotate()&&a.actualBounds.s()&&a.isVisible()&&b.actualBounds.s()&&b.If())){var c=a.wk(this.name);if(null===c||c.adornedObject!==b)c=this.makeAdornment(b);if(null!==c){c.angle=b.lj();null===c.placeholder&&(c.location=this.computeAdornmentLocation(b));a.Fh(this.name,c);return}}a.Jf(this.name)}}; Eg.prototype.makeAdornment=function(a){var b=a.part.rotateAdornmentTemplate;if(null===b){b=new Qe;b.type=X.Position;b.locationSpot=Bc;var c=this.handleArchetype;null!==c&&b.add(c.copy())}else if(Ag(b),b=b.copy(),null===b)return null;b.adornedObject=a;return b};Eg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return!a.isReadOnly&&a.allowRotate&&a.lastInput.left?null!==this.findToolHandleAt(a.firstInput.documentPoint,this.name):!1}; Eg.prototype.doActivate=function(){var a=this.diagram;if(null===this.adornedObject){null===this.handle&&(this.handle=this.findToolHandleAt(a.firstInput.documentPoint,this.name));if(null===this.handle)return;this.adornedObject=this.handle.part.adornedObject}null!==this.adornedObject&&(a.isMouseCaptured=!0,a.delaysLayout=!0,this.xa(this.name),this.Gx=this.adornedObject.angle,this.Rs=this.computeRotationPoint(this.adornedObject),this.lp=this.adornedObject.part.location.copy(),this.isActive=!0)}; Eg.prototype.computeRotationPoint=function(a){var b=a.part,c=b.locationObject;return b.rotationSpot.kb()?a.da(b.rotationSpot):a===b||a===c?c.da(b.locationSpot):a.da(Bc)}; Eg.prototype.computeAdornmentLocation=function(a){var b=this.rotationPoint;b.s()||(b=this.computeRotationPoint(a));b=a.Nt(b);var c=this.handleAngle;0>c?c+=360:360<=c&&(c-=360);c=Math.round(45*Math.round(c/45));var d=this.handleDistance;0===c?b.x=a.naturalBounds.width+d:45===c?(b.x=a.naturalBounds.width+d,b.y=a.naturalBounds.height+d):90===c?b.y=a.naturalBounds.height+d:135===c?(b.x=-d,b.y=a.naturalBounds.height+d):180===c?b.x=-d:225===c?(b.x=-d,b.y=-d):270===c?b.y=-d:315===c&&(b.x=a.naturalBounds.width+ d,b.y=-d);return a.da(b)};Eg.prototype.doDeactivate=function(){var a=this.diagram;this.Kg();this.je=this.handle=null;this.Rs=new I(NaN,NaN);this.isActive=a.isMouseCaptured=!1};Eg.prototype.doCancel=function(){this.diagram.delaysLayout=!1;this.rotate(this.originalAngle);this.stopTool()};Eg.prototype.doMouseMove=function(){var a=this.diagram;this.isActive&&(a=this.computeRotate(a.lastInput.documentPoint),this.rotate(a))}; Eg.prototype.doMouseUp=function(){var a=this.diagram;if(this.isActive){a.delaysLayout=!1;var b=this.computeRotate(a.lastInput.documentPoint);this.rotate(b);a.Oa();this.transactionResult=this.name;a.R("PartRotated",this.adornedObject,this.originalAngle)}this.stopTool()}; Eg.prototype.rotate=function(a){var b=this.adornedObject;if(null!==b){b.angle=a;b=b.part;b.Ta();var c=b.locationObject,d=b.rotateObject;if(c===d||c.Hg(d))c=this.lp.copy(),b.location=c.he(this.rotationPoint).rotate(a-this.originalAngle).add(this.rotationPoint);this.diagram.jd()}}; Eg.prototype.computeRotate=function(a){a=this.rotationPoint.Sa(a)-this.handleAngle;var b=this.adornedObject.panel;null!==b&&(a-=b.lj());360<=a?a-=360:0>a&&(a+=360);b=Math.min(Math.abs(this.snapAngleMultiple),180);var c=Math.min(Math.abs(this.snapAngleEpsilon),b/2);!this.diagram.lastInput.shift&&0<b&&0<c&&(a%b<c?a=Math.floor(a/b)*b:a%b>b-c&&(a=(Math.floor(a/b)+1)*b));360<=a?a-=360:0>a&&(a+=360);return a}; na.Object.defineProperties(Eg.prototype,{handleArchetype:{get:function(){return this.v},set:function(a){this.v=a}},handle:{get:function(){return this.l},set:function(a){if(null!==a&&!(a.part instanceof Qe))throw Error("new handle is not in an Adornment: "+a);this.l=a}},adornedObject:{get:function(){return this.je},set:function(a){if(null!==a&&a.part instanceof Qe)throw Error("new handle must not be in an Adornment: "+ a);this.je=a}},snapAngleMultiple:{get:function(){return this.Ka},set:function(a){this.Ka=a}},snapAngleEpsilon:{get:function(){return this.Ja},set:function(a){this.Ja=a}},originalAngle:{get:function(){return this.Gx}},rotationPoint:{get:function(){return this.Rs},set:function(a){this.Rs=a.copy()}},handleAngle:{get:function(){return this.I},set:function(a){this.I= a}},handleDistance:{get:function(){return this.T},set:function(a){this.T=a}}});Eg.className="RotatingTool";Na("rotatingTool",function(){return this.findTool("Rotating")},function(a){this.Xa("Rotating",a,this.mouseDownTools)});function Fg(){Ge.call(this);this.name="ClickSelecting"}ma(Fg,Ge);Fg.prototype.canStart=function(){return!this.isEnabled||this.isBeyondDragSize()?!1:!0}; Fg.prototype.doMouseUp=function(){this.isActive&&(this.standardMouseSelect(),!this.standardMouseClick()&&this.diagram.lastInput.isTouchEvent&&this.diagram.toolManager.doToolTip());this.stopTool()};Fg.className="ClickSelectingTool";function Gg(){Ge.call(this);this.name="Action";this.Xk=null}ma(Gg,Ge); Gg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram,b=a.lastInput,c=a.Vb(b.documentPoint,function(a){for(;null!==a.panel&&!a.isActionable;)a=a.panel;return a});if(null!==c){if(!c.isActionable)return!1;this.Xk=c;a.Ej=a.Vb(b.documentPoint,null,null);return!0}return!1};Gg.prototype.doMouseDown=function(){if(this.isActive){var a=this.diagram.lastInput,b=this.Xk;null!==b&&(a.targetObject=b,null!==b.actionDown&&b.actionDown(a,b))}else this.canStart()&&this.doActivate()}; Gg.prototype.doMouseMove=function(){if(this.isActive){var a=this.diagram.lastInput,b=this.Xk;null!==b&&(a.targetObject=b,null!==b.actionMove&&b.actionMove(a,b))}};Gg.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram.lastInput,b=this.Xk;if(null===b)return;a.targetObject=b;null!==b.actionUp&&b.actionUp(a,b);this.standardMouseClick(function(a){for(;null!==a.panel&&(!a.isActionable||a!==b);)a=a.panel;return a},function(a){return a===b})}this.stopTool()}; Gg.prototype.doCancel=function(){var a=this.diagram.lastInput,b=this.Xk;null!==b&&(a.targetObject=b,null!==b.actionCancel&&b.actionCancel(a,b),this.stopTool())};Gg.prototype.doStop=function(){this.Xk=null};Gg.className="ActionTool";function Hg(){Ge.call(this);this.name="ClickCreating";this.Aj=null;this.v=!0;this.l=!1;this.yx=new I(0,0)}ma(Hg,Ge); Hg.prototype.canStart=function(){if(!this.isEnabled||null===this.archetypeNodeData)return!1;var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.lastInput.left||this.isBeyondDragSize())return!1;if(this.isDoubleClick){if(1===a.lastInput.clickCount&&(this.yx=a.lastInput.viewPoint.copy()),2!==a.lastInput.clickCount||this.isBeyondDragSize(this.yx))return!1}else if(1!==a.lastInput.clickCount)return!1;return a.currentTool!==this&&null!==a.zm(a.lastInput.documentPoint,!0)?!1:!0}; Hg.prototype.doMouseUp=function(){var a=this.diagram;this.isActive&&this.insertPart(a.lastInput.documentPoint);this.stopTool()}; Hg.prototype.insertPart=function(a){var b=this.diagram,c=this.archetypeNodeData;if(null===c)return null;var d=null;try{b.R("ChangingSelection",b.selection);this.xa(this.name);if(c instanceof V)c.Pc()&&(Ag(c),d=c.copy(),null!==d&&b.add(d));else if(null!==c){var e=b.model.copyNodeData(c);za(e)&&(b.model.wf(e),d=b.zc(e))}if(null!==d){var f=I.allocAt(a.x,a.y);this.isGridSnapEnabled&&Ig(this.diagram,d,a,f);d.location=f;b.allowSelect&&(b.clearSelection(!0),d.isSelected=!0);I.free(f)}b.Oa();this.transactionResult= this.name;b.R("PartCreated",d)}finally{this.Kg(),b.R("ChangedSelection",b.selection)}return d};na.Object.defineProperties(Hg.prototype,{archetypeNodeData:{get:function(){return this.Aj},set:function(a){this.Aj=a}},isDoubleClick:{get:function(){return this.v},set:function(a){this.v=a}},isGridSnapEnabled:{get:function(){return this.l},set:function(a){this.l=a}}});Hg.className="ClickCreatingTool"; function Jg(){Ge.call(this);this.name="DragSelecting";this.pl=175;this.v=!1;var a=new V;a.layerName="Tool";a.selectable=!1;var b=new Mf;b.name="SHAPE";b.figure="Rectangle";b.fill=null;b.stroke="magenta";a.add(b);this.l=a}ma(Jg,Ge); Jg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(!a.allowSelect)return!1;var b=a.lastInput;return!b.left||a.currentTool!==this&&(!this.isBeyondDragSize()||b.timestamp-a.firstInput.timestamp<this.delay||null!==a.zm(b.documentPoint,!0))?!1:!0};Jg.prototype.doActivate=function(){var a=this.diagram;this.isActive=!0;a.isMouseCaptured=!0;a.skipsUndoManager=!0;a.add(this.box);this.doMouseMove()}; Jg.prototype.doDeactivate=function(){var a=this.diagram;a.Lf();a.remove(this.box);a.skipsUndoManager=!1;this.isActive=a.isMouseCaptured=!1};Jg.prototype.doMouseMove=function(){var a=this.diagram;if(this.isActive&&null!==this.box){var b=this.computeBoxBounds(),c=this.box.ab("SHAPE");null===c&&(c=this.box.rb());var d=M.alloc().h(b.width,b.height);b=I.allocAt(b.x,b.y);c.desiredSize=d;this.box.position=b;M.free(d);I.free(b);(a.allowHorizontalScroll||a.allowVerticalScroll)&&a.Ft(a.lastInput.viewPoint)}}; Jg.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram;a.remove(this.box);try{a.currentCursor="wait",a.R("ChangingSelection",a.selection),this.selectInRect(this.computeBoxBounds()),a.R("ChangedSelection",a.selection)}finally{a.currentCursor=""}}this.stopTool()};Jg.prototype.computeBoxBounds=function(){var a=this.diagram;return new N(a.firstInput.documentPoint,a.lastInput.documentPoint)}; Jg.prototype.selectInRect=function(a){var b=this.diagram,c=b.lastInput;a=b.ty(a,this.isPartialInclusion);if(Xa?c.meta:c.control)if(c.shift)for(a=a.iterator;a.next();)b=a.value,b.isSelected&&(b.isSelected=!1);else for(a=a.iterator;a.next();)b=a.value,b.isSelected=!b.isSelected;else if(c.shift)for(a=a.iterator;a.next();)b=a.value,b.isSelected||(b.isSelected=!0);else{c=new E;for(b=b.selection.iterator;b.next();){var d=b.value;a.contains(d)||c.add(d)}for(b=c.iterator;b.next();)b.value.isSelected=!1;for(a= a.iterator;a.next();)b=a.value,b.isSelected||(b.isSelected=!0)}};na.Object.defineProperties(Jg.prototype,{delay:{get:function(){return this.pl},set:function(a){this.pl=a}},isPartialInclusion:{get:function(){return this.v},set:function(a){this.v=a}},box:{get:function(){return this.l},set:function(a){this.l=a}}});Jg.className="DragSelectingTool"; function Kg(){Ge.call(this);this.name="Panning";this.jv=new I;this.kz=new I;this.Qg=!1;var a=this;this.Mx=function(){var b=a.diagram;null!==b&&b.removeEventListener(x.document,"scroll",a.Mx,!1);a.stopTool()}}ma(Kg,Ge);Kg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return!a.allowHorizontalScroll&&!a.allowVerticalScroll||!a.lastInput.left||a.currentTool!==this&&!this.isBeyondDragSize()?!1:!0}; Kg.prototype.doActivate=function(){var a=this.diagram;this.Qg?(a.lastInput.bubbles=!0,a.addEventListener(x.document,"scroll",this.Mx,!1)):(a.currentCursor="move",a.isMouseCaptured=!0,this.jv.assign(a.position));this.isActive=!0};Kg.prototype.doDeactivate=function(){var a=this.diagram;a.currentCursor="";this.isActive=a.isMouseCaptured=!1};Kg.prototype.doCancel=function(){var a=this.diagram;a.position=this.jv;a.isMouseCaptured=!1;this.stopTool()};Kg.prototype.doMouseMove=function(){this.move()}; Kg.prototype.doMouseUp=function(){this.move();this.stopTool()};Kg.prototype.move=function(){var a=this.diagram;if(this.isActive&&a)if(this.Qg)a.lastInput.bubbles=!0;else{var b=a.position,c=a.firstInput.documentPoint,d=a.lastInput.documentPoint,e=b.x+c.x-d.x;c=b.y+c.y-d.y;a.allowHorizontalScroll||(e=b.x);a.allowVerticalScroll||(c=b.y);a.position=this.kz.h(e,c)}}; na.Object.defineProperties(Kg.prototype,{bubbles:{get:function(){return this.Qg},set:function(a){this.Qg=a}},originalPosition:{get:function(){return this.jv}}});Kg.className="PanningTool";Na("clickCreatingTool",function(){return this.findTool("ClickCreating")},function(a){this.Xa("ClickCreating",a,this.mouseUpTools)});Na("clickSelectingTool",function(){return this.findTool("ClickSelecting")},function(a){this.Xa("ClickSelecting",a,this.mouseUpTools)}); Na("panningTool",function(){return this.findTool("Panning")},function(a){this.Xa("Panning",a,this.mouseMoveTools)});Na("dragSelectingTool",function(){return this.findTool("DragSelecting")},function(a){this.Xa("DragSelecting",a,this.mouseMoveTools)});Na("actionTool",function(){return this.findTool("Action")},function(a){this.Xa("Action",a,this.mouseDownTools)});function Ve(){this.T=this.I=this.l=this.v=null} na.Object.defineProperties(Ve.prototype,{mainElement:{get:function(){return this.I},set:function(a){this.I=a}},show:{get:function(){return this.v},set:function(a){this.v!==a&&(this.v=a)}},hide:{get:function(){return this.l},set:function(a){this.l!==a&&(this.l=a)}},valueFunction:{get:function(){return this.T},set:function(a){this.T=a}}});Ve.className="HTMLInfo"; function Lg(a,b,c){this.text=a;this.ey=b;this.visible=c}Lg.className="ContextMenuButtonInfo";function Mg(){Ge.call(this);this.name="ContextMenu";this.v=this.Bu=this.l=null;this.Ex=new I;this.Cu=null;this.Xu=!1;var a=this;this.vv=function(){a.stopTool()}}ma(Mg,Ge); function Ng(a){var b=new Ve;b.show=function(a,b,c){c.showDefaultContextMenu()};b.hide=function(a,b){b.hideDefaultContextMenu()};Og=b;a.vv=function(){a.stopTool()};b=ua("div");var c=ua("div");b.style.cssText="top: 0px;z-index:10002;position: fixed;display: none;text-align: center;left: 25%;width: 50%;background-color: #F5F5F5;padding: 16px;border: 16px solid #444;border-radius: 10px;margin-top: 10px";c.style.cssText="z-index:10001;position: fixed;display: none;top: 0;left: 0;width: 100%;height: 100%;background-color: black;opacity: 0.8;"; var d=ua("style");x.document.getElementsByTagName("head")[0].appendChild(d);d.sheet.insertRule(".goCXul { list-style: none; }",0);d.sheet.insertRule(".goCXli {font:700 1.5em Helvetica, Arial, sans-serif;position: relative;min-width: 60px; }",0);d.sheet.insertRule(".goCXa {color: #444;display: inline-block;padding: 4px;text-decoration: none;margin: 2px;border: 1px solid gray;border-radius: 10px; }",0);d=a.diagram;null!==d&&(d.addEventListener(b,"contextmenu",Pg,!1),d.addEventListener(b,"selectstart", Pg,!1),d.addEventListener(c,"contextmenu",Pg,!1));b.className="goCXforeground";c.className="goCXbackground";x.document.body&&(x.document.body.appendChild(b),x.document.body.appendChild(c));Qg=b;Rg=c;Sg=!0}function Pg(a){a.preventDefault();return!1} Mg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return this.isBeyondDragSize()||!a.lastInput.right||1<a.lastInput.clickCount?!1:a.lastInput.isTouchEvent&&null!==this.defaultTouchContextMenu||null!==this.findObjectWithContextMenu()?!0:!1};Mg.prototype.doStart=function(){this.Ex.set(this.diagram.firstInput.documentPoint)};Mg.prototype.doStop=function(){this.hideContextMenu();this.currentObject=null}; Mg.prototype.findObjectWithContextMenu=function(a){void 0===a&&(a=null);var b=this.diagram,c=b.lastInput,d=null;a instanceof R||(a instanceof Y?d=a:d=b.Vb(c.documentPoint,null,function(a){return!a.layer.isTemporary}));if(null!==d){for(a=d;null!==a;){if(null!==a.contextMenu)return a;a=a.panel}if(b.lastInput.isTouchEvent&&this.defaultTouchContextMenu)return d.part}else if(null!==b.contextMenu)return b;return null};Mg.prototype.doActivate=function(){}; Mg.prototype.doMouseDown=function(){Ge.prototype.doMouseDown.call(this);if(this.isActive&&this.currentContextMenu instanceof Qe){var a=this.diagram.toolManager.findTool("Action");null!==a&&a.canStart()&&(a.doActivate(),a.doMouseDown(),a.doDeactivate())}this.diagram.toolManager.mouseDownTools.contains(this)&&Tg(this)}; Mg.prototype.doMouseUp=function(){if(this.isActive&&this.currentContextMenu instanceof Qe){var a=this.diagram.toolManager.findTool("Action");null!==a&&a.canStart()&&(a.doActivate(),a.doCancel(),a.doDeactivate())}Tg(this)}; function Tg(a){var b=a.diagram;if(a.isActive){var c=a.currentContextMenu;if(null!==c){if(!(c instanceof Ve)){var d=b.Vb(b.lastInput.documentPoint,null,null);null!==d&&d.Hg(c)&&a.standardMouseClick(null,null)}a.stopTool();a.canStart()&&(b.currentTool=a,a.doMouseUp())}}else a.canStart()&&(Ug(a,!0),a.isActive||a.stopTool())} function Ug(a,b,c){void 0===c&&(c=null);if(!a.Xu&&(a.Xu=!0,b&&a.standardMouseSelect(),b=a.standardMouseClick(),a.Xu=!1,!b)){a.isActive=!0;b=Og;null===c&&(c=a.findObjectWithContextMenu());if(null!==c){var d=c.contextMenu;null!==d?(a.currentObject=c instanceof Y?c:null,a.showContextMenu(d,a.currentObject)):null!==b&&a.showContextMenu(b,a.currentObject)}else null!==b&&a.showContextMenu(b,null);a.currentContextMenu instanceof Qe&&!a.currentContextMenu.visible&&a.stopTool()}} Mg.prototype.doMouseMove=function(){var a=this.diagram.toolManager.findTool("Action");null!==a&&a.doMouseMove();this.isActive&&this.diagram.toolManager.doMouseMove()}; Mg.prototype.showContextMenu=function(a,b){var c=this.diagram;a!==this.currentContextMenu&&this.hideContextMenu();if(a instanceof Qe){a.layerName="Tool";a.selectable=!1;a.scale=1/c.scale;a.category=this.name;null!==a.placeholder&&(a.placeholder.scale=c.scale);var d=a.diagram;null!==d&&d!==c&&d.remove(a);c.add(a);null!==b?a.adornedObject=b:a.data=c.model;a.Ta();this.positionContextMenu(a,b)}else a instanceof Ve&&a.show(b,c,this);this.currentContextMenu=a}; Mg.prototype.positionContextMenu=function(a){if(null===a.placeholder){var b=this.diagram,c=b.lastInput.documentPoint.copy(),d=a.measuredBounds,e=b.viewportBounds;b.lastInput.isTouchEvent&&(c.x-=d.width);c.x+d.width>e.right&&(c.x-=d.width+5/b.scale);c.x<e.x&&(c.x=e.x);c.y+d.height>e.bottom&&(c.y-=d.height+5/b.scale);c.y<e.y&&(c.y=e.y);a.position=c}}; Mg.prototype.hideContextMenu=function(){var a=this.diagram,b=this.currentContextMenu;null!==b&&(b instanceof Qe?(a.remove(b),null!==this.Bu&&this.Bu.Jf(b.category),b.data=null,b.adornedObject=null):b instanceof Ve&&(null!==b.hide?b.hide(a,this):null!==b.mainElement&&(b.mainElement.style.display="none")),this.currentContextMenu=null,this.standardMouseOver())}; function Vg(a){var b=new E;b.add(new Lg("Copy",function(a){a.commandHandler.copySelection()},function(a){return a.commandHandler.canCopySelection()}));b.add(new Lg("Cut",function(a){a.commandHandler.cutSelection()},function(a){return a.commandHandler.canCutSelection()}));b.add(new Lg("Delete",function(a){a.commandHandler.deleteSelection()},function(a){return a.commandHandler.canDeleteSelection()}));b.add(new Lg("Paste",function(b){b.commandHandler.pasteSelection(a.mouseDownPoint)},function(b){return b.commandHandler.canPasteSelection(a.mouseDownPoint)})); b.add(new Lg("Select All",function(a){a.commandHandler.selectAll()},function(a){return a.commandHandler.canSelectAll()}));b.add(new Lg("Undo",function(a){a.commandHandler.undo()},function(a){return a.commandHandler.canUndo()}));b.add(new Lg("Redo",function(a){a.commandHandler.redo()},function(a){return a.commandHandler.canRedo()}));b.add(new Lg("Scroll To Part",function(a){a.commandHandler.scrollToPart()},function(a){return a.commandHandler.canScrollToPart()}));b.add(new Lg("Zoom To Fit",function(a){a.commandHandler.zoomToFit()}, function(a){return a.commandHandler.canZoomToFit()}));b.add(new Lg("Reset Zoom",function(a){a.commandHandler.resetZoom()},function(a){return a.commandHandler.canResetZoom()}));b.add(new Lg("Group Selection",function(a){a.commandHandler.groupSelection()},function(a){return a.commandHandler.canGroupSelection()}));b.add(new Lg("Ungroup Selection",function(a){a.commandHandler.ungroupSelection()},function(a){return a.commandHandler.canUngroupSelection()}));b.add(new Lg("Edit Text",function(a){a.commandHandler.editTextBlock()}, function(a){return a.commandHandler.canEditTextBlock()}));return b} Mg.prototype.showDefaultContextMenu=function(){var a=this.diagram;null===this.Cu&&(this.Cu=Vg(this));Qg.innerHTML="";Rg.addEventListener("click",this.vv,!1);var b=this,c=ua("ul");c.className="goCXul";Qg.appendChild(c);c.innerHTML="";for(var d=this.Cu.iterator;d.next();){var e=d.value,f=e.visible;if("function"===typeof e.ey&&("function"!==typeof f||f(a))){f=ua("li");f.className="goCXli";var g=ua("a");g.className="goCXa";g.href="#";g.ez=e.ey;g.addEventListener("click",function(c){this.ez(a);b.stopTool(); c.preventDefault();return!1},!1);g.textContent=e.text;f.appendChild(g);c.appendChild(f)}}Qg.style.display="block";Rg.style.display="block"};Mg.prototype.hideDefaultContextMenu=function(){if(null!==this.currentContextMenu&&this.currentContextMenu===Og){Qg.style.display="none";Rg.style.display="none";var a=this.diagram;null!==a&&a.removeEventListener(Rg,"click",this.vv,!1);this.currentContextMenu=null}}; na.Object.defineProperties(Mg.prototype,{currentContextMenu:{get:function(){return this.l},set:function(a){this.l=a;this.Bu=a instanceof Qe?a.adornedPart:null}},defaultTouchContextMenu:{get:function(){!1===Sg&&null===Og&&Wg&&Ng(this);return Og},set:function(a){null===a&&(Sg=!0);Og=a}},currentObject:{get:function(){return this.v},set:function(a){this.v=a}},mouseDownPoint:{get:function(){return this.Ex}}}); var Og=null,Sg=!1,Rg=null,Qg=null;Mg.className="ContextMenuTool";Na("contextMenuTool",function(){return this.findTool("ContextMenu")},function(a){this.Xa("ContextMenu",a,this.mouseUpTools)});function Xg(){Ge.call(this);this.name="TextEditing";this.yh=new Yg;this.Ka=null;this.Ja=Zg;this.Wi=null;this.ia=$g;this.I=1;this.T=!0;this.v=null;this.l=new Ve;this.Gu=null;ah(this,this.l)}ma(Xg,Ge); function ah(a,b){if(Wg){var c=ua("textarea");a.Gu=c;c.addEventListener("input",function(){if(null!==a.textBlock){var b=a.Ky(this.value);this.style.width=20+b.measuredBounds.width*this.cB+"px";this.rows=b.lineCount}},!1);c.addEventListener("keydown",function(b){if(null!==a.textBlock){var c=b.key;"Enter"===c?(!1===a.textBlock.isMultiline&&b.preventDefault(),a.acceptText(bh)):"Tab"===c?(a.acceptText(ch),b.preventDefault()):"Escape"===c&&(a.doCancel(),null!==a.diagram&&a.diagram.doFocus())}},!1);c.addEventListener("focus", function(){if(null!==a.currentTextEditor&&a.state!==$g){var b=a.Gu;a.ia===dh&&(a.ia=eh);"function"===typeof b.select&&a.selectsTextOnActivate&&(b.select(),b.setSelectionRange(0,9999))}},!1);c.addEventListener("blur",function(){if(null!==a.currentTextEditor&&a.state!==$g){var b=a.Gu;"function"===typeof b.focus&&b.focus();"function"===typeof b.select&&a.selectsTextOnActivate&&(b.select(),b.setSelectionRange(0,9999))}},!1);b.valueFunction=function(){return c.value};b.mainElement=c;b.show=function(a, b,f){if(a instanceof Yg&&f instanceof Xg)if(f.state===fh)c.style.border="3px solid red",c.focus();else{var d=a.da(Bc),e=b.position,k=b.scale,l=a.Cf()*k;l<f.minimumEditorScale&&(l=f.minimumEditorScale);var m=a.naturalBounds.width*l+6,n=a.naturalBounds.height*l+2,p=(d.x-e.x)*k;d=(d.y-e.y)*k;c.value=a.text;b.div.style.font=a.font;c.style.position="absolute";c.style.zIndex="100";c.style.font="inherit";c.style.fontSize=100*l+"%";c.style.lineHeight="normal";c.style.width=m+"px";c.style.left=(p-m/2|0)-1+ "px";c.style.top=(d-n/2|0)-1+"px";c.style.textAlign=a.textAlign;c.style.margin="0";c.style.padding="1px";c.style.border="0";c.style.outline="none";c.style.whiteSpace="pre-wrap";c.style.overflow="hidden";c.rows=a.lineCount;c.cB=l;c.className="goTXarea";b.div.appendChild(c);c.focus();f.selectsTextOnActivate&&(c.select(),c.setSelectionRange(0,9999))}};b.hide=function(a){a.div.removeChild(c)}}} Xg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(null===a||a.isReadOnly||gh&&gh!==this&&(gh.acceptText(hh),gh&&gh!==this)||!a.lastInput.left||this.isBeyondDragSize())return!1;var b=a.Vb(a.lastInput.documentPoint);if(!(null!==b&&b instanceof Yg&&b.editable&&b.part.canEdit()))return!1;b=b.part;return null===b||this.starting===Zg&&!b.isSelected||this.starting===ih&&2>a.lastInput.clickCount?!1:!0};Xg.prototype.doStart=function(){gh=this;null!==this.textBlock&&this.doActivate()}; Xg.prototype.doActivate=function(){if(!this.isActive){var a=this.diagram;if(null!==a){var b=this.textBlock;null===b&&(b=a.Vb(a.lastInput.documentPoint));if(null!==b&&b instanceof Yg&&(this.textBlock=b,null!==b.part)){this.isActive=!0;this.ia=dh;var c=this.defaultTextEditor;null!==b.textEditor&&(c=b.textEditor);this.yh=this.textBlock.copy();var d=new N(this.textBlock.da(vc),this.textBlock.da(Gc));a.Bw(d);c.show(b,a,this);this.currentTextEditor=c}}}};Xg.prototype.doCancel=function(){this.stopTool()}; Xg.prototype.doMouseUp=function(){this.canStart()&&this.doActivate()};Xg.prototype.doMouseDown=function(){this.isActive&&this.acceptText(hh)};Xg.prototype.acceptText=function(a){switch(a){case hh:if(this.ia===jh)this.currentTextEditor instanceof HTMLElement&&this.currentTextEditor.focus();else if(this.ia===dh||this.ia===fh||this.ia===eh)this.ia=kh,lh(this);break;case mh:case bh:case ch:if(bh!==a||!0!==this.textBlock.isMultiline)if(this.ia===dh||this.ia===fh||this.ia===eh)this.ia=kh,lh(this)}}; function lh(a){var b=a.textBlock,c=a.diagram,d=a.currentTextEditor;if(null!==b&&null!==d){var e=b.text,f="";null!==d.valueFunction&&(f=d.valueFunction());a.isValidText(b,e,f)?(a.xa(a.name),a.ia=jh,a.transactionResult=a.name,b.text=f,a.doSuccess(e,f),null!==c&&c.R("TextEdited",b,e),a.Kg(),a.stopTool(),null!==c&&c.doFocus()):(a.ia=fh,a.doError(e,f),d.show(b,c,a))}}Xg.prototype.doError=function(a,b){var c=this.textBlock;null!==c.errorFunction&&c.errorFunction(this,a,b)}; Xg.prototype.doSuccess=function(a,b){var c=this.textBlock;null!==c.textEdited&&c.textEdited(c,a,b)};Xg.prototype.doDeactivate=function(){var a=this.diagram;null!==a&&(this.ia=$g,this.textBlock=null,null!==this.currentTextEditor&&this.currentTextEditor.hide(a,this),this.isActive=!1)};Xg.prototype.doStop=function(){gh=null};Xg.prototype.isValidText=function(a,b,c){var d=this.textValidation;if(null!==d&&!d(a,b,c))return!1;d=a.textValidation;return null===d||d(a,b,c)?!0:!1}; Xg.prototype.Ky=function(a){var b=this.yh;b.text=a;b.measure(this.textBlock.Di,Infinity);return b}; na.Object.defineProperties(Xg.prototype,{textBlock:{get:function(){return this.Ka},set:function(a){this.Ka=a}},currentTextEditor:{get:function(){return this.v},set:function(a){this.v=a}},defaultTextEditor:{get:function(){return this.l},set:function(a){this.l=a}},starting:{get:function(){return this.Ja},set:function(a){this.Ja=a}},textValidation:{get:function(){return this.Wi}, set:function(a){this.Wi=a}},minimumEditorScale:{get:function(){return this.I},set:function(a){this.I=a}},selectsTextOnActivate:{get:function(){return this.T},set:function(a){this.T=a}},state:{get:function(){return this.ia},set:function(a){this.ia!==a&&(this.ia=a)}}});Xg.prototype.measureTemporaryTextBlock=Xg.prototype.Ky; var mh=new D(Xg,"LostFocus",0),hh=new D(Xg,"MouseDown",1),ch=new D(Xg,"Tab",2),bh=new D(Xg,"Enter",3),nh=new D(Xg,"SingleClick",0),Zg=new D(Xg,"SingleClickSelected",1),ih=new D(Xg,"DoubleClick",2),$g=new D(Xg,"StateNone",0),dh=new D(Xg,"StateActive",1),eh=new D(Xg,"StateEditing",2),kh=new D(Xg,"StateValidating",3),fh=new D(Xg,"StateInvalid",4),jh=new D(Xg,"StateValidated",5),gh=null;Xg.className="TextEditingTool";Xg.LostFocus=mh;Xg.MouseDown=hh;Xg.Tab=ch;Xg.Enter=bh;Xg.SingleClick=nh; Xg.SingleClickSelected=Zg;Xg.DoubleClick=ih;Xg.StateNone=$g;Xg.StateActive=dh;Xg.StateEditing=eh;Xg.StateValidating=kh;Xg.StateInvalid=fh;Xg.StateValidated=jh;Na("textEditingTool",function(){return this.findTool("TextEditing")},function(a){this.Xa("TextEditing",a,this.mouseUpTools)}); function oh(){ph||(qh(),ph=!0);this.B=He;this.Al=this.ff=this.sc=this.qs=this.jc=!1;this.Rx=!0;this.Bl=rh;this.rn=!1;this.yi=this.nd=!0;this.Yg=600;this.px=this.Qx=!1;this.Se=new G;this.Rd=new sh;this.Rd.Wc=this;this.yj=new G;this.sv=new G;this.ot=new G}oh.prototype.fe=function(a){this.B=a};oh.prototype.canStart=function(){return!0};function th(a,b){uh(a,b)&&(a.ff=!0)}function uh(a,b){if(!a.nd||!a.canStart(b))return!1;a.Se.add(b);a.defaultAnimation.isAnimating&&a.Cc();return a.sc=!0} function vh(a){if(a.nd&&a.sc){var b=a.Rd,c=a.B,d=a.Se.contains("Model");d&&(a.Al=!0,a.Bl===rh?(b.isViewportUnconstrained=!0,b.mc.clear(),b.add(c,"position",c.position.copy().offset(0,-200),c.position),b.add(c,"opacity",0,1)):a.Bl===Ih&&b.mc.clear(),a.Rx=a.Bl===Jh&&c.Vs.w(c.la)?!0:!1,c.R("InitialAnimationStarting",a));d&&!a.yi||0===b.mc.count?(a.Se.clear(),a.sc=!1,a.ff=!1,b.mc.clear(),Kh(b,c),a.Al=!1,c.M()):(a.Se.clear(),c.Fe=!1,d=b.mc.get(c),c.autoScale!==Lh&&null!==d&&(delete d.start.scale,delete d.end.scale), x.requestAnimationFrame(function(){!1===a.sc||b.jc||(c.Ke("temporaryPixelRatio")&&af(c),Mh(c),a.sc=!1,a.ff=!1,b.start(),Nh(a),c.Oa(),Oh(b,0),Jf(c,!0),Ph(a),c.R("AnimationStarting",a))}))}}function Qh(a,b,c,d){b instanceof S&&(null!==b.fromNode||null!==b.toNode)||a.Rd.add(b,"position",c,d,!1)}t=oh.prototype;t.cu=function(a){return this.Rd.cu(a)};t.dw=function(a){return this.Rd.dw(a)}; function Rh(a,b){function c(){0<e.ot.count&&(d.addAll(e.ot),e.ot.clear(),e.jc=!0);if(!1!==e.jc&&0!==d.count){e.sv.addAll(d);for(var a=e.sv.iterator;a.next();){var b=a.value;if(!1!==b.jc){a:if(0<b.pm.count)var h=!0;else{for(h=b.mc.iterator;h.next();){var k=h.key;if(k instanceof Y&&null!==k.diagram||k instanceof R){h=!0;break a}}h=!1}h?Sh(b,!1):b.Jl=!0}}e.sv.clear();Nh(e);Jf(e.B);Ph(e);x.requestAnimationFrame(c)}}var d=a.yj,e=a;a.jc?a.ot.add(b):(a.jc=!0,d.add(b),x.requestAnimationFrame(function(){c()}))} function Th(a){for(a=a.yj.iterator;a.next();)a.value.Jl=!1}function Nh(a){if(!a.qs){var b=a.B;a.Qx=b.skipsUndoManager;a.px=b.skipsModelSourceBindings;b.skipsUndoManager=!0;b.skipsModelSourceBindings=!0;a.qs=!0}}function Ph(a){var b=a.B;b.skipsUndoManager=a.Qx;b.skipsModelSourceBindings=a.px;a.qs=!1} t.Cc=function(a){var b=this.Rd;!0===this.sc&&(this.Al=this.ff=this.sc=!1,this.Se.clear(),0<b.mc.count&&this.B.Eb());if(this.jc){if(b.wm(!0),b.mc.clear(),Kh(b,null),!0===a)for(a=this.yj.ma(),b=0;b<a.length;b++)a[b].wm(!0)}else b.mc.clear(),Kh(b,this.B)};t.wm=function(a){a===this.defaultAnimation&&this.defaultAnimation.mc.clear();this.yj.remove(a);0===this.yj.count&&(this.jc=!1,this.B.Eb());a===this.defaultAnimation&&(this.defaultAnimation.mc.clear(),this.B.R("AnimationFinished",this))}; t.lk=function(a,b){this.ff&&(this.Se.contains("Expand Tree")||this.Se.contains("Expand SubGraph"))&&this.Rd.lk(a,b)};t.jk=function(a,b){this.ff&&(this.Se.contains("Collapse Tree")||this.Se.contains("Collapse SubGraph"))&&(this.Rd.jk(a,b),Uh(this.Rd,b,"position",b.position,b.position))};function Vh(a,b,c){a.ff&&!b.w(c)&&(a.B.pj||(b=c.copy()),Uh(a.Rd,a.B,"position",b,c))} function Wh(a,b,c,d,e){null===a&&(a=[0,0,0,0]);null===b&&(b=[0,0,0,0]);var f=a[0],g=a[1],h=a[2];a=a[3];var k=b[0],l=b[1],m=b[2];b=b[3];if(0===h||100===h)f=k,g=l;else if(0===m||100===m)k=f,l=g;180<Math.abs(k-f)&&(k>f?f+=360:k+=360);f=e(c,f,k-f,d)%360;g=e(c,g,l-g,d);h=e(c,h,m-h,d);c=e(c,a,b-a,d);return"hsla("+f+", "+g+"%, "+h+"%, "+c+")"} function qh(){function a(a,b,e,f,g,h){a.position=new I(f(g,b.x,e.x-b.x,h),f(g,b.y,e.y-b.y,h))}var b=new H;b.add("position:diagram",a);b.add("position",a);b.add("position:part",function(a,b,e,f,g,h){g<h?a.er(f(g,b.x,e.x-b.x,h),f(g,b.y,e.y-b.y,h),!1):a.position=new I(f(g,b.x,e.x-b.x,h),f(g,b.y,e.y-b.y,h))});b.add("location",function(a,b,e,f,g,h){g<h?a.er(f(g,b.x,e.x-b.x,h),f(g,b.y,e.y-b.y,h),!0):a.location=new I(f(g,b.x,e.x-b.x,h),f(g,b.y,e.y-b.y,h))});b.add("position:placeholder",function(a,b,e,f, g,h){g<h?a.er(f(g,b.x,e.x-b.x,h),f(g,b.y,e.y-b.y,h),!1):a.position=new I(f(g,b.x,e.x-b.x,h),f(g,b.y,e.y-b.y,h))});b.add("position:nodeCollapse",function(a,b,e,f,g,h){var c=a.actualBounds,d=e.actualBounds;e=d.x+d.width/2-c.width/2;c=d.y+d.height/2-c.height/2;g<h?a.er(f(g,b.x,e-b.x,h),f(g,b.y,c-b.y,h),!1):a.position=new I(f(g,b.x,e-b.x,h),f(g,b.y,c-b.y,h))});b.add("desiredSize",function(a,b,e,f,g,h){a.desiredSize=new N(f(g,b.width,e.width-b.width,h),f(g,b.height,e.height-b.height,h))});b.add("width", function(a,b,e,f,g,h){a.width=f(g,b,e-b,h)});b.add("height",function(a,b,e,f,g,h){a.height=f(g,b,e-b,h)});b.add("fill",function(a,b,e,f,g,h){a.fill=Wh(b,e,g,h,f)});b.add("stroke",function(a,b,e,f,g,h){a.stroke=Wh(b,e,g,h,f)});b.add("strokeWidth",function(a,b,e,f,g,h){a.strokeWidth=f(g,b,e-b,h)});b.add("strokeDashOffset",function(a,b,e,f,g,h){a.strokeDashOffset=f(g,b,e-b,h)});b.add("background",function(a,b,e,f,g,h){a.background=Wh(b,e,g,h,f)});b.add("areaBackground",function(a,b,e,f,g,h){a.areaBackground= Wh(b,e,g,h,f)});b.add("opacity",function(a,b,e,f,g,h){a.opacity=f(g,b,e-b,h)});b.add("scale",function(a,b,e,f,g,h){a.scale=f(g,b,e-b,h)});b.add("angle",function(a,b,e,f,g,h){a.angle=f(g,b,e-b,h)});Xh=b} na.Object.defineProperties(oh.prototype,{animationReasons:{get:function(){return this.Se}},isEnabled:{get:function(){return this.nd},set:function(a){(this.nd=a)&&this.yj.each(function(a){a.isAnimating||Infinity!==a.runCount||a.start()})}},duration:{get:function(){return this.Yg},set:function(a){1>a&&wa(a,">= 1",oh,"duration");this.Yg=a}},isAnimating:{get:function(){return this.jc}}, isTicking:{get:function(){return this.qs}},isInitial:{get:function(){return this.yi},set:function(a){this.yi=a}},defaultAnimation:{get:function(){return this.Rd}},activeAnimations:{get:function(){return this.yj}},initialAnimationStyle:{get:function(){return this.Bl},set:function(a){this.Bl=a}}});oh.prototype.stopAnimation=oh.prototype.Cc; var Xh=null,ph=!1,rh=new D(oh,"Default",1),Jh=new D(oh,"AnimateLocations",2),Ih=new D(oh,"None",3);oh.className="AnimationManager";oh.defineAnimationEffect=function(a,b){ph||(qh(),ph=!0);Xh.add(a,b)};oh.Default=rh;oh.AnimateLocations=Jh;oh.None=Ih; function sh(){this.wv=this.Px=this.Wc=this.B=null;this.Jl=this.jc=this.l=!1;this.Xn=this.Dd=0;this.Jr=this.Ju=Yh;this.Il=this.Ap=!1;this.mv=1;this.lv=0;this.vd=this.Yg=NaN;this.ux=0;this.Yn=null;this.v=Fb;this.mc=new H;this.hv=new H;this.pm=new G;this.iv=new G;this.qx=Zh}sh.prototype.suspend=function(){this.Jl=!0};sh.prototype.advanceTo=function(a,b){b&&(this.Jl=!1);this.Ap&&a>=this.vd&&(this.Il=!0,a-=this.vd);this.ux=a;Sh(this,!0);Nh(this.Wc);Jf(this.B);Ph(this.Wc);this.B.Ne()}; function Kh(a,b){a.hv.clear();a.Il=!1;a.lv=0;a.vd=NaN;0<a.pm.count&&a.pm.clear();0<a.iv.count&&a.iv.clear();if(null!==b)for(a=b.links;a.next();)a.value.sg=null}t=sh.prototype; t.start=function(){if(0!==this.mc.count&&!this.jc){for(var a=this.B,b=this.mc.iterator;b.next();){var c=b.value.end,d=b.key;if(c["position:placeholder"]){var e=d.findVisibleNode();if(e instanceof U&&null!==e.placeholder){var f=e.placeholder;e=f.da(vc);f=f.padding;e.x+=f.left;e.y+=f.top;c["position:placeholder"]=e}}null===a&&(d instanceof R?a=d:d instanceof Y&&(a=d.diagram))}null!==a&&(this.B=a,b=this.Wc=a.animationManager,!1!==b.isEnabled&&(this.vd=isNaN(this.Yg)?b.duration:this.Yg,this.Jr=this.Ju, b.Al&&b.Bl===rh&&this===b.defaultAnimation&&(this.Jr=$h,this.vd=isNaN(this.Yg)?600===b.duration?900:b.duration:this.Yg),this.qx=a.scrollMode,this.isViewportUnconstrained&&(a.Ti=ai),Nh(b),this.pm.each(function(b){b.data=null;a.add(b)}),Ph(b),this.jc=!0,this.Dd=+new Date,this.Xn=this.Dd+this.vd,Rh(b,this)))}};t.sz=function(a,b){a.Pc()&&(this.pm.add(a),this.B=b)}; t.add=function(a,b,c,d,e){if("position"!==b||!c.w(d)){null===this.B&&(a instanceof R?this.B=a:a instanceof Y&&null!==a.diagram&&(this.B=a.diagram));if(a instanceof V){if(!a.isAnimated)return;"position"===b&&(b="position:part")}Uh(this,a,b,c,d,e)}}; function Uh(a,b,c,d,e,f){var g=a.mc;b instanceof R&&"position"===c&&(c="position:diagram");if("fill"===c||"stroke"===c||"background"===c||"areaBackground"===c)bi(d),ci(),d=[di.l,di.I,di.v,di.T],bi(e),ci(),e=[di.l,di.I,di.v,di.T];if(g.contains(b)){var h=g.H(b);var k=h.start;var l=h.end;void 0===k[c]&&(k[c]=ei(d));l[c]=ei(e)}else k={},l={},k[c]=ei(d),l[c]=ei(e),h=k.position,b instanceof Y&&h instanceof I&&!h.s()&&b.diagram.animationManager.Se.contains("Expand SubGraph")&&h.assign(l.position),h=new fi(k, l,f),g.add(b,h);g=k[c];g instanceof I&&!g.s()&&g.assign(a.v);f&&0===c.indexOf("position:")&&b instanceof V?h.Pv.location=ei(b.location):f&&(h.Pv[c]=ei(d))}function ei(a){return a instanceof I?a.copy():a instanceof M?a.copy():a}t.cu=function(a){if(!this.jc)return!1;a=this.mc.H(a);return null!==a&&a.rw};t.dw=function(a){if(!this.jc)return!1;a=this.mc.H(a);return null!==a&&(a.start.position||a.start.location)}; function Sh(a,b){if(!a.Jl||b){var c=a.Wc;if(!1!==a.jc){var d=+new Date,e=d>a.Xn?a.vd:d-a.Dd;b&&(e=a.ux,e<a.vd?(a.Dd=+new Date-e,a.Xn=a.Dd+a.vd):e=a.vd);Nh(c);Oh(a,e);Jf(a.B,!0);Ph(c);d>a.Xn&&(a.Ap&&!a.Il?(a.Dd=+new Date,a.Xn=a.Dd+a.vd,a.Il=!0):a.wm(!1))}}} function Oh(a,b){for(var c=a.vd,d=a.mc.iterator,e=a.Il;d.next();){var f=d.key;if(!(f instanceof Y&&null===f.diagram)){var g=d.value,h=e?g.end:g.start;g=e?g.start:g.end;var k=Xh,l;for(l in g)"position"===l&&(g["position:placeholder"]||g["position:nodeCollapse"])||null===k.get(l)||k.get(l)(f,h[l],g[l],a.Jr,b,c,a)}}}t.stop=function(){this.jc&&this.wm(!0)}; t.wm=function(a){null!==this.wv&&this.wv.Hp.remove(this.Px);if(this.jc){var b=this.B,c=this.Wc;this.Jl=this.jc=c.Al=!1;Nh(c);for(var d=this.mc,e=this.pm.iterator;e.next();)b.remove(e.value);for(e=this.iv.iterator;e.next();)e.value.o();e=this.Ap;d=d.iterator;for(var f=Xh;d.next();){var g=d.key,h=d.value,k=e?h.end:h.start,l=e?h.start:h.end,m=h.Pv,n;for(n in l)if(null!==f.get(n)){var p=n;!h.Jv||"position:nodeCollapse"!==p&&"position:placeholder"!==p||(p="position");f.get(p)(g,k[n],void 0!==m[n]?m[n]: h.Jv?k[n]:l[n],this.Jr,this.vd,this.vd,this)}h.Jv&&void 0!==m.location&&g instanceof V&&(g.location=m.location);h.rw&&g instanceof V&&g.Pb(!1)}if(c.defaultAnimation===this)for(n=this.B.links;n.next();)e=n.value,null===e.sg?(d=e.path,null!==d&&(e.kd=!1,e.o(),d.o())):(e.points=e.sg,e.sg=null);b.Yt.clear();of(b,!1);b.Oa();b.M();Jf(b,!0);this.isViewportUnconstrained&&(b.scrollMode=this.qx);Ph(c);this.lv++;!a&&this.mv>this.lv?(this.Il=!1,this.start()):(this.Yn&&this.Yn(this),Kh(this,null),c.wm(this),b.Eb())}}; t.lk=function(a,b){var c=b.actualBounds,d=null;b instanceof U&&(d=b.placeholder);null!==d?(c=d.da(vc),d=d.padding,c.x+=d.left,c.y+=d.top,this.add(a,"position",c,a.position,!1)):this.add(a,"position",new I(c.x+c.width/2,c.y+c.height/2),a.position,!1);this.add(a,"scale",.01,a.scale,!1);if(a instanceof U)for(a=a.memberParts;a.next();)d=a.value,d instanceof W&&this.lk(d,b)}; t.jk=function(a,b){if(a.isVisible()){var c=null;b instanceof U&&(c=b.placeholder);null!==c?this.add(a,"position:placeholder",a.position,c,!0):this.add(a,"position:nodeCollapse",a.position,b,!0);this.add(a,"scale",a.scale,.01,!0);c=this.mc;c.contains(a)&&(c.H(a).rw=!0);if(a instanceof U)for(a=a.memberParts;a.next();)c=a.value,c instanceof W&&this.jk(c,b)}};t.pA=function(a){var b=this.hv.get(a);null===b&&(b={},this.hv.add(a,b));return b}; na.Object.defineProperties(sh.prototype,{duration:{get:function(){return this.Yg},set:function(a){1>a&&wa(a,">= 1",sh,"duration");this.Yg=a}},reversible:{get:function(){return this.Ap},set:function(a){this.Ap=a}},runCount:{get:function(){return this.mv},set:function(a){0<a?this.mv=a:B("Animation.runCount value must be a positive integer.")}},finished:{get:function(){return this.Yn}, set:function(a){this.Yn!==a&&(this.Yn=a)}},easing:{get:function(){return this.Ju},set:function(a){this.Ju=a}},isViewportUnconstrained:{get:function(){return this.l},set:function(a){this.l=a}},isAnimating:{get:function(){return this.jc}}});sh.prototype.getTemporaryState=sh.prototype.pA;sh.prototype.stop=sh.prototype.stop;sh.prototype.add=sh.prototype.add;sh.prototype.addTemporaryPart=sh.prototype.sz; function Yh(a,b,c,d){a/=d/2;return 1>a?c/2*a*a+b:-c/2*(--a*(a-2)-1)+b}function $h(a,b,c,d){return a===d?b+c:c*(-Math.pow(2,-10*a/d)+1)+b}sh.className="Animation";sh.EaseLinear=function(a,b,c,d){return c*a/d+b};sh.EaseInOutQuad=Yh;sh.EaseInQuad=function(a,b,c,d){return c*(a/=d)*a+b};sh.EaseOutQuad=function(a,b,c,d){return-c*(a/=d)*(a-2)+b};sh.EaseInExpo=function(a,b,c,d){return 0===a?b:c*Math.pow(2,10*(a/d-1))+b};sh.EaseOutExpo=$h; function fi(a,b,c){this.start=a;this.end=b;this.Pv={};this.Jv=c;this.rw=!1}fi.className="AnimationState";function gi(a,b,c){this.qd=null;this.hf=a;this.$p=c||hi;this.bl=null;void 0!==b&&(this.bl=b,void 0===c&&(this.$p=ii))}gi.prototype.copy=function(){var a=new gi(this.hf);a.$p=this.$p;var b=this.bl;if(null!==b){var c={};void 0!==b.duration&&(c.ny=b.duration);void 0!==b.finished&&(c.ny=b.finished);void 0!==b.easing&&(c.ny=b.easing);a.bl=c}return a}; function ji(a,b){a=a.bl;null!==a&&(a.duration&&(b.duration=a.duration),a.finished&&(b.finished=a.finished),a.easing&&(b.easing=a.easing))}na.Object.defineProperties(gi.prototype,{propertyName:{get:function(){return this.hf},set:function(a){this.hf=a}},animationSettings:{get:function(){return this.bl},set:function(a){this.bl=a}},startCondition:{get:function(){return this.$p},set:function(a){this.$p=a}}}); var hi=new D(gi,"Default",1),ii=new D(gi,"Immediate",2),ki=new D(gi,"Bundled",3);gi.className="AnimationTrigger";gi.Default=hi;gi.Immediate=ii;gi.Bundled=ki;function li(){Za(this);this.B=null;this.Da=new E;this.Qa="";this.hb=1;this.v=!1;this.l=this.Oi=this.I=this.hi=this.gi=this.fi=this.ei=this.ci=this.di=this.bi=this.ji=this.ai=this.ii=this.$h=this.Zh=!0;this.mp=[]}t=li.prototype;t.clear=function(){this.Da.clear();this.mp.length=0};t.fe=function(a){this.B=a}; t.toString=function(a){void 0===a&&(a=0);var b='Layer "'+this.name+'"';if(0>=a)return b;for(var c=0,d=0,e=0,f=0,g=0,h=this.Da.iterator;h.next();){var k=h.value;k instanceof U?e++:k instanceof W?d++:k instanceof S?f++:k instanceof Qe?g++:c++}h="";0<c&&(h+=c+" Parts ");0<d&&(h+=d+" Nodes ");0<e&&(h+=e+" Groups ");0<f&&(h+=f+" Links ");0<g&&(h+=g+" Adornments ");if(1<a)for(a=this.Da.iterator;a.next();)c=a.value,h+="\n "+c.toString(),d=c.data,null!==d&&mb(d)&&(h+=" #"+mb(d)),c instanceof W?h+=" "+ Ka(d):c instanceof S&&(h+=" "+Ka(c.fromNode)+" "+Ka(c.toNode));return b+" "+this.Da.count+": "+h};t.Vb=function(a,b,c){void 0===b&&(b=null);void 0===c&&(c=null);if(!1===this.Oi)return null;var d=!1;null!==this.diagram&&this.diagram.viewportBounds.$(a)&&(d=!0);for(var e=I.alloc(),f=this.Da.j,g=f.length;g--;){var h=f[g];if((!0!==d||!1!==yg(h))&&h.isVisible()&&(e.assign(a),yb(e,h.Fd),h=h.Vb(e,b,c),null!==h&&(null!==b&&(h=b(h)),null!==h&&(null===c||c(h)))))return I.free(e),h}I.free(e);return null}; t.hj=function(a,b,c,d){void 0===b&&(b=null);void 0===c&&(c=null);d instanceof E||d instanceof G||(d=new G);if(!1===this.Oi)return d;var e=!1;null!==this.diagram&&this.diagram.viewportBounds.$(a)&&(e=!0);for(var f=I.alloc(),g=this.Da.j,h=g.length;h--;){var k=g[h];if((!0!==e||!1!==yg(k))&&k.isVisible()){f.assign(a);yb(f,k.Fd);var l=k;k.hj(f,b,c,d)&&(null!==b&&(l=b(l)),null===l||null!==c&&!c(l)||d.add(l))}}I.free(f);return d}; t.Bf=function(a,b,c,d,e){void 0===b&&(b=null);void 0===c&&(c=null);void 0===d&&(d=!1);e instanceof E||e instanceof G||(e=new G);if(!1===this.Oi)return e;var f=!1;null!==this.diagram&&this.diagram.viewportBounds.He(a)&&(f=!0);for(var g=this.Da.j,h=g.length;h--;){var k=g[h];if((!0!==f||!1!==yg(k))&&k.isVisible()){var l=k;k.Bf(a,b,c,d,e)&&(null!==b&&(l=b(l)),null===l||null!==c&&!c(l)||e.add(l))}}return e}; t.Uv=function(a,b,c,d,e,f,g){if(!1===this.Oi)return e;for(var h=this.Da.j,k=h.length;k--;){var l=h[k];if((!0!==g||!1!==yg(l))&&f(l)&&l.isVisible()){var m=l;l.Bf(a,b,c,d,e)&&(null!==b&&(m=b(m)),null===m||null!==c&&!c(m)||e.add(m))}}return e}; t.Fg=function(a,b,c,d,e,f){void 0===c&&(c=null);void 0===d&&(d=null);void 0===e&&(e=!0);if(!1!==e&&!0!==e){if(e instanceof E||e instanceof G)f=e;e=!0}f instanceof E||f instanceof G||(f=new G);if(!1===this.Oi)return f;var g=!1;null!==this.diagram&&this.diagram.viewportBounds.$(a)&&(g=!0);for(var h=I.alloc(),k=I.alloc(),l=this.Da.j,m=l.length;m--;){var n=l[m];if((!0!==g||!1!==yg(n))&&n.isVisible()){h.assign(a);yb(h,n.Fd);k.h(a.x+b,a.y);yb(k,n.Fd);var p=n;n.Fg(h,k,c,d,e,f)&&(null!==c&&(p=c(p)),null=== p||null!==d&&!d(p)||f.add(p))}}I.free(h);I.free(k);return f}; t.Nd=function(a,b){if(this.visible){var c=this.Da.j,d=c.length;if(0!==d){a=Ea();for(var e=Ea(),f=0;f<d;f++){var g=c[f];g.Bx=f;if(g instanceof S){if(!1===g.kd)continue}else if(g instanceof Qe&&null!==g.adornedPart)continue;cc(g.actualBounds,b)?(g.Nd(!0),a.push(g)):(g.Nd(!1),null!==g.adornments&&0<g.adornments.count&&e.push(g))}for(b=0;b<a.length;b++)for(c=a[b],mi(c),c=c.adornments;c.next();)d=c.value,d.measure(Infinity,Infinity),d.arrange(),d.Nd(!0);for(b=0;b<e.length;b++)mi(e[b]);Ia(a);Ia(e)}}}; function ni(a,b){var c=1;1!==a.hb&&(c=b.globalAlpha,b.globalAlpha=c*a.hb);return c}t.cc=function(a,b,c){if(this.visible&&0!==this.hb&&(void 0===c&&(c=!0),c||!this.isTemporary)){c=this.Da.j;var d=c.length;if(0!==d){var e=ni(this,a),f=this.mp;f.length=0;for(var g=b.scale,h=N.alloc(),k=0;k<d;k++)this.dj(a,c[k],b,f,g,h,!0);N.free(h);a.globalAlpha=e}}}; t.dj=function(a,b,c,d,e,f,g){if(!g||yg(b)){if(null!==d&&b instanceof S&&(b.isOrthogonal&&d.push(b),!1===b.kd))return;g=!1;for(d=b.containingGroup;null!==d;)g?null!==d.Ya&&f.Dy(d.Ya):null!==d.Ya&&(g=!0,f.assign(d.Ya)),d=d.containingGroup;var h=b.actualBounds;d=!1;if(g&&b.isVisible()){if(!f.Oc(h))return;d=!f.He(h)}d&&(a.save(),a.beginPath(),a.rect(f.x,f.y,f.width,f.height),a.clip());h.width*e>c.So||h.height*e>c.So?b.cc(a,c):(e=b.actualBounds,f=b.naturalBounds,0===e.width||0===e.height||isNaN(e.x)|| isNaN(e.y)||!b.isVisible()||(c=b.transform,null!==b.areaBackground&&(oi(b,a,b.areaBackground,!0,!0,f,e),a.fillRect(e.x,e.y,e.width,e.height)),null===b.areaBackground&&null===b.background&&(oi(b,a,"rgba(0,0,0,0.3)",!0,!1,f,e),a.fillRect(e.x,e.y,e.width,e.height)),null!==b.background&&(a.transform(c.m11,c.m12,c.m21,c.m22,c.dx,c.dy),oi(b,a,b.background,!0,!1,f,e),a.fillRect(0,0,f.width/2,f.height/2),c.Ut()||(b=1/(c.m11*c.m22-c.m12*c.m21),a.transform(c.m22*b,-c.m12*b,-c.m21*b,c.m11*b,b*(c.m21*c.dy-c.m22* c.dx),b*(c.m12*c.dx-c.m11*c.dy))))));d&&(a.restore(),a.uc(!0))}};t.g=function(a,b,c,d,e){var f=this.diagram;null!==f&&f.bb(ze,a,this,b,c,d,e)};t.oj=function(a,b,c){var d=this.Da;b.Ei=this;if(a>=d.count)a=d.count;else if(d.J(a)===b)return-1;d.wb(a,b);b.Jq(c);d=this.diagram;null!==d&&(c?d.M():d.oj(b));pi(this,a,b);return a}; t.Nc=function(a,b,c){if(!c&&b.layer!==this&&null!==b.layer)return b.layer.Nc(a,b,c);var d=this.Da;if(0>a||a>=d.length){if(a=d.indexOf(b),0>a)return-1}else if(d.J(a)!==b&&(a=d.indexOf(b),0>a))return-1;b.Kq(c);d.cb(a);d=this.diagram;null!==d&&(c?d.M():d.Nc(b));b.Ei=null;return a}; function pi(a,b,c){b=qi(a,b,c);if(c instanceof U&&null!==c&&isNaN(c.zOrder)){if(0!==c.memberParts.count){for(var d=-1,e=a.Da.j,f=e.length,g=0;g<f;g++){var h=e[g];if(h===c&&(b=g,0<=d))break;if(0>d&&h.containingGroup===c&&(d=g,0<=b))break}!(0>d)&&d<b&&(e=a.Da,e.cb(b),e.wb(d,c))}c=c.containingGroup;null!==c&&pi(a,-1,c)}} function qi(a,b,c){var d=c.zOrder;if(isNaN(d))return b;a=a.Da;var e=a.count;if(1>=e)return b;0>b&&(b=a.indexOf(c));if(0>b)return-1;for(var f=b-1,g=NaN;0<=f;){g=a.J(f).zOrder;if(!isNaN(g))break;f--}for(var h=b+1,k=NaN;h<e;){k=a.J(h).zOrder;if(!isNaN(k))break;h++}if(!isNaN(g)&&g>d)for(;;){if(-1===f||g<=d){f++;if(f===b)break;a.cb(b);a.wb(f,c);return f}for(g=NaN;0<=--f&&(g=a.J(f).zOrder,isNaN(g)););}else if(!isNaN(k)&&k<d)for(;;){if(h===e||k>=d){h--;if(h===b)break;a.cb(b);a.wb(h,c);return h}for(k=NaN;++h< e&&(k=a.J(h).zOrder,isNaN(k)););}return b} na.Object.defineProperties(li.prototype,{parts:{get:function(){return this.Da.iterator}},partsBackwards:{get:function(){return this.Da.iteratorBackwards}},diagram:{get:function(){return this.B}},name:{get:function(){return this.Qa},set:function(a){var b=this.Qa;if(b!==a){var c=this.diagram;if(null!==c)for(""===b&&B("Cannot rename default Layer to: "+a),c=c.layers;c.next();)c.value.name=== a&&B("Layer.name is already present in this diagram: "+a);this.Qa=a;this.g("name",b,a);for(a=this.Da.iterator;a.next();)a.value.layerName=this.Qa}}},opacity:{get:function(){return this.hb},set:function(a){var b=this.hb;b!==a&&((0>a||1<a)&&wa(a,"0 <= value <= 1",li,"opacity"),this.hb=a,this.g("opacity",b,a),a=this.diagram,null!==a&&a.M())}},isTemporary:{get:function(){return this.v},set:function(a){var b=this.v;b!==a&&(this.v=a,this.isInDocumentBounds= !1,this.g("isTemporary",b,a))}},visible:{get:function(){return this.I},set:function(a){var b=this.I;if(b!==a){this.I=a;this.g("visible",b,a);for(b=this.Da.iterator;b.next();)b.value.Pb(a);a=this.diagram;null!==a&&a.M()}}},pickable:{get:function(){return this.Oi},set:function(a){var b=this.Oi;b!==a&&(this.Oi=a,this.g("pickable",b,a))}},isInDocumentBounds:{get:function(){return this.l},set:function(a){this.l!== a&&(this.l=a,null!==this.diagram&&this.diagram.Oa())}},allowCopy:{get:function(){return this.Zh},set:function(a){var b=this.Zh;b!==a&&(this.Zh=a,this.g("allowCopy",b,a))}},allowDelete:{get:function(){return this.$h},set:function(a){var b=this.$h;b!==a&&(this.$h=a,this.g("allowDelete",b,a))}},allowTextEdit:{get:function(){return this.ii},set:function(a){var b=this.ii;b!==a&&(this.ii=a,this.g("allowTextEdit",b, a))}},allowGroup:{get:function(){return this.ai},set:function(a){var b=this.ai;b!==a&&(this.ai=a,this.g("allowGroup",b,a))}},allowUngroup:{get:function(){return this.ji},set:function(a){var b=this.ji;b!==a&&(this.ji=a,this.g("allowUngroup",b,a))}},allowLink:{get:function(){return this.bi},set:function(a){var b=this.bi;b!==a&&(this.bi=a,this.g("allowLink",b,a))}},allowRelink:{get:function(){return this.di}, set:function(a){var b=this.di;b!==a&&(this.di=a,this.g("allowRelink",b,a))}},allowMove:{get:function(){return this.ci},set:function(a){var b=this.ci;b!==a&&(this.ci=a,this.g("allowMove",b,a))}},allowReshape:{get:function(){return this.ei},set:function(a){var b=this.ei;b!==a&&(this.ei=a,this.g("allowReshape",b,a))}},allowResize:{get:function(){return this.fi},set:function(a){var b=this.fi;b!==a&&(this.fi=a,this.g("allowResize", b,a))}},allowRotate:{get:function(){return this.gi},set:function(a){var b=this.gi;b!==a&&(this.gi=a,this.g("allowRotate",b,a))}},allowSelect:{get:function(){return this.hi},set:function(a){var b=this.hi;b!==a&&(this.hi=a,this.g("allowSelect",b,a))}}});li.prototype.findObjectsNear=li.prototype.Fg;li.prototype.findObjectsIn=li.prototype.Bf;li.prototype.findObjectsAt=li.prototype.hj;li.prototype.findObjectAt=li.prototype.Vb;li.className="Layer"; function R(a){1<arguments.length&&B("Diagram constructor can only take one optional argument, the DIV HTML element or its id.");ri||(si(),ri=!0);Za(this);He=this;Ra=[];this.Sb=!0;this.Wc=new oh;this.Wc.fe(this);this.pb=17;this.Hl=this.ov=!1;this.Us="default";this.Ea=null;if(Wg){var b=this,c=function(){b.removeEventListener(x.document,"DOMContentLoaded",c,!1);b.setRTL()};null!==x.document.body?this.setRTL():b.addEventListener(x.document,"DOMContentLoaded",c,!1)}this.La=new E;this.ua=this.va=0;this.Zl= this.ta=null;this.Lx=new H;this.jf=this.Hb=null;this.yw();this.Nj=null;this.xw();this.hb=1;this.la=(new I(NaN,NaN)).freeze();this.Vs=new I(NaN,NaN);this.On=this.ya=1;this.fs=(new I(NaN,NaN)).freeze();this.gs=NaN;this.ys=1E-4;this.ws=100;this.qb=new rd;this.xt=(new I(NaN,NaN)).freeze();this.$r=(new N(NaN,NaN,NaN,NaN)).freeze();this.Si=(new oc(0,0,0,0)).freeze();this.Ti=Zh;this.ct=!1;this.Ws=this.Ps=null;this.Pg=Lh;this.Dj=Zc;this.$f=Lh;this.po=Zc;this.hs=this.es=vc;this.Fc=!0;this.Fl=!1;this.wd=new G; this.Wg=new H;this.rl=!0;this.on=250;this.Bj=-1;this.qn=(new oc(16,16,16,16)).freeze();this.Hj=this.Fe=!1;this.Kj=!0;this.Yf=new ve;this.Yf.diagram=this;this.pd=new ve;this.pd.diagram=this;this.hh=new ve;this.hh.diagram=this;this.xe=this.Qf=null;this.hk=!1;this.Qr=this.Rr=null;this.zj=x.PointerEvent&&(Ua||Va||Wa)&&x.navigator&&!1!==x.navigator.msPointerEnabled;ti(this);this.Ch=new G;this.rs=!0;this.rt=ui;this.Tu=!1;this.tt=Of;this.Ka=null;vi.add("Model",wi);this.Kr=this.Nr=this.pt=null;this.Nn=this.Ir= "auto";this.ig=this.Bs=this.kg=this.lg=this.ng=this.Sf=this.Wf=this.Rf=null;this.ds=!1;this.Tf=this.xg=this.mg=this.jg=null;this.Cs=!1;this.Ns={};this.bk=[null,null];this.Cr=null;this.Or=this.gt=this.qv=this.wg=!1;this.$u=!0;this.xi=this.kc=!1;this.bc=null;var d=this;this.Dc=function(a){var b=d.partManager;if(a.model===b.diagram.model&&b.diagram.Z){b.diagram.Z=!1;try{var c=a.change;""===a.modelChange&&c===ze&&b.updateDataBindings(a.object,a.propertyName)}finally{b.diagram.Z=!0}}};this.Vc=function(a){d.partManager.doModelChanged(a)}; this.yv=!0;this.Xd=-2;this.Pi=new H;this.Ms=new E;this.bg=!1;this.$h=this.Zh=this.pr=this.nd=!0;this.qr=!1;this.wr=this.ur=this.hi=this.gi=this.fi=this.ei=this.ci=this.di=this.bi=this.tr=this.ji=this.ai=this.ii=this.rr=!0;this.ag=this.Wu=!1;this.vr=this.sr=this.xl=this.wl=!0;this.bt=this.Ys=16;this.Xs=this.Jp=!1;this.Kp=this.$s=null;this.Zs=this.at=0;this.ib=(new oc(5)).freeze();this.pv=(new G).freeze();this.xs=999999999;this.Qu=(new G).freeze();this.wi=this.vi=this.ui=!0;this.Ze=this.qe=!1;this.lc= null;this.Og=!0;this.re=!1;this.Cx=new G;this.Ru=new G;this.Ic=null;this.Wl=1;this.rv=0;this.Kc={scale:1,position:new I,bounds:new N,Fv:new M,jw:new M,gw:!1};this.Sx=(new N(NaN,NaN,NaN,NaN)).freeze();this.rm=(new M(NaN,NaN)).freeze();this.Pn=(new N(NaN,NaN,NaN,NaN)).freeze();this.ss=!1;this.Go=this.no=this.fp=this.Eu=this.Du=this.Fu=this.dg=this.fh=this.ef=this.Ur=null;xi(this);this.Jb=null;this.mo=!1;this.Ej=null;this.partManager=new wi;this.toolManager=new Pa;this.toolManager.initializeStandardTools(); this.currentTool=this.defaultTool=this.toolManager;this.Tr=null;this.kl=new Ye;this.Hs=this.Gs=null;this.bq=!1;this.commandHandler=yi();this.model=zi();this.wg=!0;Ai(this);this.layout=new Bi;this.wg=!1;this.vx=this.Iu=null;this.Tb=1;this.xh=null;this.So=1;this.Yo=0;this.gv=[0,0,0,0,0];this.Zo=0;this.xd=1;this.Sj=0;this.Bo=new I;this.qt=500;this.pn=new I;this.se=!1;this.Pk=this.Qk=this.Ok=this.Nk=this.Ik=this.Kk=this.Jk=this.Gk=this.Hk=this.Xw=this.Nw=this.Ow=this.Pw=null;this.Yq=function(){};this.preventDefault= null;this.ro=!1;this.ti=new Ci;this.cq=!1;void 0!==a&&Di(this,a);this.Zn=null;this.$n=Jb;this.Sb=!1}R.prototype.clear=function(){this.animationManager.Cc();this.model.clear();Ei=null;Fi="";Gi(this,!1);this.Oa();this.Ta();this.M()}; function Gi(a,b){a.animationManager.Cc(!0);a.pv=(new G).freeze();a.Qu=(new G).freeze();var c=a.skipsUndoManager;null!==a.model&&(a.skipsUndoManager=!0);var d=null;null!==a.Jb&&(d=a.Jb.part,null!==d&&a.remove(d));var e=[],f=a.La.length;if(b){for(b=0;b<f;b++)for(var g=a.La.j[b].parts;g.next();){var h=g.value;h!==d&&null===h.data&&e.push(h)}for(b=0;b<e.length;b++)a.remove(e[b])}for(b=0;b<f;b++)a.La.j[b].clear();a.partManager.clear();a.wd.clear();a.Wg.clear();a.Ch.clear();a.Ej=null;Fa=[];null!==d&&(a.add(d), a.partManager.parts.remove(d));null!==a.model&&(a.skipsUndoManager=c);return e}function yi(){return null} R.prototype.reset=function(){this.clear();this.Sb=!0;this.Wc=new oh;this.Wc.fe(this);this.pb=17;this.Hl=this.ov=!1;this.Us="default";this.La=new E;this.Lx=new H;this.jf=null;this.yw();this.Nj=null;this.xw();this.hb=1;this.la=(new I(NaN,NaN)).freeze();this.Vs=new I(NaN,NaN);this.On=this.ya=1;this.fs=(new I(NaN,NaN)).freeze();this.gs=NaN;this.ys=1E-4;this.ws=100;this.qb=new rd;this.xt=(new I(NaN,NaN)).freeze();this.$r=(new N(NaN,NaN,NaN,NaN)).freeze();this.Si=(new oc(0,0,0,0)).freeze();this.Ti=Zh;this.ct= !1;this.Ws=this.Ps=null;this.Pg=Lh;this.Dj=Zc;this.$f=Lh;this.po=Zc;this.hs=this.es=vc;this.Fc=!0;this.Fl=!1;this.wd=new G;this.Wg=new H;this.rl=!0;this.on=250;this.Bj=-1;this.qn=(new oc(16,16,16,16)).freeze();this.Hj=this.Fe=!1;this.Kj=!0;this.Yf=new ve;this.Yf.diagram=this;this.pd=new ve;this.pd.diagram=this;this.hh=new ve;this.hh.diagram=this;this.xe=this.Qf=null;this.hk=!1;this.Qr=this.Rr=null;this.zj=x.PointerEvent&&(Ua||Va||Wa)&&x.navigator&&!1!==x.navigator.msPointerEnabled;ti(this);this.Ch= new G;this.rs=!0;this.rt=ui;this.Tu=!1;this.tt=Of;this.Kr=this.Nr=this.pt=null;this.Nn=this.Ir="auto";this.ig=this.Bs=this.kg=this.lg=this.ng=this.Sf=this.Wf=this.Rf=null;this.ds=!1;this.Tf=this.xg=this.mg=this.jg=null;this.Cs=!1;this.Ns={};this.bk=[null,null];this.Cr=null;this.Or=this.gt=this.qv=this.wg=!1;this.$u=!0;this.xi=this.kc=!1;this.yv=!0;this.Xd=-2;this.Pi=new H;this.Ms=new E;this.bg=!1;this.$h=this.Zh=this.pr=this.nd=!0;this.qr=!1;this.wr=this.ur=this.hi=this.gi=this.fi=this.ei=this.ci= this.di=this.bi=this.tr=this.ji=this.ai=this.ii=this.rr=!0;this.ag=this.Wu=!1;this.vr=this.sr=this.xl=this.wl=!0;this.bt=this.Ys=16;this.Xs=this.Jp=!1;this.Zs=this.at=0;this.ib=(new oc(5)).freeze();this.pv=(new G).freeze();this.xs=999999999;this.Qu=(new G).freeze();this.wi=this.vi=this.ui=!0;this.Ze=this.qe=!1;this.lc=null;this.Og=!0;this.re=!1;this.Cx=new G;this.Ru=new G;this.Ic=null;this.Wl=1;this.rv=0;this.Kc={scale:1,position:new I,bounds:new N,Fv:new M,jw:new M,gw:!1};this.Sx=(new N(NaN,NaN, NaN,NaN)).freeze();this.rm=(new M(NaN,NaN)).freeze();this.Pn=(new N(NaN,NaN,NaN,NaN)).freeze();this.ss=!1;this.Go=this.no=this.fp=this.Eu=this.Du=this.Fu=this.dg=this.fh=this.ef=null;xi(this);this.Jb=null;this.mo=!1;this.Ej=null;this.partManager=new wi;this.toolManager=new Pa;this.toolManager.initializeStandardTools();this.currentTool=this.defaultTool=this.toolManager;this.Tr=null;this.kl=new Ye;this.Hs=this.Gs=null;this.bq=!1;this.commandHandler=yi();this.wg=!0;Ai(this);this.layout=new Bi;this.wg= !1;this.model=zi();this.model.undoManager=new Ee;this.re=!1;this.Kj=!0;this.Fe=!1;this.Tb=1;this.xh=null;this.So=1;this.Yo=0;this.gv=[0,0,0,0,0];this.Zo=0;this.xd=1;this.Sj=0;this.Bo=new I;this.qt=500;this.pn=new I;this.cq=this.ro=this.se=!1;this.Zn=null;this.$n=Jb;this.Sb=!1;this.M()}; function xi(a){a.ef=new H;var b=new W,c=new Yg;c.bind(new Ni("text","",Ka));b.add(c);a.Fu=b;a.ef.add("",b);b=new W;c=new Yg;c.stroke="brown";c.bind(new Ni("text","",Ka));b.add(c);a.ef.add("Comment",b);b=new W;b.selectable=!1;b.avoidable=!1;c=new Mf;c.figure="Ellipse";c.fill="black";c.stroke=null;c.desiredSize=(new M(3,3)).ca();b.add(c);a.ef.add("LinkLabel",b);a.fh=new H;b=new U;b.selectionObjectName="GROUPPANEL";b.type=X.Vertical;c=new Yg;c.font="bold 12pt sans-serif";c.bind(new Ni("text","",Ka)); b.add(c);c=new X(X.Auto);c.name="GROUPPANEL";var d=new Mf;d.figure="Rectangle";d.fill="rgba(128,128,128,0.2)";d.stroke="black";c.add(d);d=new zg;d.padding=(new oc(5,5,5,5)).ca();c.add(d);b.add(c);a.Du=b;a.fh.add("",b);a.dg=new H;b=new S;c=new Mf;c.isPanelMain=!0;b.add(c);c=new Mf;c.toArrow="Standard";c.fill="black";c.stroke=null;c.strokeWidth=0;b.add(c);a.Eu=b;a.dg.add("",b);b=new S;c=new Mf;c.isPanelMain=!0;c.stroke="brown";b.add(c);a.dg.add("Comment",b);b=new Qe;b.type=X.Auto;c=new Mf;c.fill=null; c.stroke="dodgerblue";c.strokeWidth=3;b.add(c);c=new zg;c.margin=(new oc(1.5,1.5,1.5,1.5)).ca();b.add(c);a.fp=b;a.no=b;b=new Qe;b.type=X.Link;c=new Mf;c.isPanelMain=!0;c.fill=null;c.stroke="dodgerblue";c.strokeWidth=3;b.add(c);a.Go=b} R.prototype.setRTL=function(a){a=void 0===a?this.div:a;null===a&&(a=x.document.body);var b=ua("div");b.dir="rtl";b.style.cssText="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll;";b.textContent="A";a.appendChild(b);var c="reverse";0<b.scrollLeft?c="default":(b.scrollLeft=1,0===b.scrollLeft&&(c="negative"));a.removeChild(b);this.Us=c}; R.prototype.setScrollWidth=function(a){a=void 0===a?this.div:a;null===a&&(a=x.document.body);var b=0;if(Wg){var c=Oi;b=Pi;null===c&&(c=Oi=ua("p"),c.style.width="100%",c.style.height="200px",c.style.boxSizing="content-box",b=Pi=ua("div"),b.style.position="absolute",b.style.visibility="hidden",b.style.width="200px",b.style.height="150px",b.style.boxSizing="content-box",b.appendChild(c));b.style.overflow="hidden";a.appendChild(b);var d=c.offsetWidth;b.style.overflow="scroll";c=c.offsetWidth;d===c&&(c= b.clientWidth);a.removeChild(b);b=d-c;0!==b||Ya||(b=11)}this.pb=b;this.ov=!0};R.prototype.jb=function(a){a.classType===R&&(this.autoScale=a)};R.prototype.toString=function(a){void 0===a&&(a=0);var b="";this.div&&this.div.id&&(b=this.div.id);b='Diagram "'+b+'"';if(0>=a)return b;for(var c=this.La.iterator;c.next();)b+="\n "+c.value.toString(a-1);return b};R.prototype.addEventListener=function(a,b,c,d){a.addEventListener(b,c,{capture:d,passive:!1})}; R.prototype.removeEventListener=function(a,b,c,d){a.removeEventListener(b,c,{capture:d})}; function Qi(a){var b=a.ta.Ga;b instanceof HTMLCanvasElement&&(a.zj?(a.addEventListener(b,"pointerdown",a.Nk,!1),a.addEventListener(b,"pointermove",a.Ok,!1),a.addEventListener(b,"pointerup",a.Qk,!1),a.addEventListener(b,"pointerout",a.Pk,!1)):(a.addEventListener(b,"touchstart",a.Pw,!1),a.addEventListener(b,"touchmove",a.Ow,!1),a.addEventListener(b,"touchend",a.Nw,!1),a.addEventListener(b,"mousemove",a.Hk,!1),a.addEventListener(b,"mousedown",a.Gk,!1),a.addEventListener(b,"mouseup",a.Jk,!1),a.addEventListener(b, "mouseout",a.Ik,!1)),a.addEventListener(b,"mouseenter",a.Oz,!1),a.addEventListener(b,"mouseleave",a.Pz,!1),a.addEventListener(b,"wheel",a.Kk,!1),a.addEventListener(b,"keydown",a.BA,!1),a.addEventListener(b,"keyup",a.CA,!1),a.addEventListener(b,"blur",a.Az,!1),a.addEventListener(b,"focus",a.Bz,!1),a.addEventListener(b,"selectstart",function(a){a.preventDefault();return!1},!1),a.addEventListener(b,"contextmenu",function(a){a.preventDefault();return!1},!1),a.addEventListener(b,"gesturestart",function(b){a.toolManager.gestureBehavior!== Te&&(a.toolManager.gestureBehavior===Se?b.preventDefault():a.se&&a.lastInput.handled||(b.preventDefault(),a.Wl=a.scale,a.currentTool.doCancel()))},!1),a.addEventListener(b,"gesturechange",function(b){if(a.toolManager.gestureBehavior!==Te)if(a.toolManager.gestureBehavior===Se)b.preventDefault();else if(!a.se||!a.lastInput.handled){b.preventDefault();var c=b.scale;if(null!==a.Wl){var e=a.ta.getBoundingClientRect();b=new I(b.pageX-x.scrollX-a.va/e.width*e.left,b.pageY-x.scrollY-a.ua/e.height*e.top); c=a.Wl*c;e=a.commandHandler;if(c!==a.scale&&e.canResetZoom(c)){var f=a.zoomPoint;a.zoomPoint=b;e.resetZoom(c);a.zoomPoint=f}}}},!1),a.addEventListener(x,"resize",a.Xw,!1))}function af(a){30<a.Yo&&(a.xh=1)}function
(a,b){null!==a.xh&&(a.xh=null,b&&a.Yq(),db&&db.my||(a.Yo=0,a.gv=[0,0,0,0,0],a.Zo=0))}R.prototype.computePixelRatio=function(){return null!==this.xh?this.xh:x.devicePixelRatio||1};R.prototype.doMouseMove=function(){this.currentTool.doMouseMove()};R.prototype.doMouseDown=function(){this.currentTool.doMouseDown()}; R.prototype.doMouseUp=function(){this.currentTool.doMouseUp()};R.prototype.doMouseWheel=function(){this.currentTool.doMouseWheel()};R.prototype.doKeyDown=function(){this.currentTool.doKeyDown()};R.prototype.doKeyUp=function(){this.currentTool.doKeyUp()};R.prototype.doFocus=function(){this.focus()};R.prototype.focus=function(){if(this.ta)if(this.scrollsPageOnFocus)this.ta.focus();else{var a=x.scrollX||x.pageXOffset,b=x.scrollY||x.pageYOffset;this.ta.focus();x.scrollTo(a,b)}};R.prototype.Bz=function(){this.B.R("GainedFocus")}; R.prototype.Az=function(){this.B.R("LostFocus")};function Mh(a){if(null!==a.ta){var b=a.Ea;if(0!==b.clientWidth&&0!==b.clientHeight){a.ov||a.setScrollWidth();var c=a.Ze?a.pb:0,d=a.qe?a.pb:0,e=a.Tb;a.Tb=a.computePixelRatio();a.Tb!==e&&(a.Fl=!0,a.Eb());if(b.clientWidth!==a.va+c||b.clientHeight!==a.ua+d)a.vi=!0,a.Fc=!0,b=a.layout,null!==b&&b.isViewportSized&&a.autoScale===Lh&&(a.Hj=!0,b.C()),a.kc||a.Eb()}}} function Ai(a){var b=new li;b.name="Background";a.tm(b);b=new li;b.name="";a.tm(b);b=new li;b.name="Foreground";a.tm(b);b=new li;b.name="Adornment";b.isTemporary=!0;b.isInDocumentBounds=!1;a.tm(b);b=new li;b.name="Tool";b.isTemporary=!0;b.isInDocumentBounds=!0;a.tm(b);b=new li;b.name="Grid";b.allowSelect=!1;b.pickable=!1;b.isTemporary=!0;b.isInDocumentBounds=!1;a.Vx(b,a.ym("Background"))} function Ri(a){a.Jb=new X(X.Grid);a.Jb.name="GRID";var b=new Mf;b.figure="LineH";b.stroke="lightgray";b.strokeWidth=.5;b.interval=1;a.Jb.add(b);b=new Mf;b.figure="LineH";b.stroke="gray";b.strokeWidth=.5;b.interval=5;a.Jb.add(b);b=new Mf;b.figure="LineH";b.stroke="gray";b.strokeWidth=1;b.interval=10;a.Jb.add(b);b=new Mf;b.figure="LineV";b.stroke="lightgray";b.strokeWidth=.5;b.interval=1;a.Jb.add(b);b=new Mf;b.figure="LineV";b.stroke="gray";b.strokeWidth=.5;b.interval=5;a.Jb.add(b);b=new Mf;b.figure= "LineV";b.stroke="gray";b.strokeWidth=1;b.interval=10;a.Jb.add(b);b=new V;b.add(a.Jb);b.layerName="Grid";b.zOrder=0;b.isInDocumentBounds=!1;b.isAnimated=!1;b.pickable=!1;b.locationObjectName="GRID";a.add(b);a.partManager.parts.remove(b);a.Jb.visible=!1}function Si(){this.B.Xs?this.B.Xs=!1:this.B.isEnabled?this.B.iy(this):Ti(this.B)}function Ui(a){this.B.isEnabled?(this.B.at=a.target.scrollTop,this.B.Zs=a.target.scrollLeft):Ti(this.B)} R.prototype.iy=function(a){if(null!==this.ta){this.Jp=!0;var b=this.documentBounds,c=this.viewportBounds,d=this.Si,e=b.x-d.left,f=b.y-d.top,g=b.width+d.left+d.right,h=b.height+d.top+d.bottom,k=b.right+d.right;d=b.bottom+d.bottom;var l=c.x;b=c.y;var m=c.width,n=c.height,p=c.right,r=c.bottom;c=this.scale;var q=a.scrollLeft;if(this.Hl)switch(this.Us){case "negative":q=q+a.scrollWidth-a.clientWidth;break;case "reverse":q=a.scrollWidth-q-a.clientWidth}var u=q;m<g||n<h?(q=I.allocAt(this.position.x,this.position.y), this.allowHorizontalScroll&&this.Zs!==u&&(q.x=u/c+e,this.Zs=u),this.allowVerticalScroll&&this.at!==a.scrollTop&&(q.y=a.scrollTop/c+f,this.at=a.scrollTop),this.position=q,I.free(q),this.vi=this.Jp=!1):(q=I.alloc(),a.hz&&this.allowHorizontalScroll&&(e<l&&(this.position=q.h(u+e,this.position.y)),k>p&&(this.position=q.h(-(this.$s.scrollWidth-this.va)+u-this.va/c+k,this.position.y))),a.iz&&this.allowVerticalScroll&&(f<b&&(this.position=q.h(this.position.x,a.scrollTop+f)),d>r&&(this.position=q.h(this.position.x, -(this.$s.scrollHeight-this.ua)+a.scrollTop-this.ua/c+d))),I.free(q),Vi(this),this.vi=this.Jp=!1,b=this.documentBounds,c=this.viewportBounds,k=b.right,p=c.right,d=b.bottom,r=c.bottom,e=b.x,l=c.x,f=b.y,b=c.y,m>=g&&e>=l&&k<=p&&(this.Kp.style.width="1px"),n>=h&&f>=b&&d<=r&&(this.Kp.style.height="1px"))}};R.prototype.computeBounds=function(){0<this.wd.count&&Wi(this);return Xi(this)}; function Xi(a){if(a.fixedBounds.s()){var b=a.fixedBounds.copy();b.rq(a.ib);return b}for(var c=!0,d=a.La.j,e=d.length,f=0;f<e;f++){var g=d[f];if(g.visible&&g.isInDocumentBounds){g=g.Da.j;for(var h=g.length,k=0;k<h;k++){var l=g[k];l.isInDocumentBounds&&l.isVisible()&&(l=l.actualBounds,l.s()&&(c?(c=!1,b=l.copy()):b.Tc(l)))}}}c&&(b=new N(0,0,0,0));b.rq(a.ib);return b} R.prototype.computePartsBounds=function(a,b){void 0===b&&(b=!1);var c=null;if(Aa(a))for(var d=0;d<a.length;d++){var e=a[d];!b&&e instanceof S||(e.Ta(),null===c?c=e.actualBounds.copy():c.Tc(e.actualBounds))}else for(a=a.iterator;a.next();)d=a.value,!b&&d instanceof S||(d.Ta(),null===c?c=d.actualBounds.copy():c.Tc(d.actualBounds));return null===c?new N(NaN,NaN,0,0):c}; function Yi(a,b){if((b||a.re)&&!a.Sb&&null!==a.ta&&a.documentBounds.s()){if(b){var c=a.initialPosition;if(c.s()){a.position=c;return}c=I.alloc();c.tj(a.documentBounds,a.initialDocumentSpot);var d=a.viewportBounds;d=N.allocAt(0,0,d.width,d.height);var e=I.alloc();e.tj(d,a.initialViewportSpot);e.h(c.x-e.x,c.y-e.y);a.position=e;N.free(d);I.free(e);I.free(c)}a.Sb=!0;c=a.Pg;b&&a.$f!==Lh&&(c=a.$f);d=c!==Lh?Zi(a,c):a.scale;c=a.viewportBounds.copy();e=a.va/d;var f=a.ua/d,g=a.Dj,h=a.po;b&&!g.kb()&&(h.kb()|| h.Nb())&&(g=h.Nb()?Bc:h);$i(a,a.documentBounds,e,f,g,b);b=a.scale;a.scale=d;a.Sb=!1;d=a.viewportBounds;d.Na(c)||a.Uq(c,d,b,!1);aj(a);bj(a,!0,!1)}} function Zi(a,b){var c=a.On;if(null===a.ta)return c;a.Ta();var d=a.documentBounds;if(!d.s())return c;var e=d.width;d=d.height;var f=a.va+(a.Ze?a.pb:0),g=a.ua+(a.qe?a.pb:0),h=f/e,k=g/d;return b===cj?(b=Math.min(k,h),b>c&&(b=c),b<a.minScale&&(b=a.minScale),b>a.maxScale&&(b=a.maxScale),b):b===dj?(b=k>h?(g-a.pb)/d:(f-a.pb)/e,b>c&&(b=c),b<a.minScale&&(b=a.minScale),b>a.maxScale&&(b=a.maxScale),b):a.scale} R.prototype.zoomToFit=function(){var a=this.Ti;this.Ti=Zh;this.scale=Zi(this,cj);a!==Zh&&(Yi(this,!1),$i(this,this.documentBounds,this.va/this.ya,this.ua/this.ya,this.Dj,!1));this.Ti=a};t=R.prototype; t.kB=function(a,b){void 0===b&&(b=cj);var c=a.width,d=a.height;if(!(0===c||0===d||isNaN(c)&&isNaN(d))){var e=1;if(b===cj||b===dj)if(isNaN(c))e=this.viewportBounds.height*this.scale/d;else if(isNaN(d))e=this.viewportBounds.width*this.scale/c;else{e=this.va;var f=this.ua;e=b===dj?f/d>e/c?(f-(this.qe?this.pb:0))/d:(e-(this.Ze?this.pb:0))/c:Math.min(f/d,e/c)}this.scale=e;this.position=new I(a.x,a.y)}}; t.uz=function(a,b){this.Ta();var c=this.documentBounds,d=this.viewportBounds;this.position=new I(c.x+(a.x*c.width+a.offsetX)-(b.x*d.width-b.offsetX),c.y+(a.y*c.height+a.offsetY)-(b.y*d.height-b.offsetY))};t.kA=function(a){if(a instanceof Y){this.Zn=a;var b=I.alloc();this.$n=this.hr(a.da(vc,b));I.free(b)}else this.Zn=null,this.$n=Jb}; function $i(a,b,c,d,e,f){var g=I.allocAt(a.la.x,a.la.y),h=g.x,k=g.y;if(null!==a.Zn){var l=I.alloc();l=a.Zn.da(vc,l);h=l.x-a.$n.x/a.scale;k=l.y-a.$n.y/a.scale;e=uc;I.free(l)}if(f||a.scrollMode===Zh)e.kb()&&(c>b.width&&(h=b.x+(e.x*b.width+e.offsetX)-(e.x*c-e.offsetX)),d>b.height&&(k=b.y+(e.y*b.height+e.offsetY)-(e.y*d-e.offsetY))),e=a.Si,f=c-b.width,c<b.width+e.left+e.right?(h=Math.min(h+c/2,b.right+Math.max(f,e.right)-c/2),h=Math.max(h,b.left-Math.max(f,e.left)+c/2),h-=c/2):h>b.left?h=b.left:h<b.right- c&&(h=b.right-c),c=d-b.height,d<b.height+e.top+e.bottom?(k=Math.min(k+d/2,b.bottom+Math.max(c,e.bottom)-d/2),k=Math.max(k,b.top-Math.max(c,e.top)+d/2),k-=d/2):k>b.top?k=b.top:k<b.bottom-d&&(k=b.bottom-d);g.x=isFinite(h)?h:-a.ib.left;g.y=isFinite(k)?k:-a.ib.top;null!==a.positionComputation&&(b=a.positionComputation(a,g),g.x=b.x,g.y=b.y);a.Wc.sc&&Vh(a.Wc,a.la,g);a.la.h(g.x,g.y);I.free(g)} t.zm=function(a,b){void 0===b&&(b=!0);if(b){if(a=yf(this,a,function(a){return a.part},function(a){return a.canSelect()}),a instanceof V)return a}else if(a=yf(this,a,function(a){return a.part}),a instanceof V)return a;return null};t.Vb=function(a,b,c){void 0===b&&(b=null);void 0===c&&(c=null);Wi(this);for(var d=this.La.iteratorBackwards;d.next();){var e=d.value;if(e.visible&&(e=e.Vb(a,b,c),null!==e))return e}return null}; function yf(a,b,c,d){void 0===c&&(c=null);void 0===d&&(d=null);Wi(a);for(a=a.La.iteratorBackwards;a.next();){var e=a.value;if(e.visible&&!e.isTemporary&&(e=e.Vb(b,c,d),null!==e))return e}return null}t.Zz=function(a,b,c){void 0===b&&(b=!0);return ej(this,a,function(a){return a.part},b?function(a){return a instanceof V&&a.canSelect()}:null,c)}; function ej(a,b,c,d,e){void 0===c&&(c=null);void 0===d&&(d=null);e instanceof E||e instanceof G||(e=new G);Wi(a);for(a=a.La.iteratorBackwards;a.next();){var f=a.value;f.visible&&!f.isTemporary&&f.hj(b,c,d,e)}return e}t.hj=function(a,b,c,d){void 0===b&&(b=null);void 0===c&&(c=null);d instanceof E||d instanceof G||(d=new G);Wi(this);for(var e=this.La.iteratorBackwards;e.next();){var f=e.value;f.visible&&f.hj(a,b,c,d)}return d}; t.ty=function(a,b,c,d){void 0===b&&(b=!1);void 0===c&&(c=!0);return fj(this,a,function(a){return a instanceof V&&(!c||a.canSelect())},b,d)};t.Bf=function(a,b,c,d,e){void 0===b&&(b=null);void 0===c&&(c=null);void 0===d&&(d=!1);e instanceof E||e instanceof G||(e=new G);Wi(this);for(var f=this.La.iteratorBackwards;f.next();){var g=f.value;g.visible&&g.Bf(a,b,c,d,e)}return e}; t.Uv=function(a,b,c,d,e,f){var g=new G;Wi(this);for(var h=this.La.iteratorBackwards;h.next();){var k=h.value;k.visible&&k.Uv(a,b,c,d,g,e,f)}return g};function fj(a,b,c,d,e){var f=null;void 0===f&&(f=null);void 0===c&&(c=null);void 0===d&&(d=!1);e instanceof E||e instanceof G||(e=new G);Wi(a);for(a=a.La.iteratorBackwards;a.next();){var g=a.value;g.visible&&!g.isTemporary&&g.Bf(b,f,c,d,e)}return e} t.$z=function(a,b,c,d,e){void 0===c&&(c=!0);void 0===d&&(d=!0);return gj(this,a,b,function(a){return a instanceof V&&(!d||a.canSelect())},c,e)};t.Fg=function(a,b,c,d,e,f){void 0===c&&(c=null);void 0===d&&(d=null);void 0===e&&(e=!0);if(!1!==e&&!0!==e){if(e instanceof E||e instanceof G)f=e;e=!0}f instanceof E||f instanceof G||(f=new G);Wi(this);for(var g=this.La.iteratorBackwards;g.next();){var h=g.value;h.visible&&h.Fg(a,b,c,d,e,f)}return f}; function gj(a,b,c,d,e,f){var g=null;void 0===g&&(g=null);void 0===d&&(d=null);void 0===e&&(e=!0);if(!1!==e&&!0!==e){if(e instanceof E||e instanceof G)f=e;e=!0}f instanceof E||f instanceof G||(f=new G);Wi(a);for(a=a.La.iteratorBackwards;a.next();){var h=a.value;h.visible&&!h.isTemporary&&h.Fg(b,c,g,d,e,f)}return f}R.prototype.acceptEvent=function(a){return hj(this,a,a instanceof MouseEvent)}; function hj(a,b,c){var d=a.pd;a.pd=a.hh;a.hh=d;d.diagram=a;d.event=b;c?ij(a,b,d):(d.viewPoint=a.pd.viewPoint,d.documentPoint=a.pd.documentPoint);a=0;b.ctrlKey&&(a+=1);b.altKey&&(a+=2);b.shiftKey&&(a+=4);b.metaKey&&(a+=8);d.modifiers=a;d.button=b.button;void 0===b.buttons||Ta||(d.buttons=b.buttons);Xa&&0===b.button&&b.ctrlKey&&(d.button=2);d.down=!1;d.up=!1;d.clickCount=1;d.delta=0;d.handled=!1;d.bubbles=!1;d.timestamp=b.timeStamp;d.isMultiTouch=!1;d.targetDiagram=jj(b);d.targetObject=null;return d} function jj(a){var b=a.target.B;if(!b){var c=a.path;c||"function"!==typeof a.composedPath||(c=a.composedPath());c&&c[0]&&(b=c[0].B)}return b?b:null}function kj(a,b,c,d){var e=lj(a,b,!0,!1,!0,d);ij(a,c,e);e.targetDiagram=jj(b);e.targetObject=null;d||e.clone(a.Yf);return e} function mj(a,b,c,d){d=lj(a,b,!1,!1,!1,d);if(null!==c){var e=x.document.elementFromPoint(c.clientX,c.clientY);null!==e&&void 0!==e.shadowRoot&&null!==e.shadowRoot&&(e=e.shadowRoot.elementFromPoint(c.clientX,c.clientY));e&&e.B?(b=c,c=e.B):(b=void 0!==b.targetTouches?b.targetTouches[0]:b,c=a);d.targetDiagram=c;ij(a,b,d)}else null!==a.pd?(d.documentPoint=a.pd.documentPoint,d.viewPoint=a.pd.viewPoint,d.targetDiagram=a.pd.targetDiagram):null!==a.Yf&&(d.documentPoint=a.Yf.documentPoint,d.viewPoint=a.Yf.viewPoint, d.targetDiagram=a.Yf.targetDiagram);d.targetObject=null;return d} function lj(a,b,c,d,e,f){var g=a.pd;a.pd=a.hh;a.hh=g;g.diagram=a;g.clickCount=1;var h=g.delta=0;b.ctrlKey&&(h+=1);b.altKey&&(h+=2);b.shiftKey&&(h+=4);b.metaKey&&(h+=8);g.modifiers=h;g.button=0;g.buttons=1;g.event=b;g.timestamp=b.timeStamp;a.zj&&b instanceof x.PointerEvent&&"touch"!==b.pointerType&&(g.button=b.button,void 0===b.buttons||Ta||(g.buttons=b.buttons),Xa&&0===b.button&&b.ctrlKey&&(g.button=2));g.down=c;g.up=d;g.handled=!1;g.bubbles=e;g.isMultiTouch=f;return g} function nj(a,b){if(a.bubbles)return!0;void 0!==b.stopPropagation&&b.stopPropagation();!1!==b.cancelable&&b.preventDefault();b.cancelBubble=!0;return!1} R.prototype.BA=function(a){var b=this.B;if(!this.B.isEnabled)return!1;var c=hj(b,a,!1);c.key=String.fromCharCode(a.which);c.down=!0;switch(a.which){case 8:c.key="Backspace";break;case 33:c.key="PageUp";break;case 34:c.key="PageDown";break;case 35:c.key="End";break;case 36:c.key="Home";break;case 37:c.key="Left";break;case 38:c.key="Up";break;case 39:c.key="Right";break;case 40:c.key="Down";break;case 45:c.key="Insert";break;case 46:c.key="Del";break;case 48:c.key="0";break;case 187:case 61:case 107:c.key= "Add";break;case 189:case 173:case 109:c.key="Subtract";break;case 27:c.key="Esc"}b.doKeyDown();return nj(c,a)}; R.prototype.CA=function(a){var b=this.B;if(!b.isEnabled)return!1;var c=hj(b,a,!1);c.key=String.fromCharCode(a.which);c.up=!0;switch(a.which){case 8:c.key="Backspace";break;case 33:c.key="PageUp";break;case 34:c.key="PageDown";break;case 35:c.key="End";break;case 36:c.key="Home";break;case 37:c.key="Left";break;case 38:c.key="Up";break;case 39:c.key="Right";break;case 40:c.key="Down";break;case 45:c.key="Insert";break;case 46:c.key="Del"}b.doKeyUp();return nj(c,a)}; R.prototype.Oz=function(a){var b=this.B;if(!b.isEnabled)return!1;var c=hj(b,a,!0);null!==b.mouseEnter&&b.mouseEnter(c);return nj(c,a)};R.prototype.Pz=function(a){var b=this.B;if(!b.isEnabled)return!1;var c=hj(b,a,!0);null!==b.mouseLeave&&b.mouseLeave(c);return nj(c,a)}; R.prototype.getMouse=function(a){var b=this.ta;if(null===b)return new I(0,0);var c=b.getBoundingClientRect();b=a.clientX-this.va/c.width*c.left;a=a.clientY-this.ua/c.height*c.top;return null!==this.qb?yb(new I(b,a),this.qb):new I(b,a)}; function ij(a,b,c){var d=a.ta,e=a.va,f=a.ua,g=0,h=0;null!==d&&(d=d.getBoundingClientRect(),g=b.clientX-e/d.width*d.left,h=b.clientY-f/d.height*d.top);c.viewPoint.h(g,h);null!==a.qb?(b=I.allocAt(g,h),a.qb.Jd(b),c.documentPoint.assign(b),I.free(b)):c.documentPoint.h(g,h)} function we(a,b,c,d){if(void 0!==b.targetTouches){if(2>b.targetTouches.length)return;b=b.targetTouches[c]}else if(null!==a.bk[0])b=a.bk[c];else return;c=a.ta;null!==c&&(c=c.getBoundingClientRect(),d.h(b.clientX-a.va/c.width*c.left,b.clientY-a.ua/c.height*c.top))}t=R.prototype;t.Oa=function(){this.ui||(this.ui=!0,this.Eb(!0))};function oj(a){a.kc||Wi(a);a.Ta()}t.Ne=function(){this.Sb||this.kc||(this.M(),aj(this),Vi(this),this.Oa(),this.jd())};t.AA=function(){return this.Fe}; t.Jz=function(a){void 0===a&&(a=null);var b=this.animationManager,c=b.isEnabled;b.Cc();b.isEnabled=!1;Jf(this);this.re=!1;this.Vs=new I(NaN,NaN);b.isEnabled=c;this.kc=!0;var d=this;null!==a&&ta(function(){d.kc=!1;th(b,"Model");a()},1)};t.Eb=function(a){void 0===a&&(a=!1);if(!0!==this.Fe&&!(this.Sb||!1===a&&this.kc)){this.Fe=!0;var b=this;x.requestAnimationFrame(function(){b.Fe&&b.jd()})}};t.jd=function(){if(!this.Kj||this.Fe)this.Kj&&(this.Kj=!1),Jf(this)}; function bj(a,b,c){a.animationManager.defaultAnimation.isAnimating||a.Sb||!a.vi||Ti(a)||(b&&Wi(a),c&&Yi(a,!1))} function Jf(a,b){if(!a.kc&&(a.Fe=!1,null!==a.Ea||a.rm.s())){a.kc=!0;var c=a.animationManager,d=a.Ms;if(!c.isAnimating&&0!==d.length){for(var e=d.j,f=e.length,g=0;g<f;g++){var h=e[g];pj(h,!1);h.o()}d.clear()}d=a.Ru;0<d.count&&(d.each(function(a){a.Ww()}),d.clear());e=d=!1;c.isAnimating&&(e=!0,d=a.skipsUndoManager,a.skipsUndoManager=!0);c.sc||Mh(a);bj(a,!1,!0);null!==a.Jb&&(a.Jb.visible&&!a.mo&&(qj(a),a.mo=!0),!a.Jb.visible&&a.mo&&(a.mo=!1));Wi(a);f=!1;if(!a.re||a.Og)a.re?rj(a,!a.Hj):(a.xa("Initial Layout"), !1===c.isEnabled&&c.Cc(),rj(a,!1)),f=!0;a.Hj=!1;Wi(a);a.gt||oj(a);bj(a,!0,!1);g=!1;f?(c=N.alloc(),c.assign(a.viewportBounds),a.re||(g=a.re=!0,a.skipsUndoManager||(a.undoManager.isPendingClear=!0),a.undoManager.isPendingUnmodified=!0,sj(a)),a.R("LayoutCompleted"),c.w(a.viewportBounds)||bj(a,!0,!1),N.free(c)):c.Al&&c.Rx&&(a.$f!==Lh?a.scale=Zi(a,a.$f):a.Pg!==Lh?a.scale=Zi(a,a.Pg):(c=a.initialScale,isFinite(c)&&0<c&&(a.scale=c)),Yi(a,!0));Wi(a);f&&g&&a.Wa("Initial Layout");a.Gv();b||a.cc(a.Hb);e&&(a.skipsUndoManager= d);a.kc=!1}}function sj(a){var b=a.ya;if(a.$f!==Lh)a.scale=Zi(a,a.$f);else if(a.Pg!==Lh)a.scale=Zi(a,a.Pg);else{var c=a.initialScale;isFinite(c)&&0<c&&(a.scale=c)}a.ya!==b&&(aj(a),bj(a,!0,!1));Yi(a,!0);b=a.La.j;a.Nd(b,b.length,a);a.R("InitialLayoutCompleted");a.Vs.assign(a.la);qj(a)} function Wi(a){if((a.kc||!a.animationManager.isTicking)&&0!==a.wd.count){for(var b=0;23>b;b++){var c=a.wd.iterator;if(null===c||0===a.wd.count)break;a.wd=new G;a.Ww(c,a.wd)}a.nodes.each(function(a){a instanceof U&&0!==(a.P&65536)!==!1&&(a.P=a.P^65536)})}} t.Ww=function(a,b){for(a.reset();a.next();){var c=a.value;!c.Pc()||c instanceof U||(c.rj()?(c.measure(Infinity,Infinity),c.arrange()):b.add(c))}for(a.reset();a.next();)c=a.value,c instanceof U&&c.isVisible()&&tj(this,c);for(a.reset();a.next();)c=a.value,c instanceof S&&c.isVisible()&&(c.rj()?(c.measure(Infinity,Infinity),c.arrange()):b.add(c));for(a.reset();a.next();)c=a.value,c instanceof Qe&&c.isVisible()&&(c.rj()?(c.measure(Infinity,Infinity),c.arrange()):b.add(c))}; function tj(a,b){for(var c=Ea(),d=Ea(),e=b.memberParts;e.next();){var f=e.value;f.isVisible()&&(f instanceof U?(uj(f)||vj(f)||wj(f))&&tj(a,f):f instanceof S?f.fromNode===b||f.toNode===b?d.push(f):c.push(f):(f.measure(Infinity,Infinity),f.arrange()))}a=c.length;for(e=0;e<a;e++)f=c[e],f.measure(Infinity,Infinity),f.arrange();Ia(c);b.measure(Infinity,Infinity);b.arrange();a=d.length;for(b=0;b<a;b++)c=d[b],c.measure(Infinity,Infinity),c.arrange();Ia(d)} t.Nd=function(a,b,c,d){if(this.wi||this.animationManager.isAnimating){void 0===d&&(d=c.viewportBounds);for(var e=0;e<b;e++)a[e].Nd(c,d)}}; t.cc=function(a,b){void 0===b&&(b=null);if(null!==this.Ea){null===this.ta&&B("No canvas specified");var c=this.animationManager;if(!c.sc&&(!c.isAnimating||c.isTicking)){var d=new Date;xj(this);if("0"!==this.Ea.style.opacity){var e=a!==this.Hb,f=this.La.j,g=f.length,h=this;this.Nd(f,g,h);if(e)a.uc(!0),Vi(this);else if(!this.Fc&&null===b&&!c.isAnimating)return;g=this.la;var k=this.ya,l=Math.round(g.x*k)/k,m=Math.round(g.y*k)/k;c=this.qb;c.reset();1!==k&&c.scale(k);0===g.x&&0===g.y||c.translate(-l,-m); k=this.Tb;a.setTransform(1,0,0,1,0,0);a.scale(k,k);a.clearRect(0,0,this.va,this.ua);1!==this.hb&&(a.globalAlpha=this.hb);yj(this,a);l=null!==b?function(c){var d=b;if(c.visible&&0!==c.hb){var e=c.Da.j,f=e.length;if(0!==f){var g=ni(c,a),k=c.mp;k.length=0;for(var l=h.scale,m=N.alloc(),n=0;n<f;n++){var A=e[n];d.contains(A)||c.dj(a,A,h,k,l,m,!0)}N.free(m);a.globalAlpha=g}}}:function(b){b.cc(a,h)};g=f.length;for(m=0;m<g;m++)a.setTransform(1,0,0,1,0,0),a.scale(k,k),a.transform(c.m11,c.m12,c.m21,c.m22,c.dx, c.dy),l(f[m]);f=!1;this.ti?zj(this.ti,this)&&(f=this.Ur()):f=!0;f&&(rd.prototype.Jd=rd.prototype.$x);e?(this.Hb.uc(!0),Vi(this)):this.Fc=this.wi=!1;f=+new Date-+d;e=db&&db.my;d=this.gv;if(e||null===this.xh){d[this.Zo]=f;this.Zo=(this.Zo+1)%d.length;for(c=f=0;c<d.length;c++)f+=d[c];this.Yo=f/d.length}1!==this.hb&&(a.globalAlpha=1);if(e)for(a.setTransform(1,0,0,1,0,0),e=0;e<d.length;e++)a.fillText(d[e].toString(),20,150+ +(20*e))}}}}; function Aj(a,b,c,d,e,f,g,h,k,l){if(null!==a.Ea){null===a.ta&&B("No canvas specified");void 0===g&&(g=null);void 0===h&&(h=null);void 0===k&&(k=!1);void 0===l&&(l=!1);xj(a);a.Hb.uc(!0);Vi(a);a.xi=!0;var m=a.ya;a.ya=e;var n=a.La.j,p=n.length;try{var r=new N(f.x,f.y,d.width/e,d.height/e),q=r.copy();q.rq(c);qj(a,q);Wi(a);a.Nd(n,p,a,r);b.setTransform(1,0,0,1,0,0);b.clearRect(0,0,d.width,d.height);null!==h&&""!==h&&(b.fillStyle=h,b.fillRect(0,0,d.width,d.height));var u=a.Tb;b.scale(u,u);var v=rd.alloc(); v.reset();v.translate(c.left,c.top);v.scale(e);0===f.x&&0===f.y||v.translate(-f.x,-f.y);b.setTransform(v.m11,v.m12,v.m21,v.m22,v.dx,v.dy);rd.free(v);yj(a,b);b.globalAlpha=a.hb;if(null!==g){var w=new G,y=g.iterator;for(y.reset();y.next();){var z=y.value;!1===l&&"Grid"===z.layer.name||null===z||w.add(z)}var A=function(c){if(c.visible&&0!==c.hb&&(k||!c.isTemporary)){var d=c.Da.j,e=d.length;if(0!==e){var f=ni(c,b),g=c.mp;g.length=0;for(var h=a.scale,l=N.alloc(),m=0;m<e;m++){var n=d[m];w.contains(n)&& c.dj(b,n,a,g,h,l,!1)}N.free(l);b.globalAlpha=f}}}}else if(!k&&l){var C=a.grid.part,F=C.layer;A=function(c){c===F?C.cc(b,a):c.cc(b,a,k)}}else A=function(c){c.cc(b,a,k)};for(c=0;c<p;c++)A(n[c]);a.xi=!1;a.ti&&zj(a.ti,a)&&a.Ur()}finally{a.ya=m,a.Hb.uc(!0),Vi(a),a.Nd(n,p,a),qj(a)}}}t.Ke=function(a){return this.jf[a]};t.Uy=function(a,b){"minDrawingLength"===a&&(this.So=b);this.jf[a]=b;this.Ne()}; t.yw=function(){this.jf=new cb;this.jf.drawShadows=!0;this.jf.textGreeking=!0;this.jf.viewportOptimizations=Ya||Ua||Va?!1:!0;this.jf.temporaryPixelRatio=!0;this.jf.pictureRatioOptimization=!0;this.So=this.jf.minDrawingLength=1};function yj(a,b){a=a.jf;null!==a&&(void 0!==a.imageSmoothingEnabled&&b.Ty(!!a.imageSmoothingEnabled),a=a.defaultFont,void 0!==a&&null!==a&&(b.font=a))}t.Bm=function(a){return this.Nj[a]};t.ZA=function(a,b){this.Nj[a]=b}; t.xw=function(){this.Nj=new cb;this.Nj.extraTouchArea=10;this.Nj.extraTouchThreshold=10;this.Nj.hasGestureZoom=!0};t.Gw=function(a){Bj(this,a)}; function Bj(a,b){var c=a instanceof X,d=a instanceof R,e;for(e in b){""===e&&B("Setting properties requires non-empty property names");var f=a,g=e;if(c||d){var h=e.indexOf(".");if(0<h){var k=e.substring(0,h);if(c)f=a.ab(k);else if(f=a[k],void 0===f||null===f)f=a.toolManager[k];za(f)?g=e.substr(h+1):B("Unable to find object named: "+k+" in "+a.toString()+" when trying to set property: "+e)}}if("_"!==g[0]&&!La(f,g))if(d&&"ModelChanged"===g){a.Xx(b[g]);continue}else if(d&&"Changed"===g){a.Gh(b[g]);continue}else if(d&& La(a.toolManager,g))f=a.toolManager;else if(d&&Cj(a,g)){a.kk(g,b[g]);continue}else if(a instanceof Z&&"Changed"===g){a.Gh(b[g]);continue}else B('Trying to set undefined property "'+g+'" on object: '+f.toString());f[g]=b[e];"_"===g[0]&&f instanceof Y&&f.Ux(g)}}t.Gv=function(){if(0===this.undoManager.transactionLevel&&0!==this.Wg.count){for(;0<this.Wg.count;){var a=this.Wg;this.Wg=new H;for(a=a.iterator;a.next();){var b=a.key;b.Mq(a.value);b.dc()}}this.M()}}; t.M=function(a){void 0===a&&(a=null);if(null===a)this.Fc=!0,this.Eb();else{var b=this.viewportBounds;null!==a&&a.s()&&b.Oc(a)&&(this.Fc=!0,this.Eb())}this.R("InvalidateDraw")}; t.Fy=function(a,b){if(!0!==this.Fc){this.Fc=!0;var c=!0===this.Ke("temporaryPixelRatio");if(!0===this.Ke("viewportOptimizations")&&this.scrollMode!==ai&&this.Si.fj(0,0,0,0)&&b.width===a.width&&b.height===a.height){var d=this.scale,e=Math.max(a.x,b.x),f=Math.max(a.y,b.y);d=N.allocAt(e,f,Math.max(0,Math.min(a.x+a.width,b.x+b.width)-e)*d,Math.max(0,Math.min(a.y+a.height,b.y+b.height)-f)*d);if(!this.cq&&0<d.width&&0<d.height){if(!(this.kc||(this.Fe=!1,null===this.Ea||(this.kc=!0,this.Gv(),this.documentBounds.s()|| Dj(this,this.computeBounds()),e=this.ta,null===e||e instanceof Ej)))){var g=this.Tb;f=this.va*g;var h=this.ua*g,k=this.scale*g,l=Math.round(Math.round(b.x*k)-Math.round(a.x*k));b=Math.round(Math.round(b.y*k)-Math.round(a.y*k));k=this.Iu;a=this.vx;k.width!==f&&(k.width=f);k.height!==h&&(k.height=h);a.clearRect(0,0,f,h);k=190*g;var m=70*g,n=Math.max(l,0),p=Math.max(b,0),r=Math.floor(f-n),q=Math.floor(h-p);a.drawImage(e.Ga,n,p,r,q,0,0,r,q);zj(this.ti,this)&&a.clearRect(0,0,k,m);e=Ea();a=Ea();q=Math.abs(l); r=Math.abs(b);var u=0===n?0:f-q;n=I.allocAt(u,0);q=I.allocAt(q+u,h);a.push(new N(Math.min(n.x,q.x),Math.min(n.y,q.y),Math.abs(n.x-q.x),Math.abs(n.y-q.y)));var v=this.qb;v.reset();v.scale(g,g);1!==this.ya&&v.scale(this.ya);g=this.la;(0!==g.x||0!==g.y)&&isFinite(g.x)&&isFinite(g.y)&&v.translate(-g.x,-g.y);yb(n,v);yb(q,v);e.push(new N(Math.min(n.x,q.x),Math.min(n.y,q.y),Math.abs(n.x-q.x),Math.abs(n.y-q.y)));u=0===p?0:h-r;n.h(0,u);q.h(f,r+u);a.push(new N(Math.min(n.x,q.x),Math.min(n.y,q.y),Math.abs(n.x- q.x),Math.abs(n.y-q.y)));yb(n,v);yb(q,v);e.push(new N(Math.min(n.x,q.x),Math.min(n.y,q.y),Math.abs(n.x-q.x),Math.abs(n.y-q.y)));zj(this.ti,this)&&(f=0<l?0:-l,h=0<b?0:-b,n.h(f,h),q.h(k+f,m+h),a.push(new N(Math.min(n.x,q.x),Math.min(n.y,q.y),Math.abs(n.x-q.x),Math.abs(n.y-q.y))),yb(n,v),yb(q,v),e.push(new N(Math.min(n.x,q.x),Math.min(n.y,q.y),Math.abs(n.x-q.x),Math.abs(n.y-q.y))));I.free(n);I.free(q);bj(this,!1,!0);null===this.Ea&&B("No div specified");null===this.ta&&B("No canvas specified");if(!this.animationManager.sc&& (f=this.Hb,this.Fc)){xj(this);h=this.Tb;f.setTransform(1,0,0,1,0,0);f.clearRect(0,0,this.va*h,this.ua*h);f.drawImage(this.Iu.Ga,0<l?0:Math.round(-l),0<b?0:Math.round(-b));l=this.la;g=this.ya;k=Math.round(l.x*g)/g;m=Math.round(l.y*g)/g;b=this.qb;b.reset();1!==g&&b.scale(g);0===l.x&&0===l.y||b.translate(-k,-m);f.save();f.beginPath();l=a.length;for(g=0;g<l;g++)k=a[g],0!==k.width&&0!==k.height&&f.rect(Math.floor(k.x),Math.floor(k.y),Math.ceil(k.width),Math.ceil(k.height));f.clip();f.setTransform(1,0, 0,1,0,0);f.scale(h,h);f.transform(b.m11,b.m12,b.m21,b.m22,b.dx,b.dy);b=this.La.j;l=b.length;this.Nd(b,l,this);yj(this,f);f.globalAlpha=this.hb;for(h=0;h<l;h++)if(g=b[h],k=e,g.visible&&0!==g.hb){m=ni(g,f);p=g.mp;p.length=0;n=this.scale;r=N.alloc();q=g.Da.j;v=q.length;u=k.length;for(var w=0;w<v;w++){var y=q[w],z=Fj(y,y.actualBounds);a:{for(var A=2/n,C=4/n,F=0;F<u;F++){var Q=k[F];if(0!==Q.width&&0!==Q.height&&z.bw(Q.x-A,Q.y-A,Q.width+C,Q.height+C)){z=!0;break a}}z=!1}z&&g.dj(f,y,this,p,n,r,!0)}N.free(r); f.globalAlpha=m}f.restore();f.uc(!0);this.ti&&zj(this.ti,this)&&this.Ur();this.Fc=this.wi=!1;this.Yq()}Ia(e);Ia(a);this.kc=!1}}else this.jd();N.free(d);c&&(af(this),this.jd(),of(this,!0))}else c?(af(this),this.jd(),of(this,!0)):this.jd()}};function aj(a){!1===a.vi&&(a.vi=!0)}function Vi(a){!1===a.wi&&(a.wi=!0)}function xj(a){!1!==a.Fl&&(a.Fl=!1,Gj(a,a.va,a.ua))}function Gj(a,b,c){var d=a.Tb;a.ta.resize(b*d,c*d,b,c)&&(a.Fc=!0,a.Hb.uc(!0))} function Ti(a){var b=a.ta;if(null===b)return!0;var c=a.Ea,d=a.va,e=a.ua,f=a.viewportBounds.copy();if(!f.s())return!0;var g=!1,h=a.Ze?a.pb:0,k=a.qe?a.pb:0,l=c.clientWidth||d+h,m=c.clientHeight||e+k;if(l!==d+h||m!==e+k)a.Ze=!1,a.qe=!1,k=h=0,a.va=l,a.ua=m,g=a.Fl=!0;if(!(g||a.Ze||a.qe||a.wl||a.xl))return!0;a.vi=!1;var n=a.viewportBounds,p=a.documentBounds,r=0,q=0,u=0,v=0;c=n.width;var w=n.height,y=a.Si;a.contentAlignment.kb()?(p.width>c&&(r=y.left,q=y.right),p.height>w&&(u=y.top,v=y.bottom)):(r=y.left, q=y.right,u=y.top,v=y.bottom);y=p.width+r+q;var z=p.height+u+v;r=p.x-r;var A=n.x;q=p.right+q;var C=n.right+h;u=p.y-u;var F=n.y;p=p.bottom+v;n=n.bottom+k;var Q="1px",K="1px";v=a.scale;l=y>l/v;m=z>m/v;a.scrollMode===Zh&&(l||m)&&(l&&a.hasHorizontalScrollbar&&a.allowHorizontalScroll&&(l=1,r+1<A&&(l=Math.max((A-r)*v+a.va,l)),q>C+1&&(l=Math.max((q-C)*v+a.va,l)),c+h+1<y&&(l=Math.max((y-c)*v+a.va,l)),Q=l.toString()+"px"),m&&a.hasVerticalScrollbar&&a.allowVerticalScroll&&(l=1,u+1<F&&(l=Math.max((F-u)*v+a.ua, l)),p>n+1&&(l=Math.max((p-n)*v+a.ua,l)),w+k+1<z&&(l=Math.max((z-w)*v+a.ua,l)),K=l.toString()+"px"));l="1px"!==Q;m="1px"!==K;l&&m||!l&&!m||(m&&(C-=a.pb),l&&(n-=a.pb),y<c+h||!a.hasHorizontalScrollbar||!a.allowHorizontalScroll||(h=1,r+1<A&&(h=Math.max((A-r)*v+a.va,h)),q>C+1&&(h=Math.max((q-C)*v+a.va,h)),c+1<y&&(h=Math.max((y-c)*v+a.va,h)),Q=h.toString()+"px"),l="1px"!==Q,h=a.ua,l!==a.qe&&(h=l?a.ua-a.pb:a.ua+a.pb),z<w+k||!a.hasVerticalScrollbar||!a.allowVerticalScroll||(k=1,u+1<F&&(k=Math.max((F-u)*v+ h,k)),p>n+1&&(k=Math.max((p-n)*v+h,k)),w+1<z&&(k=Math.max((z-w)*v+h,k)),K=k.toString()+"px"),m="1px"!==K);if(a.Jp&&l===a.qe&&m===a.Ze)return d===a.va&&e===a.ua||a.jd(),!1;l!==a.qe&&("1px"===Q?a.ua=a.ua+a.pb:a.ua=Math.max(a.ua-a.pb,1),g=!0);a.qe=l;a.Kp.style.width=Q;m!==a.Ze&&("1px"===K?a.va=a.va+a.pb:a.va=Math.max(a.va-a.pb,1),g=!0,a.Hl&&(k=I.alloc(),m?(b.style.left=a.pb+"px",a.position=k.h(a.la.x+a.pb/a.scale,a.la.y)):(b.style.left="0px",a.position=k.h(a.la.x-a.pb/a.scale,a.la.y)),I.free(k)));a.Ze= m;a.Kp.style.height=K;a.Xs=!0;g&&(a.Fl=!0);b=a.$s;k=b.scrollLeft;a.hasHorizontalScrollbar&&a.allowHorizontalScroll&&(c+1<y?k=(a.position.x-r)*v:r+1<A?k=b.scrollWidth-b.clientWidth:q>C+1&&(k=a.position.x*v));if(a.Hl)switch(a.Us){case "negative":k=-(b.scrollWidth-k-b.clientWidth);break;case "reverse":k=b.scrollWidth-k-b.clientWidth}b.scrollLeft=k;a.hasVerticalScrollbar&&a.allowVerticalScroll&&(w+1<z?b.scrollTop=(a.position.y-u)*v:u+1<F?b.scrollTop=b.scrollHeight-b.clientHeight:p>n+1&&(b.scrollTop=a.position.y* v));l=a.va;m=a.ua;b.style.width=l+(a.Ze?a.pb:0)+"px";b.style.height=m+(a.qe?a.pb:0)+"px";return d!==l||e!==m||a.animationManager.sc?(a.Uq(f,a.viewportBounds,v,g),!1):!0} t.add=function(a){var b=a.diagram;if(b!==this&&(null!==b&&B("Cannot add part "+a.toString()+" to "+this.toString()+". It is already a part of "+b.toString()),b=this.ym(a.layerName),null===b&&(b=this.ym("")),null===b&&B('Cannot add a Part when unable find a Layer named "'+a.layerName+'" and there is no default Layer'),a.layer!==b)){var c=b.oj(99999999,a,a.diagram===this);0<=c&&this.bb(Be,"parts",b,null,a,null,c);b.isTemporary||this.Oa();a.C(1);c=a.layerChanged;null!==c&&c(a,null,b)}}; t.oj=function(a){this.partManager.oj(a);var b=this;Hj(a,function(a){Ij(b,a)});(a instanceof Qe||a instanceof U&&null!==a.placeholder)&&a.o();null!==a.data&&Hj(a,function(a){Jj(b.partManager,a)});!0!==vj(a)&&!0!==wj(a)||this.wd.add(a);Kj(a,!0,this);Lj(a)?(a.actualBounds.s()&&this.M(Fj(a,a.actualBounds)),this.Oa()):a.isVisible()&&a.actualBounds.s()&&this.M(Fj(a,a.actualBounds));this.Eb()}; t.Nc=function(a){a.nk();this.partManager.Nc(a);var b=this;null!==a.data&&Hj(a,function(a){Mj(b.partManager,a,b)});this.wd.remove(a);Lj(a)?(a.actualBounds.s()&&this.M(Fj(a,a.actualBounds)),this.Oa()):a.isVisible()&&a.actualBounds.s()&&this.M(Fj(a,a.actualBounds));this.Eb()};t.remove=function(a){Nj(this,a,!0)}; function Nj(a,b,c){var d=b.layer;null!==d&&d.diagram===a&&(b.isSelected=!1,b.isHighlighted=!1,b.C(2),c&&b.uk(),c=d.Nc(-1,b,!1),0<=c&&a.bb(Ce,"parts",d,b,null,c,null),a=b.layerChanged,null!==a&&a(b,d,null))}t.gu=function(a,b){void 0===b&&(b=!1);if(Aa(a))for(var c=a.length,d=0;d<c;d++){var e=a[d];b&&!e.canDelete()||this.remove(e)}else for(c=new G,c.addAll(a),a=c.iterator;a.next();)c=a.value,b&&!c.canDelete()||this.remove(c)};t.tk=function(a,b,c){void 0===c&&(c=!1);return this.partManager.tk(a,b,c)}; R.prototype.moveParts=function(a,b,c,d){void 0===c&&(c=!1);void 0===d&&(d=Oj(this));if(null!==this.toolManager){var e=new H;if(null!==a)if(Aa(a))for(var f=0;f<a.length;f++)Pj(this,e,a[f],c,d);else for(a=a.iterator;a.next();)Pj(this,e,a.value,c,d);else{for(a=this.parts;a.next();)Pj(this,e,a.value,c,d);for(a=this.nodes;a.next();)Pj(this,e,a.value,c,d);for(a=this.links;a.next();)Pj(this,e,a.value,c,d)}vf(this,e,b,d,c)}}; function Pj(a,b,c,d,e,f){if(!b.contains(c)&&(void 0===f&&(f=!1),!d||f||c.canMove()||c.canCopy()))if(void 0===e&&(e=Oj(a)),c instanceof W){b.add(c,a.Cd(e,c,c.location));if(c instanceof U&&(null!==c.placeholder||e.dragsMembers))for(f=c.memberParts;f.next();)Pj(a,b,f.value,d,e,e.groupsAlwaysMove);for(f=c.linksConnected;f.next();){var g=f.value;if(!b.contains(g)){var h=g.fromNode,k=g.toNode;null!==h&&b.contains(h)&&null!==k&&b.contains(k)&&Pj(a,b,g,d,e)}}if(e.dragsTree)for(c=c.Vv();c.next();)Pj(a,b,c.value, d,e)}else if(c instanceof S)for(b.add(c,a.Cd(e,c)),c=c.labelNodes;c.next();)Pj(a,b,c.value,d,e);else c instanceof Qe||b.add(c,a.Cd(e,c,c.location))} function vf(a,b,c,d,e){if(null!==b&&0!==b.count){var f=I.alloc(),g=I.alloc();g.assign(c);isNaN(g.x)&&(g.x=0);isNaN(g.y)&&(g.y=0);(c=a.bq)||bf(a,b);for(var h=Ea(),k=Ea(),l=b.iterator,m=I.alloc();l.next();){var n=l.key,p=l.value;if(n.Pc()){var r=Qj(a,n,b);if(null!==r)h.push(new Rj(n,p,r));else if(!e||n.canMove())r=p.point,f.assign(r),a.computeMove(n,f.add(g),d,m),n.location=m,void 0===p.shifted&&(p.shifted=new I),p.shifted.assign(m.he(r))}else l.key instanceof S&&k.push(l.ka)}I.free(m);e=h.length;for(l= 0;l<e;l++)n=h[l],f.assign(n.info.point),void 0===n.Zv.shifted&&(n.Zv.shifted=new I),n.node.location=f.add(n.Zv.shifted);e=I.alloc();l=I.alloc();n=k.length;for(p=0;p<n;p++){var q=k[p];r=q.key;if(r instanceof S)if(r.suspendsRouting){r.sg=null;m=r.fromNode;var u=r.toNode;if(null!==a.draggedLink&&d.dragsLink)if(u=q.value.point,null===r.dragComputation)b.add(r,a.Cd(d,r,g)),tf(r,g.x-u.x,g.y-u.y);else{q=I.allocAt(0,0);(m=r.i(0))&&m.s()&&q.assign(m);var v=m=I.alloc().assign(q).add(g);d.isGridSnapEnabled&& (d.isGridSnapRealtime||a.lastInput.up)&&(v=I.alloc(),Ig(a,r,m,v,d));m.assign(r.dragComputation(r,m,v)).he(q);b.add(r,a.Cd(d,r,m));tf(r,m.x-u.x,m.y-u.y);I.free(q);I.free(m);v!==m&&I.free(v)}else null!==m&&(e.assign(m.location),v=b.H(m),null!==v&&e.he(v.point)),null!==u&&(l.assign(u.location),v=b.H(u),null!==v&&l.he(v.point)),null!==m&&null!==u?e.Na(l)?(m=q.value.point,u=f,u.assign(e),u.he(m),b.add(r,a.Cd(d,r,e)),tf(r,u.x,u.y)):(r.suspendsRouting=!1,r.Ua()):(q=q.value.point,m=null!==m?e:null!==u?l: g,b.add(r,a.Cd(d,r,m)),tf(r,m.x-q.x,m.y-q.y))}else if(null===r.fromNode||null===r.toNode)m=q.value.point,b.add(r,a.Cd(d,r,g)),tf(r,g.x-m.x,g.y-m.y)}I.free(f);I.free(g);I.free(e);I.free(l);Ia(h);Ia(k);c||(Wi(a),kf(a,b))}} R.prototype.computeMove=function(a,b,c,d){void 0===d&&(d=new I);d.assign(b);if(null===a)return d;var e=b,f=c.isGridSnapEnabled;f&&(c.isGridSnapRealtime||this.lastInput.up)&&(e=I.alloc(),Ig(this,a,b,e,c));c=null!==a.dragComputation?a.dragComputation(a,b,e):e;var g=a.minLocation,h=g.x;isNaN(h)&&(h=f?Math.round(1E3*a.location.x)/1E3:a.location.x);g=g.y;isNaN(g)&&(g=f?Math.round(1E3*a.location.y)/1E3:a.location.y);var k=a.maxLocation,l=k.x;isNaN(l)&&(l=f?Math.round(1E3*a.location.x)/1E3:a.location.x); k=k.y;isNaN(k)&&(k=f?Math.round(1E3*a.location.y)/1E3:a.location.y);d.h(Math.max(h,Math.min(c.x,l)),Math.max(g,Math.min(c.y,k)));e!==b&&I.free(e);return d};function Oj(a){var b=a.toolManager.findTool("Dragging");return null!==b?b.dragOptions:a.kl} function Ig(a,b,c,d,e){void 0===e&&(e=Oj(a));d.assign(c);if(null!==b){var f=a.grid;b=e.gridSnapCellSize;a=b.width;b=b.height;var g=e.gridSnapOrigin,h=g.x;g=g.y;e=e.gridSnapCellSpot;if(null!==f){var k=f.gridCellSize;isNaN(a)&&(a=k.width);isNaN(b)&&(b=k.height);f=f.gridOrigin;isNaN(h)&&(h=f.x);isNaN(g)&&(g=f.y)}f=I.allocAt(0,0);f.Tk(0,0,a,b,e);L.Dq(c.x,c.y,h+f.x,g+f.y,a,b,d);I.free(f)}}function bf(a,b){if(null!==b)for(a.bq=!0,a=b.iterator;a.next();)b=a.key,b instanceof S&&(b.suspendsRouting=!0)} function kf(a,b){if(null!==b){for(b=b.iterator;b.next();){var c=b.key;c instanceof S&&(c.suspendsRouting=!1,Sj(c)&&c.Ua())}a.bq=!1}}function Qj(a,b,c){b=b.containingGroup;if(null!==b){a=Qj(a,b,c);if(null!==a)return a;a=c.H(b);if(null!==a)return a}return null}t=R.prototype;t.Cd=function(a,b,c){if(void 0===c)return new ef(Fb);var d=a.isGridSnapEnabled;a.groupsSnapMembers||null===b.containingGroup||(d=!1);return d?new ef(new I(Math.round(1E3*c.x)/1E3,Math.round(1E3*c.y)/1E3)):new ef(c.copy())}; function Tj(a,b,c){null!==b.diagram&&b.diagram!==a&&B("Cannot share a Layer with another Diagram: "+b+" of "+b.diagram);null===c?null!==b.diagram&&B("Cannot add an existing Layer to this Diagram again: "+b):(c.diagram!==a&&B("Existing Layer must be in this Diagram: "+c+" not in "+c.diagram),b===c&&B("Cannot move a Layer before or after itself: "+b));if(b.diagram!==a){b=b.name;a=a.La;c=a.count;for(var d=0;d<c;d++)a.J(d).name===b&&B("Cannot add Layer with the name '"+b+"'; a Layer with the same name is already present in this Diagram.")}} t.tm=function(a){Tj(this,a,null);a.fe(this);var b=this.La,c=b.count-1;if(!a.isTemporary)for(;0<=c&&b.J(c).isTemporary;)c--;b.wb(c+1,a);null!==this.bc&&this.bb(Be,"layers",this,null,a,null,c+1);this.M();this.Oa()};t.Vx=function(a,b){Tj(this,a,b);a.fe(this);var c=this.La,d=c.indexOf(a);0<=d&&(c.remove(a),null!==this.bc&&this.bb(Ce,"layers",this,a,null,d,null));var e=c.count,f;for(f=0;f<e;f++)if(c.J(f)===b){c.wb(f,a);break}null!==this.bc&&this.bb(Be,"layers",this,null,a,null,f);this.M();0>d&&this.Oa()}; t.nz=function(a,b){Tj(this,a,b);a.fe(this);var c=this.La,d=c.indexOf(a);0<=d&&(c.remove(a),null!==this.bc&&this.bb(Ce,"layers",this,a,null,d,null));var e=c.count,f;for(f=0;f<e;f++)if(c.J(f)===b){c.wb(f+1,a);break}null!==this.bc&&this.bb(Be,"layers",this,null,a,null,f+1);this.M();0>d&&this.Oa()}; t.SA=function(a){a.diagram!==this&&B("Cannot remove a Layer from another Diagram: "+a+" of "+a.diagram);if(""!==a.name){var b=this.La,c=b.indexOf(a);if(b.remove(a)){for(b=a.Da.copy().iterator;b.next();){var d=b.value,e=d.layerName;e!==a.name?d.layerName=e:d.layerName=""}null!==this.bc&&this.bb(Ce,"layers",this,a,null,c,null);this.M();this.Oa()}}};t.ym=function(a){for(var b=this.layers;b.next();){var c=b.value;if(c.name===a)return c}return null}; t.Xx=function(a){null===this.xe&&(this.xe=new E);this.xe.add(a);this.model.Gh(a)};t.UA=function(a){null!==this.xe&&(this.xe.remove(a),0===this.xe.count&&(this.xe=null));this.model.Sk(a)};t.Gh=function(a){null===this.Qf&&(this.Qf=new E);this.Qf.add(a)};t.Sk=function(a){null!==this.Qf&&(this.Qf.remove(a),0===this.Qf.count&&(this.Qf=null))}; t.zt=function(a){this.skipsUndoManager||this.model.skipsUndoManager||this.model.undoManager.$v(a);a.change!==Ae&&(this.isModified=!0);if(null!==this.Qf)for(var b=this.Qf,c=b.length,d=0;d<c;d++)b.J(d)(a)};t.bb=function(a,b,c,d,e,f,g){void 0===f&&(f=null);void 0===g&&(g=null);var h=new ye;h.diagram=this;h.change=a;h.propertyName=b;h.object=c;h.oldValue=d;h.oldParam=f;h.newValue=e;h.newParam=g;this.zt(h)};t.g=function(a,b,c,d,e){this.bb(ze,a,this,b,c,d,e)}; R.prototype.changeState=function(a,b){if(null!==a&&a.diagram===this){var c=this.skipsModelSourceBindings;try{this.skipsModelSourceBindings=!0;var d=a.change;if(d===ze){var e=a.object;Uj(e,a.propertyName,a.H(b));if(e instanceof Y){var f=e.part;null!==f&&f.Mb()}this.isModified=!0}else if(d===Be){var g=a.object,h=a.newParam,k=a.newValue;if(g instanceof X)if("number"===typeof h&&k instanceof Y){b?g.Nc(h):g.wb(h,k);var l=g.part;null!==l&&l.Mb()}else{if("number"===typeof h&&k instanceof Vj)if(b)k.isRow? g.vw(h):g.tw(h);else{var m=k.isRow?g.getRowDefinition(k.index):g.getColumnDefinition(k.index);m.Dt(k)}}else if(g instanceof li){var n=!0===a.oldParam;"number"===typeof h&&k instanceof V&&(b?(k.isSelected=!1,k.isHighlighted=!1,k.Mb(),g.Nc(n?h:-1,k,n)):g.oj(h,k,n))}else g instanceof R?"number"===typeof h&&k instanceof li&&(b?this.La.cb(h):(k.fe(this),this.La.wb(h,k))):B("unknown ChangedEvent.Insert object: "+a.toString());this.isModified=!0}else if(d===Ce){var p=a.object,r=a.oldParam,q=a.oldValue;if(p instanceof X)"number"===typeof r&&q instanceof Y?b?p.wb(r,q):p.Nc(r):"number"===typeof r&&q instanceof Vj&&(b?(m=q.isRow?p.getRowDefinition(q.index):p.getColumnDefinition(q.index),m.Dt(q)):q.isRow?p.vw(r):p.tw(r));else if(p instanceof li){var u=!0===a.newParam;"number"===typeof r&&q instanceof V&&(b?0>p.Da.indexOf(q)&&p.oj(r,q,u):(q.isSelected=!1,q.isHighlighted=!1,q.Mb(),p.Nc(u?r:-1,q,u)))}else p instanceof R?"number"===typeof r&&q instanceof li&&(b?(q.fe(this),this.La.wb(r,q)):this.La.cb(r)):B("unknown ChangedEvent.Remove object: "+ a.toString());this.isModified=!0}else d!==Ae&&B("unknown ChangedEvent: "+a.toString())}finally{this.skipsModelSourceBindings=c}}};R.prototype.xa=function(a){return this.undoManager.xa(a)};R.prototype.Wa=function(a){return this.undoManager.Wa(a)};R.prototype.Kf=function(){return this.undoManager.Kf()}; R.prototype.commit=function(a,b){void 0===b&&(b="");var c=this.skipsUndoManager;null===b&&(this.skipsUndoManager=!0,b="");this.undoManager.xa(b);var d=!1;try{a(this),d=!0}finally{d?this.undoManager.Wa(b):this.undoManager.Kf(),this.skipsUndoManager=c}};R.prototype.updateAllTargetBindings=function(a){this.partManager.updateAllTargetBindings(a)};R.prototype.jr=function(){this.partManager.jr()}; function Wj(a,b,c){var d=a.animationManager;if(a.Sb||a.kc)a.ya=c,d.ff&&d.Rd.add(d.B,"scale",b,a.ya);else if(null===a.ta)a.ya=c;else{a.Sb=!0;var e=a.viewportBounds.copy(),f=a.va,g=a.ua;e.width=a.va/b;e.height=a.ua/b;var h=a.zoomPoint.x,k=a.zoomPoint.y,l=a.contentAlignment;isNaN(h)&&(l.Qc()?l.Gf(Ic)?h=0:l.Gf(Jc)&&(h=f-1):h=l.kb()?l.x*(f-1):f/2);isNaN(k)&&(l.Qc()?l.Gf(Hc)?k=0:l.Gf(Kc)&&(k=g-1):k=l.kb()?l.y*(g-1):g/2);null===a.scaleComputation||a.animationManager.defaultAnimation.isAnimating||(c=a.scaleComputation(a, c));c<a.minScale&&(c=a.minScale);c>a.maxScale&&(c=a.maxScale);f=I.allocAt(a.la.x+h/b-h/c,a.la.y+k/b-k/c);a.position=f;I.free(f);a.ya=c;a.Uq(e,a.viewportBounds,b,!1);a.Sb=!1;Yi(a,!1);d.ff&&d.Rd.add(d.B,"scale",b,a.ya);a.M();aj(a)}} R.prototype.Uq=function(a,b,c,d){if(!a.w(b)){void 0===d&&(d=!1);d||aj(this);Vi(this);var e=this.layout;null===e||!e.isViewportSized||this.autoScale!==Lh||d||a.width===b.width&&a.height===b.height||e.C();e=this.currentTool;!0===this.ag&&e instanceof Pa&&(this.lastInput.documentPoint=this.nu(this.lastInput.viewPoint),Ue(e,this));this.Sb||this.Fy(a,b);qj(this);this.Kc.scale=c;this.Kc.position.x=a.x;this.Kc.position.y=a.y;this.Kc.bounds.assign(a);this.Kc.Fv.width=Math.round(a.width*c);this.Kc.Fv.height= Math.round(a.height*c);this.Kc.jw.width=this.va;this.Kc.jw.height=this.ua;this.Kc.gw=d;this.R("ViewportBoundsChanged",this.Kc,a);this.isVirtualized&&this.links.each(function(a){a.isAvoiding&&a.actualBounds.Oc(b)&&a.Ua()})}}; function qj(a,b){void 0===b&&(b=null);var c=a.Jb;if(null!==c&&c.visible){for(var d=M.alloc(),e=1,f=1,g=c.W.j,h=g.length,k=0;k<h;k++){var l=g[k],m=Math.abs(l.interval);2>m||(Xj(l.figure)?f=f*m/L.uy(f,m):e=e*m/L.uy(e,m))}g=c.gridCellSize;d.h(f*g.width,e*g.height);if(null!==b)e=b.width,f=b.height,a=b.x,g=b.y;else{b=N.alloc();a=a.viewportBounds;b.h(a.x,a.y,a.width,a.height);if(!b.s()){N.free(b);return}e=b.width;f=b.height;a=b.x;g=b.y;N.free(b)}c.width=e+2*d.width;c.height=f+2*d.height;b=I.alloc();L.Dq(a, g,0,0,d.width,d.height,b);b.offset(-d.width,-d.height);M.free(d);c.part.location=b;I.free(b)}}R.prototype.clearSelection=function(a){void 0===a&&(a=!1);var b=this.selection;if(0!==b.count){a||this.R("ChangingSelection",b);for(var c=b.ma(),d=c.length,e=0;e<d;e++)c[e].isSelected=!1;b.ea();b.clear();b.freeze();a||this.R("ChangedSelection",b)}}; R.prototype.select=function(a){null!==a&&a.layer.diagram===this&&(!a.isSelected||1<this.selection.count)&&(this.R("ChangingSelection",this.selection),this.clearSelection(!0),a.isSelected=!0,this.R("ChangedSelection",this.selection))}; R.prototype.YA=function(a){this.R("ChangingSelection",this.selection);this.clearSelection(!0);if(Aa(a))for(var b=a.length,c=0;c<b;c++){var d=a[c];d instanceof V||B("Diagram.selectCollection given something that is not a Part: "+d);d.isSelected=!0}else for(a=a.iterator;a.next();)b=a.value,b instanceof V||B("Diagram.selectCollection given something that is not a Part: "+b),b.isSelected=!0;this.R("ChangedSelection",this.selection)}; R.prototype.clearHighlighteds=function(){var a=this.highlighteds;if(0<a.count){for(var b=a.ma(),c=b.length,d=0;d<c;d++)b[d].isHighlighted=!1;a.ea();a.clear();a.freeze()}};t=R.prototype;t.uA=function(a){null!==a&&a.layer.diagram===this&&(!a.isHighlighted||1<this.highlighteds.count)&&(this.clearHighlighteds(),a.isHighlighted=!0)}; t.vA=function(a){a=(new G).addAll(a);for(var b=this.highlighteds.copy().Zq(a).iterator;b.next();)b.value.isHighlighted=!1;for(a=a.iterator;a.next();)b=a.value,b instanceof V||B("Diagram.highlightCollection given something that is not a Part: "+b),b.isHighlighted=!0}; t.scroll=function(a,b,c){void 0===c&&(c=1);var d="up"===b||"down"===b,e=0;if("pixel"===a)e=c;else if("line"===a)e=c*(d?this.scrollVerticalLineChange:this.scrollHorizontalLineChange);else if("page"===a)a=d?this.viewportBounds.height:this.viewportBounds.width,a*=this.scale,0!==a&&(e=c*Math.max(a-(d?this.scrollVerticalLineChange:this.scrollHorizontalLineChange),0));else{if("document"===a){e=this.documentBounds;c=this.viewportBounds;d=I.alloc();"up"===b?this.position=d.h(c.x,e.y):"left"===b?this.position= d.h(e.x,c.y):"down"===b?this.position=d.h(c.x,e.bottom-c.height):"right"===b&&(this.position=d.h(e.right-c.width,c.y));I.free(d);return}B("scrolling unit must be 'pixel', 'line', 'page', or 'document', not: "+a)}e/=this.scale;c=this.position.copy();"up"===b?c.y=this.position.y-e:"down"===b?c.y=this.position.y+e:"left"===b?c.x=this.position.x-e:"right"===b?c.x=this.position.x+e:B("scrolling direction must be 'up', 'down', 'left', or 'right', not: "+b);this.position=c}; t.Bw=function(a){var b=this.viewportBounds;b.He(a)||(a=a.center,a.x-=b.width/2,a.y-=b.height/2,this.position=a)};t.At=function(a){var b=this.viewportBounds;a=a.center;a.x-=b.width/2;a.y-=b.height/2;this.position=a};t.hr=function(a){var b=this.qb;b.reset();1!==this.ya&&b.scale(this.ya);var c=this.la;(0!==c.x||0!==c.y)&&isFinite(c.x)&&isFinite(c.y)&&b.translate(-c.x,-c.y);return a.copy().transform(this.qb)}; t.gB=function(a){var b=this.qb,c=a.x,d=a.y,e=c+a.width,f=d+a.height,g=b.m11,h=b.m12,k=b.m21,l=b.m22,m=b.dx,n=b.dy,p=c*g+d*k+m;b=c*h+d*l+n;var r=e*g+d*k+m;a=e*h+d*l+n;d=c*g+f*k+m;c=c*h+f*l+n;g=e*g+f*k+m;e=e*h+f*l+n;f=Math.min(p,r);p=Math.max(p,r);r=Math.min(b,a);b=Math.max(b,a);f=Math.min(f,d);p=Math.max(p,d);r=Math.min(r,c);b=Math.max(b,c);f=Math.min(f,g);p=Math.max(p,g);r=Math.min(r,e);b=Math.max(b,e);return new N(f,r,p-f,b-r)}; t.nu=function(a){var b=this.qb;b.reset();1!==this.ya&&b.scale(this.ya);var c=this.la;(0!==c.x||0!==c.y)&&isFinite(c.x)&&isFinite(c.y)&&b.translate(-c.x,-c.y);return yb(a.copy(),this.qb)};function Yj(a){var b=a.isModified;a.yv!==b&&(a.yv=b,a.R("Modified"))}function Zj(a){a=vi.get(a);return null!==a?new a:new wi} R.prototype.doModelChanged=function(a){var b=this;if(a.model===this.model){var c=a.change,d=a.propertyName;if(c===Ae&&"S"===d[0])if("StartingFirstTransaction"===d){var e=this;a=this.toolManager;a.mouseDownTools.each(function(a){a.diagram=e});a.mouseMoveTools.each(function(a){a.diagram=e});a.mouseUpTools.each(function(a){a.diagram=e});this.kc||this.re||(this.Hj=!0,this.Kj&&(this.Fe=!0))}else"StartingUndo"===d||"StartingRedo"===d?(a=this.animationManager,a.defaultAnimation.isAnimating&&!this.skipsUndoManager&& a.Cc(),this.R("ChangingSelection",this.selection)):"StartedTransaction"===d&&(a=this.animationManager,a.defaultAnimation.isAnimating&&!this.skipsUndoManager&&a.Cc());else if(this.Z){this.Z=!1;try{if(""===a.modelChange&&c===Ae){if("FinishedUndo"===d||"FinishedRedo"===d)this.R("ChangedSelection",this.selection),Wi(this);var f=this.animationManager;"RolledBackTransaction"===d&&f.Cc();this.Hj=!0;this.jd();0!==this.undoManager.transactionLevel&&1!==this.undoManager.transactionLevel||vh(f);"CommittedTransaction"=== d&&this.undoManager.isJustDiscarded&&(this.Xd=Math.min(this.Xd,this.undoManager.historyIndex-1));"CommittedTransaction"!==d&&"RolledBackTransaction"!==d||!this.undoManager.isPendingUnmodified||setTimeout(function(){b.isModified=!1},1);var g=a.isTransactionFinished;g&&(Yj(this),this.Yt.clear(),Th(this.animationManager));if(!this.Cs&&g&&this.lastInput.targetDiagram){this.Cs=!0;var h=this;ta(function(){h.currentTool.standardMouseOver();h.Cs=!1},10)}}}finally{this.Z=!0}}}}; function Ij(a,b){b=b.W.j;for(var c=b.length,d=0;d<c;d++)ak(a,b[d])}function ak(a,b){if(b instanceof bk){var c=b.element;if(null!==c&&c instanceof HTMLImageElement){var d=b.Zg;null!==d&&(d.vl instanceof Event&&null!==b.Ec&&b.Ec(b,d.vl),!0===d.ms&&(null!==b.sf&&b.sf(b,d.nv),null!==b.diagram&&b.diagram.Ms.add(b)));c=c.getAttribute("src");d=a.Pi.H(c);if(null===d)d=[],d.push(b),a.Pi.add(c,d);else{for(a=0;a<d.length;a++)if(d[a]===b)return;d.push(b)}}}} function ck(a,b){if(b instanceof bk){var c=b.element;if(null!==c&&c instanceof HTMLImageElement){c=c.getAttribute("src");var d=a.Pi.H(c);if(null!==d)for(var e=0;e<d.length;e++)if(d[e]===b){d.splice(e,1);0===d.length&&(a.Pi.remove(c),dk(c));break}}}}R.prototype.Md=function(){this.partManager.Md()};R.prototype.jk=function(a,b){this.Wc.jk(a,b)};R.prototype.lk=function(a,b){this.Wc.lk(a,b)};R.prototype.findPartForKey=function(a){return this.partManager.findPartForKey(a)};R.prototype.Db=function(a){return this.partManager.Db(a)}; R.prototype.findLinkForKey=function(a){return this.partManager.findLinkForKey(a)};t=R.prototype;t.zc=function(a){return this.partManager.zc(a)};t.gj=function(a){return this.partManager.gj(a)};t.yc=function(a){return this.partManager.yc(a)};t.Jt=function(a){for(var b=[],c=0;c<arguments.length;++c)b[c]=arguments[c];return this.partManager.Jt.apply(this.partManager,b instanceof Array?b:da(ca(b)))}; t.It=function(a){for(var b=[],c=0;c<arguments.length;++c)b[c]=arguments[c];return this.partManager.It.apply(this.partManager,b instanceof Array?b:da(ca(b)))};function Dj(a,b){a.ui=!1;var c=a.Pn;c.w(b)||(b=b.G(),a.Pn=b,Yi(a,!1),a.R("DocumentBoundsChanged",null,c.copy()),aj(a))}t.Ta=function(){this.ui&&Dj(this,this.computeBounds())};t.dA=function(){for(var a=new G,b=this.nodes;b.next();){var c=b.value;c.isTopLevel&&a.add(c)}for(b=this.links;b.next();)c=b.value,c.isTopLevel&&a.add(c);return a.iterator}; t.cA=function(){return this.Ch.iterator};t.EA=function(a){Wi(this);a&&ek(this,!0);this.Hj=!0;Jf(this)};function ek(a,b){for(var c=a.Ch.iterator;c.next();)fk(a,c.value,b);null!==a.layout&&(b?a.layout.isValidLayout=!1:a.layout.C())}function fk(a,b,c){if(null!==b){for(var d=b.Tl.iterator;d.next();)fk(a,d.value,c);null!==b.layout&&(c?b.layout.isValidLayout=!1:b.layout.C())}} function rj(a,b){if(a.Og&&!a.Or){var c=a.Z;a.Z=!0;var d=a.undoManager.transactionLevel,e=a.layout,f=a.animationManager;try{0===d&&(a.undoManager.isInternalTransaction=!0,a.xa("Layout"));1>=d&&!f.defaultAnimation.isAnimating&&!f.sc&&(b||th(f,"Layout"));a.Og=!1;for(var g=a.Ch.iterator;g.next();)gk(a,g.value,b,d);e.isValidLayout||(!b||e.isRealtime||null===e.isRealtime||0===d?(e.doLayout(a),Wi(a),e.isValidLayout=!0):a.Og=!0)}finally{b=a.undoManager.isInternalTransaction,0===d&&(a.Wa("Layout"),a.undoManager.isInternalTransaction= !1),!b||0!==d&&1!==d||vh(f),a.Z=c}}}function gk(a,b,c,d){if(null!==b){for(var e=b.Tl.iterator;e.next();)gk(a,e.value,c,d);e=b.layout;null===e||e.isValidLayout||(!c||e.isRealtime||0===d?(b.Qh=!b.location.s(),e.doLayout(b),b.C(32),tj(a,b),e.isValidLayout=!0):a.Og=!0)}}t.jA=function(){for(var a=new E,b=this.nodes;b.next();){var c=b.value;c.isTopLevel&&null===c.jj()&&a.add(c)}return a.iterator}; function ti(a){function b(a){var b=a.toLowerCase(),e=new E;c.add(a,e);c.add(b,e);d.add(a,a);d.add(b,a)}var c=new H,d=new H;b("InitialAnimationStarting");b("AnimationStarting");b("AnimationFinished");b("BackgroundSingleClicked");b("BackgroundDoubleClicked");b("BackgroundContextClicked");b("ClipboardChanged");b("ClipboardPasted");b("DocumentBoundsChanged");b("ExternalObjectsDropped");b("GainedFocus");b("InitialLayoutCompleted");b("LayoutCompleted");b("LinkDrawn");b("LinkRelinked");b("LinkReshaped"); b("LostFocus");b("Modified");b("ObjectSingleClicked");b("ObjectDoubleClicked");b("ObjectContextClicked");b("PartCreated");b("PartResized");b("PartRotated");b("SelectionMoved");b("SelectionCopied");b("SelectionDeleting");b("SelectionDeleted");b("SelectionGrouped");b("SelectionUngrouped");b("ChangingSelection");b("ChangedSelection");b("SubGraphCollapsed");b("SubGraphExpanded");b("TextEdited");b("TreeCollapsed");b("TreeExpanded");b("ViewportBoundsChanged");b("InvalidateDraw");a.Rr=c;a.Qr=d} function Cj(a,b){var c=a.Qr.H(b);return null!==c?c:a.Qr.H(b.toLowerCase())}function hk(a,b){var c=a.Rr.H(b);if(null!==c)return c;c=a.Rr.H(b.toLowerCase());if(null!==c)return c;B("Unknown DiagramEvent name: "+b)}t.kk=function(a,b){a=hk(this,a);null!==a&&a.add(b)};t.Km=function(a,b){a=hk(this,a);null!==a&&a.remove(b)}; t.R=function(a,b,c){var d=hk(this,a),e=new xe;e.diagram=this;a=Cj(this,a);null!==a&&(e.name=a);void 0!==b&&(e.subject=b);void 0!==c&&(e.parameter=c);b=d.length;if(1===b)d.J(0)(e);else if(0!==b)for(d=d.ma(),c=0;c<b;c++)(0,d[c])(e)};function pk(a){if(a.animationManager.isTicking)return!1;var b=a.currentTool;return b===a.toolManager.findTool("Dragging")?!a.bq||b.isComplexRoutingRealtime:!0}t.Dk=function(a,b){void 0===b&&(b=null);return tk(this,!1,null,b).Dk(a.x,a.y,a.width,a.height)}; R.prototype.computeOccupiedArea=function(){return this.isVirtualized?this.viewportBounds.copy():this.ui?Xi(this):this.documentBounds.copy()}; function tk(a,b,c,d){null===a.Ic&&(a.Ic=new uk);if(a.Ic.St||a.Ic.group!==c||a.Ic.Wy!==d){if(null===c){b=a.computeOccupiedArea();b.Lc(100,100);a.Ic.initialize(b);b=N.alloc();for(var e=a.nodes;e.next();){var f=e.value,g=f.layer;null!==g&&g.visible&&!g.isTemporary&&vk(a,f,d,b)}N.free(b)}else{0<c.memberParts.count&&(b=a.computePartsBounds(c.memberParts,!1),b.Lc(20,20),a.Ic.initialize(b));b=N.alloc();for(e=c.memberParts;e.next();)f=e.value,f instanceof W&&vk(a,f,d,b);N.free(b)}a.Ic.group=c;a.Ic.Wy=d;a.Ic.St= !1}else b&&wk(a.Ic);return a.Ic}function vk(a,b,c,d){if(b!==c)if(b.isVisible()&&b.avoidable&&!b.isLinkLabel){b=b.getAvoidableRect(d);a=a.Ic;var e=b.x,f=b.y;if(xk(a,e,f))for(c=(f-a.Bd)/a.gc|0,d=Math.min((e+b.width-a.Ad)/a.fc|0,a.Zi),b=Math.min((f+b.height-a.Bd)/a.gc|0,a.$i),e=(e-a.Ad)/a.fc|0;e<=d;e++)if(f=a.Rb[e],f.fill)f.fill(yk,c,b+1);else for(var g=c;g<=b;g++)f[g]=yk}else if(b instanceof U)for(b=b.memberParts;b.next();)e=b.value,e instanceof W&&vk(a,e,c,d)} function zk(a,b){null!==a.Ic&&!a.Ic.St&&(void 0===b&&(b=null),null===b||b.avoidable&&!b.isLinkLabel)&&(a.Ic.St=!0)}R.prototype.Ft=function(a){this.pn.assign(a);this.computeAutoScrollPosition(this.pn).Na(this.position)?this.Lf():Ak(this)}; function Ak(a){-1===a.Bj&&(a.Bj=ta(function(){if(-1!==a.Bj&&(a.Lf(),null!==a.lastInput.event)){var b=a.computeAutoScrollPosition(a.pn);b.Na(a.position)||(a.position=b,a.lastInput.documentPoint=a.nu(a.pn),a.doMouseMove(),a.ui=!0,Dj(a,a.documentBounds.copy().Tc(a.computeBounds())),a.Fc=!0,a.jd(),Ak(a))}},a.on))}R.prototype.Lf=function(){-1!==this.Bj&&(x.clearTimeout(this.Bj),this.Bj=-1)}; R.prototype.computeAutoScrollPosition=function(a){var b=this.position,c=this.qn;if(0>=c.top&&0>=c.left&&0>=c.right&&0>=c.bottom)return b;var d=this.viewportBounds,e=this.scale;d=N.allocAt(0,0,d.width*e,d.height*e);var f=I.allocAt(0,0);if(a.x>=d.x&&a.x<d.x+c.left&&this.allowHorizontalScroll){var g=Math.max(this.scrollHorizontalLineChange,1);g|=0;f.x-=g;a.x<d.x+c.left/2&&(f.x-=g);a.x<d.x+c.left/4&&(f.x-=4*g)}else a.x<=d.x+d.width&&a.x>d.x+d.width-c.right&&this.allowHorizontalScroll&&(g=Math.max(this.scrollHorizontalLineChange, 1),g|=0,f.x+=g,a.x>d.x+d.width-c.right/2&&(f.x+=g),a.x>d.x+d.width-c.right/4&&(f.x+=4*g));a.y>=d.y&&a.y<d.y+c.top&&this.allowVerticalScroll?(g=Math.max(this.scrollVerticalLineChange,1),g|=0,f.y-=g,a.y<d.y+c.top/2&&(f.y-=g),a.y<d.y+c.top/4&&(f.y-=4*g)):a.y<=d.y+d.height&&a.y>d.y+d.height-c.bottom&&this.allowVerticalScroll&&(g=Math.max(this.scrollVerticalLineChange,1),g|=0,f.y+=g,a.y>d.y+d.height-c.bottom/2&&(f.y+=g),a.y>d.y+d.height-c.bottom/4&&(f.y+=4*g));f.Na(Fb)||(b=new I(b.x+f.x/e,b.y+f.y/e)); N.free(d);I.free(f);return b};t=R.prototype;t.$t=function(){return null};t.hw=function(){return null};t.rz=function(a,b){this.Lx.add(a,b)}; function Bk(a,b,c){function d(){var a=+new Date;f=!0;for(g.reset();g.next();)if(!g.value[0].Pl){f=!1;break}f||a-l>k?b(c,e,h):x.requestAnimationFrame(d)}for(var e=c.callback,f=!0,g=a.Pi.iterator;g.next();)if(!g.value[0].Pl){f=!1;break}if("function"!==typeof e||f)return b(c,e,a);var h=a,k=c.callbackTimeout||300,l=+new Date;x.requestAnimationFrame(function(){d()});return null}t.GA=function(a){if(!Wg)return null;void 0===a&&(a=new cb);a.returnType="Image";return this.Iy(a)}; t.Iy=function(a){void 0===a&&(a=new cb);return Bk(this,this.HA,a)}; t.HA=function(a,b,c){var d=Ck(c,a,"canvas",null);if(null===d)return null;c=d.Y.canvas;var e=null;if(null!==c)switch(e=a.returnType,void 0===e?e="string":e=e.toLowerCase(),e){case Dk+"data":e=d.getImageData(0,0,c.width,c.height);break;case Dk:d=(a.document||document).createElement("img");d.src=c.toDataURL(a.type,a.details);e=d;break;case "blob":"function"!==typeof b&&B('Error: Diagram.makeImageData called with "returnType: toBlob", but no required "callback" function property defined.');if("function"=== typeof c.toBlob)return c.toBlob(b,a.type,a.details),"toBlob";if("function"===typeof c.msToBlob)return b(c.msToBlob()),"msToBlob";b(null);return null;default:e=c.toDataURL(a.type,a.details)}return"function"===typeof b?(b(e),null):e}; function Ck(a,b,c,d){a.animationManager.Cc();a.jd();if(null===a.ta)return null;"object"!==typeof b&&B("properties argument must be an Object.");var e=b.size||null,f=b.scale||null;void 0!==b.scale&&isNaN(b.scale)&&(f="NaN");var g=b.maxSize;void 0===b.maxSize&&(g="SVG"===c?new M(Infinity,Infinity):new M(2E3,2E3));var h=b.position||null,k=b.parts||null,l=void 0===b.padding?1:b.padding,m=b.background||null,n=b.omitTemporary;void 0===n&&(n=!0);var p=b.document||document,r=b.elementFinished||null,q=b.showTemporary; void 0===q&&(q=!n);b=b.showGrid;void 0===b&&(b=q);null!==e&&isNaN(e.width)&&isNaN(e.height)&&(e=null);"number"===typeof l?l=new oc(l):l instanceof oc||B("MakeImage padding must be a Margin or a number.");l.left=Math.max(l.left,0);l.right=Math.max(l.right,0);l.top=Math.max(l.top,0);l.bottom=Math.max(l.bottom,0);a.Hb.uc(!0);n=new Ek(null,p);var u=n.context;if(!(e||f||k||h)){n.width=a.va+Math.ceil(l.left+l.right);n.height=a.ua+Math.ceil(l.top+l.bottom);if("SVG"===c){if(null===d)return null;d.resize(n.width, n.height,n.width,n.height);d.ownerDocument=p;d.Aq=r;Aj(a,d.context,l,new M(n.width,n.height),a.ya,a.la,k,m,q,b);return d.context}a.rl=!1;Aj(a,u,l,new M(n.width,n.height),a.ya,a.la,k,m,q,b);a.rl=!0;return n.context}var v=a.On,w=a.documentBounds.copy();w.Kw(a.ib);if(q)for(var y=a.La.j,z=y.length,A=0;A<z;A++){var C=y[A];if(C.visible&&C.isTemporary){C=C.Da.j;for(var F=C.length,Q=0;Q<F;Q++){var K=C[Q];K.isInDocumentBounds&&K.isVisible()&&(K=K.actualBounds,K.s()&&w.Tc(K))}}}y=new I(w.x,w.y);if(null!==k){z= !0;A=k.iterator;for(A.reset();A.next();)if(C=A.value,C instanceof V&&(F=C.layer,(null===F||F.visible)&&(null===F||q||!F.isTemporary)&&C.isVisible()&&(C=C.actualBounds,C.s())))if(z){z=!1;var T=C.copy()}else T.Tc(C);z&&(T=new N(0,0,0,0));w.width=T.width;w.height=T.height;y.x=T.x;y.y=T.y}null!==h&&h.s()&&(y=h,f||(f=v));T=h=0;null!==l&&(h=l.left+l.right,T=l.top+l.bottom);z=A=0;null!==e&&(A=e.width,z=e.height,isFinite(A)&&(A=Math.max(0,A-h)),isFinite(z)&&(z=Math.max(0,z-T)));null!==e&&null!==f?("NaN"=== f&&(f=v),e.s()?(e=A,w=z):isNaN(z)?(e=A,w=w.height*f):(e=w.width*f,w=z)):null!==e?e.s()?(f=Math.min(A/w.width,z/w.height),e=A,w=z):isNaN(z)?(f=A/w.width,e=A,w=w.height*f):(f=z/w.height,e=w.width*f,w=z):null!==f?"NaN"===f&&g.s()?(f=Math.min((g.width-h)/w.width,(g.height-T)/w.height),f>v?(f=v,e=w.width,w=w.height):(e=g.width,w=g.height)):(e=w.width*f,w=w.height*f):(f=v,e=w.width,w=w.height);null!==l?(e+=h,w+=T):l=new oc(0);null!==g&&(v=g.width,g=g.height,isNaN(v)&&(v=2E3),isNaN(g)&&(g=2E3),isFinite(v)&& (e=Math.min(e,v)),isFinite(g)&&(w=Math.min(w,g)));n.width=Math.ceil(e);n.height=Math.ceil(w);if("SVG"===c){if(null===d)return null;d.resize(n.width,n.height,n.width,n.height);d.ownerDocument=p;d.Aq=r;Aj(a,d.context,l,new M(Math.ceil(e),Math.ceil(w)),f,y,k,m,q,b);return d.context}a.rl=!1;Aj(a,u,l,new M(Math.ceil(e),Math.ceil(w)),f,y,k,m,q,b);a.rl=!0;return n.context} na.Object.defineProperties(R.prototype,{div:{get:function(){return this.Ea},set:function(a){if(this.Ea!==a){Ra=[];var b=this.Ea;null!==b?(b.B=void 0,b.goDiagram=void 0,b.innerHTML="",null!==this.ta&&(b=this.ta.Ga,this.zj?(this.removeEventListener(b,"pointermove",this.Ok,!1),this.removeEventListener(b,"pointerdown",this.Nk,!1),this.removeEventListener(b,"pointerup",this.Qk,!1),this.removeEventListener(b,"pointerout",this.Pk,!1)):(this.removeEventListener(b,"touchstart", this.Pw,!1),this.removeEventListener(b,"touchmove",this.Ow,!1),this.removeEventListener(b,"touchend",this.Nw,!1)),this.ta.ky()),this.Zl&&(this.Zl.disconnect(),this.Zl=null),b=this.toolManager,null!==b&&(b.mouseDownTools.each(function(a){a.cancelWaitAfter()}),b.mouseMoveTools.each(function(a){a.cancelWaitAfter()}),b.mouseUpTools.each(function(a){a.cancelWaitAfter()})),b.cancelWaitAfter(),this.currentTool.doCancel(),this.Hb=this.ta=null,this.removeEventListener(x,"resize",this.Xw,!1),this.zj||(this.removeEventListener(x, "mousemove",this.Hk,!0),this.removeEventListener(x,"mousedown",this.Gk,!0),this.removeEventListener(x,"mouseup",this.Jk,!0),this.removeEventListener(x,"mouseout",this.Ik,!0)),this.removeEventListener(x,"wheel",this.Kk,!0),He===this&&(He=null)):this.re=!1;this.Ea=null;if(null!==a){if(b=a.B)b.div=null;Di(this,a);this.Ne()}}}},Zx:{get:function(){return this.Yo}},pj:{get:function(){return this.re}},draggedLink:{ get:function(){return this.Tr},set:function(a){this.Tr!==a&&(this.Tr=a,null!==a&&(this.Gs=a.fromPort,this.Hs=a.toPort))}},Ly:{get:function(){return this.Gs},set:function(a){this.Gs=a}},My:{get:function(){return this.Hs},set:function(a){this.Hs=a}},animationManager:{get:function(){return this.Wc}},undoManager:{get:function(){return this.bc.undoManager}},skipsUndoManager:{ get:function(){return this.wg},set:function(a){this.wg=a;this.bc.skipsUndoManager=a}},delaysLayout:{get:function(){return this.Or},set:function(a){this.Or=a}},opacity:{get:function(){return this.hb},set:function(a){var b=this.hb;b!==a&&((0>a||1<a)&&wa(a,"0 <= value <= 1",R,"opacity"),this.hb=a,this.g("opacity",b,a),this.M())}},validCycle:{get:function(){return this.tt},set:function(a){var b=this.tt; b!==a&&(this.tt=a,this.g("validCycle",b,a))}},layers:{get:function(){return this.La.iterator}},isModelReadOnly:{get:function(){var a=this.bc;return null===a?!1:a.isReadOnly},set:function(a){var b=this.bc;null!==b&&(b.isReadOnly=a)}},isReadOnly:{get:function(){return this.bg},set:function(a){var b=this.bg;b!==a&&(this.bg=a,this.g("isReadOnly",b,a))}},isEnabled:{get:function(){return this.nd}, set:function(a){var b=this.nd;b!==a&&(this.nd=a,this.g("isEnabled",b,a))}},allowClipboard:{get:function(){return this.pr},set:function(a){var b=this.pr;b!==a&&(this.pr=a,this.g("allowClipboard",b,a))}},allowCopy:{get:function(){return this.Zh},set:function(a){var b=this.Zh;b!==a&&(this.Zh=a,this.g("allowCopy",b,a))}},allowDelete:{get:function(){return this.$h},set:function(a){var b=this.$h;b!==a&&(this.$h=a, this.g("allowDelete",b,a))}},allowDragOut:{get:function(){return this.qr},set:function(a){var b=this.qr;b!==a&&(this.qr=a,this.g("allowDragOut",b,a))}},allowDrop:{get:function(){return this.rr},set:function(a){var b=this.rr;b!==a&&(this.rr=a,this.g("allowDrop",b,a))}},allowTextEdit:{get:function(){return this.ii},set:function(a){var b=this.ii;b!==a&&(this.ii=a,this.g("allowTextEdit",b,a))}},allowGroup:{ get:function(){return this.ai},set:function(a){var b=this.ai;b!==a&&(this.ai=a,this.g("allowGroup",b,a))}},allowUngroup:{get:function(){return this.ji},set:function(a){var b=this.ji;b!==a&&(this.ji=a,this.g("allowUngroup",b,a))}},allowInsert:{get:function(){return this.tr},set:function(a){var b=this.tr;b!==a&&(this.tr=a,this.g("allowInsert",b,a))}},allowLink:{get:function(){return this.bi},set:function(a){var b= this.bi;b!==a&&(this.bi=a,this.g("allowLink",b,a))}},allowRelink:{get:function(){return this.di},set:function(a){var b=this.di;b!==a&&(this.di=a,this.g("allowRelink",b,a))}},allowMove:{get:function(){return this.ci},set:function(a){var b=this.ci;b!==a&&(this.ci=a,this.g("allowMove",b,a))}},allowReshape:{get:function(){return this.ei},set:function(a){var b=this.ei;b!==a&&(this.ei=a,this.g("allowReshape",b,a))}}, allowResize:{get:function(){return this.fi},set:function(a){var b=this.fi;b!==a&&(this.fi=a,this.g("allowResize",b,a))}},allowRotate:{get:function(){return this.gi},set:function(a){var b=this.gi;b!==a&&(this.gi=a,this.g("allowRotate",b,a))}},allowSelect:{get:function(){return this.hi},set:function(a){var b=this.hi;b!==a&&(this.hi=a,this.g("allowSelect",b,a))}},allowUndo:{get:function(){return this.ur}, set:function(a){var b=this.ur;b!==a&&(this.ur=a,this.g("allowUndo",b,a))}},allowZoom:{get:function(){return this.wr},set:function(a){var b=this.wr;b!==a&&(this.wr=a,this.g("allowZoom",b,a))}},hasVerticalScrollbar:{get:function(){return this.xl},set:function(a){var b=this.xl;b!==a&&(this.xl=a,aj(this),this.M(),this.g("hasVerticalScrollbar",b,a),Yi(this,!1))}},hasHorizontalScrollbar:{get:function(){return this.wl}, set:function(a){var b=this.wl;b!==a&&(this.wl=a,aj(this),this.M(),this.g("hasHorizontalScrollbar",b,a),Yi(this,!1))}},allowHorizontalScroll:{get:function(){return this.sr},set:function(a){var b=this.sr;b!==a&&(this.sr=a,this.g("allowHorizontalScroll",b,a),Yi(this,!1))}},allowVerticalScroll:{get:function(){return this.vr},set:function(a){var b=this.vr;b!==a&&(this.vr=a,this.g("allowVerticalScroll",b,a),Yi(this,!1))}},scrollHorizontalLineChange:{ get:function(){return this.Ys},set:function(a){var b=this.Ys;b!==a&&(0>a&&wa(a,">= 0",R,"scrollHorizontalLineChange"),this.Ys=a,this.g("scrollHorizontalLineChange",b,a))}},scrollVerticalLineChange:{get:function(){return this.bt},set:function(a){var b=this.bt;b!==a&&(0>a&&wa(a,">= 0",R,"scrollVerticalLineChange"),this.bt=a,this.g("scrollVerticalLineChange",b,a))}},lastInput:{get:function(){return this.hh},set:function(a){this.hh= a}},previousInput:{get:function(){return this.pd},set:function(a){this.pd=a}},firstInput:{get:function(){return this.Yf},set:function(a){this.Yf=a}},currentCursor:{get:function(){return this.Ir},set:function(a){""===a&&(a=this.Nn);if(this.Ir!==a){var b=this.ta,c=this.Ea;if(null!==b){this.Ir=a;var d=b.style.cursor;b.style.cursor=a;c.style.cursor=a;b.style.cursor===d&&(b.style.cursor="-webkit-"+a,c.style.cursor= "-webkit-"+a,b.style.cursor===d&&(b.style.cursor="-moz-"+a,c.style.cursor="-moz-"+a,b.style.cursor===d&&(b.style.cursor=a,c.style.cursor=a)))}}}},defaultCursor:{get:function(){return this.Nn},set:function(a){""===a&&(a="auto");var b=this.Nn;b!==a&&(this.Nn=a,this.g("defaultCursor",b,a))}},click:{get:function(){return this.Rf},set:function(a){var b=this.Rf;b!==a&&(this.Rf=a,this.g("click",b,a))}},doubleClick:{ get:function(){return this.Wf},set:function(a){var b=this.Wf;b!==a&&(this.Wf=a,this.g("doubleClick",b,a))}},contextClick:{get:function(){return this.Sf},set:function(a){var b=this.Sf;b!==a&&(this.Sf=a,this.g("contextClick",b,a))}},mouseOver:{get:function(){return this.ng},set:function(a){var b=this.ng;b!==a&&(this.ng=a,this.g("mouseOver",b,a))}},mouseHover:{get:function(){return this.lg},set:function(a){var b= this.lg;b!==a&&(this.lg=a,this.g("mouseHover",b,a))}},mouseHold:{get:function(){return this.kg},set:function(a){var b=this.kg;b!==a&&(this.kg=a,this.g("mouseHold",b,a))}},mouseDragOver:{get:function(){return this.Bs},set:function(a){var b=this.Bs;b!==a&&(this.Bs=a,this.g("mouseDragOver",b,a))}},mouseDrop:{get:function(){return this.ig},set:function(a){var b=this.ig;b!==a&&(this.ig=a,this.g("mouseDrop",b,a))}}, handlesDragDropForTopLevelParts:{get:function(){return this.ds},set:function(a){var b=this.ds;b!==a&&(this.ds=a,this.g("handlesDragDropForTopLevelParts",b,a))}},mouseEnter:{get:function(){return this.jg},set:function(a){var b=this.jg;b!==a&&(this.jg=a,this.g("mouseEnter",b,a))}},mouseLeave:{get:function(){return this.mg},set:function(a){var b=this.mg;b!==a&&(this.mg=a,this.g("mouseLeave",b,a))}},toolTip:{ get:function(){return this.xg},set:function(a){var b=this.xg;b!==a&&(this.xg=a,this.g("toolTip",b,a))}},contextMenu:{get:function(){return this.Tf},set:function(a){var b=this.Tf;b!==a&&(this.Tf=a,this.g("contextMenu",b,a))}},commandHandler:{get:function(){return this.Cr},set:function(a){this.Cr!==a&&(this.Cr=a,a.fe(this))}},toolManager:{get:function(){return this.pt},set:function(a){this.pt!==a&& (this.pt=a,a.diagram=this)}},defaultTool:{get:function(){return this.Nr},set:function(a){var b=this.Nr;b!==a&&(this.Nr=a,a.diagram=this,this.currentTool===b&&(this.currentTool=a))}},currentTool:{get:function(){return this.Kr},set:function(a){var b=this.Kr;null!==b&&(b.isActive&&b.doDeactivate(),b.cancelWaitAfter(),b.doStop());null===a&&(a=this.defaultTool);null!==a&&(this.Kr=a,a.diagram=this,a.doStart())}},selection:{ get:function(){return this.pv}},maxSelectionCount:{get:function(){return this.xs},set:function(a){var b=this.xs;if(b!==a)if(0<=a&&!isNaN(a)){if(this.xs=a,this.g("maxSelectionCount",b,a),!this.undoManager.isUndoingRedoing&&(a=this.selection.count-a,0<a)){this.R("ChangingSelection",this.selection);b=this.selection.ma();for(var c=0;c<a;c++)b[c].isSelected=!1;this.R("ChangedSelection",this.selection)}}else wa(a,">= 0",R,"maxSelectionCount")}},nodeSelectionAdornmentTemplate:{ get:function(){return this.fp},set:function(a){var b=this.fp;b!==a&&(this.fp=a,this.g("nodeSelectionAdornmentTemplate",b,a))}},groupSelectionAdornmentTemplate:{get:function(){return this.no},set:function(a){var b=this.no;b!==a&&(this.no=a,this.g("groupSelectionAdornmentTemplate",b,a))}},linkSelectionAdornmentTemplate:{get:function(){return this.Go},set:function(a){var b=this.Go;b!==a&&(this.Go=a,this.g("linkSelectionAdornmentTemplate", b,a))}},highlighteds:{get:function(){return this.Qu}},isModified:{get:function(){var a=this.undoManager;return a.isEnabled?null!==a.currentTransaction?!0:this.ro&&this.Xd!==a.historyIndex:this.ro},set:function(a){if(this.ro!==a){this.ro=a;var b=this.undoManager;!a&&b.isEnabled&&(this.Xd=b.historyIndex);a||Yj(this)}}},model:{get:function(){return this.bc},set:function(a){var b=this.bc;if(b!==a){this.currentTool.doCancel(); null!==b&&b.undoManager!==a.undoManager&&b.undoManager.isInTransaction&&B("Do not replace a Diagram.model while a transaction is in progress.");this.animationManager.Cc(!0);var c=Gi(this,!0);this.re=!1;this.Kj=!0;this.Xd=-2;this.Fe=!1;var d=this.kc;this.kc=!0;th(this.animationManager,"Model");null!==b&&(null!==this.xe&&this.xe.each(function(a){b.Sk(a)}),b.Sk(this.Vc));this.bc=a;this.partManager=Zj(this.bc.type);for(var e=0;e<c.length;e++)this.add(c[e]);a.Gh(this.Dc);this.partManager.addAllModeledParts(); a.Sk(this.Dc);a.Gh(this.Vc);null!==this.xe&&this.xe.each(function(b){a.Gh(b)});this.kc=d;this.Sb||this.M();null!==b&&a.undoManager.copyProperties(b.undoManager)}}},Z:{get:function(){return this.$u},set:function(a){this.$u=a}},Yt:{get:function(){return this.Cx}},skipsModelSourceBindings:{get:function(){return this.qv},set:function(a){this.qv=a}},mu:{get:function(){return this.gt}, set:function(a){this.gt=a}},nodeTemplate:{get:function(){return this.ef.H("")},set:function(a){var b=this.ef.H("");b!==a&&(this.ef.add("",a),this.g("nodeTemplate",b,a),this.undoManager.isUndoingRedoing||this.Md())}},nodeTemplateMap:{get:function(){return this.ef},set:function(a){var b=this.ef;b!==a&&(this.ef=a,this.g("nodeTemplateMap",b,a),this.undoManager.isUndoingRedoing||this.Md())}},groupTemplate:{get:function(){return this.fh.H("")}, set:function(a){var b=this.fh.H("");b!==a&&(this.fh.add("",a),this.g("groupTemplate",b,a),this.undoManager.isUndoingRedoing||this.Md())}},groupTemplateMap:{get:function(){return this.fh},set:function(a){var b=this.fh;b!==a&&(this.fh=a,this.g("groupTemplateMap",b,a),this.undoManager.isUndoingRedoing||this.Md())}},linkTemplate:{get:function(){return this.dg.H("")},set:function(a){var b=this.dg.H("");b!==a&&(this.dg.add("",a),this.g("linkTemplate", b,a),this.undoManager.isUndoingRedoing||this.Md())}},linkTemplateMap:{get:function(){return this.dg},set:function(a){var b=this.dg;b!==a&&(this.dg=a,this.g("linkTemplateMap",b,a),this.undoManager.isUndoingRedoing||this.Md())}},isMouseCaptured:{get:function(){return this.Wu},set:function(a){var b=this.ta;null!==b&&(b=b.Ga,b instanceof SVGElement||(a?(this.lastInput.bubbles=!1,this.zj?(this.removeEventListener(b,"pointermove",this.Ok,!1),this.removeEventListener(b, "pointerdown",this.Nk,!1),this.removeEventListener(b,"pointerup",this.Qk,!1),this.removeEventListener(b,"pointerout",this.Pk,!1),this.addEventListener(x,"pointermove",this.Ok,!0),this.addEventListener(x,"pointerdown",this.Nk,!0),this.addEventListener(x,"pointerup",this.Qk,!0),this.addEventListener(x,"pointerout",this.Pk,!0)):(this.removeEventListener(b,"mousemove",this.Hk,!1),this.removeEventListener(b,"mousedown",this.Gk,!1),this.removeEventListener(b,"mouseup",this.Jk,!1),this.removeEventListener(b, "mouseout",this.Ik,!1),this.addEventListener(x,"mousemove",this.Hk,!0),this.addEventListener(x,"mousedown",this.Gk,!0),this.addEventListener(x,"mouseup",this.Jk,!0),this.addEventListener(x,"mouseout",this.Ik,!0)),this.removeEventListener(b,"wheel",this.Kk,!1),this.addEventListener(x,"wheel",this.Kk,!0),this.addEventListener(x,"selectstart",this.preventDefault,!1)):(this.zj?(this.removeEventListener(x,"pointermove",this.Ok,!0),this.removeEventListener(x,"pointerdown",this.Nk,!0),this.removeEventListener(x, "pointerup",this.Qk,!0),this.removeEventListener(x,"pointerout",this.Pk,!0),this.addEventListener(b,"pointermove",this.Ok,!1),this.addEventListener(b,"pointerdown",this.Nk,!1),this.addEventListener(b,"pointerup",this.Qk,!1),this.addEventListener(b,"pointerout",this.Pk,!1)):(this.removeEventListener(x,"mousemove",this.Hk,!0),this.removeEventListener(x,"mousedown",this.Gk,!0),this.removeEventListener(x,"mouseup",this.Jk,!0),this.removeEventListener(x,"mouseout",this.Ik,!0),this.addEventListener(b,"mousemove", this.Hk,!1),this.addEventListener(b,"mousedown",this.Gk,!1),this.addEventListener(b,"mouseup",this.Jk,!1),this.addEventListener(b,"mouseout",this.Ik,!1)),this.removeEventListener(x,"wheel",this.Kk,!0),this.removeEventListener(x,"selectstart",this.preventDefault,!1),this.addEventListener(b,"wheel",this.Kk,!1)),this.Wu=a))}},position:{get:function(){return this.la},set:function(a){var b=I.alloc().assign(this.la);if(!b.w(a)){var c=this.viewportBounds.copy();this.la.assign(a); Vh(this.animationManager,b,this.la);this.Sb||null===this.ta&&!this.rm.s()||(this.Sb=!0,a=this.scale,$i(this,this.Pn,this.va/a,this.ua/a,this.Dj,!1),this.Sb=!1);this.Sb||this.Uq(c,this.viewportBounds,this.ya,!1)}I.free(b)}},initialPosition:{get:function(){return this.fs},set:function(a){this.fs.w(a)||(this.fs=a.G())}},initialScale:{get:function(){return this.gs},set:function(a){this.gs!==a&&(this.gs=a)}},grid:{ get:function(){null===this.Jb&&Ri(this);return this.Jb},set:function(a){var b=this.Jb;if(b!==a){null===b&&(Ri(this),b=this.Jb);a.type!==X.Grid&&B("Diagram.grid must be a Panel of type Panel.Grid");var c=b.panel;null!==c&&c.remove(b);this.Jb=a;a.name="GRID";null!==c&&c.add(a);qj(this);this.M();this.g("grid",b,a)}}},viewportBounds:{get:function(){var a=this.Sx,b=this.la,c=this.ya;if(null===this.ta)return this.rm.s()&&a.h(b.x,b.y,this.va/c,this.ua/c),a;a.h(b.x,b.y,Math.max(this.va, 0)/c,Math.max(this.ua,0)/c);return a}},viewSize:{get:function(){return this.rm},set:function(a){var b=this.viewSize;b.w(a)||(this.rm=a=a.G(),null===this.Ea&&(this.va=a.width,this.ua=a.height,this.Oa()),this.g("viewSize",b,a))}},fixedBounds:{get:function(){return this.$r},set:function(a){var b=this.$r;b.w(a)||(-Infinity!==a.width&&Infinity!==a.height&&-Infinity!==a.height||B("fixedBounds width/height must not be Infinity"),this.$r=a=a.G(), this.Oa(),this.g("fixedBounds",b,a))}},scrollMargin:{get:function(){return this.Si},set:function(a){"number"===typeof a&&(a=new oc(a));var b=this.Si;b.w(a)||(this.Si=a=a.G(),this.g("scrollMargin",b,a),this.Yq())}},scrollMode:{get:function(){return this.Ti},set:function(a){var b=this.Ti;b!==a&&(this.Ti=a,a===Zh&&Yi(this,!1),this.g("scrollMode",b,a),this.M())}},scrollsPageOnFocus:{get:function(){return this.ct}, set:function(a){var b=this.ct;b!==a&&(this.ct=a,this.g("scrollsPageOnFocus",b,a))}},positionComputation:{get:function(){return this.Ps},set:function(a){var b=this.Ps;b!==a&&(this.Ps=a,Yi(this,!1),this.g("positionComputation",b,a))}},scaleComputation:{get:function(){return this.Ws},set:function(a){var b=this.Ws;b!==a&&(this.Ws=a,Wj(this,this.scale,this.scale),this.g("scaleComputation",b,a))}},documentBounds:{ get:function(){return this.Pn}},isVirtualized:{get:function(){return this.ss},set:function(a){var b=this.ss;b!==a&&(this.ss=a,this.g("isVirtualized",b,a))}},scale:{get:function(){return this.ya},set:function(a){var b=this.ya;b!==a&&Wj(this,b,a)}},defaultScale:{get:function(){return this.On},set:function(a){this.On=a}},autoScale:{get:function(){return this.Pg},set:function(a){var b= this.Pg;b!==a&&(this.Pg=a,this.g("autoScale",b,a),a!==Lh&&Yi(this,!1))}},initialAutoScale:{get:function(){return this.$f},set:function(a){var b=this.$f;b!==a&&(this.$f=a,this.g("initialAutoScale",b,a))}},initialViewportSpot:{get:function(){return this.hs},set:function(a){var b=this.hs;b!==a&&(a.kb()||B("initialViewportSpot must be a specific Spot: "+a),this.hs=a,this.g("initialViewportSpot",b,a))}},initialDocumentSpot:{ get:function(){return this.es},set:function(a){var b=this.es;b!==a&&(a.kb()||B("initialViewportSpot must be a specific Spot: "+a),this.es=a,this.g("initialDocumentSpot",b,a))}},minScale:{get:function(){return this.ys},set:function(a){var b=this.ys;b!==a&&(0<a?(this.ys=a,this.g("minScale",b,a),a>this.scale&&(this.scale=a)):wa(a,"> 0",R,"minScale"))}},maxScale:{get:function(){return this.ws},set:function(a){var b=this.ws;b!==a&&(0<a?(this.ws= a,this.g("maxScale",b,a),a<this.scale&&(this.scale=a)):wa(a,"> 0",R,"maxScale"))}},zoomPoint:{get:function(){return this.xt},set:function(a){this.xt.w(a)||(this.xt=a=a.G())}},contentAlignment:{get:function(){return this.Dj},set:function(a){var b=this.Dj;b.w(a)||(this.Dj=a=a.G(),this.g("contentAlignment",b,a),Yi(this,!1))}},initialContentAlignment:{get:function(){return this.po},set:function(a){var b=this.po; b.w(a)||(this.po=a=a.G(),this.g("initialContentAlignment",b,a))}},padding:{get:function(){return this.ib},set:function(a){"number"===typeof a&&(a=new oc(a));var b=this.ib;b.w(a)||(this.ib=a=a.G(),this.Oa(),this.g("padding",b,a))}},partManager:{get:function(){return this.Ka},set:function(a){var b=this.Ka;b!==a&&(null!==a.diagram&&B("Cannot share PartManagers between Diagrams: "+a.toString()),null!==b&&b.fe(null),this.Ka=a,a.fe(this))}},nodes:{ get:function(){return this.partManager.nodes.iterator}},links:{get:function(){return this.partManager.links.iterator}},parts:{get:function(){return this.partManager.parts.iterator}},layout:{get:function(){return this.lc},set:function(a){var b=this.lc;b!==a&&(this.lc=a,a.diagram=this,a.group=null,this.Og=!0,this.g("layout",b,a),this.Eb())}},isTreePathToChildren:{get:function(){return this.rs}, set:function(a){var b=this.rs;if(b!==a&&(this.rs=a,this.g("isTreePathToChildren",b,a),!this.undoManager.isUndoingRedoing))for(a=this.nodes;a.next();)Fk(a.value)}},treeCollapsePolicy:{get:function(){return this.rt},set:function(a){var b=this.rt;b!==a&&(a!==ui&&a!==Gk&&a!==Hk&&B("Unknown Diagram.treeCollapsePolicy: "+a),this.rt=a,this.g("treeCollapsePolicy",b,a))}},Le:{get:function(){return this.Tu},set:function(a){this.Tu=a}},autoScrollInterval:{ get:function(){return this.on},set:function(a){var b=this.on;b!==a&&(this.on=a,this.g("autoScrollInterval",b,a))}},autoScrollRegion:{get:function(){return this.qn},set:function(a){"number"===typeof a&&(a=new oc(a));var b=this.qn;b.w(a)||(this.qn=a=a.G(),this.Oa(),this.g("autoScrollRegion",b,a))}}}); na.Object.defineProperties(R,{licenseKey:{get:function(){return Ik.Xb()},set:function(a){Ik.add(a)}},version:{get:function(){return Jk}}});R.prototype.makeImageData=R.prototype.Iy;R.prototype.makeImage=R.prototype.GA;R.prototype.addRenderer=R.prototype.rz;R.prototype.makeSVG=R.prototype.hw;R.prototype.makeSvg=R.prototype.$t;R.prototype.stopAutoScroll=R.prototype.Lf;R.prototype.doAutoScroll=R.prototype.Ft;R.prototype.isUnoccupied=R.prototype.Dk; R.prototype.raiseDiagramEvent=R.prototype.R;R.prototype.removeDiagramListener=R.prototype.Km;R.prototype.addDiagramListener=R.prototype.kk;R.prototype.findTreeRoots=R.prototype.jA;R.prototype.layoutDiagram=R.prototype.EA;R.prototype.findTopLevelGroups=R.prototype.cA;R.prototype.findTopLevelNodesAndLinks=R.prototype.dA;R.prototype.ensureBounds=R.prototype.Ta;R.prototype.findLinksByExample=R.prototype.It;R.prototype.findNodesByExample=R.prototype.Jt;R.prototype.findLinkForData=R.prototype.yc; R.prototype.findNodeForData=R.prototype.gj;R.prototype.findPartForData=R.prototype.zc;R.prototype.findLinkForKey=R.prototype.findLinkForKey;R.prototype.findNodeForKey=R.prototype.Db;R.prototype.findPartForKey=R.prototype.findPartForKey;R.prototype.rebuildParts=R.prototype.Md;R.prototype.transformViewToDoc=R.prototype.nu;R.prototype.transformRectDocToView=R.prototype.gB;R.prototype.transformDocToView=R.prototype.hr;R.prototype.centerRect=R.prototype.At;R.prototype.scrollToRect=R.prototype.Bw; R.prototype.scroll=R.prototype.scroll;R.prototype.highlightCollection=R.prototype.vA;R.prototype.highlight=R.prototype.uA;R.prototype.selectCollection=R.prototype.YA;R.prototype.select=R.prototype.select;R.prototype.updateAllRelationshipsFromData=R.prototype.jr;R.prototype.updateAllTargetBindings=R.prototype.updateAllTargetBindings;R.prototype.commit=R.prototype.commit;R.prototype.rollbackTransaction=R.prototype.Kf;R.prototype.commitTransaction=R.prototype.Wa;R.prototype.startTransaction=R.prototype.xa; R.prototype.raiseChanged=R.prototype.g;R.prototype.raiseChangedEvent=R.prototype.bb;R.prototype.removeChangedListener=R.prototype.Sk;R.prototype.addChangedListener=R.prototype.Gh;R.prototype.removeModelChangedListener=R.prototype.UA;R.prototype.addModelChangedListener=R.prototype.Xx;R.prototype.findLayer=R.prototype.ym;R.prototype.removeLayer=R.prototype.SA;R.prototype.addLayerAfter=R.prototype.nz;R.prototype.addLayerBefore=R.prototype.Vx;R.prototype.addLayer=R.prototype.tm; R.prototype.moveParts=R.prototype.moveParts;R.prototype.copyParts=R.prototype.tk;R.prototype.removeParts=R.prototype.gu;R.prototype.remove=R.prototype.remove;R.prototype.add=R.prototype.add;R.prototype.clearDelayedGeometries=R.prototype.Gv;R.prototype.setProperties=R.prototype.Gw;R.prototype.resetInputOptions=R.prototype.xw;R.prototype.setInputOption=R.prototype.ZA;R.prototype.getInputOption=R.prototype.Bm;R.prototype.resetRenderingHints=R.prototype.yw;R.prototype.setRenderingHint=R.prototype.Uy; R.prototype.getRenderingHint=R.prototype.Ke;R.prototype.maybeUpdate=R.prototype.jd;R.prototype.requestUpdate=R.prototype.Eb;R.prototype.delayInitialization=R.prototype.Jz;R.prototype.isUpdateRequested=R.prototype.AA;R.prototype.redraw=R.prototype.Ne;R.prototype.invalidateDocumentBounds=R.prototype.Oa;R.prototype.findObjectsNear=R.prototype.Fg;R.prototype.findPartsNear=R.prototype.$z;R.prototype.findObjectsIn=R.prototype.Bf;R.prototype.findPartsIn=R.prototype.ty;R.prototype.findObjectsAt=R.prototype.hj; R.prototype.findPartsAt=R.prototype.Zz;R.prototype.findObjectAt=R.prototype.Vb;R.prototype.findPartAt=R.prototype.zm;R.prototype.focusObject=R.prototype.kA;R.prototype.alignDocument=R.prototype.uz;R.prototype.zoomToRect=R.prototype.kB;R.prototype.zoomToFit=R.prototype.zoomToFit;R.prototype.diagramScroll=R.prototype.iy;R.prototype.focus=R.prototype.focus;R.prototype.reset=R.prototype.reset;R.useDOM=function(a){Wg=a?void 0!==x.document:!1};R.isUsingDOM=function(){return Wg}; var He=null,vi=new H,Pi=null,Oi=null,Wg=void 0!==x.document,Ei=null,Fi="",Lh=new D(R,"None",0),cj=new D(R,"Uniform",1),dj=new D(R,"UniformToFill",2),Of=new D(R,"CycleAll",10),Sf=new D(R,"CycleNotDirected",11),Uf=new D(R,"CycleNotDirectedFast",12),Vf=new D(R,"CycleNotUndirected",13),Pf=new D(R,"CycleDestinationTree",14),Rf=new D(R,"CycleSourceTree",15),Zh=new D(R,"DocumentScroll",1),ai=new D(R,"InfiniteScroll",2),ui=new D(R,"TreeParentCollapsed",21),Gk=new D(R,"AllParentsCollapsed",22),Hk=new D(R, "AnyParentsCollapsed",23),Ik=new E,Jk="2.1.45",Dk="image",Kk=null,ri=!1; function si(){if(Wg){var a=x.document.createElement("canvas"),b=a.getContext("2d"),c=Sa("7ca11abfd022028846");b[c]=Sa("398c3597c01238");for(var d=["5da73c80a36455d5038e4972187c3cae51fd22",ra.Dx+"4ae6247590da4bb21c324ba3a84e385776",rd.xF+"fb236cdfda5de14c134ba1a95a2d4c7cc6f93c1387",L.za],e=1;5>e;e++)b[Sa("7ca11abfd7330390")](Sa(d[e-1]),10,15*e);b[c]=Sa("39f046ebb36e4b");for(c=1;5>c;c++)b[Sa("7ca11abfd7330390")](Sa(d[c-1]),10,15*c);if(4!==d.length||"5"!==d[0][0]||"7"!==d[3][0])rd.prototype.Jd=rd.prototype.$x; Kk=a}}R.className="Diagram";R.fromDiv=function(a){var b=a;"string"===typeof a&&(b=x.document.getElementById(a));return b instanceof HTMLDivElement&&b.B instanceof R?b.B:null};R.inherit=function(a,b){function c(){}if(Object.getPrototypeOf(a).prototype)throw Error("Used go.Diagram.inherit defining already defined class \n"+a);c.prototype=b.prototype;a.prototype=new c;a.prototype.constructor=a};R.None=Lh;R.Uniform=cj;R.UniformToFill=dj;R.CycleAll=Of;R.CycleNotDirected=Sf;R.CycleNotDirectedFast=Uf; R.CycleNotUndirected=Vf;R.CycleDestinationTree=Pf;R.CycleSourceTree=Rf;R.DocumentScroll=Zh;R.InfiniteScroll=ai;R.TreeParentCollapsed=ui;R.AllParentsCollapsed=Gk;R.AnyParentsCollapsed=Hk;function Ci(){this.jz=null;this.l="zz@orderNum";"63ad05bbe23a1786468a4c741b6d2"===this._tk?this.We=this.l=!0:this.We=null} function zj(a,b){b.Hb.setTransform(b.Tb,0,0,b.Tb,0,0);if(null===a.We){b="f";var c=x[Sa("76a715b2f73f148a")][Sa("72ba13b5")];a.We=!0;if(Wg){var d=R[Sa("76a115b6ed251eaf4692")];if(d)for(var e=Ik.iterator;e.next();){d=e.value;d=Sa(d).split(Sa("39e9"));if(6>d.length)break;var f=Sa(d[1]).split(".");if("7da71ca0"!==d[4])break;var g=Sa(ra[Sa("6cae19")]).split(".");if(f[0]>g[0]||f[0]===g[0]&&f[1]>=g[1]){f=c[Sa("76ad18b4f73e")];for(g=c[Sa("73a612b6fb191d")](Sa("35e7"))+2;g<f;g++)b+=c[g];f=b[Sa("73a612b6fb191d")](Sa(d[2])); 0>f&&Sa(d[2])!==Sa("7da71ca0ad381e90")&&(f=b[Sa("73a612b6fb191d")](Sa("76a715b2ef3e149757")));0>f&&(f=b[Sa("73a612b6fb191d")](Sa("76a715b2ef3e149757")));0>f&&(f=c[Sa("73a612b6fb191d")](Sa("7baa19a6f76c1988428554")));a.We=!(0<=f&&f<b[Sa("73a612b6fb191d")](Sa("35"))||-1===b[Sa("73a612b6fb191d")](Sa("35")));if(!a.We)break;f=Sa(d[2]);if("#"!==f[0])break;g=x.document.createElement("div");for(var h=d[0].replace(/[A-Za-z]/g,"");4>h.length;)h+="9";h=h.substr(h.length-4);d="";d+=["gsh","gsf"][parseInt(h.substr(0, 1),10)%2];d+=["Header","Background","Display","Feedback"][parseInt(h.substr(0,1),10)%4];g[Sa("79a417a0f0181a8946")]=d;if(x.document[Sa("78a712aa")]){x.document[Sa("78a712aa")][Sa("7bb806b6ed32388c4a875b")](g);h=x.getComputedStyle(g).getPropertyValue(Sa("78a704b7e62456904c9b12701b6532a8"));x.document[Sa("78a712aa")][Sa("68ad1bbcf533388c4a875b")](g);if(!h)break;if(-1!==h.indexOf(parseInt(f[1]+f[2],16))&&-1!==h.indexOf(parseInt(f[3]+f[4],16))){a.We=!1;break}else if(Ta||Ua||Va||Wa)for(d="."+d,f=0;f<document.styleSheets.length;f++){g= document.styleSheets[f].rules||document.styleSheets[f].cssRules;for(var k in g)if(d===g[k].selectorText){a.We=!1;break}}}else a.We=null,a.We=!1}}else{k=c[Sa("76ad18b4f73e")];for(e=c[Sa("73a612b6fb191d")](Sa("35e7"))+2;e<k;e++)b+=c[e];c=b[Sa("73a612b6fb191d")](Sa("7da71ca0ad381e90"));a.We=!(0<=c&&c<b[Sa("73a612b6fb191d")](Sa("35")))}}}return 0<a.We&&a!==a.jz?!0:!1} function Di(a,b){if(Wg){void 0!==b&&null!==b||B("Diagram setup requires an argument DIV.");null!==a.Ea&&B("Diagram has already completed setup.");"string"===typeof b?a.Ea=x.document.getElementById(b):b instanceof HTMLDivElement?a.Ea=b:B("No DIV or DIV id supplied: "+b);null===a.Ea&&B("Invalid DIV id; could not get element with id: "+b);void 0!==a.Ea.B&&B("Invalid div id; div already has a Diagram associated with it.");if(!a.Zl&&x.ResizeObserver){var c=sa(function(){a.Eb()},250);a.Zl=new x.ResizeObserver(function(){c()}); a.Zl.observe(a.Ea)}"static"===x.getComputedStyle(a.Ea,null).position&&(a.Ea.style.position="relative");b=5;var d="rgba(2"+b+"5, 255, 255, 0)";b--;a.Ea.style["-webkit-tap-highlight-color"]=d;a.Ea.style["-ms-touch-action"]="none";a.Ea.innerHTML="";a.Ea.B=a;a.Ea.goDiagram=a;a.Ea.go=x.go;var e=a.cq?new Ej(a):new Ek(a);void 0!==e.style&&(e.style.position="absolute",e.style.top="0px",e.style.left="0px","rtl"===x.getComputedStyle(a.Ea,null).getPropertyValue("direction")&&(a.Hl=!0),e.style.zIndex="2",e.style.userSelect= "none",e.style.MozUserSelect="none");a.ta=e;a.Hb=e.context;d=a.Hb;a.Tb=a.computePixelRatio();a.va=a.Ea.clientWidth||1;a.ua=a.Ea.clientHeight||1;Gj(a,a.va,a.ua);a.Ea.insertBefore(e.Ga,a.Ea.firstChild);e=new Ek(null);e.width=1;e.height=1;a.Iu=e;a.vx=e.context;if(Wg){e=ua("div");var f=ua("div");e.style.position="absolute";e.style.overflow="auto";e.style.width=a.va+"px";e.style.height=a.ua+"px";e.style.zIndex="1";f.style.position="absolute";f.style.width="1px";f.style.height="1px";a.Ea.appendChild(e); e.appendChild(f);e.onscroll=Si;e.addEventListener("mousedown",Ui);e.addEventListener("touchstart",Ui,{passive:!0});e.B=a;e.hz=!0;e.iz=!0;a.$s=e;a.Kp=f}a.Yq=sa(function(){a.xh=null;a.M()},300);a.Xw=sa(function(){Mh(a)},250);a.preventDefault=function(a){a.preventDefault();return!1};a.Hk=function(b){if(a.isEnabled){a.ag=!0;var c=hj(a,b,!0);a.doMouseMove();a.currentTool.isBeyondDragSize()&&(a.xd=0);nj(c,b)}};a.Gk=function(b){if(a.isEnabled)if(a.ag=!0,a.se)b.preventDefault();else{var c=hj(a,b,!0);c.down= !0;c.clickCount=b.detail;if(Ua||Va)b.timeStamp-a.Sj<a.qt&&!a.currentTool.isBeyondDragSize()?a.xd++:a.xd=1,a.Sj=b.timeStamp,c.clickCount=a.xd;c.clone(a.firstInput);a.doMouseDown();1===b.button?b.preventDefault():nj(c,b)}};a.Jk=function(b){if(a.isEnabled)if(a.se&&2===b.button)b.preventDefault();else if(a.se&&0===b.button&&(a.se=!1),a.hk)b.preventDefault();else{a.ag=!0;var c=hj(a,b,!0);c.up=!0;c.clickCount=b.detail;if(Ua||Va)c.clickCount=a.xd;c.bubbles=b.bubbles;c.targetDiagram=jj(b);a.doMouseUp();a.Lf(); nj(c,b)}};a.Kk=function(b){if(a.isEnabled){var c=hj(a,b,!0);c.bubbles=!0;var d=0,e=0;c.delta=0;void 0!==b.deltaX?(0!==b.deltaX&&(d=0<b.deltaX?1:-1),0!==b.deltaY&&(e=0<b.deltaY?1:-1),c.delta=Math.abs(b.deltaX)>Math.abs(b.deltaY)?-d:-e):void 0!==b.wheelDeltaX?(0!==b.wheelDeltaX&&(d=0<b.wheelDeltaX?-1:1),0!==b.wheelDeltaY&&(e=0<b.wheelDeltaY?-1:1),c.delta=Math.abs(b.wheelDeltaX)>Math.abs(b.wheelDeltaY)?-d:-e):void 0!==b.wheelDelta&&0!==b.wheelDelta&&(c.delta=0<b.wheelDelta?1:-1);a.doMouseWheel();nj(c, b)}};a.Ik=function(b){a.isEnabled&&(a.ag=!1,hj(a,b,!0),b=a.currentTool,b.cancelWaitAfter(),b.standardMouseOver())};a.Pw=function(b){if(a.isEnabled){a.hk=!1;a.se=!0;var c=kj(a,b,b.targetTouches[0],1<b.touches.length),d=null;0<b.targetTouches.length?d=b.targetTouches[0]:0<b.changedTouches.length&&(d=b.changedTouches[0]);if(null!==d){var e=d.screenX;d=d.screenY;var f=a.Bo;b.timeStamp-a.Sj<a.qt&&!(25<Math.abs(f.x-e)||25<Math.abs(f.y-d))?a.xd++:a.xd=1;c.clickCount=a.xd;a.Sj=b.timeStamp;a.Bo.h(e,d)}a.doMouseDown(); nj(c,b)}};a.Ow=function(b){if(a.isEnabled){var c=null;0<b.targetTouches.length?c=b.targetTouches[0]:0<b.changedTouches.length&&(c=b.changedTouches[0]);c=mj(a,b,c,1<b.touches.length);a.doMouseMove();nj(c,b)}};a.Nw=function(b){if(a.isEnabled)if(a.hk)b.preventDefault();else if(!(1<b.touches.length)){var c=null,d=null;0<b.targetTouches.length?d=b.targetTouches[0]:0<b.changedTouches.length&&(d=b.changedTouches[0]);var e=lj(a,b,!1,!0,!1,!1);null!==d&&(c=x.document.elementFromPoint(d.clientX,d.clientY), null!==c&&void 0!==c.shadowRoot&&null!==c&&null!==c.shadowRoot&&(c=c.shadowRoot.elementFromPoint(d.clientX,d.clientY)),null!==c&&c.B instanceof R&&c.B!==a&&ij(c.B,d,e),ij(a,d,e),e.clickCount=a.xd);null===c?e.targetDiagram=jj(b):c.B?e.targetDiagram=c.B:e.targetDiagram=null;e.targetObject=null;a.doMouseUp();nj(e,b);a.se=!1}};a.Nk=function(b){if(a.isEnabled){a.ag=!0;var c=a.Ns;void 0===c[b.pointerId]&&(c[b.pointerId]=b);c=a.bk;var d=!1;if(null!==c[0]&&c[0].pointerId===b.pointerId)c[0]=b;else if(null!== c[1]&&c[1].pointerId===b.pointerId)c[1]=b,d=!0;else if(null===c[0])c[0]=b;else if(null===c[1])c[1]=b,d=!0;else{b.preventDefault();return}if("touch"===b.pointerType||"pen"===b.pointerType)a.hk=!1,a.se=!0;c=kj(a,b,b,d);d=a.Bo;var e="touch"===b.pointerType||"pen"===b.pointerType?25:10;b.timeStamp-a.Sj<a.qt&&!(Math.abs(d.x-b.screenX)>e||Math.abs(d.y-b.screenY)>e)?a.xd++:a.xd=1;c.clickCount=a.xd;a.Sj=b.timeStamp;a.Bo.Jg(b.screenX,b.screenY);a.doMouseDown();1===b.button?b.preventDefault():nj(c,b)}};a.Ok= function(b){if(a.isEnabled){a.ag=!0;var c=a.bk;if(null!==c[0]&&c[0].pointerId===b.pointerId)c[0]=b;else{if(null!==c[1]&&c[1].pointerId===b.pointerId){c[1]=b;return}if(null===c[0])c[0]=b;else return}c[0].pointerId===b.pointerId&&(c=mj(a,b,b,null!==c[1]),c.targetDiagram=jj(b),a.doMouseMove(),nj(c,b))}};a.Qk=function(b){if(a.isEnabled){a.ag=!0;var c="touch"===b.pointerType||"pen"===b.pointerType,d=a.Ns;if(c&&a.hk)delete d[b.pointerId],b.preventDefault();else if(d=a.bk,null!==d[0]&&d[0].pointerId===b.pointerId){d[0]= null;d=lj(a,b,!1,!0,!0,!1);var e=x.document.elementFromPoint(b.clientX,b.clientY);null!==e&&e.B instanceof R&&e.B!==a&&ij(e.B,b,d);ij(a,b,d);d.clickCount=a.xd;null===e?d.targetDiagram=jj(b):e.B?d.targetDiagram=e.B:d.targetDiagram=null;d.targetObject=null;a.doMouseUp();nj(d,b);c&&(a.se=!1)}else null!==d[1]&&d[1].pointerId===b.pointerId&&(d[1]=null)}};a.Pk=function(b){if(a.isEnabled){a.ag=!1;var c=a.Ns;c[b.pointerId]&&delete c[b.pointerId];c=a.bk;null!==c[0]&&c[0].pointerId===b.pointerId&&(c[0]=null); null!==c[1]&&c[1].pointerId===b.pointerId&&(c[1]=null);"touch"!==b.pointerType&&"pen"!==b.pointerType&&(b=a.currentTool,b.cancelWaitAfter(),b.standardMouseOver())}};a.Ur=d.Y["d"+Lk[1]+Lk[2]+"wI"+Dk.slice(1,5)]["b"+Mk.slice(1,b)](d.Y,Kk,b,b);d.uc(!0);Qi(a)}}Ci.className="DiagramHelper";function ef(a){this.l=void 0===a?new I:a;this.v=new I} na.Object.defineProperties(ef.prototype,{point:{get:function(){return this.l},set:function(a){this.l=a}},shifted:{get:function(){return this.v},set:function(a){this.v=a}}});var Lk="DraggingInfo";ef.className="DraggingInfo";function Rj(a,b,c){this.node=a;this.info=b;this.Zv=c}Rj.className="DraggingNodeInfoPair";function Ye(){this.reset()} Ye.prototype.reset=function(){this.isGridSnapEnabled=!1;this.isGridSnapRealtime=!0;this.gridSnapCellSize=(new M(NaN,NaN)).freeze();this.gridSnapCellSpot=vc;this.gridSnapOrigin=(new I(NaN,NaN)).freeze();this.groupsSnapMembers=this.dragsTree=this.dragsLink=!1;this.dragsMembers=this.groupsAlwaysMove=!0};Ye.className="DraggingOptions";function Nk(a){1<arguments.length&&B("Palette constructor can only take one optional argument, the DIV HTML element or its id.");R.call(this,a);Ok(this)}ma(Nk,R); function Ok(a){a.allowDragOut=!0;a.allowMove=!1;a.isReadOnly=!0;a.contentAlignment=yc;a.layout=new Pk}Nk.prototype.reset=function(){R.prototype.reset.call(this);Ok(this)};Nk.className="Palette"; function Qk(a){1<arguments.length&&B("Overview constructor can only take one optional argument, the DIV HTML element or its id.");R.call(this,a);var b=this;this.animationManager.isEnabled=!1;this.Sb=!0;this.Ja=null;this.xl=this.wl=!1;this.v=this.I=!0;this.eb=0;this.T=!1;this.em=null;this.Uy("drawShadows",!1);var c=new V,d=new Mf;d.stroke="magenta";d.strokeWidth=2;d.fill="transparent";d.name="BOXSHAPE";c.selectable=!0;c.selectionAdorned=!1;c.selectionObjectName="BOXSHAPE";c.locationObjectName="BOXSHAPE"; c.resizeObjectName="BOXSHAPE";c.cursor="move";c.add(d);this.l=c;this.allowDelete=this.allowCopy=!1;this.allowSelect=!0;this.autoScrollRegion=new oc(0,0,0,0);this.la.h(0,0);this.toolManager.Xa("Dragging",new Rk,this.toolManager.mouseMoveTools);this.click=function(){var a=b.observed;if(null!==a){var c=a.viewportBounds,d=b.lastInput.documentPoint;a.position=new I(d.x-c.width/2,d.y-c.height/2)}};this.Wh=function(){b.Oa();Sk(b)};this.Vh=function(){null!==b.observed&&(b.Oa(),b.M())};this.Uc=function(){1> b.updateDelay?b.M():b.T||(b.T=!0,setTimeout(function(){b.T=!1;var a=b.ta,c=b.Hb;if(null!==a&&null!==c){xj(b);if(null===b.em){var d=new Ek(null);d.width=a.width;d.height=a.height;b.em=d}try{b.ta=b.em,b.Hb=b.ta.context,b.Hb.uc(!0),b.Hb.setTransform(1,0,0,1,0,0),b.Hb.clearRect(0,0,b.ta.width,b.ta.height),Tk(b)}finally{b.ta=a,b.Hb=c}}b.M()},b.updateDelay))};this.Od=function(){null!==b.observed&&Sk(b)};this.autoScale=cj;this.Sb=!1}ma(Qk,R);Qk.prototype.computePixelRatio=function(){return 1}; Qk.prototype.cc=function(){null===this.Ea&&B("No div specified");null===this.ta&&B("No canvas specified");if(!(this.ta instanceof Ej)&&(mi(this.box),this.Fc)){var a=this.observed;if(null!==a&&!a.animationManager.defaultAnimation.isAnimating&&a.pj){xj(this);var b=this.ta;a=this.Hb;a.uc(!0);a.setTransform(1,0,0,1,0,0);a.clearRect(0,0,b.width,b.height);1>this.updateDelay?Tk(this):null!==this.em&&(a.drawImage(this.em.Ga,0,0),b=this.qb,b.reset(),1!==this.scale&&b.scale(this.scale),0===this.position.x&& 0===this.position.y||b.translate(-this.position.x,-this.position.y),a.scale(this.Tb,this.Tb),a.transform(b.m11,b.m12,b.m21,b.m22,b.dx,b.dy));b=this.La.j;for(var c=b.length,d=0;d<c;d++)b[d].cc(a,this);this.Fc=this.wi=!1}}}; function Tk(a){var b=a.observed;if(null!==b){var c=a.drawsTemporaryLayers,d=a.drawsGrid&&c,e=b.grid;d&&null!==e&&e.visible&&!isNaN(e.width)&&!isNaN(e.height)&&(e=N.alloc().assign(a.viewportBounds).Tc(b.viewportBounds),qj(b,e),N.free(e),Wi(b));var f=a.qb;f.reset();1!==a.scale&&f.scale(a.scale);0===a.position.x&&0===a.position.y||f.translate(-a.position.x,-a.position.y);e=a.Hb;e.scale(a.Tb,a.Tb);e.transform(f.m11,f.m12,f.m21,f.m22,f.dx,f.dy);b=b.La.j;f=b.length;for(var g=0;g<f;g++){var h=b[g],k=a;if(h.visible&& 0!==h.opacity){var l=h.diagram.grid.part;if(!c&&h.isTemporary)d&&l.layer===h&&(h=ni(h,e),l.cc(e,k),e.globalAlpha=h);else{for(var m=ni(h,e),n=k.scale,p=N.alloc(),r=h.Da.j,q=r.length,u=0;u<q;u++){var v=r[u];(d||v!==l)&&h.dj(e,v,k,null,n,p,!1)}N.free(p);e.globalAlpha=m}}}}} function Sk(a){var b=a.box;if(null!==b){var c=a.observed;if(null!==c){a.Fc=!0;c=c.viewportBounds;var d=b.selectionObject,e=M.alloc();e.h(c.width,c.height);d.desiredSize=e;M.free(e);a=2/a.scale;d instanceof Mf&&(d.strokeWidth=a);b.location=new I(c.x-a/2,c.y-a/2);b.isSelected=!0}}}Qk.prototype.computeBounds=function(){var a=this.observed;if(null===a)return kc;var b=a.documentBounds.copy();b.Tc(a.viewportBounds);return b};Qk.prototype.Fy=function(){!0!==this.Fc&&(this.Fc=!0,this.Eb())}; Qk.prototype.Uq=function(a,b,c,d){this.Sb||(Vi(this),this.M(),aj(this),this.Oa(),Sk(this),this.Kc.scale=c,this.Kc.position.x=a.x,this.Kc.position.y=a.y,this.Kc.bounds.assign(a),this.Kc.gw=d,this.R("ViewportBoundsChanged",this.Kc,a))}; na.Object.defineProperties(Qk.prototype,{observed:{get:function(){return this.Ja},set:function(a){var b=this.Ja;a instanceof Qk&&B("Overview.observed Diagram may not be an Overview itself: "+a);if(b!==a){null!==b&&(this.remove(this.box),b.Km("ViewportBoundsChanged",this.Wh),b.Km("DocumentBoundsChanged",this.Vh),b.Km("InvalidateDraw",this.Uc),b.Km("AnimationFinished",this.Od));this.Ja=a;null!==a&&(a.kk("ViewportBoundsChanged",this.Wh),a.kk("DocumentBoundsChanged",this.Vh), a.kk("InvalidateDraw",this.Uc),a.kk("AnimationFinished",this.Od),this.add(this.box));this.Oa();if(null===a){this.em=null;var c=this.ta,d=this.Hb;c&&d&&(d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,c.width,c.height))}else this.Uc(null),Sk(this),this.M();this.g("observed",b,a)}}},box:{get:function(){return this.l},set:function(a){var b=this.l;b!==a&&(this.l=a,this.remove(b),this.add(this.l),Sk(this),this.g("box",b,a))}},drawsTemporaryLayers:{ get:function(){return this.I},set:function(a){this.I!==a&&(this.I=a,this.Ne())}},drawsGrid:{get:function(){return this.v},set:function(a){this.v!==a&&(this.v=a,this.Ne())}},updateDelay:{get:function(){return this.eb},set:function(a){0>a&&(a=0);this.eb!==a&&(this.eb=a)}}});Qk.className="Overview";function Rk(){Xe.call(this);this.l=null}ma(Rk,Xe); Rk.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(null===a||!a.allowMove||!a.allowSelect)return!1;var b=a.observed;if(null===b)return!1;var c=a.lastInput;if(!c.left||a.currentTool!==this&&(!this.isBeyondDragSize()||c.isTouchEvent&&c.timestamp-a.firstInput.timestamp<this.delay))return!1;null===this.findDraggablePart()&&(c=b.viewportBounds,this.l=new I(c.width/2,c.height/2),a=a.firstInput.documentPoint,b.position=new I(a.x-this.l.x,a.y-this.l.y));return!0}; Rk.prototype.doActivate=function(){this.l=null;Xe.prototype.doActivate.call(this)};Rk.prototype.doUpdateCursor=function(){var a=this.diagram,b=a.box;null!==b&&b.cursor&&(a.currentCursor=b.cursor)};Rk.prototype.moveParts=function(){var a=this.diagram,b=a.observed;if(null!==b){var c=a.box;if(null!==c){if(null===this.l){var d=a.firstInput.documentPoint;c=c.location;this.l=new I(d.x-c.x,d.y-c.y)}a=a.lastInput.documentPoint;b.position=new I(a.x-this.l.x,a.y-this.l.y)}}};Rk.className="OverviewDraggingTool"; function Uk(){Za(this);this.B=He;this.eb=this.I=this.v=!0;this.T=this.Ja=this.Uc=this.Ka=!1;this.Ji=this.l=null;this.Od=1.05;this.av=NaN;this.Ax=null;this.Av=NaN;this.zv=kc;this.Dc=!0;this.tg=null;this.Vc=200}Uk.prototype.toString=function(){return"CommandHandler"};Uk.prototype.fe=function(a){this.B=a}; Uk.prototype.doKeyDown=function(){var a=this.diagram,b=a.lastInput,c=Xa?b.meta:b.control,d=b.shift,e=b.alt,f=b.key;!c||"C"!==f&&"Insert"!==f?c&&"X"===f||d&&"Del"===f?this.canCutSelection()&&this.cutSelection():c&&"V"===f||d&&"Insert"===f?this.canPasteSelection()&&this.pasteSelection():c&&"Y"===f||e&&d&&"Backspace"===f?this.canRedo()&&this.redo():c&&"Z"===f||e&&"Backspace"===f?this.canUndo()&&this.undo():"Del"===f||"Backspace"===f?this.canDeleteSelection()&&this.deleteSelection():c&&"A"===f?this.canSelectAll()&& this.selectAll():"Esc"===f?this.canStopCommand()&&this.stopCommand():"Up"===f?a.allowVerticalScroll&&(c?a.scroll("pixel","up"):a.scroll("line","up")):"Down"===f?a.allowVerticalScroll&&(c?a.scroll("pixel","down"):a.scroll("line","down")):"Left"===f?a.allowHorizontalScroll&&(c?a.scroll("pixel","left"):a.scroll("line","left")):"Right"===f?a.allowHorizontalScroll&&(c?a.scroll("pixel","right"):a.scroll("line","right")):"PageUp"===f?d&&a.allowHorizontalScroll?a.scroll("page","left"):a.allowVerticalScroll&& a.scroll("page","up"):"PageDown"===f?d&&a.allowHorizontalScroll?a.scroll("page","right"):a.allowVerticalScroll&&a.scroll("page","down"):"Home"===f?c&&a.allowVerticalScroll?a.scroll("document","up"):!c&&a.allowHorizontalScroll&&a.scroll("document","left"):"End"===f?c&&a.allowVerticalScroll?a.scroll("document","down"):!c&&a.allowHorizontalScroll&&a.scroll("document","right"):" "===f?this.canScrollToPart()&&this.scrollToPart():"Subtract"===f?this.canDecreaseZoom()&&this.decreaseZoom():"Add"===f?this.canIncreaseZoom()&& this.increaseZoom():c&&"0"===f?this.canResetZoom()&&this.resetZoom():d&&"Z"===f?this.canZoomToFit()&&this.zoomToFit():c&&!d&&"G"===f?this.canGroupSelection()&&this.groupSelection():c&&d&&"G"===f?this.canUngroupSelection()&&this.ungroupSelection():b.event&&"F2"===b.event.key?this.canEditTextBlock()&&this.editTextBlock():b.event&&"ContextMenu"===b.event.key?this.canShowContextMenu()&&this.showContextMenu():b.bubbles=!0:this.canCopySelection()&&this.copySelection()}; Uk.prototype.doKeyUp=function(){this.diagram.lastInput.bubbles=!0};Uk.prototype.stopCommand=function(){var a=this.diagram,b=a.currentTool;b instanceof Pa&&a.allowSelect&&a.clearSelection();null!==b&&b.doCancel()};Uk.prototype.canStopCommand=function(){return!0}; Uk.prototype.selectAll=function(){var a=this.diagram;a.M();try{a.currentCursor="wait";a.R("ChangingSelection",a.selection);for(var b=a.parts;b.next();)b.value.isSelected=!0;for(var c=a.nodes;c.next();)c.value.isSelected=!0;for(var d=a.links;d.next();)d.value.isSelected=!0}finally{a.R("ChangedSelection",a.selection),a.currentCursor=""}};Uk.prototype.canSelectAll=function(){return this.diagram.allowSelect}; Uk.prototype.deleteSelection=function(){var a=this.diagram;try{a.currentCursor="wait";a.R("ChangingSelection",a.selection);a.xa("Delete");a.R("SelectionDeleting",a.selection);for(var b=new G,c=a.selection.iterator;c.next();)Vk(b,c.value,!0,this.deletesTree?Infinity:0,this.deletesConnectedLinks?null:!1,function(a){return a.canDelete()});a.gu(b,!0);a.R("SelectionDeleted",b)}finally{a.Wa("Delete"),a.R("ChangedSelection",a.selection),a.currentCursor=""}}; Uk.prototype.canDeleteSelection=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly||!a.allowDelete||0===a.selection.count?!1:!0};Uk.prototype.copySelection=function(){var a=this.diagram,b=new G;for(a=a.selection.iterator;a.next();)Vk(b,a.value,!0,this.copiesTree?Infinity:0,this.copiesConnectedLinks,function(a){return a.canCopy()});this.copyToClipboard(b)};Uk.prototype.canCopySelection=function(){var a=this.diagram;return a.allowCopy&&a.allowClipboard&&0!==a.selection.count?!0:!1}; Uk.prototype.cutSelection=function(){this.copySelection();this.deleteSelection()};Uk.prototype.canCutSelection=function(){var a=this.diagram;return!a.isReadOnly&&!a.isModelReadOnly&&a.allowCopy&&a.allowDelete&&a.allowClipboard&&0!==a.selection.count?!0:!1}; Uk.prototype.copyToClipboard=function(a){var b=this.diagram,c=null;if(null===a)Ei=null,Fi="";else{c=b.model;var d=!1,e=!1,f=null;try{c.Dm()&&(d=c.sk,c.sk=this.copiesParentKey),c.Bk()&&(e=c.rk,c.rk=this.copiesGroupKey),f=b.tk(a,null,!0)}finally{c.Dm()&&(c.sk=d),c.Bk()&&(c.rk=e),c=new E,c.addAll(f),Ei=c,Fi=b.model.dataFormat}}b.R("ClipboardChanged",c)}; Uk.prototype.pasteFromClipboard=function(){var a=new G,b=Ei;if(null===b)return a;var c=this.diagram;if(Fi!==c.model.dataFormat)return a;var d=c.model,e=!1,f=!1,g=null;try{d.Dm()&&(e=d.sk,d.sk=this.copiesParentKey),d.Bk()&&(f=d.rk,d.rk=this.copiesGroupKey),g=c.tk(b,c,!1)}finally{for(d.Dm()&&(d.sk=e),d.Bk()&&(d.rk=f),b=g.iterator;b.next();)c=b.value,d=b.key,c.location.s()||(d.location.s()?c.location=d.location:!c.position.s()&&d.position.s()&&(c.position=d.position)),a.add(c)}return a}; Uk.prototype.pasteSelection=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.currentCursor="wait";b.R("ChangingSelection",b.selection);b.xa("Paste");var c=this.pasteFromClipboard();0<c.count&&b.clearSelection(!0);for(var d=c.iterator;d.next();)d.value.isSelected=!0;if(null!==a){var e=b.computePartsBounds(b.selection);if(e.s()){var f=this.computeEffectiveCollection(b.selection,b.kl);vf(b,f,new I(a.x-e.centerX,a.y-e.centerY),b.kl,!1)}}b.R("ClipboardPasted",c)}finally{b.Wa("Paste"),b.R("ChangedSelection", b.selection),b.currentCursor=""}};Uk.prototype.canPasteSelection=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.allowClipboard||null===Ei||0===Ei.count||Fi!==a.model.dataFormat?!1:!0};Uk.prototype.undo=function(){this.diagram.undoManager.undo()};Uk.prototype.canUndo=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly?!1:a.allowUndo&&a.undoManager.canUndo()};Uk.prototype.redo=function(){this.diagram.undoManager.redo()}; Uk.prototype.canRedo=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly?!1:a.allowUndo&&a.undoManager.canRedo()};Uk.prototype.decreaseZoom=function(a){void 0===a&&(a=1/this.zoomFactor);var b=this.diagram;b.autoScale===Lh&&(a=b.scale*a,a<b.minScale||a>b.maxScale||(b.scale=a))};Uk.prototype.canDecreaseZoom=function(a){void 0===a&&(a=1/this.zoomFactor);var b=this.diagram;if(b.autoScale!==Lh)return!1;a=b.scale*a;return a<b.minScale||a>b.maxScale?!1:b.allowZoom}; Uk.prototype.increaseZoom=function(a){void 0===a&&(a=this.zoomFactor);var b=this.diagram;b.autoScale===Lh&&(a=b.scale*a,a<b.minScale||a>b.maxScale||(b.scale=a))};Uk.prototype.canIncreaseZoom=function(a){void 0===a&&(a=this.zoomFactor);var b=this.diagram;if(b.autoScale!==Lh)return!1;a=b.scale*a;return a<b.minScale||a>b.maxScale?!1:b.allowZoom};Uk.prototype.resetZoom=function(a){void 0===a&&(a=this.defaultScale);var b=this.diagram;a<b.minScale||a>b.maxScale||(b.scale=a)}; Uk.prototype.canResetZoom=function(a){void 0===a&&(a=this.defaultScale);var b=this.diagram;return a<b.minScale||a>b.maxScale?!1:b.allowZoom}; Uk.prototype.zoomToFit=function(){var a=this.diagram,b=a.animationManager;b.Cc();a.Ne();var c=a.position,d=a.scale;th(b,"Zoom To Fit");this.isZoomToFitRestoreEnabled&&d===this.Av&&!isNaN(this.av)&&a.documentBounds.w(this.zv)?(a.scale=this.av,a.position=this.Ax,this.Av=NaN,this.zv=kc):(this.av=d,this.Ax=c.copy(),a.zoomToFit(),this.Av=a.scale,this.zv=a.documentBounds.copy());vh(b)};Uk.prototype.canZoomToFit=function(){return this.diagram.allowZoom}; Uk.prototype.scrollToPart=function(a){void 0===a&&(a=null);var b=this.diagram;b.Ta();if(null===a){try{null!==this.tg&&(this.tg.next()?a=this.tg.value:this.tg=null)}catch(k){this.tg=null}null===a&&(0<b.highlighteds.count?this.tg=b.highlighteds.iterator:0<b.selection.count&&(this.tg=b.selection.iterator),null!==this.tg&&this.tg.next()&&(a=this.tg.value))}if(null!==a){var c=b.animationManager;th(c,"Scroll To Part");var d=this.scrollToPartPause;if(0<d){var e=Wk(this,a,[a]);if(1===e.length)b.xa(),b.At(a.actualBounds), b.Wa("Scroll To Part");else{var f=function(){b.xa();for(var a=e.pop();0<e.length&&a instanceof W&&a.isTreeExpanded&&(!(a instanceof U)||a.isSubGraphExpanded);)a=e.pop();0<e.length?(a instanceof V&&b.Bw(a.actualBounds),a instanceof W&&!a.isTreeExpanded&&(a.isTreeExpanded=!0),a instanceof U&&!a.isSubGraphExpanded&&(a.isSubGraphExpanded=!0)):(a instanceof V&&b.At(a.actualBounds),b.Km("LayoutCompleted",g));b.Wa("Scroll To Part")},g=function(){ta(f,(c.isEnabled?c.duration:0)+d)};b.kk("LayoutCompleted", g);f()}}else{var h=b.position.copy();b.At(a.actualBounds);h.Na(b.position)&&c.Cc()}}}; function Wk(a,b,c){if(b.isVisible())return c;if(b instanceof Qe)Wk(a,b.adornedPart,c);else if(b instanceof S){var d=b.fromNode;null!==d&&Wk(a,d,c);b=b.toNode;null!==b&&Wk(a,b,c)}else b instanceof W&&(d=b.labeledLink,null!==d&&Wk(a,d,c),d=b.Gg(),null!==d&&(d.isTreeExpanded||d.wasTreeExpanded||c.push(d),Wk(a,d,c))),b=b.containingGroup,null!==b&&(b.isSubGraphExpanded||b.wasSubGraphExpanded||c.push(b),Wk(a,b,c));return c} Uk.prototype.canScrollToPart=function(a){void 0===a&&(a=null);if(null!==a&&!(a instanceof V))return!1;a=this.diagram;return 0===a.selection.count&&0===a.highlighteds.count?!1:a.allowHorizontalScroll&&a.allowVerticalScroll}; Uk.prototype.collapseTree=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.xa("Collapse Tree");th(b.animationManager,"Collapse Tree");var c=new E;if(null!==a&&a.isTreeExpanded)a.collapseTree(),c.add(a);else if(null===a)for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof W&&e.isTreeExpanded&&(e.collapseTree(),c.add(e))}b.R("TreeCollapsed",c)}finally{b.Wa("Collapse Tree")}}; Uk.prototype.canCollapseTree=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a){if(!(a instanceof W&&a.isTreeExpanded))return!1;if(0<a.Eq().count)return!0}else for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof W&&b.isTreeExpanded&&0<b.Eq().count)return!0;return!1}; Uk.prototype.expandTree=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.xa("Expand Tree");th(b.animationManager,"Expand Tree");var c=new E;if(null!==a&&!a.isTreeExpanded)a.expandTree(),c.add(a);else if(null===a)for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof W&&!e.isTreeExpanded&&(e.expandTree(),c.add(e))}b.R("TreeExpanded",c)}finally{b.Wa("Expand Tree")}}; Uk.prototype.canExpandTree=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a){if(!(a instanceof W)||a.isTreeExpanded)return!1;if(0<a.Eq().count)return!0}else for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof W&&!b.isTreeExpanded&&0<b.Eq().count)return!0;return!1}; Uk.prototype.groupSelection=function(){var a=this.diagram,b=a.model;if(b.Ck()){var c=this.archetypeGroupData;if(null!==c){var d=null;try{a.currentCursor="wait";a.R("ChangingSelection",a.selection);a.xa("Group");for(var e=new E,f=a.selection.iterator;f.next();){var g=f.value;g.Pc()&&g.canGroup()&&e.add(g)}for(var h=new E,k=e.iterator;k.next();){var l=k.value;f=!1;for(var m=e.iterator;m.next();)if(l.Kd(m.value)){f=!0;break}f||h.add(l)}if(0<h.count){var n=h.first().containingGroup;if(null!==n)for(;null!== n;){e=!1;for(var p=h.iterator;p.next();)if(!p.value.Kd(n)){e=!0;break}if(e)n=n.containingGroup;else break}if(c instanceof U)Ag(c),d=c.copy(),null!==d&&a.add(d);else if(b.ew(c)){var r=b.copyNodeData(c);za(r)&&(b.wf(r),d=a.gj(r))}if(null!==d){null!==n&&this.isValidMember(n,d)&&(d.containingGroup=n);for(var q=h.iterator;q.next();){var u=q.value;this.isValidMember(d,u)&&(u.containingGroup=d)}a.clearSelection(!0);d.isSelected=!0}}a.R("SelectionGrouped",d)}finally{a.Wa("Group"),a.R("ChangedSelection",a.selection), a.currentCursor=""}}}};Uk.prototype.canGroupSelection=function(){var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.allowGroup||!a.model.Ck()||null===this.archetypeGroupData)return!1;for(a=a.selection.iterator;a.next();){var b=a.value;if(b.Pc()&&b.canGroup())return!0}return!1}; function Xk(a){var b=Ea();for(a=a.iterator;a.next();){var c=a.value;c instanceof S||b.push(c)}a=new G;c=b.length;for(var d=0;d<c;d++){for(var e=b[d],f=!0,g=0;g<c;g++)if(e.Kd(b[g])){f=!1;break}f&&a.add(e)}Ia(b);return a} Uk.prototype.isValidMember=function(a,b){if(null===b||a===b||b instanceof S)return!1;if(null!==a){if(a===b||a.Kd(b))return!1;var c=a.memberValidation;if(null!==c&&!c(a,b)||null===a.data&&null!==b.data||null!==a.data&&null===b.data)return!1}c=this.memberValidation;return null!==c?c(a,b):!0}; Uk.prototype.ungroupSelection=function(a){void 0===a&&(a=null);var b=this.diagram,c=b.model;if(c.Ck())try{b.currentCursor="wait";b.R("ChangingSelection",b.selection);b.xa("Ungroup");var d=new E;if(null!==a)d.add(a);else for(var e=b.selection.iterator;e.next();){var f=e.value;f instanceof U&&f.canUngroup()&&d.add(f)}var g=new E;if(0<d.count){b.clearSelection(!0);for(var h=d.iterator;h.next();){var k=h.value;k.expandSubGraph();var l=k.containingGroup,m=null!==l&&null!==l.data?c.ja(l.data):void 0;g.addAll(k.memberParts); for(var n=g.iterator;n.next();){var p=n.value;p.isSelected=!0;if(!(p instanceof S)){var r=p.data;null!==r?c.dr(r,m):p.containingGroup=l}}b.remove(k)}}b.R("SelectionUngrouped",d,g)}finally{b.Wa("Ungroup"),b.R("ChangedSelection",b.selection),b.currentCursor=""}}; Uk.prototype.canUngroupSelection=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly||b.isModelReadOnly||!b.allowDelete||!b.allowUngroup||!b.model.Ck())return!1;if(null!==a){if(!(a instanceof U))return!1;if(a.canUngroup())return!0}else for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof U&&b.canUngroup())return!0;return!1}; Uk.prototype.addTopLevelParts=function(a,b){var c=!0;for(a=Xk(a).iterator;a.next();){var d=a.value;null!==d.containingGroup&&(!b||this.isValidMember(null,d)?d.containingGroup=null:c=!1)}return c}; Uk.prototype.collapseSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.xa("Collapse SubGraph");th(b.animationManager,"Collapse SubGraph");var c=new E;if(null!==a&&a.isSubGraphExpanded)a.collapseSubGraph(),c.add(a);else if(null===a)for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof U&&e.isSubGraphExpanded&&(e.collapseSubGraph(),c.add(e))}b.R("SubGraphCollapsed",c)}finally{b.Wa("Collapse SubGraph")}}; Uk.prototype.canCollapseSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a)return a instanceof U&&a.isSubGraphExpanded?!0:!1;for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof U&&b.isSubGraphExpanded)return!0;return!1}; Uk.prototype.expandSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.xa("Expand SubGraph");th(b.animationManager,"Expand SubGraph");var c=new E;if(null!==a&&!a.isSubGraphExpanded)a.expandSubGraph(),c.add(a);else if(null===a)for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof U&&!e.isSubGraphExpanded&&(e.expandSubGraph(),c.add(e))}b.R("SubGraphExpanded",c)}finally{b.Wa("Expand SubGraph")}}; Uk.prototype.canExpandSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a)return a instanceof U&&!a.isSubGraphExpanded?!0:!1;for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof U&&!b.isSubGraphExpanded)return!0;return!1}; Uk.prototype.editTextBlock=function(a){void 0===a&&(a=null);var b=this.diagram,c=b.toolManager.findTool("TextEditing");if(null!==c){if(null===a){a=null;for(var d=b.selection.iterator;d.next();){var e=d.value;if(e.canEdit()){a=e;break}}if(null===a)return;a=a.xm(function(a){return a instanceof Yg&&a.editable})}null!==a&&(b.currentTool=null,c.textBlock=a,b.currentTool=c)}}; Uk.prototype.canEditTextBlock=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly||b.isModelReadOnly||!b.allowTextEdit||null===b.toolManager.findTool("TextEditing"))return!1;if(null!==a){if(!(a instanceof Yg))return!1;a=a.part;if(null!==a&&a.canEdit())return!0}else for(b=b.selection.iterator;b.next();)if(a=b.value,a.canEdit()&&(a=a.xm(function(a){return a instanceof Yg&&a.editable}),null!==a))return!0;return!1}; Uk.prototype.showContextMenu=function(a){var b=this.diagram,c=b.toolManager.findTool("ContextMenu");if(null!==c&&(void 0===a&&(a=0<b.selection.count?b.selection.first():b),a=c.findObjectWithContextMenu(a),null!==a)){var d=b.lastInput,e=null;a instanceof Y?e=a.da(Bc):b.viewportBounds.$(d.documentPoint)||(e=b.viewportBounds,e=new I(e.x+e.width/2,e.y+e.height/2));null!==e&&(d.viewPoint=b.hr(e),d.documentPoint=e,d.left=!1,d.right=!0,d.up=!0);b.currentTool=c;Ug(c,!1,a)}}; Uk.prototype.canShowContextMenu=function(a){var b=this.diagram,c=b.toolManager.findTool("ContextMenu");if(null===c)return!1;void 0===a&&(a=0<b.selection.count?b.selection.first():b);return null===c.findObjectWithContextMenu(a)?!1:!0}; Uk.prototype.computeEffectiveCollection=function(a,b){var c=this.diagram,d=c.toolManager.findTool("Dragging"),e=c.currentTool===d;void 0===b&&(b=e?d.dragOptions:c.kl);d=new H;if(null===a)return d;for(var f=a.iterator;f.next();)Pj(c,d,f.value,e,b);if(null!==c.draggedLink&&b.dragsLink)return d;for(f=a.iterator;f.next();)a=f.value,a instanceof S&&(b=a.fromNode,null===b||d.contains(b)?(b=a.toNode,null===b||d.contains(b)||d.remove(a)):d.remove(a));return d}; na.Object.defineProperties(Uk.prototype,{diagram:{get:function(){return this.B}},copiesClipboardData:{get:function(){return this.v},set:function(a){this.v=a}},copiesConnectedLinks:{get:function(){return this.I},set:function(a){this.I=a}},deletesConnectedLinks:{get:function(){return this.eb},set:function(a){this.eb=a}},copiesTree:{get:function(){return this.Ka}, set:function(a){this.Ka=a}},deletesTree:{get:function(){return this.Uc},set:function(a){this.Uc=a}},copiesParentKey:{get:function(){return this.Ja},set:function(a){this.Ja=a}},copiesGroupKey:{get:function(){return this.T},set:function(a){this.T=a}},archetypeGroupData:{get:function(){return this.l},set:function(a){this.l=a}},memberValidation:{get:function(){return this.Ji}, set:function(a){this.Ji=a}},defaultScale:{get:function(){return this.diagram.defaultScale},set:function(a){this.diagram.defaultScale=a}},zoomFactor:{get:function(){return this.Od},set:function(a){1<a||B("zoomFactor must be larger than 1.0, not: "+a);this.Od=a}},isZoomToFitRestoreEnabled:{get:function(){return this.Dc},set:function(a){this.Dc=a}},scrollToPartPause:{get:function(){return this.Vc}, set:function(a){this.Vc=a}}});Uk.className="CommandHandler";yi=function(){return new Uk}; function Y(){Za(this);this.F=4225027;this.hb=1;this.qg=null;this.Qa="";this.ec=this.mb=null;this.la=(new I(NaN,NaN)).freeze();this.Zc=Qb;this.hg=Kb;this.gg=Pb;this.qb=new rd;this.Yh=new rd;this.eg=new rd;this.ya=this.ql=1;this.Yb=0;this.Ee=Yk;this.jh=sc;this.qc=(new N(NaN,NaN,NaN,NaN)).freeze();this.yb=(new N(NaN,NaN,NaN,NaN)).freeze();this.rc=(new N(0,0,NaN,NaN)).freeze();this.O=this.rp=this.sp=null;this.$k=this.zb=Zc;this.Ep=0;this.Fp=1;this.Sg=0;this.xn=1;this.Yp=null;this.Lp=-Infinity;this.$l= 0;this.am=Fb;this.bm=cg;this.ni="";this.fb=this.N=null;this.dl=-1;this.dm=this.Ya=this.mi=this.hm=null;this.Qs=Bg;this.Hp=this.Ng=this.ak=null}var vd,Bg,Dg,Yk,Zk,$k,al,bl,cl,dl; Y.prototype.cloneProtected=function(a){a.F=this.F|6144;a.hb=this.hb;a.Qa=this.Qa;a.mb=this.mb;a.ec=this.ec;a.Ng=this.Ng;a.la.assign(this.la);a.Zc=this.Zc.G();a.hg=this.hg.G();a.gg=this.gg.G();a.eg=this.eg.copy();a.ya=this.ya;a.Yb=this.Yb;a.Ee=this.Ee;a.jh=this.jh.G();a.qc.assign(this.qc);a.yb.assign(this.yb);a.rc.assign(this.rc);a.rp=this.rp;null!==this.O&&(a.O=this.O.copy());a.zb=this.zb.G();a.$k=this.$k.G();a.Ep=this.Ep;a.Fp=this.Fp;a.Sg=this.Sg;a.xn=this.xn;a.Yp=this.Yp;a.Lp=this.Lp;a.$l=this.$l; a.am=this.am.G();a.bm=this.bm;a.ni=this.ni;null!==this.N&&(a.N=this.N.copy());a.fb=this.fb;a.dl=this.dl;null!==this.mi&&(a.mi=Ba(this.mi));null!==this.Ya&&(a.Ya=this.Ya.copy());a.dm=this.dm};Y.prototype.Ux=function(a){var b=this.mi;if(Aa(b))for(var c=0;c<b.length;c++){if(b[c]===a)return}else this.mi=b=[];b.push(a)};Y.prototype.Af=function(a){a.sp=null;a.ak=null;a.o()}; Y.prototype.clone=function(){var a=new this.constructor;this.cloneProtected(a);if(null!==this.mi)for(var b=0;b<this.mi.length;b++){var c=this.mi[b];a[c]=this[c]}return a};Y.prototype.copy=function(){return this.clone()};t=Y.prototype;t.jb=function(a){a.classType===S?0===a.name.indexOf("Orient")?this.segmentOrientation=a:B("Unknown Link enum value for GraphObject.segmentOrientation property: "+a):a.classType===Y&&(this.stretch=a)};t.toString=function(){return Ja(this.constructor)+"#"+mb(this)}; function el(a){null===a.N&&(a.N=new fl)}t.Mc=function(){if(null===this.O){var a=new gl;a.bh=uc;a.Bh=uc;a.$g=10;a.zh=10;a.ah=0;a.Ah=0;this.O=a}}; t.bb=function(a,b,c,d,e,f,g){var h=this.part;if(null!==h&&(h.Rk(a,b,c,d,e,f,g),c===this&&a===ze&&hl(this)&&il(this,h,b),f=this.diagram,null===this.Ng||null===f||!f.pj||f.undoManager.isUndoingRedoing||f.currentTool!==f.toolManager||f.animationManager.rn||(a=this.Ng.get(b),null!==a&&f.animationManager.isEnabled&&!f.animationManager.isTicking&&(null===this.Hp&&(this.Hp=new H),g=0===f.undoManager.transactionLevel,a.startCondition===ii?g=!0:a.startCondition===ki&&(g=!1),g?(f=new sh,ji(a,f),g=this.Hp.get(a), null!==g&&g.stop(),this.Hp.add(a,f),f.wv=this,f.Px=a,f.add(this,b,d,e),f.start()):(uh(f.animationManager,"Trigger"),f.animationManager.defaultAnimation.add(this,b,d,e)))),this instanceof X&&c===h&&0!==(h.F&16777216)&&null!==h.data))for(c=this.W.j,d=c.length,e=0;e<d;e++)h=c[e],h instanceof X&&Hj(h,function(a){null!==a.data&&0!==(a.F&16777216)&&a.Ca(b)})}; function il(a,b,c){var d=a.ij();if(null!==d)for(var e=a.fb.iterator;e.next();){var f=e.value,g=null;if(null!==f.sourceName){g=jl(f,d,a);if(null===g)continue;f.kr(a,g,c,null)}else if(f.isToModel){var h=b.diagram;null===h||h.skipsModelSourceBindings||f.kr(a,h.model.modelData,c,d)}else{h=d.data;if(null===h)continue;var k=b.diagram;null===k||k.skipsModelSourceBindings||f.kr(a,h,c,d)}g===a&&(h=d.Ht(f.wj),null!==h&&f.Uw(h,g,c))}}t.Ht=function(a){return this.dl===a?this:null}; t.g=function(a,b,c){this.bb(ze,a,this,b,c)};function kl(a,b,c,d,e){var f=a.qc,g=a.eg;g.reset();ll(a,g,b,c,d,e);a.eg=g;f.h(b,c,d,e);g.Ut()||g.Qw(f)}function ml(a,b,c,d){if(!1===a.pickable)return!1;d.multiply(a.transform);return c?a.Oc(b,d):a.Ih(b,d)} t.sy=function(a,b,c){if(!1===this.pickable)return!1;var d=this.naturalBounds;b=a.Ie(b);return c?zb(a.x,a.y,0,0,0,d.height)<=b||zb(a.x,a.y,0,d.height,d.width,d.height)<=b||zb(a.x,a.y,d.width,d.height,d.width,0)<=b||zb(a.x,a.y,d.width,0,0,0)<=b:a.rd(0,0)<=b&&a.rd(0,d.height)<=b&&a.rd(d.width,0)<=b&&a.rd(d.width,d.height)<=b};t.ie=function(){return!0}; t.$=function(a){var b=I.alloc();b.assign(a);this.transform.sa(b);var c=this.actualBounds;if(!c.s())return I.free(b),!1;var d=this.diagram;if(null!==d&&d.se){var e=d.Bm("extraTouchThreshold"),f=d.Bm("extraTouchArea"),g=f/2,h=this.naturalBounds;d=this.Cf()*d.scale;var k=1/d;if(h.width*d<e&&h.height*d<e)return a=hc(c.x-g*k,c.y-g*k,c.width+f*k,c.height+f*k,b.x,b.y),I.free(b),a}e=!1;if(this instanceof Qe||this instanceof Mf?hc(c.x-5,c.y-5,c.width+10,c.height+10,b.x,b.y):c.$(b))this.Ya&&!this.Ya.$(b)?e= !1:null!==this.ec&&c.$(b)?e=!0:null!==this.mb&&this.rc.$(a)?e=!0:e=this.Jh(a);I.free(b);return e};t.Jh=function(a){var b=this.naturalBounds;return hc(0,0,b.width,b.height,a.x,a.y)};t.He=function(a){if(0===this.angle)return this.actualBounds.He(a);var b=this.naturalBounds;b=N.allocAt(0,0,b.width,b.height);var c=this.transform,d=!1,e=I.allocAt(a.x,a.y);b.$(c.Jd(e))&&(e.h(a.x,a.bottom),b.$(c.Jd(e))&&(e.h(a.right,a.bottom),b.$(c.Jd(e))&&(e.h(a.right,a.y),b.$(c.Jd(e))&&(d=!0))));I.free(e);N.free(b);return d}; t.Ih=function(a,b){if(void 0===b)return a.He(this.actualBounds);var c=this.naturalBounds,d=!1,e=I.allocAt(0,0);a.$(b.sa(e))&&(e.h(0,c.height),a.$(b.sa(e))&&(e.h(c.width,c.height),a.$(b.sa(e))&&(e.h(c.width,0),a.$(b.sa(e))&&(d=!0))));I.free(e);return d}; t.Oc=function(a,b){if(void 0===b&&(b=this.transform,0===this.angle))return a.Oc(this.actualBounds);var c=this.naturalBounds,d=I.allocAt(0,0),e=I.allocAt(0,c.height),f=I.allocAt(c.width,c.height),g=I.allocAt(c.width,0),h=!1;if(a.$(b.sa(d))||a.$(b.sa(e))||a.$(b.sa(f))||a.$(b.sa(g)))h=!0;else{c=N.allocAt(0,0,c.width,c.height);var k=I.allocAt(a.x,a.y);c.$(b.Jd(k))?h=!0:(k.h(a.x,a.bottom),c.$(b.Jd(k))?h=!0:(k.h(a.right,a.bottom),c.$(b.Jd(k))?h=!0:(k.h(a.right,a.y),c.$(b.Jd(k))&&(h=!0))));I.free(k);N.free(c); !h&&(L.Rt(a,d,e)||L.Rt(a,e,f)||L.Rt(a,f,g)||L.Rt(a,g,d))&&(h=!0)}I.free(d);I.free(e);I.free(f);I.free(g);return h};t.da=function(a,b){void 0===b&&(b=new I);if(a instanceof O){var c=this.naturalBounds;b.h(a.x*c.width+a.offsetX,a.y*c.height+a.offsetY)}else b.set(a);this.Fd.sa(b);return b}; t.mj=function(a){void 0===a&&(a=new N);var b=this.naturalBounds,c=this.Fd,d=I.allocAt(0,0).transform(c);a.h(d.x,d.y,0,0);d.h(b.width,0).transform(c);gc(a,d.x,d.y,0,0);d.h(b.width,b.height).transform(c);gc(a,d.x,d.y,0,0);d.h(0,b.height).transform(c);gc(a,d.x,d.y,0,0);I.free(d);return a};t.lj=function(){var a=this.Fd;1===a.m11&&0===a.m12?a=0:(a=180*Math.atan2(a.m12,a.m11)/Math.PI,0>a&&(a+=360));return a}; t.Cf=function(){if(0!==(this.F&4096)===!1)return this.ql;var a=this.ya;return null!==this.panel?a*this.panel.Cf():a};t.Nt=function(a,b){void 0===b&&(b=new I);b.assign(a);this.Fd.Jd(b);return b};t.Ot=function(a,b,c){return this.yk(a.x,a.y,b.x,b.y,c)}; t.yk=function(a,b,c,d,e){var f=this.transform,g=1/(f.m11*f.m22-f.m12*f.m21),h=f.m22*g,k=-f.m12*g,l=-f.m21*g,m=f.m11*g,n=g*(f.m21*f.dy-f.m22*f.dx),p=g*(f.m12*f.dx-f.m11*f.dy);if(null!==this.areaBackground)return f=this.actualBounds,L.Ef(f.left,f.top,f.right,f.bottom,a,b,c,d,e);g=a*h+b*l+n;a=a*k+b*m+p;b=c*h+d*l+n;c=c*k+d*m+p;e.h(0,0);d=this.naturalBounds;c=L.Ef(0,0,d.width,d.height,g,a,b,c,e);e.transform(f);return c}; Y.prototype.measure=function(a,b,c,d){if(!1!==uj(this)){var e=this.jh,f=e.right+e.left;e=e.top+e.bottom;a=Math.max(a-f,0);b=Math.max(b-e,0);c=Math.max((c||0)-f,0);d=Math.max((d||0)-e,0);f=this.angle;e=this.desiredSize;var g=0;this instanceof Mf&&(g=this.strokeWidth);90===f||270===f?(a=isFinite(e.height)?e.height+g:a,b=isFinite(e.width)?e.width+g:b):(a=isFinite(e.width)?e.width+g:a,b=isFinite(e.height)?e.height+g:b);e=c||0;g=d||0;var h=this instanceof X;switch(nl(this,!0)){case Bg:g=e=0;h&&(b=a=Infinity); break;case vd:isFinite(a)&&a>c&&(e=a);isFinite(b)&&b>d&&(g=b);break;case Zk:isFinite(a)&&a>c&&(e=a);g=0;h&&(b=Infinity);break;case $k:isFinite(b)&&b>d&&(g=b),e=0,h&&(a=Infinity)}h=this.maxSize;var k=this.minSize;e>h.width&&k.width<h.width&&(e=h.width);g>h.height&&k.height<h.height&&(g=h.height);c=Math.max(e/this.scale,k.width);d=Math.max(g/this.scale,k.height);h.width<c&&(c=Math.min(k.width,c));h.height<d&&(d=Math.min(k.height,d));a=Math.min(h.width,a);b=Math.min(h.height,b);a=Math.max(c,a);b=Math.max(d, b);if(90===f||270===f)f=a,a=b,b=f,f=c,c=d,d=f;this.qc.ea();this.Gm(a,b,c,d);this.qc.freeze();this.qc.s()||B("Non-real measuredBounds has been set. Object "+this+", measuredBounds: "+this.qc.toString());pj(this,!1)}};Y.prototype.Gm=function(){};Y.prototype.Hf=function(){return!1}; Y.prototype.arrange=function(a,b,c,d,e){this.Gl();var f=N.alloc();f.assign(this.yb);this.yb.ea();!1===vj(this)?this.yb.h(a,b,c,d):this.Hh(a,b,c,d);this.yb.freeze();void 0===e?this.Ya=null:this.Ya=e;c=!1;if(void 0!==e)c=!0;else if(e=this.panel,null===e||e.type!==X.TableRow&&e.type!==X.TableColumn||(e=e.panel),null!==e&&(e=e.rc,d=this.measuredBounds,null!==this.areaBackground&&(d=this.yb),c=b+d.height,d=a+d.width,c=!(0<=a+.05&&d<=e.width+.05&&0<=b+.05&&c<=e.height+.05),this instanceof Yg&&(a=this.naturalBounds, this.vs>a.height||this.ub>a.width)))c=!0;this.F=c?this.F|256:this.F&-257;this.yb.s()||B("Non-real actualBounds has been set. Object "+this+", actualBounds: "+this.yb.toString());this.Hm(f,this.yb);ol(this,!1);N.free(f)};t=Y.prototype;t.Hh=function(){}; function pl(a,b,c,d,e){a.yb.h(b,c,d,e);if(!a.desiredSize.s()){var f=a.qc;c=a.jh;b=c.right+c.left;var g=c.top+c.bottom;c=f.width+b;f=f.height+g;d+=b;e+=g;b=nl(a,!0);c===d&&f===e&&(b=Bg);switch(b){case Bg:if(c>d||f>e)pj(a,!0),a.measure(c>d?d:c,f>e?e:f,0,0);break;case vd:pj(a,!0);a.measure(d,e,0,0);break;case Zk:pj(a,!0);a.measure(d,f,0,0);break;case $k:pj(a,!0),a.measure(c,e,0,0)}}} t.Hm=function(a,b){var c=this.part;null!==c&&null!==c.diagram&&(c.selectionObject!==this&&c.resizeObject!==this&&c.rotateObject!==this||ql(c,!0),this.M(),$b(a,b)||(c.Nh(),this.hp(c)))};t.hp=function(a){null!==this.portId&&(ql(a,!0),a instanceof W&&rl(a,this))}; t.cc=function(a,b){if(this.visible){var c=this instanceof X&&(this.type===X.TableRow||this.type===X.TableColumn),d=this.yb;if(c||0!==d.width&&0!==d.height&&!isNaN(d.x)&&!isNaN(d.y)){var e=this.opacity;if(0!==e){var f=1;1!==e&&(f=a.globalAlpha,a.globalAlpha=f*e);if(!this.ly(a,b))if(c)sl(this,a,b);else{this instanceof S&&this.Fk(!1);c=this.transform;var g=this.panel;0!==(this.F&4096)===!0&&tl(this);var h=this.part,k=!1,l=0;if(h&&b.Ke("drawShadows")&&(k=h.isShadowed)){var m=h.shadowOffset;l=Math.max(m.y, m.x)*b.scale*b.Tb}if(!(m=b.xi||!this.Hf())){var n=this.naturalBounds;m=this.Yh;var p=m.m11,r=m.m21,q=m.dx,u=m.m12,v=m.m22,w=m.dy,y,z=y=0;m=y*p+z*r+q;var A=y*u+z*v+w;y=n.width+l;z=0;var C=y*p+z*r+q;y=y*u+z*v+w;z=Math.min(m,C);var F=Math.min(A,y);var Q=Math.max(m+0,C)-z;var K=Math.max(A+0,y)-F;m=z;A=F;y=n.width+l;z=n.height+l;C=y*p+z*r+q;y=y*u+z*v+w;z=Math.min(m,C);F=Math.min(A,y);Q=Math.max(m+Q,C)-z;K=Math.max(A+K,y)-F;m=z;A=F;y=0;z=n.height+l;C=y*p+z*r+q;y=y*u+z*v+w;z=Math.min(m,C);F=Math.min(A,y); Q=Math.max(m+Q,C)-z;K=Math.max(A+K,y)-F;m=z;A=F;l=b.viewportBounds;n=l.x;p=l.y;m=!(m>l.width+n||n>Q+m||A>l.height+p||p>K+A)}if(m){m=0!==(this.F&256);a.clipInsteadOfFill&&(m=!1);this instanceof Yg&&(a.font=this.font);if(m){A=g.ie()?g.naturalBounds:g.actualBounds;null!==this.Ya?(n=this.Ya,Q=n.x,K=n.y,l=n.width,n=n.height):(Q=Math.max(d.x,A.x),K=Math.max(d.y,A.y),l=Math.min(d.right,A.right)-Q,n=Math.min(d.bottom,A.bottom)-K);if(Q>d.width+d.x||d.x>A.width+A.x){1!==e&&(a.globalAlpha=f);return}a.save(); a.beginPath();a.rect(Q,K,l,n);a.clip()}if(this.Hf()){if(!h.isVisible()){1!==e&&(a.globalAlpha=f);return}k&&(A=h.shadowOffset,a.Jw(A.x*b.scale*b.Tb,A.y*b.scale*b.Tb,h.shadowBlur),ul(a),a.shadowColor=h.shadowColor)}k&&!0===this.shadowVisible?ul(a):k&&!1===this.shadowVisible&&vl(a);h=this.naturalBounds;null!==this.ec&&(oi(this,a,this.ec,!0,!0,h,d),this.ec instanceof wl&&this.ec.type===xl?(a.beginPath(),a.rect(d.x,d.y,d.width,d.height),a.Je(this.ec)):a.fillRect(d.x,d.y,d.width,d.height));a.transform(c.m11, c.m12,c.m21,c.m22,c.dx,c.dy);k&&(null!==g&&0!==(g.F&512)||null!==g&&(g.type===X.Auto||g.type===X.Spot)&&g.rb()!==this)&&null===this.shadowVisible&&vl(a);null!==this.mb&&(l=this.naturalBounds,Q=A=0,K=l.width,l=l.height,n=0,this instanceof Mf&&(l=this.na.bounds,A=l.x,Q=l.y,K=l.width,l=l.height,n=this.strokeWidth),oi(this,a,this.mb,!0,!1,h,d),this.mb instanceof wl&&this.mb.type===xl?(a.beginPath(),a.rect(A-n/2,Q-n/2,K+n,l+n),a.Je(this.mb)):a.fillRect(A-n/2,Q-n/2,K+n,l+n));k&&(null!==this.mb||null!== this.ec||null!==g&&0!==(g.F&512)||null!==g&&(g.type===X.Auto||g.type===X.Spot)&&g.rb()!==this)?(yl(this,!0),null===this.shadowVisible&&vl(a)):yl(this,!1);this.ej(a,b);k&&0!==(this.F&512)===!0&&ul(a);this.Hf()&&k&&vl(a);m?(a.restore(),this instanceof X?a.uc(!0):a.uc(!1)):c.Ut()||(b=1/(c.m11*c.m22-c.m12*c.m21),a.transform(c.m22*b,-c.m12*b,-c.m21*b,c.m11*b,b*(c.m21*c.dy-c.m22*c.dx),b*(c.m12*c.dx-c.m11*c.dy)))}}1!==e&&(a.globalAlpha=f)}}}};t.ly=function(){return!1}; function sl(a,b,c){var d=a.yb,e=a.rc;null!==a.ec&&(oi(a,b,a.ec,!0,!0,e,d),a.ec instanceof wl&&a.ec.type===xl?(b.beginPath(),b.rect(d.x,d.y,d.width,d.height),b.Je(a.ec)):b.fillRect(d.x,d.y,d.width,d.height));null!==a.mb&&(oi(a,b,a.mb,!0,!1,e,d),a.mb instanceof wl&&a.mb.type===xl?(b.beginPath(),b.rect(d.x,d.y,d.width,d.height),b.Je(a.mb)):b.fillRect(d.x,d.y,d.width,d.height));a.ej(b,c)}t.ej=function(){}; function oi(a,b,c,d,e,f,g){if(null!==c){var h=1,k=1;if("string"===typeof c)d?b.fillStyle=c:b.strokeStyle=c;else if(c.type===zl)d?b.fillStyle=c.color:b.strokeStyle=c.color;else{var l=0;a instanceof Mf&&(l=a.strokeWidth);h=f.width;k=f.height;e?(h=g.width,k=g.height):d||(h+=l,k+=l);if((f=b instanceof Al)&&c.le&&(c.type===Bl||c.gl===h&&c.zu===k))var m=c.le;else{var n=0,p=0,r=0,q=0,u=0,v=0;v=u=0;e?(u=g.x,v=g.y):d||(u-=l/2,v-=l/2);n=c.start.x*h+c.start.offsetX;p=c.start.y*k+c.start.offsetY;r=c.end.x*h+ c.end.offsetX;q=c.end.y*k+c.end.offsetY;n+=u;r+=u;p+=v;q+=v;if(c.type===Cl)m=b.createLinearGradient(n,p,r,q);else if(c.type===xl)v=isNaN(c.endRadius)?Math.max(h,k)/2:c.endRadius,isNaN(c.startRadius)?(u=0,v=Math.max(h,k)/2):u=c.startRadius,m=b.createRadialGradient(n,p,u,r,q,v);else if(c.type===Bl)try{m=b.createPattern(c.pattern,"repeat")}catch(y){m=null}if(c.type!==Bl&&(e=c.colorStops,null!==e))for(e=e.iterator;e.next();)m.addColorStop(e.key,e.value);if(f&&(c.le=m,null!==m&&(c.gl=h,c.zu=k),null=== m&&c.type===Bl&&-1!==c.gl)){c.gl=-1;var w=a.diagram;null!==w&&-1===c.gl&&ta(function(){w.Ne()},600)}}d?b.fillStyle=m:b.strokeStyle=m}}}t.Hg=function(a){if(a instanceof X)a:{if(this!==a&&null!==a)for(var b=this.panel;null!==b;){if(b===a){a=!0;break a}b=b.panel}a=!1}else a=!1;return a};t.If=function(){if(!this.visible)return!1;var a=this.panel;return null!==a?a.If():!0};t.Ig=function(){for(var a=this instanceof X?this:this.panel;null!==a&&a.isEnabled;)a=a.panel;return null===a}; function tl(a){if(0!==(a.F&2048)===!0){var b=a.qb;b.reset();if(!a.yb.s()||!a.qc.s()){Dl(a,!1);return}b.translate(a.yb.x-a.qc.x,a.yb.y-a.qc.y);if(1!==a.scale||0!==a.angle){var c=a.naturalBounds;ll(a,b,c.x,c.y,c.width,c.height)}Dl(a,!1);El(a,!0)}0!==(a.F&4096)===!0&&(b=a.panel,null===b?(a.Yh.set(a.qb),a.ql=a.scale,El(a,!1)):null!==b.Fd&&(c=a.Yh,c.reset(),b.ie()?c.multiply(b.Yh):null!==b.panel&&c.multiply(b.panel.Yh),c.multiply(a.qb),a.ql=a.scale*b.ql,El(a,!1)))} function ll(a,b,c,d,e,f){1!==a.scale&&b.scale(a.scale);if(0!==a.Yb){var g=Bc;a.Hf()&&a.locationSpot.kb()&&(g=a.locationSpot);var h=I.alloc();if(a instanceof V&&a.locationObject!==a)for(c=a.locationObject,d=c.naturalBounds,h.Tk(d.x,d.y,d.width,d.height,g),c.eg.sa(h),h.offset(-c.measuredBounds.x,-c.measuredBounds.y),g=c.panel;null!==g&&g!==a;)g.eg.sa(h),h.offset(-g.measuredBounds.x,-g.measuredBounds.y),g=g.panel;else h.Tk(c,d,e,f,g);b.rotate(a.Yb,h.x,h.y);I.free(h)}} t.o=function(a){if(!uj(this)){void 0===a&&(a=!1);pj(this,!0);ol(this,!0);var b=this.panel;null===b||a||b.o()}};t.Ak=function(){uj(this)||(pj(this,!0),ol(this,!0))};function Fl(a){if(!vj(a)){var b=a.panel;null!==b?b.o():a.Hf()&&(b=a.diagram,null!==b&&(b.wd.add(a),a instanceof W&&a.td(),b.Eb()));ol(a,!0)}}t.Gl=function(){0!==(this.F&2048)===!1&&(Dl(this,!0),El(this,!0))};t.cw=function(){El(this,!0)};t.M=function(){var a=this.part;null!==a&&a.M()}; function nl(a,b){var c=a.stretch,d=a.panel;if(null!==d&&d.type===X.Table)return Gl(a,d.getRowDefinition(a.row),d.getColumnDefinition(a.column),b);if(null!==d&&d.type===X.Auto&&d.rb()===a)return Hl(a,vd,b);if(c===Yk){if(null!==d){if(d.type===X.Spot&&d.rb()===a)return Hl(a,vd,b);c=d.defaultStretch;return c===Yk?Hl(a,Bg,b):Hl(a,c,b)}return Hl(a,Bg,b)}return Hl(a,c,b)} function Gl(a,b,c,d){var e=a.stretch;if(e!==Yk)return Hl(a,e,d);var f=e=null;switch(b.stretch){case $k:f=!0;break;case vd:f=!0}switch(c.stretch){case Zk:e=!0;break;case vd:e=!0}b=a.panel.defaultStretch;null===e&&(e=b===Zk||b===vd);null===f&&(f=b===$k||b===vd);return!0===e&&!0===f?Hl(a,vd,d):!0===e?Hl(a,Zk,d):!0===f?Hl(a,$k,d):Hl(a,Bg,d)} function Hl(a,b,c){if(c)return b;if(b===Bg)return Bg;c=a.desiredSize;if(c.s())return Bg;a=a.angle;if(!isNaN(c.width))if(90!==a&&270!==a){if(b===Zk)return Bg;if(b===vd)return $k}else{if(b===$k)return Bg;if(b===vd)return Zk}if(!isNaN(c.height))if(90!==a&&270!==a){if(b===$k)return Bg;if(b===vd)return Zk}else{if(b===Zk)return Bg;if(b===vd)return $k}return b}function yl(a,b){a.F=b?a.F|512:a.F&-513}function hl(a){return 0!==(a.F&1024)}function Il(a,b){a.F=b?a.F|1024:a.F&-1025} function Dl(a,b){a.F=b?a.F|2048:a.F&-2049}function El(a,b){a.F=b?a.F|4096:a.F&-4097}function uj(a){return 0!==(a.F&8192)}function pj(a,b){a.F=b?a.F|8192:a.F&-8193}function vj(a){return 0!==(a.F&16384)}function ol(a,b){a.F=b?a.F|16384:a.F&-16385}t.sj=function(a){this.qg=a};t.lu=function(){};t.Fw=function(a){this.la.assign(a);Fl(this);return!0};t.er=function(a,b){if(this.la.x!==a||this.la.y!==b)this.la.h(a,b),this.Gl()}; function Jl(a){var b=a.part;if(b instanceof W&&(null!==a.portId||a===b.port)){var c=b.diagram;null===c||c.undoManager.isUndoingRedoing||rl(b,a)}}function Kl(a){var b=a.diagram;null===b||b.undoManager.isUndoingRedoing||(a instanceof X?a instanceof W?a.td():a.Zm(a,function(a){Jl(a)}):Jl(a))}t.bind=function(a){a.qd=this;var b=this.ij();null!==b&&Ll(b)&&B("Cannot add a Binding to a template that has already been copied: "+a);null===this.fb&&(this.fb=new E);this.fb.add(a)}; t.ij=function(){for(var a=this instanceof X?this:this.panel;null!==a;){if(null!==a.ki)return a;a=a.panel}return null};t.Gw=function(a){Bj(this,a)};t.Rw=function(a){a.qd=this;null===this.Ng&&(this.Ng=new H);this.Ng.add(a.propertyName,a)}; function Ml(a,b){for(var c=1;c<arguments.length;++c);c=arguments;var d=null,e=null;if("function"===typeof a)e=a;else if("string"===typeof a){var f=Nl.H(a);"function"===typeof f?(c=Ba(arguments),d=f(c),za(d)||B('GraphObject.make invoked object builder "'+a+'", but it did not return an Object')):e=x.go[a]}null===d&&(void 0!==e&&null!==e&&e.constructor||B("GraphObject.make requires a class function or GoJS class name or name of an object builder, not: "+a),d=new e);e=1;if(d instanceof R&&1<c.length){f= d;var g=c[1];if("string"===typeof g||g instanceof HTMLDivElement)Di(f,g),e++}for(;e<c.length;e++)f=c[e],void 0===f?B("Undefined value at argument "+e+" for object being constructed by GraphObject.make: "+d):Ol(d,f);return d} function Ol(a,b){if("string"===typeof b)if(a instanceof Yg)a.text=b;else if(a instanceof Mf)a.figure=b;else if(a instanceof bk)a.source=b;else if(a instanceof X)b=Pl.H(b),null!==b&&(a.type=b);else if(a instanceof wl){var c=$a(wl,b);null!==c?a.type=c:B("Unknown Brush type as an argument to GraphObject.make: "+b)}else a instanceof td?(b=$a(td,b),null!==b&&(a.type=b)):a instanceof te&&(b=$a(te,b),null!==b&&(a.type=b));else if(b instanceof Y)a instanceof X||B("A GraphObject can only be added to a Panel, not to: "+ a),a.add(b);else if(b instanceof Vj){var d;b.isRow&&"function"===typeof a.getRowDefinition?d=a.getRowDefinition(b.index):b.isRow||"function"!==typeof a.getColumnDefinition||(d=a.getColumnDefinition(b.index));d instanceof Vj?d.Dt(b):B("A RowColumnDefinition can only be added to an object that implements getRowDefinition/getColumnDefinition, not to: "+a)}else if(b instanceof D)"function"===typeof a.jb&&a.jb(b);else if(b instanceof Ql)a.type=b;else if(b instanceof Ni)a instanceof Y?a.bind(b):a instanceof Vj?a.bind(b):B("A Binding can only be applied to a GraphObject or RowColumnDefinition, not to: "+a);else if(b instanceof gi)a instanceof Y?a.Rw(b):B("An AnimationTrigger can only be applied to a GraphObject, not to: "+a);else if(b instanceof se)a instanceof td?a.figures.add(b):B("A PathFigure can only be added to a Geometry, not to: "+a);else if(b instanceof te)a instanceof se?a.segments.add(b):B("A PathSegment can only be added to a PathFigure, not to: "+a);else if(b instanceof Bi)a instanceof R? a.layout=b:a instanceof U?a.layout=b:B("A Layout can only be assigned to a Diagram or a Group, not to: "+a);else if(Array.isArray(b))for(c=0;c<b.length;c++)Ol(a,b[c]);else if("object"===typeof b&&null!==b)if(a instanceof wl){c=new cb;for(var e in b)d=parseFloat(e),isNaN(d)?c[e]=b[e]:a.addColorStop(d,b[e]);Bj(a,c)}else if(a instanceof Vj){void 0!==b.row?(e=b.row,(void 0===e||null===e||Infinity===e||isNaN(e)||0>e)&&B("Must specify non-negative integer row for RowColumnDefinition "+b+", not: "+e),a.isRow= !0,a.index=e):void 0!==b.column&&(e=b.column,(void 0===e||null===e||Infinity===e||isNaN(e)||0>e)&&B("Must specify non-negative integer column for RowColumnDefinition "+b+", not: "+e),a.isRow=!1,a.index=e);e=new cb;for(c in b)"row"!==c&&"column"!==c&&(e[c]=b[c]);Bj(a,e)}else Bj(a,b);else B('Unknown initializer "'+b+'" for object being constructed by GraphObject.make: '+a)}function Rl(a,b){Nl.add(a,b)} function Sl(a,b,c){void 0===c&&(c=null);var d=a[1];if("function"===typeof c?c(d):"string"===typeof d)return a.splice(1,1),d;if(void 0===b)throw Error("no "+("function"===typeof c?"satisfactory":"string")+" argument for GraphObject builder "+a[0]);return b} na.Object.defineProperties(Y.prototype,{shadowVisible:{get:function(){return this.dm},set:function(a){var b=this.dm;b!==a&&(this.dm=a,this.M(),this.g("shadowVisible",b,a))}},enabledChanged:{get:function(){return null!==this.N?this.N.Un:null},set:function(a){el(this);var b=this.N.Un;b!==a&&(this.N.Un=a,this.g("enabledChanged",b,a))}},segmentOrientation:{get:function(){return this.bm},set:function(a){var b=this.bm; b!==a&&(this.bm=a,this.o(),this.g("segmentOrientation",b,a),a===cg&&(this.angle=0))}},segmentIndex:{get:function(){return this.Lp},set:function(a){a=Math.round(a);var b=this.Lp;b!==a&&(this.Lp=a,this.o(),this.g("segmentIndex",b,a))}},segmentFraction:{get:function(){return this.$l},set:function(a){isNaN(a)?a=0:0>a?a=0:1<a&&(a=1);var b=this.$l;b!==a&&(this.$l=a,this.o(),this.g("segmentFraction",b,a))}},segmentOffset:{ get:function(){return this.am},set:function(a){var b=this.am;b.w(a)||(this.am=a=a.G(),this.o(),this.g("segmentOffset",b,a))}},stretch:{get:function(){return this.Ee},set:function(a){var b=this.Ee;b!==a&&(this.Ee=a,this.o(),this.g("stretch",b,a))}},name:{get:function(){return this.Qa},set:function(a){var b=this.Qa;b!==a&&(this.Qa=a,null!==this.part&&(this.part.Xj=null),this.g("name",b,a))}},opacity:{get:function(){return this.hb}, set:function(a){var b=this.hb;b!==a&&((0>a||1<a)&&wa(a,"0 <= value <= 1",Y,"opacity"),this.hb=a,this.g("opacity",b,a),a=this.diagram,b=this.part,null!==a&&null!==b&&a.M(Fj(b,b.actualBounds)))}},visible:{get:function(){return 0!==(this.F&1)},set:function(a){var b=0!==(this.F&1);b!==a&&(this.F^=1,this.g("visible",b,a),b=this.panel,null!==b?b.o():this.Hf()&&this.Pb(a),this.M(),Kl(this))}},pickable:{get:function(){return 0!==(this.F&2)},set:function(a){var b= 0!==(this.F&2);b!==a&&(this.F^=2,this.g("pickable",b,a))}},fromLinkableDuplicates:{get:function(){return 0!==(this.F&4)},set:function(a){var b=0!==(this.F&4);b!==a&&(this.F^=4,this.g("fromLinkableDuplicates",b,a))}},fromLinkableSelfNode:{get:function(){return 0!==(this.F&8)},set:function(a){var b=0!==(this.F&8);b!==a&&(this.F^=8,this.g("fromLinkableSelfNode",b,a))}},toLinkableDuplicates:{get:function(){return 0!== (this.F&16)},set:function(a){var b=0!==(this.F&16);b!==a&&(this.F^=16,this.g("toLinkableDuplicates",b,a))}},toLinkableSelfNode:{get:function(){return 0!==(this.F&32)},set:function(a){var b=0!==(this.F&32);b!==a&&(this.F^=32,this.g("toLinkableSelfNode",b,a))}},isPanelMain:{get:function(){return 0!==(this.F&64)},set:function(a){var b=0!==(this.F&64);b!==a&&(this.F^=64,this.o(),this.g("isPanelMain",b,a))}},isActionable:{ get:function(){return 0!==(this.F&128)},set:function(a){var b=0!==(this.F&128);b!==a&&(this.F^=128,this.g("isActionable",b,a))}},areaBackground:{get:function(){return this.ec},set:function(a){var b=this.ec;b!==a&&(null!==a&&Tl(a,"GraphObject.areaBackground"),a instanceof wl&&a.freeze(),this.ec=a,this.M(),this.g("areaBackground",b,a))}},background:{get:function(){return this.mb},set:function(a){var b=this.mb;b!==a&&(null!==a&&Tl(a,"GraphObject.background"), a instanceof wl&&a.freeze(),this.mb=a,this.M(),this.g("background",b,a))}},part:{get:function(){if(this.Hf())return this;if(null!==this.ak)return this.ak;var a;for(a=this.panel;a;){if(a instanceof V)return this.ak=a;a=a.panel}return null}},svg:{get:function(){return this.cq},set:function(a){this.cq=a}},panel:{get:function(){return this.qg}},layer:{get:function(){var a=this.part; return null!==a?a.layer:null}},diagram:{get:function(){var a=this.part;return null!==a?a.diagram:null}},position:{get:function(){return this.la},set:function(a){var b=a.x,c=a.y,d=this.la,e=d.x,f=d.y;(e===b||isNaN(e)&&isNaN(b))&&(f===c||isNaN(f)&&isNaN(c))?this.lu():(a=a.copy(),this.Fw(a,d)&&this.g("position",d.copy(),a.copy()))}},actualBounds:{get:function(){return this.yb}},scale:{ get:function(){return this.ya},set:function(a){var b=this.ya;b!==a&&(0>=a&&B("GraphObject.scale for "+this+" must be greater than zero, not: "+a),this.ya=a,this.o(),this.g("scale",b,a))}},angle:{get:function(){return this.Yb},set:function(a){var b=this.Yb;b!==a&&(a%=360,0>a&&(a+=360),b!==a&&(this.Yb=a,Kl(this),this.o(),this.g("angle",b,a)))}},desiredSize:{get:function(){return this.Zc},set:function(a){var b=a.width,c=a.height,d=this.Zc,e= d.width,f=d.height;(e===b||isNaN(e)&&isNaN(b))&&(f===c||isNaN(f)&&isNaN(c))||(this.Zc=a=a.G(),this.o(),this instanceof Mf&&this.dc(),this.g("desiredSize",d,a),hl(this)&&(a=this.part,null!==a&&(il(this,a,"width"),il(this,a,"height"))))}},width:{get:function(){return this.Zc.width},set:function(a){var b=this.Zc.width;b===a||isNaN(b)&&isNaN(a)||(b=this.Zc,this.Zc=a=(new M(a,this.Zc.height)).freeze(),this.o(),this instanceof Mf&&this.dc(),this.g("desiredSize",b,a),hl(this)&& (a=this.part,null!==a&&il(this,a,"width")))}},height:{get:function(){return this.Zc.height},set:function(a){var b=this.Zc.height;b===a||isNaN(b)&&isNaN(a)||(b=this.Zc,this.Zc=a=(new M(this.Zc.width,a)).freeze(),this.o(),this instanceof Mf&&this.dc(),this.g("desiredSize",b,a),hl(this)&&(a=this.part,null!==a&&il(this,a,"height")))}},minSize:{get:function(){return this.hg},set:function(a){var b=this.hg;b.w(a)||(a=a.copy(),isNaN(a.width)&&(a.width= 0),isNaN(a.height)&&(a.height=0),a.freeze(),this.hg=a,this.o(),this.g("minSize",b,a))}},maxSize:{get:function(){return this.gg},set:function(a){var b=this.gg;b.w(a)||(a=a.copy(),isNaN(a.width)&&(a.width=Infinity),isNaN(a.height)&&(a.height=Infinity),a.freeze(),this.gg=a,this.o(),this.g("maxSize",b,a))}},measuredBounds:{get:function(){return this.qc}},naturalBounds:{get:function(){return this.rc}},margin:{ get:function(){return this.jh},set:function(a){"number"===typeof a&&(a=new oc(a));var b=this.jh;b.w(a)||(this.jh=a=a.G(),this.o(),this.g("margin",b,a))}},transform:{get:function(){0!==(this.F&2048)===!0&&tl(this);return this.qb}},Fd:{get:function(){0!==(this.F&4096)===!0&&tl(this);return this.Yh}},alignment:{get:function(){return this.zb},set:function(a){var b=this.zb;b.w(a)||(a.nc()&&!a.Nb()&& B("GraphObject.alignment for "+this+" must be a real Spot or Spot.Default, not: "+a),this.zb=a=a.G(),Fl(this),this.g("alignment",b,a))}},column:{get:function(){return this.Sg},set:function(a){a=Math.round(a);var b=this.Sg;b!==a&&(0>a&&wa(a,">= 0",Y,"column"),this.Sg=a,this.o(),this.g("column",b,a))}},columnSpan:{get:function(){return this.xn},set:function(a){a=Math.round(a);var b=this.xn;b!==a&&(1>a&&wa(a,">= 1",Y,"columnSpan"),this.xn=a, this.o(),this.g("columnSpan",b,a))}},row:{get:function(){return this.Ep},set:function(a){a=Math.round(a);var b=this.Ep;b!==a&&(0>a&&wa(a,">= 0",Y,"row"),this.Ep=a,this.o(),this.g("row",b,a))}},rowSpan:{get:function(){return this.Fp},set:function(a){a=Math.round(a);var b=this.Fp;b!==a&&(1>a&&wa(a,">= 1",Y,"rowSpan"),this.Fp=a,this.o(),this.g("rowSpan",b,a))}},spanAllocation:{get:function(){return this.Yp},set:function(a){var b= this.Yp;b!==a&&(this.Yp=a,this.o(),this.g("spanAllocation",b,a))}},alignmentFocus:{get:function(){return this.$k},set:function(a){var b=this.$k;b.w(a)||(this.$k=a=a.G(),this.o(),this.g("alignmentFocus",b,a))}},portId:{get:function(){return this.rp},set:function(a){var b=this.rp;if(b!==a){var c=this.part;null===c||c instanceof W||(B("Cannot set portID on a Link: "+a),c=null);null!==b&&null!==c&&Ul(c,this);this.rp=a;null!==a&&null!==c&&(c.Mh= !0,Vl(c,this));this.g("portId",b,a)}}},toSpot:{get:function(){return null!==this.O?this.O.Bh:uc},set:function(a){this.Mc();var b=this.O.Bh;b.w(a)||(a=a.G(),this.O.Bh=a,this.g("toSpot",b,a),Jl(this))}},toEndSegmentLength:{get:function(){return null!==this.O?this.O.zh:10},set:function(a){this.Mc();var b=this.O.zh;b!==a&&(0>a&&wa(a,">= 0",Y,"toEndSegmentLength"),this.O.zh=a,this.g("toEndSegmentLength",b,a),Jl(this))}},toShortLength:{ get:function(){return null!==this.O?this.O.Ah:0},set:function(a){this.Mc();var b=this.O.Ah;b!==a&&(this.O.Ah=a,this.g("toShortLength",b,a),Jl(this))}},toLinkable:{get:function(){return null!==this.O?this.O.hq:null},set:function(a){this.Mc();var b=this.O.hq;b!==a&&(this.O.hq=a,this.g("toLinkable",b,a))}},toMaxLinks:{get:function(){return null!==this.O?this.O.iq:Infinity},set:function(a){this.Mc();var b=this.O.iq;b!==a&&(0>a&& wa(a,">= 0",Y,"toMaxLinks"),this.O.iq=a,this.g("toMaxLinks",b,a))}},fromSpot:{get:function(){return null!==this.O?this.O.bh:uc},set:function(a){this.Mc();var b=this.O.bh;b.w(a)||(a=a.G(),this.O.bh=a,this.g("fromSpot",b,a),Jl(this))}},fromEndSegmentLength:{get:function(){return null!==this.O?this.O.$g:10},set:function(a){this.Mc();var b=this.O.$g;b!==a&&(0>a&&wa(a,">= 0",Y,"fromEndSegmentLength"),this.O.$g=a,this.g("fromEndSegmentLength", b,a),Jl(this))}},fromShortLength:{get:function(){return null!==this.O?this.O.ah:0},set:function(a){this.Mc();var b=this.O.ah;b!==a&&(this.O.ah=a,this.g("fromShortLength",b,a),Jl(this))}},fromLinkable:{get:function(){return null!==this.O?this.O.ao:null},set:function(a){this.Mc();var b=this.O.ao;b!==a&&(this.O.ao=a,this.g("fromLinkable",b,a))}},fromMaxLinks:{get:function(){return null!==this.O?this.O.bo:Infinity}, set:function(a){this.Mc();var b=this.O.bo;b!==a&&(0>a&&wa(a,">= 0",Y,"fromMaxLinks"),this.O.bo=a,this.g("fromMaxLinks",b,a))}},cursor:{get:function(){return this.ni},set:function(a){var b=this.ni;b!==a&&(this.ni=a,this.g("cursor",b,a))}},click:{get:function(){return null!==this.N?this.N.Rf:null},set:function(a){el(this);var b=this.N.Rf;b!==a&&(this.N.Rf=a,this.g("click",b,a))}},doubleClick:{get:function(){return null!== this.N?this.N.Wf:null},set:function(a){el(this);var b=this.N.Wf;b!==a&&(this.N.Wf=a,this.g("doubleClick",b,a))}},contextClick:{get:function(){return null!==this.N?this.N.Sf:null},set:function(a){el(this);var b=this.N.Sf;b!==a&&(this.N.Sf=a,this.g("contextClick",b,a))}},mouseEnter:{get:function(){return null!==this.N?this.N.jg:null},set:function(a){el(this);var b=this.N.jg;b!==a&&(this.N.jg=a,this.g("mouseEnter",b,a))}},mouseLeave:{ get:function(){return null!==this.N?this.N.mg:null},set:function(a){el(this);var b=this.N.mg;b!==a&&(this.N.mg=a,this.g("mouseLeave",b,a))}},mouseOver:{get:function(){return null!==this.N?this.N.ng:null},set:function(a){el(this);var b=this.N.ng;b!==a&&(this.N.ng=a,this.g("mouseOver",b,a))}},mouseHover:{get:function(){return null!==this.N?this.N.lg:null},set:function(a){el(this);var b=this.N.lg;b!==a&&(this.N.lg=a,this.g("mouseHover", b,a))}},mouseHold:{get:function(){return null!==this.N?this.N.kg:null},set:function(a){el(this);var b=this.N.kg;b!==a&&(this.N.kg=a,this.g("mouseHold",b,a))}},mouseDragEnter:{get:function(){return null!==this.N?this.N.Vo:null},set:function(a){el(this);var b=this.N.Vo;b!==a&&(this.N.Vo=a,this.g("mouseDragEnter",b,a))}},mouseDragLeave:{get:function(){return null!==this.N?this.N.Wo:null},set:function(a){el(this); var b=this.N.Wo;b!==a&&(this.N.Wo=a,this.g("mouseDragLeave",b,a))}},mouseDrop:{get:function(){return null!==this.N?this.N.ig:null},set:function(a){el(this);var b=this.N.ig;b!==a&&(this.N.ig=a,this.g("mouseDrop",b,a))}},actionDown:{get:function(){return null!==this.N?this.N.en:null},set:function(a){el(this);var b=this.N.en;b!==a&&(this.N.en=a,this.g("actionDown",b,a))}},actionMove:{get:function(){return null!== this.N?this.N.fn:null},set:function(a){el(this);var b=this.N.fn;b!==a&&(this.N.fn=a,this.g("actionMove",b,a))}},actionUp:{get:function(){return null!==this.N?this.N.gn:null},set:function(a){el(this);var b=this.N.gn;b!==a&&(this.N.gn=a,this.g("actionUp",b,a))}},actionCancel:{get:function(){return null!==this.N?this.N.dn:null},set:function(a){el(this);var b=this.N.dn;b!==a&&(this.N.dn=a,this.g("actionCancel",b,a))}},toolTip:{ get:function(){return null!==this.N?this.N.xg:null},set:function(a){el(this);var b=this.N.xg;b!==a&&(this.N.xg=a,this.g("toolTip",b,a))}},contextMenu:{get:function(){return null!==this.N?this.N.Tf:null},set:function(a){el(this);var b=this.N.Tf;b!==a&&(this.N.Tf=a,this.g("contextMenu",b,a))}}});Y.prototype.trigger=Y.prototype.Rw;Y.prototype.setProperties=Y.prototype.Gw;Y.prototype.findTemplateBinder=Y.prototype.ij;Y.prototype.bind=Y.prototype.bind; Y.prototype.isEnabledObject=Y.prototype.Ig;Y.prototype.isVisibleObject=Y.prototype.If;Y.prototype.isContainedBy=Y.prototype.Hg;Y.prototype.getNearestIntersectionPoint=Y.prototype.Ot;Y.prototype.getLocalPoint=Y.prototype.Nt;Y.prototype.getDocumentScale=Y.prototype.Cf;Y.prototype.getDocumentAngle=Y.prototype.lj;Y.prototype.getDocumentBounds=Y.prototype.mj;Y.prototype.getDocumentPoint=Y.prototype.da;Y.prototype.intersectsRect=Y.prototype.Oc;Y.prototype.containedInRect=Y.prototype.Ih; Y.prototype.containsRect=Y.prototype.He;Y.prototype.containsPoint=Y.prototype.$;Y.prototype.raiseChanged=Y.prototype.g;Y.prototype.raiseChangedEvent=Y.prototype.bb;Y.prototype.addCopyProperty=Y.prototype.Ux;var Nl=null;Y.className="GraphObject";Nl=new H; Rl("Button",function(){function a(a,b){return null!==a.diagram.Vb(a.documentPoint,function(a){for(;null!==a.panel&&!a.isActionable;)a=a.panel;return a},function(a){return a===b})}var b=Ml(X,X.Auto,{isActionable:!0,enabledChanged:function(a,b){if(a instanceof X){var c=a.ab("ButtonBorder");null!==c&&(c.fill=b?a._buttonFillNormal:a._buttonFillDisabled)}},cursor:"pointer",_buttonFillNormal:"#F5F5F5",_buttonStrokeNormal:"#BDBDBD",_buttonFillOver:"#E0E0E0",_buttonStrokeOver:"#9E9E9E",_buttonFillPressed:"#BDBDBD", _buttonStrokePressed:"#9E9E9E",_buttonFillDisabled:"#E5E5E5"},Ml(Mf,{name:"ButtonBorder",figure:"RoundedRectangle",spot1:new O(0,0,2.76142374915397,2.761423749153969),spot2:new O(1,1,-2.76142374915397,-2.761423749153969),parameter1:2,parameter2:2,fill:"#F5F5F5",stroke:"#BDBDBD"}));b.mouseEnter=function(a,b){if(b.Ig()&&b instanceof X&&(a=b.ab("ButtonBorder"),a instanceof Mf)){var c=b._buttonFillOver;b._buttonFillNormal=a.fill;a.fill=c;c=b._buttonStrokeOver;b._buttonStrokeNormal=a.stroke;a.stroke=c}}; b.mouseLeave=function(a,b){b.Ig()&&b instanceof X&&(a=b.ab("ButtonBorder"),a instanceof Mf&&(a.fill=b._buttonFillNormal,a.stroke=b._buttonStrokeNormal))};b.actionDown=function(a,b){if(b.Ig()&&b instanceof X&&null!==b._buttonFillPressed&&0===a.button){var c=b.ab("ButtonBorder");if(c instanceof Mf){a=a.diagram;var d=a.skipsUndoManager;a.skipsUndoManager=!0;var g=b._buttonFillPressed;b._buttonFillOver=c.fill;c.fill=g;g=b._buttonStrokePressed;b._buttonStrokeOver=c.stroke;c.stroke=g;a.skipsUndoManager= d}}};b.actionUp=function(b,d){if(d.Ig()&&d instanceof X&&null!==d._buttonFillPressed&&0===b.button){var c=d.ab("ButtonBorder");if(c instanceof Mf){var f=b.diagram,g=f.skipsUndoManager;f.skipsUndoManager=!0;a(b,d)?(c.fill=d._buttonFillOver,c.stroke=d._buttonStrokeOver):(c.fill=d._buttonFillNormal,c.stroke=d._buttonStrokeNormal);f.skipsUndoManager=g}}};b.actionCancel=function(b,d){if(d.Ig()&&d instanceof X&&null!==d._buttonFillPressed){var c=d.ab("ButtonBorder");if(c instanceof Mf){var f=b.diagram, g=f.skipsUndoManager;f.skipsUndoManager=!0;a(b,d)?(c.fill=d._buttonFillOver,c.stroke=d._buttonStrokeOver):(c.fill=d._buttonFillNormal,c.stroke=d._buttonStrokeNormal);f.skipsUndoManager=g}}};b.actionMove=function(b,d){if(d.Ig()&&d instanceof X&&null!==d._buttonFillPressed){var c=b.diagram;if(0===c.firstInput.button&&(c.currentTool.standardMouseOver(),a(b,d)&&(b=d.ab("ButtonBorder"),b instanceof Mf))){var f=c.skipsUndoManager;c.skipsUndoManager=!0;var g=d._buttonFillPressed;b.fill!==g&&(b.fill=g);g= d._buttonStrokePressed;b.stroke!==g&&(b.stroke=g);c.skipsUndoManager=f}}};return b}); Rl("TreeExpanderButton",function(){var a=Ml("Button",{_treeExpandedFigure:"MinusLine",_treeCollapsedFigure:"PlusLine"},Ml(Mf,{name:"ButtonIcon",figure:"MinusLine",stroke:"#424242",strokeWidth:2,desiredSize:Nb},(new Ni("figure","isTreeExpanded",function(a,c){c=c.panel;return a?c._treeExpandedFigure:c._treeCollapsedFigure})).Tq()),{visible:!1},(new Ni("visible","isTreeLeaf",function(a){return!a})).Tq());a.click=function(a,c){c=c.part;c instanceof Qe&&(c=c.adornedPart);if(c instanceof W){var b=c.diagram; if(null!==b){b=b.commandHandler;if(c.isTreeExpanded){if(!b.canCollapseTree(c))return}else if(!b.canExpandTree(c))return;a.handled=!0;c.isTreeExpanded?b.collapseTree(c):b.expandTree(c)}}};return a}); Rl("SubGraphExpanderButton",function(){var a=Ml("Button",{_subGraphExpandedFigure:"MinusLine",_subGraphCollapsedFigure:"PlusLine"},Ml(Mf,{name:"ButtonIcon",figure:"MinusLine",stroke:"#424242",strokeWidth:2,desiredSize:Nb},(new Ni("figure","isSubGraphExpanded",function(a,c){c=c.panel;return a?c._subGraphExpandedFigure:c._subGraphCollapsedFigure})).Tq()));a.click=function(a,c){c=c.part;c instanceof Qe&&(c=c.adornedPart);if(c instanceof U){var b=c.diagram;if(null!==b){b=b.commandHandler;if(c.isSubGraphExpanded){if(!b.canCollapseSubGraph(c))return}else if(!b.canExpandSubGraph(c))return; a.handled=!0;c.isSubGraphExpanded?b.collapseSubGraph(c):b.expandSubGraph(c)}}};return a});Rl("ToolTip",function(){return Ml(Qe,X.Auto,{isShadowed:!0,shadowColor:"rgba(0, 0, 0, .4)",shadowOffset:new I(0,3),shadowBlur:5},Ml(Mf,{name:"Border",figure:"RoundedRectangle",parameter1:1,parameter2:1,fill:"#F5F5F5",stroke:"#F0F0F0",spot1:new O(0,0,4,6),spot2:new O(1,1,-4,-4)}))}); Rl("ContextMenu",function(){return Ml(Qe,X.Vertical,{background:"#F5F5F5",isShadowed:!0,shadowColor:"rgba(0, 0, 0, .4)",shadowOffset:new I(0,3),shadowBlur:5},new Ni("background","",function(a){return null!==a.adornedPart&&null!==a.placeholder?null:"#F5F5F5"}))});Rl("ContextMenuButton",function(){var a=Ml("Button");a.stretch=Zk;var b=a.ab("ButtonBorder");b instanceof Mf&&(b.figure="Rectangle",b.strokeWidth=0,b.spot1=new O(0,0,2,3),b.spot2=new O(1,1,-2,-2));return a}); Rl("PanelExpanderButton",function(a){var b=Sl(a,"COLLAPSIBLE"),c=Ml("Button",{_buttonExpandedFigure:"M0 0 M0 6 L4 2 8 6 M8 8",_buttonCollapsedFigure:"M0 0 M0 2 L4 6 8 2 M8 8",_buttonFillNormal:"rgba(0, 0, 0, 0)",_buttonStrokeNormal:null,_buttonFillOver:"rgba(0, 0, 0, .2)",_buttonStrokeOver:null,_buttonFillPressed:"rgba(0, 0, 0, .4)",_buttonStrokePressed:null},Ml(Mf,{name:"ButtonIcon",strokeWidth:2},(new Ni("geometryString","visible",function(a){return a?c._buttonExpandedFigure:c._buttonCollapsedFigure})).Tq(b))); a=c.ab("ButtonBorder");a instanceof Mf&&(a.stroke=null,a.fill="rgba(0, 0, 0, 0)");c.click=function(a,c){var d=c.diagram;if(null!==d&&!d.isReadOnly){var e=c.ij();null===e&&(e=c.part);null!==e&&(c=e.ab(b),null!==c&&(a.handled=!0,d.xa("Collapse/Expand Panel"),c.visible=!c.visible,d.Wa("Collapse/Expand Panel")))}};return c}); Rl("CheckBoxButton",function(a){var b=Sl(a);a=Ml("Button",{desiredSize:new M(14,14)},Ml(Mf,{name:"ButtonIcon",geometryString:"M0 0 M0 8.85 L4.9 13.75 16.2 2.45 M16.2 16.2",strokeWidth:2,stretch:vd,geometryStretch:Dg,visible:!1},""!==b?(new Ni("visible",b)).Jy():[]));a.click=function(a,d){if(d instanceof X){var c=a.diagram;if(!(null===c||c.isReadOnly||""!==b&&c.model.isReadOnly)){a.handled=!0;var f=d.ab("ButtonIcon");c.xa("checkbox");f.visible=!f.visible;"function"===typeof d._doClick&&d._doClick(a, d);c.Wa("checkbox")}}};return a}); Rl("CheckBox",function(a){a=Sl(a);a=Ml("CheckBoxButton",a,{name:"Button",isActionable:!1,margin:new oc(0,1,0,0)});var b=Ml(X,"Horizontal",a,{isActionable:!0,cursor:a.cursor,margin:1,_buttonFillNormal:a._buttonFillNormal,_buttonStrokeNormal:a._buttonStrokeNormal,_buttonFillOver:a._buttonFillOver,_buttonStrokeOver:a._buttonStrokeOver,_buttonFillPressed:a._buttonFillPressed,_buttonStrokePressed:a._buttonStrokePressed,_buttonFillDisabled:a._buttonFillDisabled,mouseEnter:a.mouseEnter,mouseLeave:a.mouseLeave, actionDown:a.actionDown,actionUp:a.actionUp,actionCancel:a.actionCancel,actionMove:a.actionMove,click:a.click,_buttonClick:a.click});a.mouseEnter=null;a.mouseLeave=null;a.actionDown=null;a.actionUp=null;a.actionCancel=null;a.actionMove=null;a.click=null;return b});Y.None=Bg=new D(Y,"None",0);Y.Default=Yk=new D(Y,"Default",0);Y.Vertical=$k=new D(Y,"Vertical",4);Y.Horizontal=Zk=new D(Y,"Horizontal",5);Y.Fill=vd=new D(Y,"Fill",3);Y.Uniform=Dg=new D(Y,"Uniform",1); Y.UniformToFill=al=new D(Y,"UniformToFill",2);Y.FlipVertical=bl=new D(Y,"FlipVertical",1);Y.FlipHorizontal=cl=new D(Y,"FlipHorizontal",2);Y.FlipBoth=dl=new D(Y,"FlipBoth",3);Y.make=Ml;Y.getBuilders=function(){var a=new H,b;for(b in Nl)if(b!==b.toLowerCase()){var c=Nl.H(b);"function"===typeof c&&a.add(b,c)}a.freeze();return a};Y.defineBuilder=Rl;Y.takeBuilderArgument=Sl; function fl(){this.Un=this.Tf=this.xg=this.dn=this.gn=this.fn=this.en=this.ig=this.Wo=this.Vo=this.kg=this.lg=this.ng=this.mg=this.jg=this.Sf=this.Wf=this.Rf=null}fl.prototype.copy=function(){var a=new fl;a.Rf=this.Rf;a.Wf=this.Wf;a.Sf=this.Sf;a.jg=this.jg;a.mg=this.mg;a.ng=this.ng;a.lg=this.lg;a.kg=this.kg;a.Vo=this.Vo;a.Wo=this.Wo;a.ig=this.ig;a.en=this.en;a.fn=this.fn;a.gn=this.gn;a.dn=this.dn;a.xg=this.xg;a.Tf=this.Tf;a.Un=this.Un;return a};fl.className="GraphObjectEventHandlers"; function Wl(){this.Ma=[1,0,0,1,0,0]}Wl.prototype.copy=function(){var a=new Wl;a.Ma[0]=this.Ma[0];a.Ma[1]=this.Ma[1];a.Ma[2]=this.Ma[2];a.Ma[3]=this.Ma[3];a.Ma[4]=this.Ma[4];a.Ma[5]=this.Ma[5];return a};Wl.prototype.translate=function(a,b){this.Ma[4]+=this.Ma[0]*a+this.Ma[2]*b;this.Ma[5]+=this.Ma[1]*a+this.Ma[3]*b};Wl.prototype.scale=function(a,b){this.Ma[0]*=a;this.Ma[1]*=a;this.Ma[2]*=b;this.Ma[3]*=b};Wl.className="STransform"; function Xl(a){this.type=a;this.r2=this.y2=this.x2=this.r1=this.y1=this.x1=0;this.by=[];this.pattern=null}Xl.prototype.addColorStop=function(a,b){this.by.push({offset:a,color:b})};Xl.className="SGradient"; function Ej(a,b){this.ownerDocument=a=void 0===b?x.document:b;this.LA="http://www.w3.org/2000/svg";void 0!==a&&(this.Ga=this.xb("svg",{width:"1px",height:"1px",viewBox:"0 0 1 1"}),this.Ga.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns","http://www.w3.org/2000/svg"),this.Ga.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"));this.Aq=null;this.context=new Yl(this)} Ej.prototype.resize=function(a,b,c,d){return this.width!==a||this.height!==b?(this.style.width=c+"px",this.style.height=d+"px",this.Ga.setAttributeNS(null,"width",c+"px"),this.Ga.setAttributeNS(null,"height",d+"px"),this.Ga.setAttributeNS(null,"viewBox","0 0 "+c+" "+d),this.context.cv.firstElementChild.setAttributeNS(null,"width",c+"px"),this.context.cv.firstElementChild.setAttributeNS(null,"height",d+"px"),!0):!1}; Ej.prototype.xb=function(a,b,c){a=this.ownerDocument.createElementNS(this.LA,a);if(za(b))for(var d in b)a.setAttributeNS("href"===d?"http://www.w3.org/1999/xlink":"",d,b[d]);void 0!==c&&(a.textContent=c);return a};Ej.prototype.getBoundingClientRect=function(){return this.Ga.getBoundingClientRect()};Ej.prototype.focus=function(){this.Ga.focus()};Ej.prototype.ky=function(){this.ownerDocument=null}; na.Object.defineProperties(Ej.prototype,{width:{get:function(){return this.Ga.width.baseVal.value},set:function(a){this.Ga.width=a}},height:{get:function(){return this.Ga.height.baseVal.value},set:function(a){this.Ga.height=a}},style:{get:function(){return this.Ga.style}}});Ej.className="SVGSurface"; function Yl(a){this.Uk=a;this.svg=a.Ga;this.stack=[];this.Ac=[];this.fillStyle="#000000";this.font="10px sans-serif";this.globalAlpha=1;this.lineCap="butt";this.lineDashOffset=0;this.lineJoin="miter";this.lineWidth=1;this.miterLimit=10;this.shadowBlur=0;this.shadowColor="rgba(0, 0, 0, 0)";this.shadowOffsetY=this.shadowOffsetX=0;this.strokeStyle="#000000";this.textAlign="start";this.clipInsteadOfFill=!1;this.lf=this.Up=this.Tp=0;this.Nq=null;this.path=[];this.Uu=!1;this.uh=null;this.vh=0;this.de=new Wl; Zl(this,1,0,0,1,0,0);var b=qb++,c=this.xb("clipPath",{id:"mainClip"+b});c.appendChild(this.xb("rect",{x:0,y:0,width:a.width,height:a.height}));this.cv=c;this.Uk.Ga.appendChild(c);this.Ac[0].setAttributeNS(null,"clip-path","url(#mainClip"+b+")");this.NA={}}t=Yl.prototype; t.reset=function(){this.stack=[];this.Ac=[];this.fillStyle="#000000";this.font="10px sans-serif";this.globalAlpha=1;this.lineCap="butt";this.lineDashOffset=0;this.lineJoin="miter";this.lineWidth=1;this.miterLimit=10;this.shadowBlur=0;this.shadowColor="rgba(0, 0, 0, 0)";this.shadowOffsetY=this.shadowOffsetX=0;this.strokeStyle="#000000";this.textAlign="start";this.clipInsteadOfFill=!1;this.lf=this.Up=this.Tp=0;this.Nq=null;this.path=[];this.de=new Wl;Zl(this,1,0,0,1,0,0);var a=qb++,b=this.xb("clipPath", {id:"mainClip"+a});b.appendChild(this.xb("rect",{x:0,y:0,width:this.Uk.width,height:this.Uk.height}));this.cv=b;this.Uk.Ga.appendChild(b);this.Ac[0].setAttributeNS(null,"clip-path","url(#mainClip"+a+")")}; t.arc=function(a,b,c,d,e,f,g,h){var k=2*Math.PI,l=k-1E-6,m=c*Math.cos(d),n=c*Math.sin(d),p=a+m,r=b+n,q=f?0:1;d=f?d-e:e-d;(1E-6<Math.abs(g-p)||1E-6<Math.abs(h-r))&&this.path.push(["L",p,+r]);0>d&&(d=d%k+k);d>l?(this.path.push(["A",c,c,0,1,q,a-m,b-n]),this.path.push(["A",c,c,0,1,q,p,r])):1E-6<d&&this.path.push(["A",c,c,0,+(d>=Math.PI),q,a+c*Math.cos(e),b+c*Math.sin(e)])};t.beginPath=function(){this.path=[]};t.bezierCurveTo=function(a,b,c,d,e,f){this.path.push(["C",a,b,c,d,e,f])};t.clearRect=function(){}; t.clip=function(){this.addPath("clipPath",this.path,this.de);this.addPath("clipPath",this.path,new Wl)};t.closePath=function(){this.path.push(["z"])};t.createLinearGradient=function(a,b,c,d){var e=new Xl("linear");e.x1=a;e.y1=b;e.x2=c;e.y2=d;return e}; t.createPattern=function(a){var b="";a instanceof HTMLCanvasElement&&(b=a.toDataURL());a instanceof HTMLImageElement&&(b=a.getAttribute("src"));var c=this.NA;if(c[b])return"url(#"+c[b]+")";var d="PATTERN"+qb++,e={x:0,y:0,width:a.width,height:a.height,href:b};a=this.xb("pattern",{width:a.width,height:a.height,id:d,patternUnits:"userSpaceOnUse"});a.appendChild(this.xb(Dk,e));this.svg.appendChild(a);c[b]=d;return"url(#"+d+")"}; t.createRadialGradient=function(a,b,c,d,e,f){var g=new Xl("radial");g.x1=a;g.y1=b;g.r1=c;g.x2=d;g.y2=e;g.r2=f;return g}; t.drawImage=function(a,b,c,d,e,f,g,h,k){var l="";a instanceof HTMLCanvasElement&&(l=a.toDataURL());a instanceof HTMLImageElement&&(l=a.getAttribute("src"));var m=a instanceof HTMLImageElement?a.naturalWidth:a.width,n=a instanceof HTMLImageElement?a.naturalHeight:a.height;void 0===d&&(f=b,g=c,h=d=m,k=e=n);d=d||0;e=e||0;f=f||0;g=g||0;h=h||0;k=k||0;a={x:0,y:0,width:m||d,height:n||e,href:l};L.aa(d,h)&&L.aa(e,k)?-1===l.toLowerCase().indexOf(".svg")&&-1===l.toLowerCase().indexOf("data:image/svg")&&(a.preserveAspectRatio= "xMidYMid slice"):a.preserveAspectRatio="none";l="";h/=d;k/=e;if(0!==f||0!==g)l+=" translate("+f+", "+g+")";if(1!==h||1!==k)l+=" scale("+h+", "+k+")";if(0!==b||0!==c)l+=" translate("+-b+", "+-c+")";if(0!==b||0!==c||d!==m||e!==n)f="CLIP"+qb++,g=this.xb("clipPath",{id:f}),g.appendChild(this.xb("rect",{x:b,y:c,width:d,height:e})),this.svg.appendChild(g),a["clip-path"]="url(#"+f+")";$l(this,Dk,a,this.de,l);this.addElement(Dk,a)};t.fill=function(){this.addPath("fill",this.path,this.de)}; t.Je=function(){this.clipInsteadOfFill?this.clip():this.fill()};t.fillRect=function(a,b,c,d){a=[a,b,c,d];a={x:a[0],y:a[1],width:a[2],height:a[3]};$l(this,"fill",a,this.de);this.addElement("rect",a)};t.fillText=function(a,b,c){a=[a,b,c];b=this.textAlign;"left"===b?b="start":"right"===b?b="end":"center"===b&&(b="middle");b={x:a[1],y:a[2],style:"font: "+this.font,"text-anchor":b};$l(this,"fill",b,this.de);this.addElement("text",b,a[0])};t.lineTo=function(a,b){this.path.push(["L",a,b])}; t.moveTo=function(a,b){this.path.push(["M",a,b])};t.quadraticCurveTo=function(a,b,c,d){this.path.push(["Q",a,b,c,d])};t.rect=function(a,b,c,d){this.path.push(["M",a,b],["L",a+c,b],["L",a+c,b+d],["L",a,b+d],["z"])}; t.restore=function(){this.de=this.stack.pop();this.path=this.stack.pop();var a=this.stack.pop();this.fillStyle=a.fillStyle;this.font=a.font;this.globalAlpha=a.globalAlpha;this.lineCap=a.lineCap;this.lineDashOffset=a.lineDashOffset;this.lineJoin=a.lineJoin;this.lineWidth=a.lineWidth;this.miterLimit=a.miterLimit;this.shadowBlur=a.shadowBlur;this.shadowColor=a.shadowColor;this.shadowOffsetX=a.shadowOffsetX;this.shadowOffsetY=a.shadowOffsetY;this.strokeStyle=a.strokeStyle;this.textAlign=a.textAlign}; t.save=function(){this.stack.push({fillStyle:this.fillStyle,font:this.font,globalAlpha:this.globalAlpha,lineCap:this.lineCap,lineDashOffset:this.lineDashOffset,lineJoin:this.lineJoin,lineWidth:this.lineWidth,miterLimit:this.miterLimit,shadowBlur:this.shadowBlur,shadowColor:this.shadowColor,shadowOffsetX:this.shadowOffsetX,shadowOffsetY:this.shadowOffsetY,strokeStyle:this.strokeStyle,textAlign:this.textAlign});for(var a=[],b=0;b<this.path.length;b++)a.push(this.path[b]);this.stack.push(a);this.stack.push(this.de.copy())}; t.setTransform=function(a,b,c,d,e,f){1===a&&0===b&&0===c&&1===d&&0===e&&0===f||Zl(this,a,b,c,d,e,f)};t.scale=function(a,b){this.de.scale(a,b)};t.translate=function(a,b){this.de.translate(a,b)};t.transform=function(){};t.stroke=function(){this.addPath("stroke",this.path,this.de)};t.vj=function(){this.clipInsteadOfFill||this.stroke()};t.xb=function(a,b,c){return this.Uk.xb(a,b,c)}; t.addElement=function(a,b,c){a=this.xb(a,b,c);0<this.Ac.length?this.Ac[this.Ac.length-1].appendChild(a):this.svg.appendChild(a);return this.Nq=a}; function $l(a,b,c,d,e){1!==a.globalAlpha&&(c.opacity=a.globalAlpha);"fill"===b?(a.fillStyle instanceof Xl?c.fill=am(a,a.fillStyle):/^rgba\(/.test(a.fillStyle)?(a=/^\s*rgba\s*\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\)\s*$/i.exec(a.fillStyle),c.fill="rgb("+a[1]+","+a[2]+","+a[3]+")",c["fill-opacity"]=a[4]):c.fill=a.fillStyle,c.stroke="none"):"stroke"===b&&(c.fill="none",a.strokeStyle instanceof Xl?c.stroke=am(a,a.strokeStyle):/^rgba\(/.test(a.strokeStyle)?(b=/^\s*rgba\s*\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\)\s*$/i.exec(a.strokeStyle), c.stroke="rgb("+b[1]+","+b[2]+","+b[3]+")",c["stroke-opacity"]=b[4]):c.stroke=a.strokeStyle,c["stroke-width"]=a.lineWidth,c["stroke-linecap"]=a.lineCap,c["stroke-linejoin"]=a.lineJoin,c["stroke-miterlimit"]=a.miterLimit);d=d.Ma;d="matrix("+d[0]+", "+d[1]+", "+d[2]+", "+d[3]+", "+d[4]+", "+d[5]+")";void 0!==e&&(d+=e);c.transform=d} function am(a,b){var c="GRAD"+qb++;if("linear"===b.type)var d=a.xb("linearGradient",{x1:b.x1,x2:b.x2,y1:b.y1,y2:b.y2,id:c,gradientUnits:"userSpaceOnUse"});else if("radial"===b.type)d=a.xb("radialGradient",{x1:b.x1,x2:b.x2,y1:b.y1,y2:b.y2,r1:b.r1,r2:b.r2,id:c});else throw Error("invalid gradient");var e=b.by;b=e.length;for(var f=[],g=0;g<b;g++){var h=e[g],k=h.color;h={offset:h.offset,"stop-color":k};/^rgba\(/.test(k)&&(k=/^\s*rgba\s*\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\)\s*$/i.exec(k), h["stop-color"]="rgb("+k[1]+","+k[2]+","+k[3]+")",h["stop-opacity"]=k[4]);f.push(h)}f.sort(function(a,b){return a.offset>b.offset?1:-1});for(e=0;e<b;e++)d.appendChild(a.xb("stop",f[e]));a.svg.appendChild(d);return"url(#"+c+")"} t.addPath=function(a,b,c){for(var d=[],e=0;e<b.length;e++){var f=Ba(b[e]),g=[f.shift()];if("A"===g[0])g.push(f.shift()+","+f.shift(),f.shift(),f.shift()+","+f.shift(),f.shift()+","+f.shift());else for(;f.length;)g.push(f.shift()+","+f.shift());d.push(g.join(" "))}b={d:d.join(" ")};"stroke"===a&&this.Uu&&(b["stroke-dasharray"]=this.uh.toString(),b["stroke-dashoffset"]=this.vh);$l(this,a,b,c);"clipPath"===a?(a="CLIP"+qb++,c=this.xb("clipPath",{id:a}),c.appendChild(this.xb("path",b)),this.svg.appendChild(c), 0<this.Ac.length&&this.Ac[this.Ac.length-1].setAttributeNS(null,"clip-path","url(#"+a+")")):this.addElement("path",b)};function Zl(a,b,c,d,e,f,g){var h=new Wl;h.Ma=[b,c,d,e,f,g];b={};$l(a,"g",b,h);h=a.addElement("g",b);a.Ac.push(h)} t.fr=function(){if(0!==this.shadowOffsetX||0!==this.shadowOffsetY||0!==this.shadowBlur){var a="SHADOW"+qb++,b=this.addElement("filter",{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},null);var c=this.xb("feGaussianBlur",{"in":"SourceAlpha",result:"blur",zB:this.shadowBlur/2});var d=this.xb("feFlood",{"in":"blur",result:"flood","flood-color":this.shadowColor});var e=this.xb("feComposite",{"in":"flood",in2:"blur",operator:"in",result:"comp"});var f=this.xb("feOffset",{"in":"comp",result:"offsetBlur", dx:this.shadowOffsetX,dy:this.shadowOffsetY});var g=this.xb("feMerge",{});g.appendChild(this.xb("feMergeNode",{"in":"offsetBlur"}));g.appendChild(this.xb("feMergeNode",{"in":"SourceGraphic"}));b.appendChild(c);b.appendChild(d);b.appendChild(e);b.appendChild(f);b.appendChild(g);0<this.Ac.length&&this.Ac[this.Ac.length-1].setAttributeNS(null,"filter","url(#"+a+")")}};t.Jw=function(a,b,c){this.Tp=a;this.Up=b;this.lf=c};function vl(a){a.shadowOffsetX=0;a.shadowOffsetY=0;a.shadowBlur=0} function ul(a){a.shadowOffsetX=a.Tp;a.shadowOffsetY=a.Up;a.shadowBlur=a.lf}t.Gt=function(a,b){this.Uu=!0;this.uh=a;this.vh=b};t.Et=function(){this.Uu=!1};t.uc=function(){};t.Ty=function(){};Yl.prototype.rotate=function(){};Yl.prototype.getImageData=function(){return null};Yl.prototype.measureText=function(){return null};Yl.className="SVGContext"; R.prototype.$t=function(a){var b=new Ej(this,x.document);void 0===a&&(a=new cb);var c=this;return Bk(this,function(a,e){a=Ck(c,a,"SVG",b);a=null!==a?a.svg:null;return"function"===typeof e?(e(a),null):a},a)};R.prototype.makeSvg=R.prototype.$t;R.prototype.hw=function(a){return this.$t(a)};R.prototype.makeSVG=R.prototype.hw; Y.prototype.ly=function(a,b){if(!(a instanceof Yl))return!1;if(!this.visible)return!0;var c=null,d=a.Nq;if(this instanceof X&&(this.type===X.TableRow||this.type===X.TableColumn))return sl(this,a,b),!0;var e=this.yb;if(0===e.width||0===e.height||isNaN(e.x)||isNaN(e.y))return!0;var f=this.transform,g=this.panel;0!==(this.F&4096)===!0&&tl(this);var h=0!==(this.F&256),k=!1;this instanceof Yg&&(a.font=this.font);if(h){k=g.ie()?g.naturalBounds:g.actualBounds;if(null!==this.Ya){var l=this.Ya;var m=l.x;var n= l.y;var p=l.width;l=l.height}else m=Math.max(e.x,k.x),n=Math.max(e.y,k.y),p=Math.min(e.right,k.right)-m,l=Math.min(e.bottom,k.bottom)-n;if(m>e.width+e.x||e.x>k.width+k.x||n>e.height+e.y||e.y>k.height+k.y)return!0;k=!0;Zl(a,1,0,0,1,0,0);a.save();a.beginPath();a.rect(m,n,p,l);a.clip()}if(this.Hf()&&!this.isVisible())return!0;a.de.Ma=[1,0,0,1,0,0];(this instanceof Yg&&1<this.lineCount||this instanceof Mf&&1<this.geometry.figures.length)&&Zl(a,1,0,0,1,0,0);m=!1;this.Hf()&&this.isShadowed&&b.Ke("drawShadows")&& (n=this.shadowOffset,a.Jw(n.x*b.scale*b.Tb,n.y*b.scale*b.Tb,this.shadowBlur),ul(a),a.shadowColor=this.shadowColor);n=!1;this.part&&b.Ke("drawShadows")&&(n=this.part.isShadowed);!0===this.shadowVisible?(ul(a),!1===m&&n&&(Zl(a,1,0,0,1,0,0),a.fr(),m=!0)):!1===this.shadowVisible&&vl(a);p=this.naturalBounds;null!==this.areaBackground&&(oi(this,a,this.areaBackground,!0,!0,p,e),!1===m&&n&&(Zl(a,1,0,0,1,0,0),a.fr(),m=!0),this.areaBackground instanceof wl&&this.areaBackground.type===xl?(a.beginPath(),a.rect(e.x, e.y,e.width,e.height),a.Je(this.areaBackground)):a.fillRect(e.x,e.y,e.width,e.height));this instanceof X?Zl(a,f.m11,f.m12,f.m21,f.m22,f.dx,f.dy):a.de.Ma=[f.m11,f.m12,f.m21,f.m22,f.dx,f.dy];if(null!==this.background){!1===m&&n&&(Zl(a,1,0,0,1,0,0),a.fr(),m=!0);var r=this.naturalBounds;l=f=0;var q=r.width;r=r.height;var u=0;this instanceof Mf&&(r=this.geometry.bounds,f=r.x,l=r.y,q=r.width,r=r.height,u=this.strokeWidth);oi(this,a,this.background,!0,!1,p,e);this.background instanceof wl&&this.background.type=== xl?(a.beginPath(),a.rect(f-u/2,l-u/2,q+u,r+u),a.Je(this.background)):a.fillRect(f-u/2,l-u/2,q+u,r+u)}n&&(null!==this.background||null!==this.areaBackground||null!==g&&0!==(g.F&512)||null!==g&&(g.type===X.Auto||g.type===X.Spot)&&g.rb()!==this)?(yl(this,!0),null===this.shadowVisible&&vl(a)):yl(this,!1);this.ej(a,b);n&&0!==(this.F&512)===!0&&ul(a);this.Hf()&&n&&vl(a);h&&(a.restore(),k&&a.Ac.pop());this instanceof X&&(c=a.Ac.pop());!0===m&&a.Ac.pop();if(this instanceof Yg&&1<this.lineCount||this instanceof Mf&&1<this.geometry.figures.length)c=a.Ac.pop();null!==a.Uk.Aq&&(null===c&&(d===a.Nq?(Zl(a,1,0,0,1,0,0),c=a.Ac.pop()):c=a.Nq),a.Uk.Aq(this,c));this.svg=c;return!0};function Ek(a,b){this.ownerDocument=b=void 0===b?x.document:b;this.Aq=null;b=b.createElement("canvas");b.tabIndex=0;this.Ga=b;this.Ga.innerHTML="This text is displayed if your browser does not support the Canvas HTML element.";this.context=new Al(b);b.B=a} Ek.prototype.resize=function(a,b,c,d){return this.width!==a||this.height!==b?(this.width=a,this.height=b,this.style.width=c+"px",this.style.height=d+"px",!0):!1};Ek.prototype.toDataURL=function(a,b){return this.Ga.toDataURL(a,b)};Ek.prototype.getBoundingClientRect=function(){return this.Ga.getBoundingClientRect()};Ek.prototype.focus=function(){this.Ga.focus()};Ek.prototype.ky=function(){this.ownerDocument=this.Ga.B=null}; na.Object.defineProperties(Ek.prototype,{width:{get:function(){return this.Ga.width},set:function(a){this.Ga.width=a}},height:{get:function(){return this.Ga.height},set:function(a){this.Ga.height=a}},style:{get:function(){return this.Ga.style}}});Ek.className="CanvasSurface"; function Al(a){a.getContext&&a.getContext("2d")||B("Browser does not support HTML Canvas Element");this.Y=a.getContext("2d");this.wu=this.yu=this.xu="";this.wn=!1;this.lf=this.Up=this.Tp=0}t=Al.prototype;t.Ty=function(a){this.Y.imageSmoothingEnabled=a};t.arc=function(a,b,c,d,e,f){this.Y.arc(a,b,c,d,e,f)};t.beginPath=function(){this.Y.beginPath()};t.bezierCurveTo=function(a,b,c,d,e,f){this.Y.bezierCurveTo(a,b,c,d,e,f)};t.clearRect=function(a,b,c,d){this.Y.clearRect(a,b,c,d)};t.clip=function(){this.Y.clip()}; t.closePath=function(){this.Y.closePath()};t.createLinearGradient=function(a,b,c,d){return this.Y.createLinearGradient(a,b,c,d)};t.createPattern=function(a,b){return this.Y.createPattern(a,b)};t.createRadialGradient=function(a,b,c,d,e,f){return this.Y.createRadialGradient(a,b,c,d,e,f)};t.drawImage=function(a,b,c,d,e,f,g,h,k){void 0===d?this.Y.drawImage(a,b,c):this.Y.drawImage(a,b,c,d,e,f,g,h,k)};t.fill=function(){this.Y.fill()};t.fillRect=function(a,b,c,d){this.Y.fillRect(a,b,c,d)}; t.fillText=function(a,b,c){this.Y.fillText(a,b,c)};t.getImageData=function(a,b,c,d){return this.Y.getImageData(a,b,c,d)};t.lineTo=function(a,b){this.Y.lineTo(a,b)};t.measureText=function(a){return this.Y.measureText(a)};t.moveTo=function(a,b){this.Y.moveTo(a,b)};t.quadraticCurveTo=function(a,b,c,d){this.Y.quadraticCurveTo(a,b,c,d)};t.rect=function(a,b,c,d){this.Y.rect(a,b,c,d)};t.restore=function(){this.Y.restore()};Al.prototype.rotate=function(a){this.Y.rotate(a)};t=Al.prototype;t.save=function(){this.Y.save()}; t.setTransform=function(a,b,c,d,e,f){this.Y.setTransform(a,b,c,d,e,f)};t.scale=function(a,b){this.Y.scale(a,b)};t.stroke=function(){this.Y.stroke()};t.transform=function(a,b,c,d,e,f){1===a&&0===b&&0===c&&1===d&&0===e&&0===f||this.Y.transform(a,b,c,d,e,f)};t.translate=function(a,b){this.Y.translate(a,b)}; t.Je=function(a){if(a instanceof wl&&a.type===xl){var b=a.gl;a=a.zu;a>b?(this.scale(b/a,1),this.translate((a-b)/2,0)):b>a&&(this.scale(1,a/b),this.translate(0,(b-a)/2));this.wn?this.clip():this.fill();a>b?(this.translate(-(a-b)/2,0),this.scale(1/(b/a),1)):b>a&&(this.translate(0,-(b-a)/2),this.scale(1,1/(a/b)))}else this.wn?this.clip():this.fill()};t.vj=function(){this.wn||this.stroke()};t.Jw=function(a,b,c){this.Tp=a;this.Up=b;this.lf=c}; t.Gt=function(a,b){var c=this.Y;void 0!==c.setLineDash&&(c.setLineDash(a),c.lineDashOffset=b)};t.Et=function(){var a=this.Y;void 0!==a.setLineDash&&(a.setLineDash(bm),a.lineDashOffset=0)};t.uc=function(a){a&&(this.xu="");this.wu=this.yu=""}; na.Object.defineProperties(Al.prototype,{fillStyle:{get:function(){return this.Y.fillStyle},set:function(a){this.wu!==a&&(this.wu=this.Y.fillStyle=a)}},font:{get:function(){return this.Y.font},set:function(a){this.xu!==a&&(this.xu=this.Y.font=a)}},globalAlpha:{get:function(){return this.Y.globalAlpha},set:function(a){this.Y.globalAlpha=a}},lineCap:{get:function(){return this.Y.lineCap}, set:function(a){this.Y.lineCap=a}},lineDashOffset:{get:function(){return this.Y.lineDashOffset},set:function(a){this.Y.lineDashOffset=a}},lineJoin:{get:function(){return this.Y.lineJoin},set:function(a){this.Y.lineJoin=a}},lineWidth:{get:function(){return this.Y.lineWidth},set:function(a){this.Y.lineWidth=a}},miterLimit:{get:function(){return this.Y.miterLimit},set:function(a){this.Y.miterLimit= a}},shadowBlur:{get:function(){return this.Y.shadowBlur},set:function(a){this.Y.shadowBlur=a}},shadowColor:{get:function(){return this.Y.shadowColor},set:function(a){this.Y.shadowColor=a}},shadowOffsetX:{get:function(){return this.Y.shadowOffsetX},set:function(a){this.Y.shadowOffsetX=a}},shadowOffsetY:{get:function(){return this.Y.shadowOffsetY},set:function(a){this.Y.shadowOffsetY= a}},strokeStyle:{get:function(){return this.Y.strokeStyle},set:function(a){this.yu!==a&&(this.yu=this.Y.strokeStyle=a)}},textAlign:{get:function(){return this.Y.textAlign},set:function(a){this.Y.textAlign=a}},imageSmoothingEnabled:{get:function(){return this.Y.imageSmoothingEnabled},set:function(a){this.Y.imageSmoothingEnabled=a}},clipInsteadOfFill:{get:function(){return this.wn}, set:function(a){this.wn=a}}});var bm=Object.freeze([]);Al.className="CanvasSurfaceContext";function cm(){this.T=this.v=this.I=this.l=0}cm.className="ColorNumbers";function wl(a){dm||(em(),dm=!0);Za(this);this.u=!1;void 0===a?(this.pa=zl,this.fl="black"):"string"===typeof a?(this.pa=zl,this.fl=a):(this.pa=a,this.fl="black");a=this.pa;a===Cl?(this.Dd=yc,this.sl=Fc):this.sl=a===xl?this.Dd=Bc:this.Dd=uc;this.jt=0;this.Wr=NaN;this.le=this.Ls=this.ke=null;this.zu=this.gl=0} wl.prototype.copy=function(){var a=new wl;a.pa=this.pa;a.fl=this.fl;a.Dd=this.Dd.G();a.sl=this.sl.G();a.jt=this.jt;a.Wr=this.Wr;null!==this.ke&&(a.ke=this.ke.copy());a.Ls=this.Ls;return a};t=wl.prototype;t.freeze=function(){this.u=!0;null!==this.ke&&this.ke.freeze();return this};t.ea=function(){Object.isFrozen(this)&&B("cannot thaw constant: "+this);this.u=!1;null!==this.ke&&this.ke.ea();return this};t.jb=function(a){a.classType===wl&&(this.type=a)}; t.toString=function(){var a="Brush(";if(this.type===zl)a+=this.color;else if(a=this.type===Cl?a+"Linear ":this.type===xl?a+"Radial ":this.type===Bl?a+"Pattern ":a+"(unknown) ",a+=this.start+" "+this.end,null!==this.colorStops)for(var b=this.colorStops.iterator;b.next();)a+=" "+b.key+":"+b.value;return a+")"}; t.addColorStop=function(a,b){this.u&&va(this);("number"!==typeof a||!isFinite(a)||1<a||0>a)&&wa(a,"0 <= loc <= 1",wl,"addColorStop:loc");null===this.ke&&(this.ke=new H);this.ke.add(a,b);this.pa===zl&&(this.type=Cl);this.le=null;return this}; t.FA=function(a,b){this.u&&va(this);a=void 0===a||"number"!==typeof a?.2:a;b=void 0===b?fm:b;if(this.type===zl)bi(this.color),this.color=gm(a,b);else if((this.type===Cl||this.type===xl)&&null!==this.colorStops)for(var c=this.colorStops.iterator;c.next();)bi(c.value),this.addColorStop(c.key,gm(a,b));return this};function hm(a,b,c){b=void 0===b||"number"!==typeof b?.2:b;c=void 0===c?fm:c;bi(a);return gm(b,c)} t.Iz=function(a,b){this.u&&va(this);a=void 0===a||"number"!==typeof a?.2:a;b=void 0===b?fm:b;if(this.type===zl)bi(this.color),this.color=gm(-a,b);else if((this.type===Cl||this.type===xl)&&null!==this.colorStops)for(var c=this.colorStops.iterator;c.next();)bi(c.value),this.addColorStop(c.key,gm(-a,b));return this};function im(a,b,c){b=void 0===b||"number"!==typeof b?.2:b;c=void 0===c?fm:c;bi(a);return gm(-b,c)} function jm(a,b,c){bi(a);a=km.l;var d=km.I,e=km.v,f=km.T;bi(b);void 0===c&&(c=.5);return"rgba("+Math.round((km.l-a)*c+a)+", "+Math.round((km.I-d)*c+d)+", "+Math.round((km.v-e)*c+e)+", "+Math.round((km.T-f)*c+f)+")"} t.Gy=function(){if(this.type===zl)return lm(this.color);if((this.type===Cl||this.type===xl)&&null!==this.colorStops){var a=this.colorStops;if(this.type===xl)return lm(a.first().value);if(null!==a.get(.5))return lm(a.get(.5));if(2===a.count)return a=a.ma(),lm(jm(a[0].value,a[1].value));for(var b=a.iterator,c=-1,d=-1,e=1,f=1;b.next();){var g=b.key,h=Math.abs(.5-b.key);e>f&&h<e?(c=g,e=h):f>=e&&h<f&&(d=g,f=h)}c>d&&(f=c,c=d,d=f,f=e);e=d-c;return lm(jm(a.get(c),a.get(d),1-f/e))}return!1}; function lm(a){if(!a)return!1;if(a instanceof wl)return a.Gy();bi(a);return 128>(299*km.l+587*km.I+114*km.v)/1E3} function gm(a,b){switch(b){case fm:b=100*mm(km.l);var c=100*mm(km.I),d=100*mm(km.v);nm.l=.4124564*b+.3575761*c+.1804375*d;nm.I=.2126729*b+.7151522*c+.072175*d;nm.v=.0193339*b+.119192*c+.9503041*d;nm.T=km.T;b=om(nm.l/pm[0]);c=om(nm.I/pm[1]);d=om(nm.v/pm[2]);qm.l=116*c-16;qm.I=500*(b-c);qm.v=200*(c-d);qm.T=nm.T;qm.l=Math.min(100,Math.max(0,qm.l+100*a));a=(qm.l+16)/116;b=a-qm.v/200;nm.l=pm[0]*rm(qm.I/500+a);nm.I=pm[1]*(qm.l>sm*tm?Math.pow(a,3):qm.l/sm);nm.v=pm[2]*rm(b);nm.T=qm.T;a=-.969266*nm.l+1.8760108* nm.I+.041556*nm.v;b=.0556434*nm.l+-.2040259*nm.I+1.0572252*nm.v;km.l=255*um((3.2404542*nm.l+-1.5371385*nm.I+-.4985314*nm.v)/100);km.I=255*um(a/100);km.v=255*um(b/100);km.T=nm.T;km.l=Math.round(km.l);255<km.l?km.l=255:0>km.l&&(km.l=0);km.I=Math.round(km.I);255<km.I?km.I=255:0>km.I&&(km.I=0);km.v=Math.round(km.v);255<km.v?km.v=255:0>km.v&&(km.v=0);return"rgba("+km.l+", "+km.I+", "+km.v+", "+km.T+")";case vm:return ci(),di.v=Math.min(100,Math.max(0,di.v+100*a)),"hsla("+di.l+", "+di.I+"%, "+di.v+"%, "+ di.T+")";default:return B("Unknown color space: "+b),"rgba(0, 0, 0, 1)"}}function bi(a){dm||(em(),dm=!0);var b=wm;if(null!==b){b.clearRect(0,0,1,1);b.fillStyle="#000000";var c=b.fillStyle;b.fillStyle=a;b.fillStyle!==c?(b.fillRect(0,0,1,1),a=b.getImageData(0,0,1,1).data,km.l=a[0],km.I=a[1],km.v=a[2],km.T=a[3]/255):(b.fillStyle="#FFFFFF",b.fillStyle=a,km.l=0,km.I=0,km.v=0,km.T=1)}} function ci(){var a=km.l/255,b=km.I/255,c=km.v/255,d=Math.max(a,b,c),e=Math.min(a,b,c),f=d-e;e=(d+e)/2;if(0===f)var g=a=0;else{switch(d){case a:g=(b-c)/f%6;break;case b:g=(c-a)/f+2;break;case c:g=(a-b)/f+4}g*=60;0>g&&(g+=360);a=f/(1-Math.abs(2*e-1))}di.l=Math.round(g);di.I=Math.round(100*a);di.v=Math.round(100*e);di.T=km.T}function mm(a){a/=255;return.04045>=a?a/12.92:Math.pow((a+.055)/1.055,2.4)}function um(a){return.0031308>=a?12.92*a:1.055*Math.pow(a,1/2.4)-.055} function om(a){return a>tm?Math.pow(a,1/3):(sm*a+16)/116}function rm(a){var b=a*a*a;return b>tm?b:(116*a-16)/sm}function Tl(a,b){"string"!==typeof a&&(a instanceof wl||B("Value for "+b+" must be a color string or a Brush, not "+a))}function em(){wm=Wg?(new Ek(null)).context:null} na.Object.defineProperties(wl.prototype,{type:{get:function(){return this.pa},set:function(a){this.u&&va(this,a);this.pa=a;this.start.nc()&&(a===Cl?this.start=yc:a===xl&&(this.start=Bc));this.end.nc()&&(a===Cl?this.end=Fc:a===xl&&(this.end=Bc));this.le=null}},color:{get:function(){return this.fl},set:function(a){this.u&&va(this,a);this.fl=a;this.le=null}},start:{get:function(){return this.Dd},set:function(a){this.u&& va(this,a);this.Dd=a.G();this.le=null}},end:{get:function(){return this.sl},set:function(a){this.u&&va(this,a);this.sl=a.G();this.le=null}},startRadius:{get:function(){return this.jt},set:function(a){this.u&&va(this,a);0>a&&wa(a,">= zero",wl,"startRadius");this.jt=a;this.le=null}},endRadius:{get:function(){return this.Wr},set:function(a){this.u&&va(this,a);0>a&&wa(a,">= zero",wl,"endRadius");this.Wr=a;this.le= null}},colorStops:{get:function(){return this.ke},set:function(a){this.u&&va(this,a);this.ke=a;this.le=null}},pattern:{get:function(){return this.Ls},set:function(a){this.u&&va(this,a);this.Ls=a;this.le=null}}});wl.prototype.isDark=wl.prototype.Gy;wl.prototype.darkenBy=wl.prototype.Iz;wl.prototype.lightenBy=wl.prototype.FA;wl.prototype.addColorStop=wl.prototype.addColorStop; var tm=216/24389,sm=24389/27,pm=[95.047,100,108.883],wm=null,km=new cm,di=new cm,nm=new cm,qm=new cm,dm=!1;wl.className="Brush";var zl;wl.Solid=zl=new D(wl,"Solid",0);var Cl;wl.Linear=Cl=new D(wl,"Linear",1);var xl;wl.Radial=xl=new D(wl,"Radial",2);var Bl;wl.Pattern=Bl=new D(wl,"Pattern",4);var fm;wl.Lab=fm=new D(wl,"Lab",5);var vm;wl.HSL=vm=new D(wl,"HSL",6); wl.randomColor=function(a,b){void 0===a&&(a=128);void 0===b&&(b=Math.max(a,255));var c=Math.abs(b-a);b=Math.floor(a+Math.random()*c).toString(16);var d=Math.floor(a+Math.random()*c).toString(16);a=Math.floor(a+Math.random()*c).toString(16);2>b.length&&(b="0"+b);2>d.length&&(d="0"+d);2>a.length&&(a="0"+a);return"#"+b+d+a}; wl.isValidColor=function(a){if("black"===a)return!0;if(""===a)return!1;dm||(em(),dm=!0);var b=wm;if(null===b)return!0;b.fillStyle="#000000";var c=b.fillStyle;b.fillStyle=a;if(b.fillStyle!==c)return!0;b.fillStyle="#FFFFFF";c=b.fillStyle;b.fillStyle=a;return b.fillStyle!==c};wl.lighten=function(a){return hm(a)};wl.lightenBy=hm;wl.darken=function(a){return im(a)};wl.darkenBy=im;wl.mix=jm;wl.isDark=lm;function Ql(){this.name="Base"}Ql.prototype.measure=function(){}; Ql.prototype.IA=function(a,b,c,d,e){a.measure(b,c,d,e)};Ql.prototype.arrange=function(){};Ql.prototype.wz=function(a,b,c,d,e,f){a.arrange(b,c,d,e,f)};Ql.prototype.RA=function(a){a.Ak()};Ql.prototype.cc=function(){};na.Object.defineProperties(Ql.prototype,{classType:{get:function(){return X}}});Ql.prototype.remeasureObject=Ql.prototype.RA;Ql.prototype.arrangeElement=Ql.prototype.wz;Ql.prototype.measureElement=Ql.prototype.IA;Ql.className="PanelLayout"; function xm(){this.name="Base"}ma(xm,Ql);xm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length;a=ym(a);for(var k=0;k<h;k++){var l=d[k];if(l.visible||l===a){var m=l.margin,n=m.right+m.left;m=m.top+m.bottom;l.measure(b,c,f,g);var p=l.measuredBounds;n=Math.max(p.width+n,0);m=Math.max(p.height+m,0);p=l.position.x;var r=l.position.y;isFinite(p)||(p=0);isFinite(r)||(r=0);l instanceof Mf&&l.isGeometryPositioned&&(l=l.strokeWidth/2,p-=l,r-=l);gc(e,p,r,n,m)}}}; xm.prototype.arrange=function(a,b,c){var d=b.length,e=a.padding;a=c.x-e.left;c=c.y-e.top;for(e=0;e<d;e++){var f=b[e],g=f.measuredBounds,h=f.margin,k=f.position.x,l=f.position.y;k=isNaN(k)?-a:k-a;l=isNaN(l)?-c:l-c;if(f instanceof Mf&&f.isGeometryPositioned){var m=f.strokeWidth/2;k-=m;l-=m}f.visible&&f.arrange(k+h.left,l+h.top,g.width,g.height)}};function zm(){this.name="Base"}ma(zm,Ql); zm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length;b=Ea();f=ym(a);for(var k=0;k<h;k++){var l=d[k];if(l.visible||l===f){var m=nl(l,!1);if(m!==Bg&&m!==Zk)b.push(l);else{l.measure(Infinity,c,0,g);m=l.margin;l=l.measuredBounds;var n=Math.max(l.height+m.top+m.bottom,0);e.width+=Math.max(l.width+m.right+m.left,0);e.height=Math.max(e.height,n)}}}d=b.length;a.desiredSize.height?c=Math.min(a.desiredSize.height,a.maxSize.height):0!==e.height&&(c=Math.min(e.height,a.maxSize.height));for(a=0;a<d;a++)if(k= b[a],k.visible||k===f)m=k.margin,h=m.right+m.left,m=m.top+m.bottom,k.measure(Infinity,c,0,g),k=k.measuredBounds,m=Math.max(k.height+m,0),e.width+=Math.max(k.width+h,0),e.height=Math.max(e.height,m);Ia(b)}; zm.prototype.arrange=function(a,b,c){for(var d=b.length,e=a.padding,f=e.top,g=a.isOpposite,h=g?c.width:e.left,k=0;k<d;k++){var l=f,m=b[k];if(m.visible){var n=m.measuredBounds,p=m.margin,r=p.top+p.bottom,q=f+e.bottom,u=n.height,v=nl(m,!1);if(isNaN(m.desiredSize.height)&&v===vd||v===$k)u=Math.max(c.height-r-q,0);r=u+r+q;q=m.alignment;q.Nb()&&(q=a.defaultAlignment);q.kb()||(q=Bc);g&&(h-=n.width+p.left+p.right);m.arrange(h+q.offsetX+p.left,l+q.offsetY+p.top+(c.height*q.y-r*q.y),n.width,u);g||(h+=n.width+ p.left+p.right)}}};function Am(){this.name="Base"}ma(Am,Ql); Am.prototype.measure=function(a,b,c,d,e,f){var g=d.length;c=Ea();for(var h=ym(a),k=0;k<g;k++){var l=d[k];if(l.visible||l===h){var m=nl(l,!1);if(m!==Bg&&m!==$k)c.push(l);else{var n=l.margin;m=n.right+n.left;n=n.top+n.bottom;l.measure(b,Infinity,f,0);l=l.measuredBounds;Ub(e,Math.max(e.width,Math.max(l.width+m,0)),e.height+Math.max(l.height+n,0))}}}d=c.length;if(0!==d){a.desiredSize.width?b=Math.min(a.desiredSize.width,a.maxSize.width):0!==e.width&&(b=Math.min(e.width,a.maxSize.width));for(a=0;a<d;a++)if(k= c[a],k.visible||k===h)l=k.margin,g=l.right+l.left,l=l.top+l.bottom,k.measure(b,Infinity,f,0),k=k.measuredBounds,l=Math.max(k.height+l,0),e.width=Math.max(e.width,Math.max(k.width+g,0)),e.height+=l;Ia(c)}}; Am.prototype.arrange=function(a,b,c){for(var d=b.length,e=a.padding,f=e.left,g=a.isOpposite,h=g?c.height:e.top,k=0;k<d;k++){var l=f,m=b[k];if(m.visible){var n=m.measuredBounds,p=m.margin,r=p.left+p.right,q=f+e.right,u=n.width,v=nl(m,!1);if(isNaN(m.desiredSize.width)&&v===vd||v===Zk)u=Math.max(c.width-r-q,0);r=u+r+q;q=m.alignment;q.Nb()&&(q=a.defaultAlignment);q.kb()||(q=Bc);g&&(h-=n.height+p.bottom+p.top);m.arrange(l+q.offsetX+p.left+(c.width*q.x-r*q.x),h+q.offsetY+p.top,u,n.height);g||(h+=n.height+ p.bottom+p.top)}}};function Bm(){this.name="Base"}ma(Bm,Ql); Bm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length,k=a.rb(),l=k.margin,m=l.right+l.left,n=l.top+l.bottom;k.measure(b,c,f,g);var p=k.measuredBounds;f=p.width;g=p.height;var r=Math.max(f+m,0);var q=Math.max(g+n,0);for(var u=a.isClipping,v=N.allocAt(-l.left,-l.top,r,q),w=!0,y=ym(a),z=0;z<h;z++){var A=d[z];if(A!==k&&(A.visible||A===y)){l=A.margin;r=l.right+l.left;q=l.top+l.bottom;p=nl(A,!1);switch(p){case vd:b=f;c=g;break;case Zk:b=f;break;case $k:c=g}A.measure(b,c,0,0);p=A.measuredBounds;r= Math.max(p.width+r,0);q=Math.max(p.height+q,0);var C=A.alignment;C.Nb()&&(C=a.defaultAlignment);C.kb()||(C=Bc);var F=A.alignmentFocus;F.Nb()&&(F=Bc);var Q=null;A instanceof X&&""!==A.Mg&&(A.arrange(0,0,p.width,p.height),Q=A.ab(A.Mg),Q===A&&(Q=null));if(null!==Q){l=Q.naturalBounds;p=Q.margin;for(l=I.allocAt(F.x*l.width-F.offsetX-p.left,F.y*l.height-F.offsetY-p.top);Q!==A;)Q.transform.sa(l),Q=Q.panel;A=C.x*f+C.offsetX-l.x;p=C.y*g+C.offsetY-l.y;I.free(l)}else A=C.x*f+C.offsetX-(F.x*p.width+F.offsetX)- l.left,p=C.y*g+C.offsetY-(F.y*p.height+F.offsetY)-l.top;w?(w=!1,e.h(A,p,r,q)):gc(e,A,p,r,q)}}w?e.assign(v):u?e.aw(v.x,v.y,v.width,v.height):gc(e,v.x,v.y,v.width,v.height);N.free(v);p=k.stretch;p===Yk&&(p=nl(k,!1));switch(p){case Bg:return;case vd:if(!isFinite(b)&&!isFinite(c))return;break;case Zk:if(!isFinite(b))return;break;case $k:if(!isFinite(c))return}p=k.measuredBounds;f=p.width;g=p.height;r=Math.max(f+m,0);q=Math.max(g+n,0);l=k.margin;v=N.allocAt(-l.left,-l.top,r,q);for(b=0;b<h;b++)c=d[b],c=== k||!c.visible&&c!==y||(l=c.margin,r=l.right+l.left,q=l.top+l.bottom,p=c.measuredBounds,r=Math.max(p.width+r,0),q=Math.max(p.height+q,0),m=c.alignment,m.Nb()&&(m=a.defaultAlignment),m.kb()||(m=Bc),c=c.alignmentFocus,c.Nb()&&(c=Bc),w?(w=!1,e.h(m.x*f+m.offsetX-(c.x*p.width+c.offsetX)-l.left,m.y*g+m.offsetY-(c.y*p.height+c.offsetY)-l.top,r,q)):gc(e,m.x*f+m.offsetX-(c.x*p.width+c.offsetX)-l.left,m.y*g+m.offsetY-(c.y*p.height+c.offsetY)-l.top,r,q));w?e.assign(v):u?e.aw(v.x,v.y,v.width,v.height):gc(e,v.x, v.y,v.width,v.height);N.free(v)}; Bm.prototype.arrange=function(a,b,c){var d=b.length,e=a.rb(),f=e.measuredBounds,g=f.width;f=f.height;var h=a.padding,k=h.left;h=h.top;var l=k-c.x,m=h-c.y;e.arrange(l,m,g,f);for(var n=0;n<d;n++){var p=b[n];if(p!==e){var r=p.measuredBounds,q=r.width;r=r.height;m=p.alignment;m.Nb()&&(m=a.defaultAlignment);m.kb()||(m=Bc);var u=p.alignmentFocus;u.Nb()&&(u=Bc);l=null;p instanceof X&&""!==p.Mg&&(l=p.ab(p.Mg),l===p&&(l=null));if(null!==l){var v=l.naturalBounds;for(u=I.allocAt(u.x*v.width-u.offsetX,u.y*v.height- u.offsetY);l!==p;)l.transform.sa(u),l=l.panel;l=m.x*g+m.offsetX-u.x;m=m.y*f+m.offsetY-u.y;I.free(u)}else l=m.x*g+m.offsetX-(u.x*q+u.offsetX),m=m.y*f+m.offsetY-(u.y*r+u.offsetY);l-=c.x;m-=c.y;p.visible&&p.arrange(k+l,h+m,q,r)}}};function Cm(){this.name="Base"}ma(Cm,Ql); Cm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length,k=a.rb(),l=k.margin,m=b,n=c,p=l.right+l.left,r=l.top+l.bottom;k.measure(b,c,f,g);l=k.measuredBounds;var q=0,u=null;k instanceof Mf&&(u=k,q=u.strokeWidth*u.scale);var v=Math.max(l.width+p,0);l=Math.max(l.height+r,0);var w=Dm(k),y=w.x*v+w.offsetX;w=w.y*l+w.offsetY;var z=Em(k),A=z.x*v+z.offsetX;z=z.y*l+z.offsetY;isFinite(b)&&(m=Math.max(Math.abs(y-A)-q,0));isFinite(c)&&(n=Math.max(Math.abs(w-z)-q,0));q=M.alloc();q.h(0,0);a=ym(a);for(z=0;z<h;z++)w= d[z],w===k||!w.visible&&w!==a||(l=w.margin,v=l.right+l.left,y=l.top+l.bottom,w.measure(m,n,0,0),l=w.measuredBounds,v=Math.max(l.width+v,0),l=Math.max(l.height+y,0),q.h(Math.max(v,q.width),Math.max(l,q.height)));if(1===h)e.width=v,e.height=l,M.free(q);else{w=Dm(k);z=Em(k);h=d=0;z.x!==w.x&&z.y!==w.y&&(d=q.width/Math.abs(z.x-w.x),h=q.height/Math.abs(z.y-w.y));M.free(q);q=0;null!==u&&(q=u.strokeWidth*u.scale,Cg(u)===Dg&&(d=h=Math.max(d,h)));d+=Math.abs(w.offsetX)+Math.abs(z.offsetX)+q;h+=Math.abs(w.offsetY)+ Math.abs(z.offsetY)+q;u=k.stretch;u===Yk&&(u=nl(k,!1));switch(u){case Bg:g=f=0;break;case vd:isFinite(b)&&(d=b);isFinite(c)&&(h=c);break;case Zk:isFinite(b)&&(d=b);g=0;break;case $k:f=0,isFinite(c)&&(h=c)}k.Ak();k.measure(d,h,f,g);e.width=k.measuredBounds.width+p;e.height=k.measuredBounds.height+r}}; Cm.prototype.arrange=function(a,b){var c=b.length,d=a.rb(),e=d.measuredBounds,f=N.alloc();f.h(0,0,1,1);var g=d.margin,h=g.left;g=g.top;var k=a.padding,l=k.left;k=k.top;d.arrange(l+h,k+g,e.width,e.height);var m=Dm(d),n=Em(d),p=m.y*e.height+m.offsetY,r=n.x*e.width+n.offsetX;n=n.y*e.height+n.offsetY;f.x=m.x*e.width+m.offsetX;f.y=p;gc(f,r,n,0,0);f.x+=h+l;f.y+=g+k;for(e=0;e<c;e++)h=b[e],h!==d&&(l=h.measuredBounds,g=h.margin,k=Math.max(l.width+g.right+g.left,0),m=Math.max(l.height+g.top+g.bottom,0),p=h.alignment, p.Nb()&&(p=a.defaultAlignment),p.kb()||(p=Bc),k=f.width*p.x+p.offsetX-k*p.x+g.left+f.x,g=f.height*p.y+p.offsetY-m*p.y+g.top+f.y,h.visible&&(hc(f.x,f.y,f.width,f.height,k,g,l.width,l.height)?h.arrange(k,g,l.width,l.height):h.arrange(k,g,l.width,l.height,new N(f.x,f.y,f.width,f.height))));N.free(f)};function Fm(){this.name="Base";this.name="Table"}ma(Fm,Ql); Fm.prototype.measure=function(a,b,c,d,e){for(var f=d.length,g=Ea(),h=Ea(),k=0;k<f;k++){var l=d[k],m=l instanceof X?l:null;if(null===m||m.type!==X.TableRow&&m.type!==X.TableColumn||!l.visible)g.push(l);else{h.push(m);for(var n=m.W.j,p=n.length,r=0;r<p;r++){var q=n[r];m.type===X.TableRow?q.row=l.row:m.type===X.TableColumn&&(q.column=l.column);g.push(q)}}}f=g.length;0===f&&(a.getRowDefinition(0),a.getColumnDefinition(0));for(var u=[],v=0;v<f;v++){var w=g[v];pj(w,!0);ol(w,!0);u[w.row]||(u[w.row]=[]); u[w.row][w.column]||(u[w.row][w.column]=[]);u[w.row][w.column].push(w)}Ia(g);var y=Ea(),z=Ea(),A=Ea(),C={count:0},F={count:0},Q=b,K=c,T=a.vb;f=T.length;for(var P=0;P<f;P++){var J=T[P];void 0!==J&&(J.actual=0)}T=a.sb;f=T.length;for(var ka=0;ka<f;ka++)J=T[ka],void 0!==J&&(J.actual=0);for(var ba=u.length,qa=0,Ma=0;Ma<ba;Ma++)u[Ma]&&(qa=Math.max(qa,u[Ma].length));var eb=Math.min(a.topIndex,ba-1),Ga=Math.min(a.leftIndex,qa-1),Ha=0;ba=u.length;for(var Ad=ym(a),Xb=0;Xb<ba;Xb++)if(u[Xb]){qa=u[Xb].length; var Yb=a.getRowDefinition(Xb);Yb.actual=0;for(var fb=Yb.ac=0;fb<qa;fb++)if(u[Xb][fb]){var Bd=a.getColumnDefinition(fb);void 0===y[fb]&&(Bd.actual=0,Bd.ac=0,y[fb]=!0);for(var eg=u[Xb][fb],fg=eg.length,Le=0;Le<fg;Le++){var Db=eg[Le];if(Db.visible||Db===Ad){var wh=1<Db.rowSpan||1<Db.columnSpan;wh&&(Xb<eb||fb<Ga||z.push(Db));var gg=Db.margin,xh=gg.right+gg.left,yh=gg.top+gg.bottom;var ab=Gl(Db,Yb,Bd,!1);var Hi=Db.desiredSize,ik=!isNaN(Hi.height),hg=!isNaN(Hi.width)&&ik;wh||ab===Bg||hg||Xb<eb||fb<Ga|| (void 0!==C[fb]||ab!==vd&&ab!==Zk||(C[fb]=-1,C.count++),void 0!==F[Xb]||ab!==vd&&ab!==$k||(F[Xb]=-1,F.count++),A.push(Db));Db.measure(Infinity,Infinity,0,0);if(!(Xb<eb||fb<Ga)){var md=Db.measuredBounds,mc=Math.max(md.width+xh,0),Ef=Math.max(md.height+yh,0);if(1===Db.rowSpan&&(ab===Bg||ab===Zk)){J=a.getRowDefinition(Xb);var wc=J.wc();Ha=Math.max(Ef-J.actual,0);Ha+wc>K&&(Ha=Math.max(K-wc,0));var ig=0===J.ha;J.ac=J.ac+Ha;J.actual=J.ha+Ha;K=Math.max(K-(Ha+(ig?wc:0)),0)}if(1===Db.columnSpan&&(ab===Bg|| ab===$k)){J=a.getColumnDefinition(fb);var zh=J.wc();Ha=Math.max(mc-J.actual,0);Ha+zh>Q&&(Ha=Math.max(Q-zh,0));var Bn=0===J.ha;J.ac=J.ac+Ha;J.actual=J.ha+Ha;Q=Math.max(Q-(Ha+(Bn?zh:0)),0)}wh&&Db.Ak()}}}}}Ia(y);var Jd=0,le=0;f=a.columnCount;for(var jg=0;jg<f;jg++){var kg=a.sb[jg];void 0!==kg&&(Jd+=kg.ac,0!==kg.ac&&(Jd+=kg.wc()))}f=a.rowCount;for(var Wc=0;Wc<f;Wc++){var me=a.vb[Wc];void 0!==me&&(le+=me.ac,0!==me.ac&&(le+=me.wc()))}Q=Math.max(b-Jd,0);var dc=K=Math.max(c-le,0),Ah=Q;f=A.length;for(var Bh= 0;Bh<f;Bh++){var Xc=A[Bh],Ii=a.getRowDefinition(Xc.row),ne=a.getColumnDefinition(Xc.column),ff=Xc.measuredBounds,Cd=Xc.margin,jk=Cd.right+Cd.left,Cn=Cd.top+Cd.bottom;C[Xc.column]=0===ne.ac&&void 0!==C[Xc.column]?Math.max(ff.width+jk,C[Xc.column]):null;F[Xc.row]=0===Ii.ac&&void 0!==F[Xc.row]?Math.max(ff.height+Cn,F[Xc.row]):null}var Ff=0,Eb=0,Kd;for(Kd in F)"count"!==Kd&&(Ff+=F[Kd]);for(Kd in C)"count"!==Kd&&(Eb+=C[Kd]);for(var gb=M.alloc(),Ji=0;Ji<f;Ji++){var Zb=A[Ji];if(Zb.visible||Zb===Ad){var xc= a.getRowDefinition(Zb.row),nc=a.getColumnDefinition(Zb.column),Ld=0;isFinite(nc.width)?Ld=nc.width:(isFinite(Q)&&null!==C[Zb.column]?0===Eb?Ld=nc.actual+Q:Ld=C[Zb.column]/Eb*Ah:null!==C[Zb.column]?Ld=Q:Ld=nc.actual||Q,Ld=Math.max(0,Ld-nc.wc()));var Md=0;isFinite(xc.height)?Md=xc.height:(isFinite(K)&&null!==F[Zb.row]?0===Ff?Md=xc.actual+K:Md=F[Zb.row]/Ff*dc:null!==F[Zb.row]?Md=K:Md=xc.actual||K,Md=Math.max(0,Md-xc.wc()));gb.h(Math.max(nc.minimum,Math.min(Ld,nc.maximum)),Math.max(xc.minimum,Math.min(Md, xc.maximum)));ab=Gl(Zb,xc,nc,!1);switch(ab){case Zk:gb.height=Math.max(gb.height,xc.actual+K);break;case $k:gb.width=Math.max(gb.width,nc.actual+Q)}var lg=Zb.margin,Ec=lg.right+lg.left,Ch=lg.top+lg.bottom;Zb.Ak();Zb.measure(gb.width,gb.height,nc.minimum,xc.minimum);var mg=Zb.measuredBounds,Nd=Math.max(mg.width+Ec,0),Dh=Math.max(mg.height+Ch,0);isFinite(Q)&&(Nd=Math.min(Nd,gb.width));isFinite(K)&&(Dh=Math.min(Dh,gb.height));var gf=0;gf=xc.actual;xc.actual=Math.max(xc.actual,Dh);xc.ac=Math.max(xc.ac, Dh);Ha=xc.actual-gf;K=Math.max(K-Ha,0);null===F[Zb.row]&&(dc=Math.max(dc-Ha,0));gf=nc.actual;nc.actual=Math.max(nc.actual,Nd);nc.ac=Math.max(nc.ac,Nd);Ha=nc.actual-gf;Q=Math.max(Q-Ha,0);null===C[Zb.column]&&(Ah=Math.max(Ah-Ha,0))}}Ia(A);var Od=M.alloc(),Pd=Ea(),Qd=Ea();f=z.length;if(0!==f)for(var Me=0;Me<ba;Me++)if(u[Me]){qa=u[Me].length;var Eh=a.getRowDefinition(Me);Pd[Me]=Eh.actual;for(var oe=0;oe<qa;oe++)if(u[Me][oe]){var Dn=a.getColumnDefinition(oe);Qd[oe]=Dn.actual}}for(var ec=0;ec<f;ec++){var Oa= z[ec];if(Oa.visible||Oa===Ad){var fc=a.getRowDefinition(Oa.row),Rd=a.getColumnDefinition(Oa.column);gb.h(Math.max(Rd.minimum,Math.min(b,Rd.maximum)),Math.max(fc.minimum,Math.min(c,fc.maximum)));ab=Gl(Oa,fc,Rd,!1);switch(ab){case vd:0!==Qd[Rd.index]&&(gb.width=Math.min(gb.width,Qd[Rd.index]));0!==Pd[fc.index]&&(gb.height=Math.min(gb.height,Pd[fc.index]));break;case Zk:0!==Qd[Rd.index]&&(gb.width=Math.min(gb.width,Qd[Rd.index]));break;case $k:0!==Pd[fc.index]&&(gb.height=Math.min(gb.height,Pd[fc.index]))}isFinite(Rd.width)&& (gb.width=Rd.width);isFinite(fc.height)&&(gb.height=fc.height);Od.h(0,0);for(var Ne=Rd.minimum,Fh=fc.minimum,Oe=1;Oe<Oa.rowSpan&&!(Oa.row+Oe>=a.rowCount);Oe++)J=a.getRowDefinition(Oa.row+Oe),Ha=0,Ha=ab===vd||ab===$k?Math.max(J.minimum,0===Pd[Oa.row+Oe]?J.maximum:Math.min(Pd[Oa.row+Oe],J.maximum)):Math.max(J.minimum,isNaN(J.cd)?J.maximum:Math.min(J.cd,J.maximum)),Od.height+=Ha,Fh+=J.minimum;for(var Oc=1;Oc<Oa.columnSpan&&!(Oa.column+Oc>=a.columnCount);Oc++)J=a.getColumnDefinition(Oa.column+Oc),Ha= 0,Ha=ab===vd||ab===Zk?Math.max(J.minimum,0===Qd[Oa.column+Oc]?J.maximum:Math.min(Qd[Oa.column+Oc],J.maximum)):Math.max(J.minimum,isNaN(J.cd)?J.maximum:Math.min(J.cd,J.maximum)),Od.width+=Ha,Ne+=J.minimum;gb.width+=Od.width;gb.height+=Od.height;var hf=Oa.margin,Gh=hf.right+hf.left,En=hf.top+hf.bottom;Oa.measure(gb.width,gb.height,Ne,Fh);for(var ng=Oa.measuredBounds,nd=Math.max(ng.width+Gh,0),Sd=Math.max(ng.height+En,0),pe=0,qe=0;qe<Oa.rowSpan&&!(Oa.row+qe>=a.rowCount);qe++)J=a.getRowDefinition(Oa.row+ qe),pe+=J.total||0;if(pe<Sd){var Td=Sd-pe,re=Sd-pe;if(null!==Oa.spanAllocation)for(var kk=Oa.spanAllocation,Pe=0;Pe<Oa.rowSpan&&!(0>=Td)&&!(Oa.row+Pe>=a.rowCount);Pe++){J=a.getRowDefinition(Oa.row+Pe);var Ki=J.ha||0,Fn=kk(Oa,J,re);J.actual=Math.min(J.maximum,Ki+Fn);J.ha!==Ki&&(Td-=J.ha-Ki)}for(;0<Td;){var od=J.ha||0;isNaN(J.height)&&J.maximum>od&&(J.actual=Math.min(J.maximum,od+Td),J.ha!==od&&(Td-=J.ha-od));if(0===J.index)break;J=a.getRowDefinition(J.index-1)}}for(var Gf=0,Hh=0;Hh<Oa.columnSpan&& !(Oa.column+Hh>=a.columnCount);Hh++)J=a.getColumnDefinition(Oa.column+Hh),Gf+=J.total||0;if(Gf<nd){var og=nd-Gf,cu=nd-Gf;if(null!==Oa.spanAllocation)for(var du=Oa.spanAllocation,lk=0;lk<Oa.columnSpan&&!(0>=og)&&!(Oa.column+lk>=a.columnCount);lk++){J=a.getColumnDefinition(Oa.column+lk);var Gn=J.ha||0,eu=du(Oa,J,cu);J.actual=Math.min(J.maximum,Gn+eu);J.ha!==Gn&&(og-=J.ha-Gn)}for(;0<og;){var mk=J.ha||0;isNaN(J.width)&&J.maximum>mk&&(J.actual=Math.min(J.maximum,mk+og),J.ha!==mk&&(og-=J.ha-mk));if(0=== J.index)break;J=a.getColumnDefinition(J.index-1)}}}}Ia(z);M.free(Od);M.free(gb);void 0!==Pd&&Ia(Pd);void 0!==Qd&&Ia(Qd);var pg=0,qg=0,nk=a.desiredSize,pr=a.maxSize;ab=nl(a,!0);var Li=le=Jd=0,Mi=0;f=a.columnCount;for(var ok=0;ok<f;ok++)void 0!==a.sb[ok]&&(J=a.getColumnDefinition(ok),isFinite(J.width)?(Li+=J.width,Li+=J.wc()):Gm(J)===Hm?(Li+=J.ha,Li+=J.wc()):0!==J.ha&&(Jd+=J.ha,Jd+=J.wc()));isFinite(nk.width)?pg=Math.min(nk.width,pr.width):pg=ab!==Bg&&isFinite(b)?b:Jd;pg=Math.max(pg,a.minSize.width); pg=Math.max(pg-Li,0);for(var fu=0===Jd?1:Math.max(pg/Jd,1),qk=0;qk<f;qk++)void 0!==a.sb[qk]&&(J=a.getColumnDefinition(qk),isFinite(J.width)||Gm(J)===Hm||(J.actual=J.ha*fu),J.position=e.width,0!==J.ha&&(e.width+=J.ha,e.width+=J.wc()));f=a.rowCount;for(var rk=0;rk<f;rk++)void 0!==a.vb[rk]&&(J=a.getRowDefinition(rk),isFinite(J.height)?(Mi+=J.height,Mi+=J.wc()):Gm(J)===Hm?(Mi+=J.ha,Mi+=J.wc()):0!==J.ha&&(le+=J.ha,0!==J.ha&&(le+=J.wc())));isFinite(nk.height)?qg=Math.min(nk.height,pr.height):qg=ab!==Bg&& isFinite(c)?c:le;qg=Math.max(qg,a.minSize.height);qg=Math.max(qg-Mi,0);for(var gu=0===le?1:Math.max(qg/le,1),sk=0;sk<f;sk++)void 0!==a.vb[sk]&&(J=a.getRowDefinition(sk),isFinite(J.height)||Gm(J)===Hm||(J.actual=J.ha*gu),J.position=e.height,0!==J.ha&&(e.height+=J.ha,0!==J.ha&&(e.height+=J.wc())));f=h.length;for(var Hn=0;Hn<f;Hn++){var pd=h[Hn],In=0,Jn=0;pd.type===X.TableRow?(In=e.width,J=a.getRowDefinition(pd.row),Jn=J.actual):(J=a.getColumnDefinition(pd.column),In=J.actual,Jn=e.height);pd.measuredBounds.h(0, 0,In,Jn);pj(pd,!1);u[pd.row]||(u[pd.row]=[]);u[pd.row][pd.column]||(u[pd.row][pd.column]=[]);u[pd.row][pd.column].push(pd)}Ia(h);a.Gp=u}; Fm.prototype.arrange=function(a,b,c){var d=b.length,e=a.padding,f=e.left;e=e.top;for(var g=a.Gp,h,k,l=g.length,m=0,n=0;n<l;n++)g[n]&&(m=Math.max(m,g[n].length));for(n=Math.min(a.topIndex,l-1);n!==l&&(void 0===a.vb[n]||0===a.vb[n].ha);)n++;n=Math.min(n,l-1);n=-a.vb[n].position;for(h=Math.min(a.leftIndex,m-1);h!==m&&(void 0===a.sb[h]||0===a.sb[h].ha);)h++;h=Math.min(h,m-1);for(var p=-a.sb[h].position,r=M.alloc(),q=0;q<l;q++)if(g[q]){m=g[q].length;var u=a.getRowDefinition(q);k=u.position+n+e;0!==u.ha&& (k+=u.Iv());for(var v=0;v<m;v++)if(g[q][v]){var w=a.getColumnDefinition(v);h=w.position+p+f;0!==w.ha&&(h+=w.Iv());for(var y=g[q][v],z=y.length,A=0;A<z;A++){var C=y[A],F=C.measuredBounds,Q=C instanceof X?C:null;if(null===Q||Q.type!==X.TableRow&&Q.type!==X.TableColumn){r.h(0,0);for(var K=1;K<C.rowSpan&&!(q+K>=a.rowCount);K++)Q=a.getRowDefinition(q+K),r.height+=Q.total;for(K=1;K<C.columnSpan&&!(v+K>=a.columnCount);K++)Q=a.getColumnDefinition(v+K),r.width+=Q.total;var T=w.ha+r.width,P=u.ha+r.height;K= h;Q=k;var J=T,ka=P,ba=h,qa=k,Ma=T,eb=P;h+T>c.width&&(Ma=Math.max(c.width-h,0));k+P>c.height&&(eb=Math.max(c.height-k,0));var Ga=C.alignment;if(Ga.Nb()){Ga=a.defaultAlignment;Ga.kb()||(Ga=Bc);var Ha=Ga.x;var Ad=Ga.y;var Xb=Ga.offsetX;Ga=Ga.offsetY;var Yb=w.alignment,fb=u.alignment;Yb.kb()&&(Ha=Yb.x,Xb=Yb.offsetX);fb.kb()&&(Ad=fb.y,Ga=fb.offsetY)}else Ha=Ga.x,Ad=Ga.y,Xb=Ga.offsetX,Ga=Ga.offsetY;if(isNaN(Ha)||isNaN(Ad))Ad=Ha=.5,Ga=Xb=0;Yb=F.width;fb=F.height;var Bd=C.margin,eg=Bd.left+Bd.right,fg=Bd.top+ Bd.bottom,Le=Gl(C,u,w,!1);!isNaN(C.desiredSize.width)||Le!==vd&&Le!==Zk||(Yb=Math.max(T-eg,0));!isNaN(C.desiredSize.height)||Le!==vd&&Le!==$k||(fb=Math.max(P-fg,0));T=C.maxSize;P=C.minSize;Yb=Math.min(T.width,Yb);fb=Math.min(T.height,fb);Yb=Math.max(P.width,Yb);fb=Math.max(P.height,fb);T=fb+fg;K+=J*Ha-(Yb+eg)*Ha+Xb+Bd.left;Q+=ka*Ad-T*Ad+Ga+Bd.top;C.visible&&(hc(ba,qa,Ma,eb,K,Q,F.width,F.height)?C.arrange(K,Q,Yb,fb):C.arrange(K,Q,Yb,fb,new N(ba,qa,Ma,eb)))}else C.Gl(),C.actualBounds.ea(),J=C.actualBounds, K=N.allocAt(J.x,J.y,J.width,J.height),J.x=Q.type===X.TableRow?f:h,J.y=Q.type===X.TableColumn?e:k,J.width=F.width,J.height=F.height,C.actualBounds.freeze(),ol(C,!1),$b(K,J)||(F=C.part,null!==F&&(F.Nh(),C.hp(F))),N.free(K)}}}M.free(r);for(a=0;a<d;a++)c=b[a],f=c instanceof X?c:null,null===f||f.type!==X.TableRow&&f.type!==X.TableColumn||(f=c.actualBounds,c.naturalBounds.ea(),c.naturalBounds.h(0,0,f.width,f.height),c.naturalBounds.freeze())};function Im(){this.name="Base"}ma(Im,Ql); Im.prototype.measure=function(){};Im.prototype.arrange=function(){};function Jm(){this.name="Base"}ma(Jm,Ql);Jm.prototype.measure=function(){};Jm.prototype.arrange=function(){};function Km(){this.name="Base"}ma(Km,Ql); Km.prototype.measure=function(a,b,c,d,e,f,g){1<d.length&&B("Viewbox Panel cannot contain more than one GraphObject.");d=d[0];d.ya=1;d.Ak();d.measure(Infinity,Infinity,f,g);var h=d.measuredBounds,k=d.margin,l=k.right+k.left;k=k.top+k.bottom;if(isFinite(b)||isFinite(c)){var m=d.scale,n=h.width;h=h.height;var p=Math.max(b-l,0),r=Math.max(c-k,0),q=1;a.viewboxStretch===Dg?0!==n&&0!==h&&(q=Math.min(p/n,r/h)):0!==n&&0!==h&&(q=Math.max(p/n,r/h));0===q&&(q=1E-4);d.ya*=q;m!==d.scale&&(pj(d,!0),d.measure(Infinity, Infinity,f,g))}h=d.measuredBounds;e.width=isFinite(b)?b:Math.max(h.width+l,0);e.height=isFinite(c)?c:Math.max(h.height+k,0)};Km.prototype.arrange=function(a,b,c){b=b[0];var d=b.measuredBounds,e=b.margin,f=Math.max(d.width+(e.right+e.left),0);e=Math.max(d.height+(e.top+e.bottom),0);var g=b.alignment;g.Nb()&&(g=a.defaultAlignment);g.kb()||(g=Bc);b.arrange(c.width*g.x-f*g.x+g.offsetX,c.height*g.y-e*g.y+g.offsetY,d.width,d.height)};function Lm(){this.name="Base"}ma(Lm,Ql);Lm.prototype.measure=function(){}; Lm.prototype.arrange=function(){}; Lm.prototype.cc=function(a,b,c){c=a.Cf()*c.scale;0>=c&&(c=1);var d=a.gridCellSize,e=d.width;d=d.height;var f=a.naturalBounds,g=a.actualBounds,h=f.width,k=f.height,l=Math.ceil(h/e),m=Math.ceil(k/d),n=a.gridOrigin,p=n.x;n=n.y;b.save();b.beginPath();b.rect(0,0,h,k);b.clip();for(var r=[],q=a.W.j,u=q.length,v=0;v<u;v++){var w=q[v],y=[];r.push(y);if(w.visible){var z=w.interval;if(!(0>z)){w=Xj(w.figure);for(var A=0;A<u;A++)if(A!==v){var C=q[A];C.visible&&Xj(C.figure)===w&&(C=C.interval,C>z&&y.push(C))}}}}q= a.W.j;u=q.length;for(v=0;v<u;v++){var F=q[v];if(F.visible&&(y=F.interval||1,w=Math.abs(y),!(2>e*w*c))){z=F.segmentIndex;if(!isFinite(z)||isNaN(z))z=0;0>z&&(z=w-Math.min(-z,w));z=Math.round(z%w);w=F.opacity;A=1;if(1!==w){if(0===w)continue;A=b.globalAlpha;b.globalAlpha=A*w}C=r[v];var Q=!1,K=F.strokeDashArray;null!==K&&(Q=!0,b.Gt(K,F.strokeDashOffset));if("LineV"===F.figure&&null!==F.stroke&&0<F.strokeWidth){b.lineWidth=F.strokeWidth;oi(a,b,F.stroke,!1,!1,f,g);b.beginPath();for(K=F=Math.floor((p-e)/ e);K<=F+l;K++){var T=K*e+p;0<=T&&T<=h&&Mm(K,y,z,C)&&(b.moveTo(T,0),b.lineTo(T,k))}b.stroke()}else if("LineH"===F.figure&&null!==F.stroke&&0<F.strokeWidth){b.lineWidth=F.strokeWidth;oi(a,b,F.stroke,!1,!1,f,g);b.beginPath();for(K=F=Math.floor((n-d)/d);K<=F+m;K++)T=K*d+n,0<=T&&T<=k&&Mm(K,y,z,C)&&(b.moveTo(0,T),b.lineTo(h,T));b.stroke()}else if("BarV"===F.figure&&null!==F.fill)for(oi(a,b,F.fill,!0,!1,f,g),F=F.width,isNaN(F)&&(F=e),T=K=Math.floor((p-e)/e);T<=K+l;T++){var P=T*e+p;0<=P+F&&P<=h&&Mm(T,y,z, C)&&b.fillRect(P,0,F,k)}else if("BarH"===F.figure&&null!==F.fill)for(oi(a,b,F.fill,!0,!1,f,g),F=F.height,isNaN(F)&&(F=d),T=K=Math.floor((n-d)/d);T<=K+m;T++)P=T*d+n,0<=P+F&&P<=k&&Mm(T,y,z,C)&&b.fillRect(0,P,h,F);Q&&b.Et();1!==w&&(b.globalAlpha=A)}}b.restore();b.uc(!1)};function Mm(a,b,c,d){if(0>b)return a%b===c;if(a%b!==c)return!1;b=d.length;for(var e=0;e<b;e++)if(a%d[e]===c)return!1;return!0}function Nm(){this.name="Base"}ma(Nm,Ql); Nm.prototype.measure=function(a,b,c,d,e){c=d.length;if(a instanceof Qe||a instanceof S){var f=null,g=null,h=null;a instanceof S&&(g=f=a);a instanceof Qe&&(h=a,f=h.adornedPart);if(f instanceof S){var k=f;if(0===c)Ub(a.naturalBounds,0,0),a.measuredBounds.h(0,0,0,0);else{var l=a instanceof Qe?null:f.path,m=f.routeBounds;b=a.yg;b.h(0,0,m.width,m.height);var n=k.points;f=f.pointsCount;null!==h?h.Fk(!1):null!==g&&g.Fk(!1);var p=m.width,r=m.height;a.location.h(m.x,m.y);a.l.length=0;null!==l&&(Om(a,p,r,l), h=l.measuredBounds,b.Tc(h),a.l.push(h));h=rd.alloc();for(var q=I.alloc(),u=I.alloc(),v=0;v<c;v++){var w=d[v];if(w!==l)if(w.isPanelMain&&w instanceof Mf){Om(a,p,r,w);var y=w.measuredBounds;b.Tc(y);a.l.push(y)}else if(2>f)w.measure(Infinity,Infinity,0,0),y=w.measuredBounds,b.Tc(y),a.l.push(y);else{var z=w.segmentIndex,A=w.segmentFraction,C=w.alignmentFocus;C.nc()&&(C=Bc);var F=w.segmentOrientation,Q=w.segmentOffset;if(isNaN(z)){var K=k.na;y=Ea();K.Xv(A,y);var T=I.allocAt(y[0],y[1]);T.add(k.i(0));K.type=== wd?T.offset(-K.startX,-K.startY):(K=K.figures.first(),T.offset(-K.startX,-K.startY));K=y[2];if(F!==cg){var P=k.computeAngle(w,F,K);w.Yb=P}P=T.x-m.x;var J=T.y-m.y;I.free(T);Ia(y)}else if(z<-f||z>=f)J=k.midPoint,K=k.midAngle,F!==cg&&(P=k.computeAngle(w,F,K),w.Yb=P),P=J.x-m.x,J=J.y-m.y;else{P=0;0<=z?(J=n.J(z),y=z<f-1?n.J(z+1):J):(P=f+z,J=n.J(P),y=0<P?n.J(P-1):J);if(J.Na(y)){0<=z?(K=0<z?n.J(z-1):J,P=z<f-2?n.J(z+2):y):(K=P<f-1?n.J(P+1):J,P=1<P?n.J(P-2):y);T=K.Ie(J);var ka=y.Ie(P);K=T>ka+10?0<=z?K.Sa(J): J.Sa(K):ka>T+10?0<=z?y.Sa(P):P.Sa(y):0<=z?K.Sa(P):P.Sa(K)}else K=0<=z?J.Sa(y):y.Sa(J);F!==cg&&(P=k.computeAngle(w,F,K),w.Yb=P);P=J.x+(y.x-J.x)*A-m.x;J=J.y+(y.y-J.y)*A-m.y}w.measure(Infinity,Infinity,0,0);y=w.measuredBounds;T=w.naturalBounds;var ba=0;w instanceof Mf&&(ba=w.strokeWidth);ka=T.width+ba;var qa=T.height+ba;h.reset();h.translate(-y.x,-y.y);h.scale(w.scale,w.scale);h.rotate(F===cg?w.angle:K,ka/2,qa/2);F!==Pm&&F!==Qm||h.rotate(90,ka/2,qa/2);F!==Rm&&F!==Sm||h.rotate(-90,ka/2,qa/2);F===Tm&& (45<K&&135>K||225<K&&315>K)&&h.rotate(-K,ka/2,qa/2);T=new N(0,0,ka,qa);q.tj(T,C);h.sa(q);C=-q.x+ba/2*w.scale;w=-q.y+ba/2*w.scale;u.assign(Q);ba=isNaN(Q.x);var Ma=isNaN(Q.y);if(ba||Ma){ka=ka/2+3;qa=qa/2+3;var eb=45<=K&&135>=K,Ga=225<=K&&315>=K;F===cg&&(eb||Ga)?(u.x=Ma?ka:Q.y,u.y=ba?qa:Q.x,eb?0<=z||isNaN(z)&&.5>A||!ba||(u.y=-qa):Ga&&((0<=z||isNaN(z)&&.5>A)&&ba&&(u.y=-qa),Ma&&(u.x=-ka))):(ba&&(u.x=0<=z||isNaN(z)&&.5>A?ka:-ka),Ma&&(u.y=-qa),u.rotate(K))}else u.rotate(K);P+=u.x;J+=u.y;T.set(y);T.h(P+C, J+w,y.width,y.height);a.l.push(T);b.Tc(T)}}if(null!==g)for(d=g.labelNodes;d.next();)d.value.measure(Infinity,Infinity);a.yg=b;a=a.location;a.h(a.x+b.x,a.y+b.y);Ub(e,b.width||0,b.height||0);rd.free(h);I.free(q);I.free(u)}}}}; Nm.prototype.arrange=function(a,b){var c=b.length;if(a instanceof Qe||a instanceof S){var d=null,e=null,f=null;a instanceof S&&(e=d=a);a instanceof Qe&&(f=a,d=f.adornedPart);var g=a instanceof Qe?null:d.path;if(0!==a.l.length){var h=a.l,k=0;if(null!==g&&k<a.l.length){var l=h[k];k++;g.arrange(l.x-a.yg.x,l.y-a.yg.y,l.width,l.height)}for(l=0;l<c;l++){var m=b[l];if(m!==g&&k<a.l.length){var n=h[k];k++;m.arrange(n.x-a.yg.x,n.y-a.yg.y,n.width,n.height)}}}b=d.points;c=b.count;if(2<=c&&a instanceof S)for(d= a.labelNodes;d.next();){var p=a;g=d.value;h=g.segmentIndex;k=g.segmentFraction;var r=g.alignmentFocus;l=g.segmentOrientation;m=g.segmentOffset;if(isNaN(h)){n=p.na;var q=Ea();n.Xv(k,q);var u=I.allocAt(q[0],q[1]);u.add(p.i(0));n.type===wd?u.offset(-n.startX,-n.startY):(n=n.figures.first(),u.offset(-n.startX,-n.startY));n=q[2];l!==cg&&(p=p.computeAngle(g,l,n),g.angle=p);p=u.x;var v=u.y;I.free(u);Ia(q)}else if(h<-c||h>=c)v=p.midPoint,n=p.midAngle,l!==cg&&(p=p.computeAngle(g,l,n),g.angle=p),p=v.x,v=v.y; else{u=0;0<=h?(q=b.j[h],v=h<c-1?b.j[h+1]:q):(u=c+h,q=b.j[u],v=0<u?b.j[u-1]:q);if(q.Na(v)){0<=h?(n=0<h?b.j[h-1]:q,u=h<c-2?b.j[h+2]:v):(n=u<c-1?b.j[u+1]:q,u=1<u?b.j[u-2]:v);var w=n.Ie(q),y=v.Ie(u);n=w>y+10?0<=h?n.Sa(q):q.Sa(n):y>w+10?0<=h?v.Sa(u):u.Sa(v):0<=h?n.Sa(u):u.Sa(n)}else n=0<=h?q.Sa(v):v.Sa(q);l!==cg&&(p=p.computeAngle(g,l,n),g.angle=p);p=q.x+(v.x-q.x)*k;v=q.y+(v.y-q.y)*k}if(r.Wt())g.location=new I(p,v);else{r.nc()&&(r=Bc);q=rd.alloc();q.reset();q.scale(g.scale,g.scale);q.rotate(g.angle,0, 0);var z=g.naturalBounds;u=N.allocAt(0,0,z.width,z.height);w=I.alloc();w.tj(u,r);q.sa(w);r=-w.x;y=-w.y;var A=z.width,C=z.height;z=I.alloc();z.assign(m);var F=isNaN(m.x),Q=isNaN(m.y);if(F||Q){A=A/2+3;C=C/2+3;var K=45<=n&&135>=n,T=225<=n&&315>=n;l===cg&&(K||T)?(z.x=Q?A:m.y,z.y=F?C:m.x,K?0<=h||isNaN(h)&&.5>k||!F||(z.y=-C):T&&((0<=h||isNaN(h)&&.5>k)&&F&&(z.y=-C),Q&&(z.x=-A))):(F&&(z.x=0<=h||isNaN(h)&&.5>k?A:-A),Q&&(z.y=-C),z.rotate(n))}else z.rotate(n);p+=z.x;v+=z.y;q.Qw(u);r+=u.x;y+=u.y;h=I.allocAt(p+ r,v+y);g.move(h);I.free(h);I.free(z);I.free(w);N.free(u);rd.free(q)}}null!==f?f.Fk(!1):null!==e&&e.Fk(!1)}}; function Om(a,b,c,d){if(!1!==uj(d)){var e=d.strokeWidth;0===e&&a instanceof Qe&&a.type===X.Link&&a.adornedObject instanceof Mf&&(e=a.adornedObject.strokeWidth);e*=d.ya;a instanceof S&&null!==a.na?(a=a.na.bounds,kl(d,a.x-e/2,a.y-e/2,a.width+e,a.height+e)):a instanceof Qe&&null!==a.adornedPart.na?(a=a.adornedPart.na.bounds,kl(d,a.x-e/2,a.y-e/2,a.width+e,a.height+e)):kl(d,-(e/2),-(e/2),b+e,c+e);pj(d,!1)}}function Um(){this.name="Base"}ma(Um,Ql); Um.prototype.measure=function(a,b,c,d,e,f,g){var h=a.rb();a.dh=[];var k=h.margin,l=k.right+k.left,m=k.top+k.bottom;h.measure(b,c,f,g);var n=h.measuredBounds,p=new N(-k.left,-k.top,Math.max(n.width+l,0),Math.max(n.height+m,0));a.dh.push(p);e.assign(p);for(var r=h.geometry,q=h.strokeWidth,u=r.flattenedSegments,v=r.flattenedLengths,w=r.flattenedTotalLength,y=u.length,z=0,A=0,C=Ea(),F=0;F<y;F++){var Q=u[F],K=[];A=z=0;for(var T=Q.length,P=0;P<T;P+=2){var J=Q[P],ka=Q[P+1];if(0!==P){var ba=180*Math.atan2(ka- A,J-z)/Math.PI;0>ba&&(ba+=360);K.push(ba)}z=J;A=ka}C.push(K)}if(null===a.eh){for(var qa=[],Ma=a.W.j,eb=Ma.length,Ga=0;Ga<eb;Ga++){var Ha=Ma[Ga],Ad=[];qa.push(Ad);if(Ha.visible){var Xb=Ha.interval;if(!(0>Xb))for(var Yb=0;Yb<eb;Yb++)if(Yb!==Ga){var fb=Ma[Yb];if(fb.visible&&Ha.constructor===fb.constructor){var Bd=fb.interval;Bd>Xb&&Ad.push(Bd)}}}}a.eh=qa}var eg=a.eh;var fg=a.W.j,Le=fg.length,Db=0,wh=0,gg=w;a.Mj=[];for(var xh,yh=0;yh<Le;yh++){var ab=fg[yh];xh=[];if(ab.visible&&ab!==h){var Hi=Math.abs(ab.interval), ik=a.graduatedTickUnit;if(!(2>ik*Hi*w/a.graduatedRange)){var hg=v[0][0],md=0,mc=0;wh=w*ab.graduatedStart-1E-4;gg=w*ab.graduatedEnd+1E-4;var Ef=ik*Hi,wc=a.graduatedTickBase;if(wc<a.graduatedMin){var ig=(a.graduatedMin-wc)/Ef;ig=0===ig%1?ig:Math.floor(ig+1);wc+=ig*Ef}else wc>a.graduatedMin+Ef&&(wc-=Math.floor((wc-a.graduatedMin)/Ef)*Ef);for(var zh=eg[yh],Bn=wc,Jd=1;wc<a.graduatedMax+5E-8;Jd++){a:{for(var le=zh.length,jg=0;jg<le;jg++)if(L.aa((wc-a.graduatedTickBase)%(zh[jg]*a.graduatedTickUnit),0)){var kg= !1;break a}kg=!0}if(kg&&(null===ab.graduatedSkip||!ab.graduatedSkip(wc))&&(Db=(wc-a.graduatedMin)*w/a.graduatedRange,Db>w&&(Db=w),wh<=Db&&Db<=gg)){for(var Wc=C[md][mc],me=v[md][mc];md<v.length;){for(;Db>hg&&mc<v[md].length-1;)mc++,Wc=C[md][mc],me=v[md][mc],hg+=me;if(Db<=hg)break;md++;mc=0;Wc=C[md][mc];me=v[md][mc];hg+=me}var dc=u[md],Ah=dc[2*mc],Bh=dc[2*mc+1],Xc=(Db-(hg-me))/me,Ii=new I(Ah+(dc[2*mc+2]-Ah)*Xc+q/2-r.bounds.x,Bh+(dc[2*mc+3]-Bh)*Xc+q/2-r.bounds.y);Ii.scale(h.scale,h.scale);var ne=Wc, ff=C[md];1E-4>Xc?0<mc?ne=ff[mc-1]:L.aa(dc[0],dc[dc.length-2])&&L.aa(dc[1],dc[dc.length-1])&&(ne=ff[ff.length-1]):.9999<Xc&&(mc+1<ff.length?ne=ff[mc+1]:L.aa(dc[0],dc[dc.length-2])&&L.aa(dc[1],dc[dc.length-1])&&(ne=ff[0]));Wc!==ne&&(180<Math.abs(Wc-ne)&&(Wc<ne?Wc+=360:ne+=360),Wc=(Wc+ne)/2%360);if(ab instanceof Yg){var Cd="";null!==ab.graduatedFunction?(Cd=ab.graduatedFunction(wc),Cd=null!==Cd&&void 0!==Cd?Cd.toString():""):Cd=(+wc.toFixed(2)).toString();""!==Cd&&xh.push({Jm:Ii,angle:Wc,text:Cd})}else xh.push({Jm:Ii, angle:Wc})}wc=Bn+Jd*Ef}}}a.Mj.push(xh)}Ia(C);var jk=a.Mj;if(null!==jk)for(var Cn=d.length,Ff=0;Ff<Cn;Ff++){var Eb=d[Ff],Kd=jk[Ff];if(Eb.visible&&Eb!==h&&0!==Kd.length){if(Eb instanceof Mf){var gb=a,Ji=e,Zb=Eb.alignmentFocus;Zb.nc()&&(Zb=yc);var xc=Eb.angle;Eb.Yb=0;Eb.measure(Infinity,Infinity,0,0);Eb.Yb=xc;var nc=Eb.measuredBounds,Ld=nc.width,Md=nc.height,lg=N.allocAt(0,0,Ld,Md),Ec=I.alloc();Ec.tj(lg,Zb);N.free(lg);for(var Ch=-Ec.x,mg=-Ec.y,Nd=new N,Dh=Kd.length,gf=0;gf<Dh;gf++)for(var Od=Kd[gf], Pd=Od.Jm.x,Qd=Od.Jm.y,Me=Od.angle,Eh=0;4>Eh;Eh++){switch(Eh){case 0:Ec.h(Ch,mg);break;case 1:Ec.h(Ch+Ld,mg);break;case 2:Ec.h(Ch,mg+Md);break;case 3:Ec.h(Ch+Ld,mg+Md)}Ec.rotate(Me+Eb.angle);Ec.offset(Pd,Qd);0===gf&&0===Eh?Nd.h(Ec.x,Ec.y,0,0):Nd.Pe(Ec);Ec.offset(-Pd,-Qd);Ec.rotate(-Me-Eb.angle)}I.free(Ec);null!==gb.dh&&gb.dh.push(Nd);gc(Ji,Nd.x,Nd.y,Nd.width,Nd.height)}else if(Eb instanceof Yg){var oe=a,Dn=e;null===oe.yh&&(oe.yh=new Yg);var ec=oe.yh;Vm(ec,Eb);var Oa=Eb.alignmentFocus;Oa.nc()&&(Oa= yc);for(var fc=Eb.segmentOrientation,Rd=Eb.segmentOffset,Ne=new N,Fh=0,Oe=0,Oc=0,hf=0,Gh=0,En=Kd.length,ng=0;ng<En;ng++){var nd=Kd[ng];Fh=nd.Jm.x;Oe=nd.Jm.y;Oc=nd.angle;Gh=hf=Eb.angle;fc!==cg&&(Gh=fc===Wm||fc===Xm?Oc+Eb.angle:Oc,hf=S.computeAngle(fc,Gh));ec.Yb=hf;ec.text=nd.text||"";ec.measure(Infinity,Infinity,0,0);var Sd=ec.measuredBounds,pe=ec.naturalBounds,qe=pe.width,Td=pe.height,re=rd.alloc();re.reset();re.translate(-Sd.x,-Sd.y);re.scale(ec.scale,ec.scale);re.rotate(Gh,qe/2,Td/2);fc!==Pm&&fc!== Qm||re.rotate(90,qe/2,Td/2);fc!==Rm&&fc!==Sm||re.rotate(-90,qe/2,Td/2);fc===Tm&&(45<Oc&&135>Oc||225<Oc&&315>Oc)&&re.rotate(-Oc,qe/2,Td/2);var kk=N.allocAt(0,0,qe,Td),Pe=I.alloc();Pe.tj(kk,Oa);re.sa(Pe);var Ki=-Pe.x,Fn=-Pe.y,od=I.alloc();od.assign(Rd);isNaN(od.x)&&(od.x=qe/2+3);isNaN(od.y)&&(od.y=-(Td/2+3));od.rotate(Oc);Fh+=od.x+Ki;Oe+=od.y+Fn;var Gf=new N(Fh,Oe,Sd.width,Sd.height),Hh=new N(Sd.x,Sd.y,Sd.width,Sd.height),og=new N(pe.x,pe.y,pe.width,pe.height);nd.DA=hf;nd.lineCount=ec.lineCount;nd.lines= [ec.ub,ec.Di,ec.pe,ec.Ce,ec.Qb,ec.lb,ec.ne];nd.actualBounds=Gf;nd.measuredBounds=Hh;nd.naturalBounds=og;0===ng?Ne.assign(Gf):Ne.Tc(Gf);I.free(od);I.free(Pe);N.free(kk);rd.free(re)}null!==oe.dh&&oe.dh.push(Ne);gc(Dn,Ne.x,Ne.y,Ne.width,Ne.height)}pj(Eb,!1)}}}; Um.prototype.arrange=function(a,b,c){if(null!==a.dh){var d=a.rb(),e=a.Mj;if(null!==e){var f=a.dh,g=0,h=f[g];g++;null!==d&&d.arrange(h.x-c.x,h.y-c.y,h.width,h.height);for(var k=b.length,l=0;l<k;l++){var m=b[l];h=e[l];m.visible&&m!==d&&0!==h.length&&(h=f[g],g++,m.arrange(h.x-c.x,h.y-c.y,h.width,h.height))}a.dh=null}}}; Um.prototype.cc=function(a,b,c){var d=c.xi;c.xi=!0;var e=a.naturalBounds,f=e.width;e=e.height;b.save();b.beginPath();b.rect(-1,-1,f+1,e+1);b.clip();f=a.rb();f.cc(b,c);e=a.Cf()*c.scale;0>=e&&(e=1);for(var g=f.actualBounds,h=a.W.j,k=a.Mj,l=h.length,m=0;m<l;m++){var n=h[m],p=k[m],r=p.length;if(n.visible&&n!==f&&0!==p.length)if(n instanceof Mf){if(!(2>a.graduatedTickUnit*n.interval*f.geometry.flattenedTotalLength/a.graduatedRange*e)){var q=n.measuredBounds,u=n.strokeWidth*n.scale,v=n.alignmentFocus;v.nc()&& (v=yc);for(var w=0;w<r;w++){var y=p[w].Jm,z=p[w].angle,A=v,C=n.qb;C.reset();C.translate(y.x+g.x,y.y+g.y);C.rotate(z+n.angle,0,0);C.translate(-q.width*A.x+A.offsetX+u/2,-q.height*A.y+A.offsetY+u/2);C.scale(n.scale,n.scale);Dl(n,!1);n.Yh.set(n.qb);n.ql=n.scale;El(n,!1);n.cc(b,c);n.qb.reset()}}}else if(n instanceof Yg)for(null===a.yh&&(a.yh=new Yg),q=a.yh,Vm(q,n),n=0;n<r;n++)u=p[n],u.actualBounds&&u.measuredBounds&&u.naturalBounds&&(q.Ub=u.text||"",q.Yb=u.DA||0,q.ad=u.lineCount||0,v=u.lines,void 0!== v&&(q.ub=v[0],q.Di=v[1],q.pe=v[2],q.Ce=v[3],q.Qb=v[4],q.lb=v[5],q.ne=v[6]),u.naturalBounds&&(q.rc=u.naturalBounds),u.actualBounds&&(v=u.actualBounds,q.arrange(v.x,v.y,v.width,v.height)),v=u.actualBounds,q.arrange(v.x,v.y,v.width,v.height),w=u.measuredBounds,u=u.naturalBounds,y=q.qb,y.reset(),y.translate(v.x+g.x,v.y+g.y),y.translate(-w.x,-w.y),ll(q,y,u.x,u.y,u.width,u.height),Dl(q,!1),q.Yh.set(q.qb),q.ql=q.scale,El(q,!1),q.cc(b,c))}c.xi=d;b.restore();b.uc(!0)}; function X(a){Y.call(this);this.pa=void 0===a?X.Position:a;null===this.pa&&B("Panel type not specified or PanelLayout not loaded: "+a);this.W=new E;this.ib=sc;this.pa===X.Grid&&(this.isAtomic=!0);this.Kn=Zc;this.Uf=Yk;this.pa===X.Table&&Ym(this);this.mq=Dg;this.ko=Ob;this.lo=Fb;this.ho=0;this.fo=100;this.jo=10;this.io=0;this.ki=this.nb=this.eh=this.dh=this.Mj=null;this.yo=NaN;this.ue=this.Bi=null;this.Kl="category";this.Zd=null;this.yg=new N(NaN,NaN,NaN,NaN);this.yh=this.Gp=this.Ui=null;this.Mg=""} ma(X,Y);function Ym(a){a.Fj=sc;a.Vg=1;a.ri=null;a.pi=null;a.Ug=1;a.Tg=null;a.oi=null;a.vb=[];a.sb=[];a.dk=Zm;a.Cj=Zm;a.Xi=0;a.Fi=0} X.prototype.cloneProtected=function(a){Y.prototype.cloneProtected.call(this,a);a.pa=this.pa;a.ib=this.ib.G();a.Kn=this.Kn.G();a.Uf=this.Uf;if(a.pa===X.Table){a.Fj=this.Fj.G();a.Vg=this.Vg;a.ri=this.ri;a.pi=this.pi;a.Ug=this.Ug;a.Tg=this.Tg;a.oi=this.oi;var b=[];if(0<this.vb.length)for(var c=this.vb,d=c.length,e=0;e<d;e++)if(void 0!==c[e]){var f=c[e].copy();f.sj(a);b[e]=f}a.vb=b;b=[];if(0<this.sb.length)for(c=this.sb,d=c.length,e=0;e<d;e++)void 0!==c[e]&&(f=c[e].copy(),f.sj(a),b[e]=f);a.sb=b;a.dk= this.dk;a.Cj=this.Cj;a.Xi=this.Xi;a.Fi=this.Fi}a.mq=this.mq;a.ko=this.ko.G();a.lo=this.lo.G();a.ho=this.ho;a.fo=this.fo;a.jo=this.jo;a.io=this.io;a.Mj=this.Mj;a.eh=this.eh;a.nb=this.nb;a.ki=this.ki;a.yo=this.yo;a.Bi=this.Bi;a.ue=this.ue;a.Kl=this.Kl;a.yg.assign(this.yg);a.Mg=this.Mg;null!==this.Gp&&(a.Gp=this.Gp)};X.prototype.Af=function(a){Y.prototype.Af.call(this,a);a.W=this.W;for(var b=a.W.j,c=b.length,d=0;d<c;d++)b[d].qg=a;a.Ui=null}; X.prototype.copy=function(){var a=Y.prototype.copy.call(this);if(null!==a){for(var b=this.W.j,c=b.length,d=0;d<c;d++){var e=b[d].copy();e.sj(a);e.ak=null;var f=a.W,g=f.count;f.wb(g,e);f=a.part;if(null!==f){f.Xj=null;null!==e.portId&&f instanceof W&&(f.Mh=!0);var h=a.diagram;null!==h&&h.undoManager.isUndoingRedoing||f.bb(Be,"elements",a,null,e,null,g)}}return a}return null};t=X.prototype;t.toString=function(){return"Panel("+this.type+")#"+mb(this)}; t.hp=function(a){Y.prototype.hp.call(this,a);for(var b=this.W.j,c=b.length,d=0;d<c;d++)b[d].hp(a)}; t.ej=function(a,b){if(this.pa===X.Grid)this.pa.cc(this,a,b);else if(this.pa===X.Graduated)this.pa.cc(this,a,b);else{this.pa===X.Table&&(a.lineCap="butt",$m(this,a,!0,this.vb,!0),$m(this,a,!1,this.sb,!0),an(this,a,!0,this.vb),an(this,a,!1,this.sb),$m(this,a,!0,this.vb,!1),$m(this,a,!1,this.sb,!1));var c=this.isClipping&&this.pa===X.Spot;c&&a.save();for(var d=this.rb(),e=this.W.j,f=e.length,g=0;g<f;g++){var h=e[g];c&&h===d&&(a.clipInsteadOfFill=!0);h.cc(a,b);c&&h===d&&(a.clipInsteadOfFill=!1)}c&&(a.restore(), a.uc(!0))}}; function an(a,b,c,d){for(var e=d.length,f=a.actualBounds,g=a.naturalBounds,h=!0,k=0;k<e;k++){var l=d[k];if(void 0!==l)if(h)h=!1;else if(0!==l.actual){if(c){if(l.position>f.height)continue}else if(l.position>f.width)continue;var m=l.separatorStrokeWidth;isNaN(m)&&(m=c?a.Vg:a.Ug);var n=l.separatorStroke;null===n&&(n=c?a.ri:a.Tg);if(0!==m&&null!==n){oi(a,b,n,!1,!1,g,f);n=!1;var p=l.separatorDashArray;null===p&&(p=c?a.pi:a.oi);null!==p&&(n=!0,b.Gt(p,0));b.beginPath();p=l.position+m;c?p>f.height&&(m-= p-f.height):p>f.width&&(m-=p-f.width);l=l.position+m/2;b.lineWidth=m;m=a.ib;c?(l+=m.top,p=f.width-m.right,b.moveTo(m.left,l),b.lineTo(p,l)):(l+=m.left,p=f.height-m.bottom,b.moveTo(l,m.top),b.lineTo(l,p));b.stroke();n&&b.Et()}}}} function $m(a,b,c,d,e){for(var f=d.length,g=a.actualBounds,h=a.naturalBounds,k=0;k<f;k++){var l=d[k];if(void 0!==l&&null!==l.background&&l.coversSeparators!==e&&0!==l.actual){var m=c?g.height:g.width;if(!(l.position>m)){var n=l.wc(),p=l.separatorStrokeWidth;isNaN(p)&&(p=c?a.Vg:a.Ug);var r=l.separatorStroke;null===r&&(r=c?a.ri:a.Tg);null===r&&(p=0);n-=p;p=l.position+p;n+=l.actual;p+n>m&&(n=m-p);0>=n||(m=a.ib,oi(a,b,l.background,!0,!1,h,g),c?b.fillRect(m.left,p+m.top,g.width-(m.left+m.right),n):b.fillRect(p+ m.left,m.top,n,g.height-(m.top+m.bottom)))}}}}function Xj(a){return"LineV"===a||"BarV"===a} t.yk=function(a,b,c,d,e){var f=this.ie(),g=this.transform,h=1/(g.m11*g.m22-g.m12*g.m21),k=g.m22*h,l=-g.m12*h,m=-g.m21*h,n=g.m11*h,p=h*(g.m21*g.dy-g.m22*g.dx),r=h*(g.m12*g.dx-g.m11*g.dy);if(null!==this.areaBackground)return g=this.actualBounds,L.Ef(g.left,g.top,g.right,g.bottom,a,b,c,d,e);if(null!==this.background)return f=a*k+b*m+p,h=a*l+b*n+r,a=c*k+d*m+p,k=c*l+d*n+r,e.h(0,0),c=this.naturalBounds,f=L.Ef(0,0,c.width,c.height,f,h,a,k,e),e.transform(g),f;f||(k=1,m=l=0,n=1,r=p=0);h=a*k+b*m+p;a=a*l+b* n+r;k=c*k+d*m+p;c=c*l+d*n+r;e.h(k,c);d=(k-h)*(k-h)+(c-a)*(c-a);l=!1;n=this.W.j;r=n.length;m=I.alloc();p=null;b=Infinity;var q=null,u=this.isClipping&&this.pa===X.Spot;u&&(q=I.alloc(),p=this.rb(),(l=p.yk(h,a,k,c,q))&&(b=(h-q.x)*(h-q.x)+(a-q.y)*(a-q.y)));for(var v=0;v<r;v++){var w=n[v];w.visible&&w!==p&&w.yk(h,a,k,c,m)&&(l=!0,w=(h-m.x)*(h-m.x)+(a-m.y)*(a-m.y),w<d&&(d=w,e.set(m)))}u&&(b>d&&e.set(q),I.free(q));I.free(m);f&&e.transform(g);return l}; t.o=function(a){if(!uj(this)){Y.prototype.o.call(this,a);a=null;if(this.pa===X.Auto||this.pa===X.Link)a=this.rb();for(var b=this.W.j,c=b.length,d=0;d<c;d++){var e=b[d];(e===a||e.isPanelMain)&&e.o(!0);if(!e.desiredSize.s()){var f=nl(e,!1);(e instanceof zg||e instanceof X||e instanceof Yg||f!==Bg)&&e.o(!0)}}}};t.Ak=function(){if(!uj(this)){pj(this,!0);ol(this,!0);for(var a=this.W.j,b=a.length,c=0;c<b;c++)a[c].Ak()}}; t.Gl=function(){if(0!==(this.F&2048)===!1){Dl(this,!0);El(this,!0);for(var a=this.W.j,b=a.length,c=0;c<b;c++)a[c].cw()}};t.cw=function(){El(this,!0);for(var a=this.W.j,b=a.length,c=0;c<b;c++)a[c].cw()}; t.Gm=function(a,b,c,d){var e=this.yg;e.h(0,0,0,0);var f=this.desiredSize,g=this.minSize;void 0===c&&(c=g.width,d=g.height);c=Math.max(c,g.width);d=Math.max(d,g.height);var h=this.maxSize;isNaN(f.width)||(a=Math.min(f.width,h.width));isNaN(f.height)||(b=Math.min(f.height,h.height));a=Math.max(c,a);b=Math.max(d,b);var k=this.ib;a=Math.max(a-k.left-k.right,0);b=Math.max(b-k.top-k.bottom,0);var l=this.W.j;0!==l.length&&this.pa.measure(this,a,b,l,e,c,d);a=e.width+k.left+k.right;k=e.height+k.top+k.bottom; isFinite(f.width)&&(a=f.width);isFinite(f.height)&&(k=f.height);a=Math.min(h.width,a);k=Math.min(h.height,k);a=Math.max(g.width,a);k=Math.max(g.height,k);a=Math.max(c,a);k=Math.max(d,k);Ub(e,a,k);Ub(this.naturalBounds,a,k);kl(this,0,0,a,k)};t.rb=function(){if(null===this.Ui){var a=this.W.j,b=a.length;if(0===b)return null;for(var c=0;c<b;c++){var d=a[c];if(!0===d.isPanelMain)return this.Ui=d}this.Ui=a[0]}return this.Ui};function ym(a){return null!==a.part?a.part.locationObject:null} t.Hh=function(a,b,c,d){var e=this.W.j;this.actualBounds.h(a,b,c,d);if(0!==e.length){if(!this.desiredSize.s()){a=nl(this,!0);var f=this.measuredBounds;b=f.width;f=f.height;var g=this.jh,h=g.left+g.right;g=g.top+g.bottom;b===c&&f===d&&(a=Bg);switch(a){case Bg:if(b>c||f>d)this.o(),this.measure(b>c?c:b,f>d?d:f,0,0);break;case vd:this.o(!0);this.measure(c+h,d+g,0,0);break;case Zk:this.o(!0);this.measure(c+h,f+g,0,0);break;case $k:this.o(!0),this.measure(b+h,d+g,0,0)}}this.pa.arrange(this,e,this.yg)}}; t.Jh=function(a){var b=this.naturalBounds,c=ym(this);if(hc(0,0,b.width,b.height,a.x,a.y)){b=this.W.j;for(var d=b.length,e=I.allocAt(0,0);d--;){var f=b[d];if(f.visible||f===c)if(yb(e.set(a),f.transform),f.$(e))return I.free(e),!0}I.free(e);return null===this.mb&&null===this.ec?!1:!0}return!1};t.Ht=function(a){if(this.dl===a)return this;for(var b=this.W.j,c=b.length,d=0;d<c;d++){var e=b[d].Ht(a);if(null!==e)return e}return null}; t.Zm=function(a,b){b(this,a);if(a instanceof X){a=a.W.j;for(var c=a.length,d=0;d<c;d++)this.Zm(a[d],b)}};function Hj(a,b){bn(a,a,b)}function bn(a,b,c){c(b);b=b.W.j;for(var d=b.length,e=0;e<d;e++){var f=b[e];f instanceof X&&bn(a,f,c)}}function cn(a,b){dn(a,a,b)}function dn(a,b,c){c(b);if(b instanceof X){b=b.W.j;for(var d=b.length,e=0;e<d;e++)dn(a,b[e],c)}}t.xm=function(a){return en(this,this,a)}; function en(a,b,c){if(c(b))return b;if(b instanceof X){b=b.W.j;for(var d=b.length,e=0;e<d;e++){var f=en(a,b[e],c);if(null!==f)return f}}return null}t.ab=function(a){if(this.name===a)return this;var b=this.W.j,c=b.length;null===this.Bi&&null===this.ue||(c=fn(this));for(var d=0;d<c;d++){var e=b[d];if(e instanceof X){var f=e.ab(a);if(null!==f)return f}if(e.name===a)return e}return null}; function gn(a){a=a.W.j;for(var b=a.length,c=0,d=0;d<b;d++){var e=a[d];e instanceof X?c=Math.max(c,gn(e)):e instanceof Mf&&(c=Math.max(c,e.wh/2*e.gk*e.Cf()))}return c}t.ie=function(){return!(this.type===X.TableRow||this.type===X.TableColumn)}; t.Vb=function(a,b,c){if(!1===this.pickable)return null;void 0===b&&(b=null);void 0===c&&(c=null);if(vj(this))return null;var d=this.naturalBounds,e=1/this.Cf(),f=this.ie(),g=f?a:yb(I.allocAt(a.x,a.y),this.transform),h=this.diagram,k=10,l=5;null!==h&&(k=h.Bm("extraTouchArea"),l=k/2);if(hc(-(l*e),-(l*e),d.width+k*e,d.height+k*e,g.x,g.y)){if(!this.isAtomic){e=this.W.j;var m=e.length;h=I.alloc();l=(k=this.isClipping&&this.pa===X.Spot)?this.rb():null;if(k&&(l.ie()?yb(h.set(a),l.transform):h.set(a),!l.$(h)))return I.free(h), f||I.free(g),null;for(var n=ym(this);m--;){var p=e[m];if(p.visible||p===n)if(p.ie()?yb(h.set(a),p.transform):h.set(a),!k||p!==l){var r=null;p instanceof X?r=p.Vb(h,b,c):!0===p.pickable&&p.$(h)&&(r=p);if(null!==r&&(null!==b&&(r=b(r)),null!==r&&(null===c||c(r))))return I.free(h),f||I.free(g),r}}I.free(h)}if(null===this.background&&null===this.areaBackground)return f||I.free(g),null;a=hc(0,0,d.width,d.height,g.x,g.y)?this:null;f||I.free(g);return a}f||I.free(g);return null}; t.hj=function(a,b,c,d){if(!1===this.pickable)return!1;void 0===b&&(b=null);void 0===c&&(c=null);var e=this.naturalBounds,f=this.ie(),g=f?a:yb(I.allocAt(a.x,a.y),this.transform);e=hc(0,0,e.width,e.height,g.x,g.y);if(this.type===X.TableRow||this.type===X.TableColumn||e){if(!this.isAtomic){for(var h=this.W.j,k=h.length,l=I.alloc(),m=ym(this);k--;){var n=h[k];if(n.visible||n===m){n.ie()?yb(l.set(a),n.transform):l.set(a);var p=n;n=n instanceof X?n:null;(null!==n?n.hj(l,b,c,d):p.$(l))&&!1!==p.pickable&& (null!==b&&(p=b(p)),null===p||null!==c&&!c(p)||d.add(p))}}I.free(l)}f||I.free(g);return e&&(null!==this.background||null!==this.areaBackground)}f||I.free(g);return!1}; t.Bf=function(a,b,c,d,e,f){if(!1===this.pickable)return!1;void 0===b&&(b=null);void 0===c&&(c=null);var g=f;void 0===f&&(g=rd.alloc(),g.reset());g.multiply(this.transform);if(this.Ih(a,g))return hn(this,b,c,e),void 0===f&&rd.free(g),!0;if(this.Oc(a,g)){if(!this.isAtomic)for(var h=ym(this),k=this.W.j,l=k.length;l--;){var m=k[l];if(m.visible||m===h){var n=m.actualBounds,p=this.naturalBounds;if(!(n.x>p.width||n.y>p.height||0>n.x+n.width||0>n.y+n.height)){n=m;m=m instanceof X?m:null;p=rd.alloc();p.set(g); if(null!==m?m.Bf(a,b,c,d,e,p):ml(n,a,d,p))null!==b&&(n=b(n)),null===n||null!==c&&!c(n)||e.add(n);rd.free(p)}}}void 0===f&&rd.free(g);return d}void 0===f&&rd.free(g);return!1};function hn(a,b,c,d){for(var e=a.W.j,f=e.length;f--;){var g=e[f];if(g.visible){var h=g.actualBounds,k=a.naturalBounds;h.x>k.width||h.y>k.height||0>h.x+h.width||0>h.y+h.height||(g instanceof X&&hn(g,b,c,d),null!==b&&(g=b(g)),null===g||null!==c&&!c(g)||d.add(g))}}} t.Fg=function(a,b,c,d,e,f){if(!1===this.pickable)return!1;void 0===c&&(c=null);void 0===d&&(d=null);var g=this.naturalBounds,h=this.ie(),k=h?a:yb(I.allocAt(a.x,a.y),this.transform),l=h?b:yb(I.allocAt(b.x,b.y),this.transform),m=k.Ie(l),n=0<k.x&&k.x<g.width&&0<k.y&&k.y<g.height||zb(k.x,k.y,0,0,0,g.height)<=m||zb(k.x,k.y,0,g.height,g.width,g.height)<=m||zb(k.x,k.y,g.width,g.height,g.width,0)<=m||zb(k.x,k.y,g.width,0,0,0)<=m;g=k.rd(0,0)<=m&&k.rd(0,g.height)<=m&&k.rd(g.width,0)<=m&&k.rd(g.width,g.height)<= m;h||(I.free(k),I.free(l));if(n){if(!this.isAtomic){k=I.alloc();l=I.alloc();m=ym(this);for(var p=this.W.j,r=p.length;r--;){var q=p[r];if(q.visible||q===m){var u=q.actualBounds,v=this.naturalBounds;if(!h||!(u.x>v.width||u.y>v.height||0>u.x+u.width||0>u.y+u.height))if(q.ie()?(u=q.transform,yb(k.set(a),u),yb(l.set(b),u)):(k.set(a),l.set(b)),u=q,q=q instanceof X?q:null,null!==q?q.Fg(k,l,c,d,e,f):u.sy(k,l,e))null!==c&&(u=c(u)),null===u||null!==d&&!d(u)||f.add(u)}}I.free(k);I.free(l)}return e?n:g}return!1}; function Dm(a){var b=null;a instanceof Mf&&(b=a.spot1,b===Zc&&(b=null),a=a.geometry,null!==a&&null===b&&(b=a.spot1));null===b&&(b=vc);return b}function Em(a){var b=null;a instanceof Mf&&(b=a.spot2,b===Zc&&(b=null),a=a.geometry,null!==a&&null===b&&(b=a.spot2));null===b&&(b=Gc);return b}t.add=function(a){this.wb(this.W.count,a)};t.J=function(a){return this.W.J(a)}; t.wb=function(a,b){b instanceof V&&B("Cannot add a Part to a Panel: "+b+"; use a Panel instead");if(this===b||this.Hg(b))this===b&&B("Cannot make a Panel contain itself: "+this.toString()),B("Cannot make a Panel indirectly contain itself: "+this.toString()+" already contains "+b.toString());var c=b.panel;null!==c&&c!==this&&B("Cannot add a GraphObject that already belongs to another Panel to this Panel: "+b.toString()+", already contained by "+c.toString()+", cannot be shared by this Panel: "+this.toString()); this.pa!==X.Grid||b instanceof Mf||B("Can only add Shapes to a Grid Panel, not: "+b);this.pa!==X.Graduated||b instanceof Mf||b instanceof Yg||B("Can only add Shapes or TextBlocks to a Graduated Panel, not: "+b);b.sj(this);b.ak=null;if(null!==this.itemArray){var d=b.data;null!==d&&"object"===typeof d&&(null===this.Zd&&(this.Zd=new H),this.Zd.add(d,b))}var e=this.W;d=-1;if(c===this){for(var f=-1,g=this.W.j,h=g.length,k=0;k<h;k++)if(g[k]===b){f=k;break}if(-1!==f){if(f===a||f+1>=e.count&&a>=e.count)return; e.cb(f);d=f}else B("element "+b.toString()+" has panel "+c.toString()+" but is not contained by it.")}if(0>a||a>e.count)a=e.count;e.wb(a,b);if(0===a||b.isPanelMain)this.Ui=null;uj(this)||this.o();b.o(!1);null!==b.portId?this.Mh=!0:b instanceof X&&!0===b.Mh&&(this.Mh=!0);this.eh=null;c=this.part;null!==c&&(c.Xj=null,c.kh=NaN,this.Mh&&c instanceof W&&(c.Mh=!0),c.Mh&&c instanceof W&&(c.tc=null),e=this.diagram,null!==e&&e.undoManager.isUndoingRedoing||(-1!==d&&c.bb(Ce,"elements",this,b,null,d,null),c.bb(Be, "elements",this,null,b,null,a),this.Ig()||jn(this,b,!1)))};function kn(a,b){a.F=b?a.F|16777216:a.F&-16777217}t.remove=function(a){for(var b=this.W.j,c=b.length,d=-1,e=0;e<c;e++)if(b[e]===a){d=e;break}-1!==d&&this.Nc(d,!0)};t.cb=function(a){0<=a&&this.Nc(a,!0)}; t.Nc=function(a,b){var c=this.W,d=c.J(a);d.ak=null;d.sj(null);if(null!==this.Zd){var e=d.data;"object"===typeof e&&this.Zd.remove(e)}c.cb(a);pj(this,!1);this.o();this.Ui===d&&(this.Ui=null);this.eh=null;var f=this.part;null!==f&&(f.Xj=null,f.kh=NaN,f.Mb(),f instanceof W&&(d instanceof X?d.Zm(d,function(a,c){Ul(f,c,b)}):Ul(f,d,b)),c=this.diagram,null!==c&&c.undoManager.isUndoingRedoing||f.bb(Ce,"elements",this,d,null,a,null))}; X.prototype.getRowDefinition=function(a){0>a&&wa(a,">= 0",X,"getRowDefinition:idx");a=Math.round(a);var b=this.vb;if(void 0===b)return null;if(void 0===b[a]){var c=new Vj;c.sj(this);c.isRow=!0;c.index=a;b[a]=c}return b[a]};X.prototype.vw=function(a){0>a&&wa(a,">= 0",X,"removeRowDefinition:idx");a=Math.round(a);var b=this.vb;void 0!==b&&(this.bb(Ce,"coldefs",this,b[a],null,a,null),b[a]&&delete b[a],this.o())}; X.prototype.getColumnDefinition=function(a){0>a&&wa(a,">= 0",X,"getColumnDefinition:idx");a=Math.round(a);var b=this.sb;if(void 0===b)return null;if(void 0===b[a]){var c=new Vj;c.sj(this);c.isRow=!1;c.index=a;b[a]=c}return b[a]};t=X.prototype;t.tw=function(a){0>a&&wa(a,">= 0",X,"removeColumnDefinition:idx");a=Math.round(a);var b=this.sb;void 0!==b&&(this.bb(Ce,"coldefs",this,b[a],null,a,null),b[a]&&delete b[a],this.o())}; t.aA=function(a){if(0>a||this.type!==X.Table)return-1;for(var b=0,c=this.vb,d=c.length,e=this.Xi;e<d;e++){var f=c[e];if(void 0!==f&&(b+=f.total,a<b))break}return e};t.Tz=function(a){if(0>a||this.type!==X.Table)return-1;for(var b=0,c=this.sb,d=c.length,e=this.Fi;e<d;e++){var f=c[e];if(void 0!==f&&(b+=f.total,a<b))break}return e}; t.qA=function(a,b){void 0===b&&(b=new I(NaN,NaN));if(this.type!==X.Graduated)return b.h(NaN,NaN),b;a=Math.min(Math.max(a,this.graduatedMin),this.graduatedMax);var c=this.rb();c.geometry.Wv((a-this.graduatedMin)/this.graduatedRange,b);return c.transform.sa(b)};t.rA=function(a){if(this.type!==X.Graduated)return NaN;var b=this.rb();b.transform.Jd(a);return b.geometry.wy(a)*this.graduatedRange+this.graduatedMin};function Ll(a){a=a.ki;return null!==a&&a.u} function Ag(a){var b=a.ki;if(null===b)null!==a.data&&B("Template cannot have .data be non-null: "+a),a.ki=b=new E;else if(b.u)return;var c=new E;kn(a,!1);a.Zm(a,function(a,d){var e=d.fb;if(null!==e)for(Il(d,!1),e=e.iterator;e.next();){var f=e.value;f.mode===ln&&Il(d,!0);var g=f.sourceName;null!==g&&("/"===g&&kn(a,!0),g=jl(f,a,d),null!==g&&(c.add(g),null===g.hm&&(g.hm=new E),g.hm.add(f)));b.add(f)}if(d instanceof X&&d.type===X.Table){if(0<d.vb.length)for(a=d.vb,e=a.length,f=0;f<e;f++)if(g=a[f],void 0!== g&&null!==g.fb)for(var h=g.fb.iterator;h.next();){var k=h.value;k.qd=g;k.eq=2;k.nm=g.index;b.add(k)}if(0<d.sb.length)for(d=d.sb,a=d.length,e=0;e<a;e++)if(f=d[e],void 0!==f&&null!==f.fb)for(g=f.fb.iterator;g.next();)h=g.value,h.qd=f,h.eq=1,h.nm=f.index,b.add(h)}});for(var d=c.iterator;d.next();){var e=d.value;if(null!==e.hm){Il(e,!0);for(var f=e.hm.iterator;f.next();){var g=f.value;null===e.fb&&(e.fb=new E);e.fb.add(g)}}e.hm=null}for(d=b.iterator;d.next();)if(e=d.value,f=e.qd,null!==f){e.qd=null;var h= e.targetProperty,k=h.indexOf(".");0<k&&f instanceof X&&(g=h.substring(0,k),h=h.substr(k+1),k=f.ab(g),null!==k?(f=k,e.targetProperty=h):xa('Warning: unable to find GraphObject named "'+g+'" for Binding: '+e.toString()));f instanceof Vj?(g=mb(f.panel),e.wj=void 0===g?-1:g,f.panel.dl=e.wj):f instanceof Y?(g=mb(f),e.wj=void 0===g?-1:g,f.dl=e.wj):B("Unknown type of binding target: "+f)}b.freeze();a instanceof V&&a.Pc()&&a.Ta()} t.Gz=function(a){void 0===a&&(a=!1);var b=this.copy();cn(b,function(a){a instanceof X&&(a.ki=null,a.nb=null);var b=a.fb;null!==b&&(a.fb=null,b.each(function(b){a.bind(b.copy())}));b=a.Ng;null!==b&&(a.Ng=null,b.each(function(b){a.Rw(b.value.copy())}))});a&&Ag(b);return b}; t.Ca=function(a){var b=this.ki;if(null!==b)for(void 0===a&&(a=""),b=b.iterator;b.next();){var c=b.value,d=c.sourceProperty;if(""===a||""===d||d===a)if(d=c.targetProperty,null!==c.converter||""!==d){d=this.data;var e=c.sourceName;if(null!==e)d=""===e?this:"/"===e?this:"."===e?this:".."===e?this:this.ab(e);else{var f=this.diagram;null!==f&&c.isToModel&&(d=f.model.modelData)}if(null!==d){f=this;var g=c.wj;if(-1!==g){if(f=this.Ht(g),null===f)continue}else null!==c.qd&&(f=c.qd);"/"===e?d=f.part:"."=== e?d=f:".."===e&&(d=f.panel);e=c.eq;if(0!==e){if(!(f instanceof X))continue;1===e?f=f.getColumnDefinition(c.nm):2===e&&(f=f.getRowDefinition(c.nm))}void 0!==f&&c.Uw(f,d)}}}};function mn(a,b){a=a.W.j;for(var c=a.length,d=b.length,e=0,f=null;e<c&&!(f=a[e],f instanceof X&&null!==f.data);)e++,f=a[e];if(c-e!==d)return!0;if(null===f)return 0<d;for(var g=0;e<c&&g<d;){f=a[e];if(!(f instanceof X)||f.data!==b[g])return!0;e++;g++}return!1} function fn(a){if(a.type===X.Spot||a.type===X.Auto)return Math.min(a.W.length,1);if(a.type===X.Link){a=a.W;for(var b=a.length,c=0;c<b;c++){var d=a.J(c);if(!(d instanceof Mf&&d.isPanelMain))break}return c}return a.type===X.Table&&0<a.W.length&&(a=a.W.J(0),a.isPanelMain&&a instanceof X&&(a.type===X.TableRow||a.type===X.TableColumn))?1:0}t.eu=function(){for(var a=fn(this);this.W.length>a;)this.Nc(this.W.length-1,!1);a=this.itemArray;if(null!==a)for(var b=a.length,c=0;c<b;c++)nn(this,a[c],c)}; t.qy=function(a){return void 0===a||null===a||null===this.Zd?null:this.Zd.H(a)}; function nn(a,b,c){if(!(void 0===b||null===b||0>c)){var d=on(a,b),e=a.itemTemplateMap,f=null;null!==e&&(f=e.H(d));null===f&&(pn||(pn=!0,xa('No item template Panel found for category "'+d+'" on '+a),xa(" Using default item template."),d=new X,e=new Yg,e.bind(new Ni("text","",Ka)),d.add(e),qn=d),f=qn);d=f;null!==d&&(Ag(d),d=d.copy(),0!==(d.F&16777216)&&(e=a.ij(),null!==e&&kn(e,!0)),"object"===typeof b&&(null===a.Zd&&(a.Zd=new H),a.Zd.add(b,d)),e=c+fn(a),a.wb(e,d),d.nb=b,rn(a,e,c),d.nb=null,d.data= b)}}function rn(a,b,c){for(a=a.W;b<a.length;){var d=a.J(b);if(d instanceof X){var e=b,f=c;d.type===X.TableRow?d.row=e:d.type===X.TableColumn&&(d.column=e);d.itemIndex=f}b++;c++}}function on(a,b){if(null===b)return"";a=a.Kl;if("function"===typeof a)a=a(b);else if("string"===typeof a&&"object"===typeof b){if(""===a)return"";a=sn(b,a)}else return"";if(void 0===a)return"";if("string"===typeof a)return a;B("Panel.getCategoryForItemData found a non-string category for "+b+": "+a);return""} function jn(a,b,c){var d=b.enabledChanged;null!==d&&d(b,c);if(b instanceof X){b=b.W.j;d=b.length;for(var e=0;e<d;e++){var f=b[e];c&&f instanceof X&&!f.isEnabled||jn(a,f,c)}}}function tn(a,b){b.name=a;Pl.add(a,b)} na.Object.defineProperties(X.prototype,{type:{get:function(){return this.pa},set:function(a){var b=this.pa;b!==a&&(this.pa=a,this.pa===X.Grid?this.isAtomic=!0:this.pa===X.Table&&Ym(this),this.o(),this.g("type",b,a))}},elements:{get:function(){return this.W.iterator}},naturalBounds:{get:function(){return this.rc}},padding:{get:function(){return this.ib},set:function(a){"number"=== typeof a?(0>a&&wa(a,">= 0",X,"padding"),a=new oc(a)):(0>a.left&&wa(a.left,">= 0",X,"padding:value.left"),0>a.right&&wa(a.right,">= 0",X,"padding:value.right"),0>a.top&&wa(a.top,">= 0",X,"padding:value.top"),0>a.bottom&&wa(a.bottom,">= 0",X,"padding:value.bottom"));var b=this.ib;b.w(a)||(this.ib=a=a.G(),this.o(),this.g("padding",b,a))}},defaultAlignment:{get:function(){return this.Kn},set:function(a){var b=this.Kn;b.w(a)||(this.Kn=a=a.G(),this.o(),this.g("defaultAlignment", b,a))}},defaultStretch:{get:function(){return this.Uf},set:function(a){var b=this.Uf;b!==a&&(this.Uf=a,this.o(),this.g("defaultStretch",b,a))}},defaultSeparatorPadding:{get:function(){return void 0===this.Fj?sc:this.Fj},set:function(a){if(void 0!==this.Fj){"number"===typeof a&&(a=new oc(a));var b=this.Fj;b.w(a)||(this.Fj=a=a.G(),this.o(),this.g("defaultSeparatorPadding",b,a))}}},defaultRowSeparatorStroke:{get:function(){return void 0=== this.ri?null:this.ri},set:function(a){var b=this.ri;b!==a&&(null===a||"string"===typeof a||a instanceof wl)&&(a instanceof wl&&a.freeze(),this.ri=a,this.M(),this.g("defaultRowSeparatorStroke",b,a))}},defaultRowSeparatorStrokeWidth:{get:function(){return void 0===this.Vg?1:this.Vg},set:function(a){if(void 0!==this.Vg){var b=this.Vg;b!==a&&isFinite(a)&&0<=a&&(this.Vg=a,this.o(),this.g("defaultRowSeparatorStrokeWidth",b,a))}}},defaultRowSeparatorDashArray:{ get:function(){return void 0===this.pi?null:this.pi},set:function(a){if(void 0!==this.pi){var b=this.pi;if(b!==a){if(null!==a){for(var c=a.length,d=0,e=0;e<c;e++){var f=a[e];"number"===typeof f&&0<=f&&isFinite(f)||B("defaultRowSeparatorDashArray value "+f+" at index "+e+" must be a positive number or zero.");d+=f}if(0===d){if(null===b)return;a=null}}this.pi=a;this.M();this.g("defaultRowSeparatorDashArray",b,a)}}}},defaultColumnSeparatorStroke:{get:function(){return void 0=== this.Tg?null:this.Tg},set:function(a){if(void 0!==this.Tg){var b=this.Tg;b!==a&&(null===a||"string"===typeof a||a instanceof wl)&&(a instanceof wl&&a.freeze(),this.Tg=a,this.M(),this.g("defaultColumnSeparatorStroke",b,a))}}},defaultColumnSeparatorStrokeWidth:{get:function(){return void 0===this.Ug?1:this.Ug},set:function(a){if(void 0!==this.Ug){var b=this.Ug;b!==a&&isFinite(a)&&0<=a&&(this.Ug=a,this.o(),this.g("defaultColumnSeparatorStrokeWidth",b,a))}}},defaultColumnSeparatorDashArray:{ get:function(){return void 0===this.oi?null:this.oi},set:function(a){if(void 0!==this.oi){var b=this.oi;if(b!==a){if(null!==a){for(var c=a.length,d=0,e=0;e<c;e++){var f=a[e];"number"===typeof f&&0<=f&&isFinite(f)||B("defaultColumnSeparatorDashArray value "+f+" at index "+e+" must be a positive number or zero.");d+=f}if(0===d){if(null===b)return;a=null}}this.oi=a;this.M();this.g("defaultColumnSeparatorDashArray",b,a)}}}},viewboxStretch:{get:function(){return this.mq}, set:function(a){var b=this.mq;b!==a&&(this.mq=a,this.o(),this.g("viewboxStretch",b,a))}},gridCellSize:{get:function(){return this.ko},set:function(a){var b=this.ko;if(!b.w(a)){a.s()&&0!==a.width&&0!==a.height||B("Invalid Panel.gridCellSize: "+a);this.ko=a.G();var c=this.diagram;null!==c&&this===c.grid&&qj(c);this.M();this.g("gridCellSize",b,a)}}},gridOrigin:{get:function(){return this.lo},set:function(a){var b=this.lo;if(!b.w(a)){a.s()|| B("Invalid Panel.gridOrigin: "+a);this.lo=a.G();var c=this.diagram;null!==c&&this===c.grid&&qj(c);this.M();this.g("gridOrigin",b,a)}}},graduatedMin:{get:function(){return this.ho},set:function(a){var b=this.ho;b!==a&&(this.ho=a,this.o(),this.g("graduatedMin",b,a),hl(this)&&(a=this.part,null!==a&&il(this,a,"graduatedRange")))}},graduatedMax:{get:function(){return this.fo},set:function(a){var b=this.fo;b!==a&&(this.fo=a,this.o(),this.g("graduatedMax", b,a),hl(this)&&(a=this.part,null!==a&&il(this,a,"graduatedRange")))}},graduatedRange:{get:function(){return this.graduatedMax-this.graduatedMin}},graduatedTickUnit:{get:function(){return this.jo},set:function(a){var b=this.jo;b!==a&&0<a&&(this.jo=a,this.o(),this.g("graduatedTickUnit",b,a))}},graduatedTickBase:{get:function(){return this.io},set:function(a){var b=this.io;b!==a&&(this.io=a,this.o(),this.g("graduatedTickBase", b,a))}},Mh:{get:function(){return 0!==(this.F&8388608)},set:function(a){0!==(this.F&8388608)!==a&&(this.F^=8388608)}},rowCount:{get:function(){return void 0===this.vb?0:this.vb.length}},columnCount:{get:function(){return void 0===this.sb?0:this.sb.length}},rowSizing:{get:function(){return void 0===this.dk?Zm:this.dk},set:function(a){if(void 0!==this.dk){var b=this.dk;b!==a&&(this.dk= a,this.o(),this.g("rowSizing",b,a))}}},columnSizing:{get:function(){return void 0===this.Cj?Zm:this.Cj},set:function(a){if(void 0!==this.Cj){var b=this.Cj;b!==a&&(this.Cj=a,this.o(),this.g("columnSizing",b,a))}}},topIndex:{get:function(){return void 0===this.Xi?0:this.Xi},set:function(a){if(void 0!==this.Xi){var b=this.Xi;b!==a&&((!isFinite(a)||0>a)&&B("Panel.topIndex must be greater than zero and a real number, not: "+a),this.Xi=a,this.o(), this.g("topIndex",b,a))}}},leftIndex:{get:function(){return void 0===this.Fi?0:this.Fi},set:function(a){if(void 0!==this.Fi){var b=this.Fi;b!==a&&((!isFinite(a)||0>a)&&B("Panel.leftIndex must be greater than zero and a real number, not: "+a),this.Fi=a,this.o(),this.g("leftIndex",b,a))}}},data:{get:function(){return this.nb},set:function(a){var b=this.nb;if(b!==a){var c=this instanceof V&&!(this instanceof Qe);Ag(this);this.nb=a;var d=this.diagram; null!==d&&(c?(c=d.partManager,this instanceof S?(null!==b&&c.Ue.remove(b),null!==a&&c.Ue.add(a,this)):this instanceof V&&(null!==b&&c.Ve.remove(b),null!==a&&c.Ve.add(a,this))):(c=this.panel,null!==c&&null!==c.Zd&&(null!==b&&c.Zd.remove(b),null!==a&&c.Zd.add(a,this))));this.g("data",b,a);null!==d&&d.undoManager.isUndoingRedoing||null!==a&&this.Ca()}}},itemIndex:{get:function(){return this.yo},set:function(a){var b=this.yo;b!==a&&(this.yo=a,this.g("itemIndex",b,a))}},itemArray:{ get:function(){return this.Bi},set:function(a){var b=this.Bi;if(b!==a||null!==a&&mn(this,a)){var c=this.diagram;b!==a&&(null!==c&&null!==b&&Mj(c.partManager,this,c),this.Bi=a,null!==c&&null!==a&&Jj(c.partManager,this));this.g("itemArray",b,a);null!==c&&c.undoManager.isUndoingRedoing||this.eu()}}},itemTemplate:{get:function(){return null===this.ue?null:this.ue.H("")},set:function(a){if(null===this.ue){if(null===a)return;this.ue=new H}var b=this.ue.H(""); b!==a&&((a instanceof V||a.isPanelMain)&&B("Panel.itemTemplate must not be a Part or be Panel.isPanelMain: "+a),this.ue.add("",a),this.g("itemTemplate",b,a),a=this.diagram,null!==a&&a.undoManager.isUndoingRedoing||this.eu())}},itemTemplateMap:{get:function(){return this.ue},set:function(a){var b=this.ue;if(b!==a){for(var c=a.iterator;c.next(););this.ue=a;this.g("itemTemplateMap",b,a);a=this.diagram;null!==a&&a.undoManager.isUndoingRedoing||this.eu()}}},itemCategoryProperty:{ get:function(){return this.Kl},set:function(a){var b=this.Kl;b!==a&&(this.Kl=a,this.g("itemCategoryProperty",b,a))}},isAtomic:{get:function(){return 0!==(this.F&1048576)},set:function(a){var b=0!==(this.F&1048576);b!==a&&(this.F^=1048576,this.g("isAtomic",b,a))}},isClipping:{get:function(){return 0!==(this.F&2097152)},set:function(a){var b=0!==(this.F&2097152);b!==a&&(!a||this.type===X.Spot||this instanceof U||xa("Warning: Panel.isClipping set on non-Spot Panel: "+ this.toString()),this.F^=2097152,this instanceof U&&(this.Ya=null),this.o(),this.g("isClipping",b,a))}},isOpposite:{get:function(){return 0!==(this.F&33554432)},set:function(a){var b=0!==(this.F&33554432);b!==a&&(this.F^=33554432,this.o(),this.g("isOpposite",b,a))}},isEnabled:{get:function(){return 0!==(this.F&4194304)},set:function(a){var b=0!==(this.F&4194304);if(b!==a){var c=null===this.panel||this.panel.Ig();this.F^=4194304;this.g("isEnabled", b,a);b=this.diagram;null!==b&&b.undoManager.isUndoingRedoing||c&&jn(this,this,a)}}},alignmentFocusName:{get:function(){return this.Mg},set:function(a){var b=this.Mg;b!==a&&(this.Mg=a,this.o(),this.g("alignmentFocusName",b,a))}}}); na.Object.defineProperties(X,{Position:{get:function(){return Pl.H("Position")}},Horizontal:{get:function(){return Pl.H("Horizontal")}},Vertical:{get:function(){return Pl.H("Vertical")}},Spot:{get:function(){return Pl.H("Spot")}},Auto:{get:function(){return Pl.H("Auto")}},Table:{get:function(){return Pl.H("Table")}},Viewbox:{ get:function(){return Pl.H("Viewbox")}},TableRow:{get:function(){return Pl.H("TableRow")}},TableColumn:{get:function(){return Pl.H("TableColumn")}},Link:{get:function(){return Pl.H("Link")}},Grid:{get:function(){return Pl.H("Grid")}},Graduated:{get:function(){return Pl.H("Graduated")}}});X.prototype.findItemPanelForData=X.prototype.qy; X.prototype.rebuildItemElements=X.prototype.eu;X.prototype.updateTargetBindings=X.prototype.Ca;X.prototype.copyTemplate=X.prototype.Gz;X.prototype.graduatedValueForPoint=X.prototype.rA;X.prototype.graduatedPointForValue=X.prototype.qA;X.prototype.findColumnForLocalX=X.prototype.Tz;X.prototype.findRowForLocalY=X.prototype.aA;X.prototype.removeColumnDefinition=X.prototype.tw;X.prototype.removeRowDefinition=X.prototype.vw;X.prototype.removeAt=X.prototype.cb;X.prototype.remove=X.prototype.remove; X.prototype.insertAt=X.prototype.wb;X.prototype.elt=X.prototype.J;X.prototype.add=X.prototype.add;X.prototype.findObject=X.prototype.ab;X.prototype.findInVisualTree=X.prototype.xm;X.prototype.walkVisualTreeFrom=X.prototype.Zm;X.prototype.findMainElement=X.prototype.rb;var pn=!1,qn=null,Pl=new H;X.className="Panel";X.definePanelLayout=tn;tn("Position",new xm);tn("Vertical",new Am);tn("Auto",new Cm);tn("Link",new Nm); function Vj(){Za(this);this.qg=null;this.os=!0;this.Pa=0;this.cd=NaN;this.nh=0;this.lh=Infinity;this.zb=Zc;this.la=this.ac=this.ha=0;this.fb=null;this.Vp=un;this.Ee=Yk;this.Pp=this.ug=null;this.Qp=NaN;this.mb=this.fk=null;this.Gn=!1} Vj.prototype.copy=function(){var a=new Vj;a.os=this.os;a.Pa=this.Pa;a.cd=this.cd;a.nh=this.nh;a.lh=this.lh;a.zb=this.zb;a.ha=this.ha;a.ac=this.ac;a.la=this.la;a.Ee=this.Ee;a.Vp=this.Vp;null===this.ug?a.ug=null:a.ug=this.ug.G();a.Pp=this.Pp;a.Qp=this.Qp;a.fk=null;null!==this.fk&&(a.separatorDashArray=Ba(this.separatorDashArray));a.mb=this.mb;a.Gn=this.Gn;a.fb=this.fb;return a};t=Vj.prototype; t.Dt=function(a){a.isRow?this.height=a.height:this.width=a.width;this.minimum=a.minimum;this.maximum=a.maximum;this.alignment=a.alignment;this.stretch=a.stretch;this.sizing=a.sizing;this.ug=null===a.separatorPadding?null:a.separatorPadding.G();this.separatorStroke=a.separatorStroke;this.separatorStrokeWidth=a.separatorStrokeWidth;this.fk=null;a.separatorDashArray&&(this.fk=Ba(a.separatorDashArray));this.background=a.background;this.coversSeparators=a.coversSeparators;this.fb=a.fb}; t.jb=function(a){a.classType===Vj&&(this.sizing=a)};t.toString=function(){return"RowColumnDefinition "+(this.isRow?"(Row ":"(Column ")+this.index+") #"+mb(this)};t.sj=function(a){this.qg=a}; t.Iv=function(){var a=0,b=0,c=this.qg,d=this.isRow;if(null!==c&&c.type===X.Table)for(var e=d?c.vb.length:c.sb.length,f=0;f<e;f++){var g=d?c.vb[f]:c.sb[f];if(void 0!==g){b=g.index;break}}this.index!==b&&(b=this.separatorStroke,null===b&&null!==c&&(b=this.isRow?c.defaultRowSeparatorStroke:c.defaultColumnSeparatorStroke),null!==b&&(a=this.separatorStrokeWidth,isNaN(a)&&(null!==c?a=this.isRow?c.defaultRowSeparatorStrokeWidth:c.defaultColumnSeparatorStrokeWidth:a=0)));b=this.ug;if(null===b)if(null!==c)b= c.defaultSeparatorPadding;else return a;return a+(this.isRow?b.top:b.left)}; t.wc=function(){var a=0,b=this.qg,c=0,d=this.isRow;if(null!==b&&b.type===X.Table)for(var e=d?b.vb.length:b.sb.length,f=0;f<e;f++){var g=d?b.vb[f]:b.sb[f];if(void 0!==g){c=g.index;break}}this.index!==c&&(c=this.separatorStroke,null===c&&null!==b&&(c=d?b.defaultRowSeparatorStroke:b.defaultColumnSeparatorStroke),null!==c&&(a=this.separatorStrokeWidth,isNaN(a)&&(null!==b?a=d?b.defaultRowSeparatorStrokeWidth:b.defaultColumnSeparatorStrokeWidth:a=0)));d=this.ug;if(null===d)if(null!==b)d=b.defaultSeparatorPadding; else return a;return a+(this.isRow?d.top+d.bottom:d.left+d.right)};t.Cb=function(a,b,c){var d=this.qg;if(null!==d&&(d.bb(ze,a,this,b,c,void 0,void 0),null!==this.fb&&(b=d.diagram,null!==b&&!b.skipsModelSourceBindings&&(d=d.ij(),null!==d&&(b=d.data,null!==b)))))for(c=this.fb.iterator;c.next();)c.value.kr(this,b,a,d)};function Gm(a){if(a.sizing===un){var b=a.qg;return a.isRow?b.rowSizing:b.columnSizing}return a.sizing} t.bind=function(a){a.qd=this;var b=this.panel;if(null!==b){var c=b.ij();null!==c&&Ll(c)&&B("Cannot add a Binding to a RowColumnDefinition that is already frozen: "+a+" on "+b)}null===this.fb&&(this.fb=new E);this.fb.add(a)}; na.Object.defineProperties(Vj.prototype,{panel:{get:function(){return this.qg}},isRow:{get:function(){return this.os},set:function(a){this.os=a}},index:{get:function(){return this.Pa},set:function(a){this.Pa=a}},height:{get:function(){return this.cd},set:function(a){var b=this.cd;b!==a&&(0>a&&wa(a,">= 0",Vj,"height"),this.cd=a,this.actual=this.ha,null!==this.panel&&this.panel.o(), this.Cb("height",b,a))}},width:{get:function(){return this.cd},set:function(a){var b=this.cd;b!==a&&(0>a&&wa(a,">= 0",Vj,"width"),this.cd=a,this.actual=this.ha,null!==this.panel&&this.panel.o(),this.Cb("width",b,a))}},minimum:{get:function(){return this.nh},set:function(a){var b=this.nh;b!==a&&((0>a||!isFinite(a))&&wa(a,">= 0",Vj,"minimum"),this.nh=a,this.actual=this.ha,null!==this.panel&&this.panel.o(),this.Cb("minimum",b,a))}},maximum:{ get:function(){return this.lh},set:function(a){var b=this.lh;b!==a&&(0>a&&wa(a,">= 0",Vj,"maximum"),this.lh=a,this.actual=this.ha,null!==this.panel&&this.panel.o(),this.Cb("maximum",b,a))}},alignment:{get:function(){return this.zb},set:function(a){var b=this.zb;b.w(a)||(this.zb=a.G(),null!==this.panel&&this.panel.o(),this.Cb("alignment",b,a))}},stretch:{get:function(){return this.Ee},set:function(a){var b=this.Ee;b!==a&&(this.Ee= a,null!==this.panel&&this.panel.o(),this.Cb("stretch",b,a))}},separatorPadding:{get:function(){return this.ug},set:function(a){"number"===typeof a&&(a=new oc(a));var b=this.ug;null!==a&&null!==b&&b.w(a)||(null!==a&&(a=a.G()),this.ug=a,null!==this.panel&&this.panel.o(),this.Cb("separatorPadding",b,a))}},separatorStroke:{get:function(){return this.Pp},set:function(a){var b=this.Pp;b!==a&&(null!==a&&Tl(a,"RowColumnDefinition.separatorStroke"), a instanceof wl&&a.freeze(),this.Pp=a,null!==this.panel&&this.panel.o(),this.Cb("separatorStroke",b,a))}},separatorStrokeWidth:{get:function(){return this.Qp},set:function(a){var b=this.Qp;b!==a&&(this.Qp=a,null!==this.panel&&this.panel.o(),this.Cb("separatorStrokeWidth",b,a))}},separatorDashArray:{get:function(){return this.fk},set:function(a){var b=this.fk;if(b!==a){if(null!==a){for(var c=a.length,d=0,e=0;e<c;e++){var f=a[e];"number"=== typeof f&&0<=f&&isFinite(f)||B("separatorDashArray value "+f+" at index "+e+" must be a positive number or zero.");d+=f}if(0===d){if(null===b)return;a=null}}this.fk=a;null!==this.panel&&this.panel.M();this.Cb("separatorDashArray",b,a)}}},background:{get:function(){return this.mb},set:function(a){var b=this.mb;b!==a&&(null!==a&&Tl(a,"RowColumnDefinition.background"),a instanceof wl&&a.freeze(),this.mb=a,null!==this.panel&&this.panel.M(),this.Cb("background",b,a))}},coversSeparators:{ get:function(){return this.Gn},set:function(a){var b=this.Gn;b!==a&&(this.Gn=a,null!==this.panel&&this.panel.M(),this.Cb("coversSeparators",b,a))}},sizing:{get:function(){return this.Vp},set:function(a){var b=this.Vp;b!==a&&(this.Vp=a,null!==this.panel&&this.panel.o(),this.Cb("sizing",b,a))}},actual:{get:function(){return this.ha},set:function(a){this.ha=isNaN(this.cd)?Math.max(Math.min(this.lh,a),this.nh):Math.max(Math.min(this.lh, this.cd),this.nh)}},measured:{get:function(){return this.ac},set:function(a){this.ac=a}},total:{get:function(){return this.ha+this.wc()},set:function(a){this.ha=isNaN(this.cd)?Math.max(Math.min(this.lh,a),this.nh):Math.max(Math.min(this.lh,this.cd),this.nh);this.ha=Math.max(0,this.ha-this.wc())}},position:{get:function(){return this.la},set:function(a){this.la=a}}});Vj.prototype.bind=Vj.prototype.bind; Vj.prototype.computeEffectiveSpacing=Vj.prototype.wc;Vj.prototype.computeEffectiveSpacingTop=Vj.prototype.Iv;var un=new D(Vj,"Default",0),Hm=new D(Vj,"None",1),Zm=new D(Vj,"ProportionalExtra",2);Vj.className="RowColumnDefinition";Vj.Default=un;Vj.None=Hm;Vj.ProportionalExtra=Zm; function Mf(){Y.call(this);this.Ed=this.na=null;this.Wn="None";this.eo=Yk;this.Jc=this.tl="black";this.wh=1;this.jm="butt";this.km="miter";this.gk=10;this.uh=null;this.vh=0;this.rf=this.qf=Zc;this.op=this.np=NaN;this.qo=!1;this.qp=null;this.ul=this.qm="None";this.Yd=1;this.Wd=0;this.Ud=1;this.Vd=null}ma(Mf,Y); Mf.prototype.cloneProtected=function(a){Y.prototype.cloneProtected.call(this,a);a.na=this.na;a.Wn=this.Wn;a.eo=this.eo;a.Ed=this.Ed;a.tl=this.tl;a.Jc=this.Jc;a.wh=this.wh;a.jm=this.jm;a.km=this.km;a.gk=this.gk;null!==this.uh&&(a.uh=Ba(this.uh));a.vh=this.vh;a.qf=this.qf.G();a.rf=this.rf.G();a.np=this.np;a.op=this.op;a.qo=this.qo;a.qp=this.qp;a.qm=this.qm;a.ul=this.ul;a.Yd=this.Yd;a.Wd=this.Wd;a.Ud=this.Ud;a.Vd=this.Vd};t=Mf.prototype; t.jb=function(a){a===Bg||a===Dg||a===al||a===Yk?this.geometryStretch=a:Y.prototype.jb.call(this,a)};t.toString=function(){return"Shape("+("None"!==this.figure?this.figure:"None"!==this.toArrow?this.toArrow:this.fromArrow)+")#"+mb(this)}; function vn(a,b,c,d){var e=c.length;if(!(4>e)){var f=d.measuredBounds,g=Math.max(1,f.width);f=f.height;for(var h=c[0],k=c[1],l,m,n,p,r,q,u=0,v=Ea(),w=2;w<e;w+=2)l=c[w],m=c[w+1],n=l-h,h=m-k,0===n&&(n=.001),p=h/n,r=Math.atan2(h,n),q=Math.sqrt(n*n+h*h),v.push([n,r,p,q]),u+=q,h=l,k=m;h=c[0];k=c[1];n=d.measuredBounds.width;d instanceof Mf&&(n-=d.strokeWidth);1>n&&(n=1);e=c=n;l=g/2;m=0===l?!1:!0;w=0;q=v[w];n=q[0];r=q[1];p=q[2];q=q[3];for(var y=0;.1<=u;){0===y&&(m?(e=c,e-=l,u-=l,m=!1):e=c,0===e&&(e=1)); if(e>u){Ia(v);return}e>q?(y=e-q,e=q):y=0;var z=Math.sqrt(e*e/(1+p*p));0>n&&(z=-z);h+=z;k+=p*z;a.translate(h,k);a.rotate(r);a.translate(-(g/2),-(f/2));0===y&&d.ej(a,b);a.translate(g/2,f/2);a.rotate(-r);a.translate(-h,-k);u-=e;q-=e;if(0!==y){w++;if(w===v.length){Ia(v);return}q=v[w];n=q[0];r=q[1];p=q[2];q=q[3];e=y}}Ia(v)}} t.ej=function(a,b){var c=this.Jc,d=this.tl;if(null!==c||null!==d){var e=this.actualBounds,f=this.naturalBounds;null!==d&&oi(this,a,d,!0,!1,f,e);var g=this.part,h=this.wh;null===c||0!==h||null===g||!this.isPanelMain&&g.rb()!==this||(h=g.type===X.Link&&g instanceof Qe&&"Selection"===g.category&&g.adornedObject instanceof Mf&&g.adornedPart.rb()===g.adornedObject?g.adornedObject.strokeWidth:0);0===h&&(c=null);null!==c&&0!==h&&(oi(this,a,c,!1,!1,f,e),a.lineWidth=h,a.lineJoin=this.km,a.lineCap=this.jm, a.miterLimit=this.gk);e=!1;g&&b.Ke("drawShadows")&&(e=g.isShadowed);g=!0;null===c||null!==d&&"transparent"!==d||(g=!1);f=!1;h=this.strokeDashArray;null!==h&&(f=!0,a.Gt(h,this.vh));var k=this.na;if(null!==k){if(k.type===wd)a.beginPath(),a.moveTo(k.startX,k.startY),a.lineTo(k.endX,k.endY),null!==c&&a.vj();else if(k.type===Dd){var l=k.startX;h=k.startY;var m=k.endX,n=k.endY;k=Math.min(l,m);var p=Math.min(h,n);l=Math.abs(m-l);h=Math.abs(n-h);a.beginPath();a.rect(k,p,l,h);null!==d&&a.Je(d);if(null!==c){g&& e&&vl(a);if(0===l||0===h)a.beginPath(),a.rect(k,p,Math.max(l,.1),Math.max(h,.1));a.vj();g&&e&&ul(a)}}else if(k.type===Ed)l=k.startX,h=k.startY,m=k.endX,n=k.endY,k=Math.abs(m-l)/2,p=Math.abs(n-h)/2,l=Math.min(l,m)+k,h=Math.min(h,n)+p,a.beginPath(),a.moveTo(l,h-p),a.bezierCurveTo(l+L.Lg*k,h-p,l+k,h-L.Lg*p,l+k,h),a.bezierCurveTo(l+k,h+L.Lg*p,l+L.Lg*k,h+p,l,h+p),a.bezierCurveTo(l-L.Lg*k,h+p,l-k,h+L.Lg*p,l-k,h),a.bezierCurveTo(l-k,h-L.Lg*p,l-L.Lg*k,h-p,l,h-p),a.closePath(),null!==d&&a.Je(d),null!==c&& (g&&e?(vl(a),a.vj(),ul(a)):a.vj());else if(k.type===ud)for(h=k.figures,k=h.length,p=0;p<k;p++){l=h.j[p];a.beginPath();a.moveTo(l.startX,l.startY);m=l.segments.j;n=m.length;for(var r=null,q=0;q<n;q++){var u=m[q];switch(u.type){case ae:a.moveTo(u.endX,u.endY);break;case yd:a.lineTo(u.endX,u.endY);break;case be:a.bezierCurveTo(u.point1X,u.point1Y,u.point2X,u.point2Y,u.endX,u.endY);break;case ce:a.quadraticCurveTo(u.point1X,u.point1Y,u.endX,u.endY);break;case de:if(u.radiusX===u.radiusY){var v=Math.PI/ 180;a.arc(u.point1X,u.point1Y,u.radiusX,u.startAngle*v,(u.startAngle+u.sweepAngle)*v,0>u.sweepAngle,null!==r?r.endX:l.startX,null!==r?r.endY:l.startY)}else if(r=fe(u,l),v=r.length,0===v)a.lineTo(u.centerX,u.centerY);else for(var w=0;w<v;w++){var y=r[w];0===w&&a.lineTo(y[0],y[1]);a.bezierCurveTo(y[2],y[3],y[4],y[5],y[6],y[7])}break;case ee:w=v=0;if(null!==r&&r.type===de){r=fe(r,l);y=r.length;if(0===y){a.lineTo(u.endX,u.endY);break}r=r[y-1]||null;null!==r&&(v=r[6],w=r[7])}else v=null!==r?r.endX:l.startX, w=null!==r?r.endY:l.startY;r=ge(u,l,v,w);v=r.length;if(0===v){a.lineTo(u.endX,u.endY);break}for(w=0;w<v;w++)y=r[w],a.bezierCurveTo(y[2],y[3],y[4],y[5],y[6],y[7]);break;default:B("Segment not of valid type: "+u.type)}u.isClosed&&a.closePath();r=u}m=l.isFilled;e?l.isShadowed?(!0===m&&"transparent"!==d&&null!==d&&a.Je(d),null!==c&&(m&&g&&vl(a),a.vj(),m&&g&&ul(a))):(vl(a),m&&"transparent"!==d&&null!==d&&a.Je(d),null!==c&&a.vj(),ul(a)):(m&&null!==d&&a.Je(d),null!==c&&a.vj())}f&&a.Et();if(null!==this.pathPattern){c= this.pathPattern;c.measure(Infinity,Infinity);d=c.measuredBounds;c.arrange(0,0,d.width,d.height);e=this.geometry;a.save();a.beginPath();d=Ea();if(e.type===wd)d.push(e.startX),d.push(e.startY),d.push(e.endX),d.push(e.endY),vn(a,b,d,c);else if(e.type===ud)for(e=e.figures.iterator;e.next();){g=e.value;d.length=0;d.push(g.startX);d.push(g.startY);f=g.startX;h=g.startY;k=f;p=h;l=g.segments.j;m=l.length;for(n=0;n<m;n++){q=l[n];switch(q.type){case ae:vn(a,b,d,c);d.length=0;d.push(q.endX);d.push(q.endY); f=q.endX;h=q.endY;k=f;p=h;break;case yd:d.push(q.endX);d.push(q.endY);f=q.endX;h=q.endY;break;case be:L.Ge(f,h,q.point1X,q.point1Y,q.point2X,q.point2Y,q.endX,q.endY,.5,d);f=q.endX;h=q.endY;break;case ce:L.Vq(f,h,q.point1X,q.point1Y,q.endX,q.endY,.5,d);f=q.endX;h=q.endY;break;case de:u=fe(q,g);r=u.length;if(0===r){d.push(q.centerX);d.push(q.centerY);f=q.centerX;h=q.centerY;break}for(v=0;v<r;v++)w=u[v],L.Ge(f,h,w[2],w[3],w[4],w[5],w[6],w[7],.5,d),f=w[6],h=w[7];break;case ee:u=ge(q,g,f,h);r=u.length; if(0===r){d.push(q.endX);d.push(q.endY);f=q.endX;h=q.endY;break}for(v=0;v<r;v++)w=u[v],L.Ge(f,h,w[2],w[3],w[4],w[5],w[6],w[7],.5,d),f=w[6],h=w[7];break;default:B("Segment not of valid type: "+q.type)}q.isClosed&&(d.push(k),d.push(p),vn(a,b,d,c))}vn(a,b,d,c)}else if(e.type===Dd)d.push(e.startX),d.push(e.startY),d.push(e.endX),d.push(e.startY),d.push(e.endX),d.push(e.endY),d.push(e.startX),d.push(e.endY),d.push(e.startX),d.push(e.startY),vn(a,b,d,c);else if(e.type===Ed){h=new se;h.startX=e.endX;h.startY= (e.startY+e.endY)/2;f=new te(de);f.startAngle=0;f.sweepAngle=360;f.centerX=(e.startX+e.endX)/2;f.centerY=(e.startY+e.endY)/2;f.radiusX=Math.abs(e.startX-e.endX)/2;f.radiusY=Math.abs(e.startY-e.endY)/2;h.add(f);e=fe(f,h);g=e.length;if(0===g)d.push(f.centerX),d.push(f.centerY);else for(f=h.startX,h=h.startY,k=0;k<g;k++)p=e[k],L.Ge(f,h,p[2],p[3],p[4],p[5],p[6],p[7],.5,d),f=p[6],h=p[7];vn(a,b,d,c)}Ia(d);a.restore();a.uc(!1)}}}}; t.da=function(a,b){void 0===b&&(b=new I);if(a instanceof O){a.nc()&&B("getDocumentPoint Spot must be a real, specific Spot, not: "+a.toString());var c=this.naturalBounds,d=this.strokeWidth;b.h(a.x*(c.width+d)-d/2+c.x+a.offsetX,a.y*(c.height+d)-d/2+c.y+a.offsetY)}else b.set(a);this.Fd.sa(b);return b}; t.mj=function(a){void 0===a&&(a=new N);var b=this.naturalBounds,c=this.Fd;b=N.allocAt(b.x,b.y,b.width,b.height);var d=this.strokeWidth;b.Lc(d/2,d/2);d=I.allocAt(b.x,b.y).transform(c);a.h(d.x,d.y,0,0);d.h(b.right,b.y).transform(c);gc(a,d.x,d.y,0,0);d.h(b.right,b.bottom).transform(c);gc(a,d.x,d.y,0,0);d.h(b.x,b.bottom).transform(c);gc(a,d.x,d.y,0,0);N.free(b);I.free(d);return a}; t.Jh=function(a,b){var c=this.geometry;if(null===c||null===this.fill&&null===this.stroke)return!1;var d=c.bounds,e=this.strokeWidth/2;c.type!==wd||b||(e+=2);var f=N.alloc();f.assign(d);f.Lc(e+2,e+2);if(!f.$(a))return N.free(f),!1;d=e+1E-4;if(c.type===wd){if(null===this.stroke)return!1;d=(c.endX-c.startX)*(a.x-c.startX)+(c.endY-c.startY)*(a.y-c.startY);if(0>(c.startX-c.endX)*(a.x-c.endX)+(c.startY-c.endY)*(a.y-c.endY)||0>d)return!1;N.free(f);return L.Ob(c.startX,c.startY,c.endX,c.endY,e,a.x,a.y)}if(c.type=== Dd){b=c.startX;var g=c.startY,h=c.endX;c=c.endY;f.x=Math.min(b,h);f.y=Math.min(g,c);f.width=Math.abs(h-b);f.height=Math.abs(c-g);if(null===this.fill){f.Lc(-d,-d);if(f.$(a))return N.free(f),!1;f.Lc(d,d)}null!==this.stroke&&f.Lc(e,e);a=f.$(a);N.free(f);return a}if(c.type===Ed){g=c.startX;e=c.startY;h=c.endX;var k=c.endY;c=Math.min(g,h);b=Math.min(e,k);g=Math.abs(h-g)/2;e=Math.abs(k-e)/2;c=a.x-(c+g);b=a.y-(b+e);if(null===this.fill){g-=d;e-=d;if(0>=g||0>=e||1>=c*c/(g*g)+b*b/(e*e))return N.free(f),!1; g+=d;e+=d}null!==this.stroke&&(g+=d,e+=d);N.free(f);return 0>=g||0>=e?!1:1>=c*c/(g*g)+b*b/(e*e)}if(c.type===ud)return N.free(f),null===this.fill?je(c,a.x,a.y,e):he(c,a,e,1<this.strokeWidth,b);B("Unknown Geometry type: "+c.type);return!1}; t.Gm=function(a,b,c,d){var e=this.desiredSize,f=this.wh;a=Math.max(a,0);b=Math.max(b,0);if(null!==this.Ed)var g=this.geometry.bounds;else{var h=this.figure,k=wn[h];if(void 0===k){var l=L.Re[h];"string"===typeof l&&(l=L.Re[l]);"function"===typeof l?(k=l(null,100,100),wn[h]=k):B("Unsupported Figure: "+h)}g=k.bounds}h=g.width;k=g.height;l=g.width;var m=g.height;switch(nl(this,!0)){case Bg:d=c=0;break;case vd:l=Math.max(a-f,0);m=Math.max(b-f,0);break;case Zk:l=Math.max(a-f,0);d=0;break;case $k:c=0,m= Math.max(b-f,0)}isFinite(e.width)&&(l=e.width);isFinite(e.height)&&(m=e.height);e=this.maxSize;g=this.minSize;c=Math.max(c-f,g.width);d=Math.max(d-f,g.height);l=Math.min(e.width,l);m=Math.min(e.height,m);l=isFinite(l)?Math.max(c,l):Math.max(h,c);m=isFinite(m)?Math.max(d,m):Math.max(k,d);c=Cg(this);switch(c){case Bg:break;case vd:h=l;k=m;break;case Dg:c=Math.min(l/h,m/k);isFinite(c)||(c=1);h*=c;k*=c;break;default:B(c+" is not a valid geometryStretch.")}null!==this.Ed?(0===h&&(h=.001),0===k&&(k=.001), c=null!==this.Ed?this.Ed:this.na,e=c.bounds,d=h/e.width,e=k/e.height,isFinite(d)||(d=1),isFinite(e)||(e=1),this.na=1===d&&1===e?c:c.copy().scale(d,e)):null!==this.na&&L.aa(this.na.El,a-f)&&L.aa(this.na.Dl,b-f)||(this.na=Mf.makeGeometry(this,h,k));g=this.na.bounds;Infinity===a||Infinity===b?kl(this,g.x-f/2,g.y-f/2,0===a&&0===h?0:g.width+f,0===b&&0===k?0:g.height+f):kl(this,-(f/2),-(f/2),l+f,m+f)}; function Cg(a){var b=a.geometryStretch;return null!==a.Ed?b===Yk?vd:b:b===Yk?wn[a.figure].defaultStretch:b}t.Hh=function(a,b,c,d){pl(this,a,b,c,d)};t.Ot=function(a,b,c){return this.yk(a.x,a.y,b.x,b.y,c)}; t.yk=function(a,b,c,d,e){var f=this.transform,g=1/(f.m11*f.m22-f.m12*f.m21),h=f.m22*g,k=-f.m12*g,l=-f.m21*g,m=f.m11*g,n=g*(f.m21*f.dy-f.m22*f.dx),p=g*(f.m12*f.dx-f.m11*f.dy);f=a*h+b*l+n;g=a*k+b*m+p;h=c*h+d*l+n;k=c*k+d*m+p;n=this.wh/2;l=this.na;null===l&&(this.measure(Infinity,Infinity),l=this.na);var r=l.bounds;m=!1;if(l.type===wd)if(1.5>=this.strokeWidth)m=L.Me(l.startX,l.startY,l.endX,l.endY,f,g,h,k,e);else{l.startX===l.endX?(d=n,m=0):(b=(l.endY-l.startY)/(l.endX-l.startX),m=n/Math.sqrt(1+b*b), d=m*b);b=Ea();a=new I;L.Me(l.startX+d,l.startY+m,l.endX+d,l.endY+m,f,g,h,k,a)&&b.push(a);a=new I;L.Me(l.startX-d,l.startY-m,l.endX-d,l.endY-m,f,g,h,k,a)&&b.push(a);a=new I;L.Me(l.startX+d,l.startY+m,l.startX-d,l.startY-m,f,g,h,k,a)&&b.push(a);a=new I;L.Me(l.endX+d,l.endY+m,l.endX-d,l.endY-m,f,g,h,k,a)&&b.push(a);h=b.length;if(0===h)return Ia(b),!1;m=!0;k=Infinity;for(d=0;d<h;d++)a=b[d],c=(a.x-f)*(a.x-f)+(a.y-g)*(a.y-g),c<k&&(k=c,e.x=a.x,e.y=a.y);Ia(b)}else if(l.type===Dd)m=L.Ef(r.x-n,r.y-n,r.x+r.width+ n,r.y+r.height+n,f,g,h,k,e);else if(l.type===Ed){b=N.allocAt(r.x,r.y,r.width,r.height).Lc(n,n);a:if(0===b.width)m=L.Me(b.x,b.y,b.x,b.y+b.height,f,g,h,k,e);else if(0===b.height)m=L.Me(b.x,b.y,b.x+b.width,b.y,f,g,h,k,e);else{a=b.width/2;l=b.height/2;d=b.x+a;m=b.y+l;c=9999;f!==h&&(c=(g-k)/(f-h));if(9999>Math.abs(c)){k=g-m-c*(f-d);if(0>a*a*c*c+l*l-k*k){e.x=NaN;e.y=NaN;m=!1;break a}n=Math.sqrt(a*a*c*c+l*l-k*k);h=(-(a*a*c*k)+a*l*n)/(l*l+a*a*c*c)+d;a=(-(a*a*c*k)-a*l*n)/(l*l+a*a*c*c)+d;l=c*(h-d)+k+m;k=c* (a-d)+k+m;Math.abs((f-h)*(f-h))+Math.abs((g-l)*(g-l))<Math.abs((f-a)*(f-a))+Math.abs((g-k)*(g-k))?(e.x=h,e.y=l):(e.x=a,e.y=k)}else{h=l*l;k=f-d;h-=h/(a*a)*k*k;if(0>h){e.x=NaN;e.y=NaN;m=!1;break a}k=Math.sqrt(h);h=m+k;k=m-k;Math.abs(h-g)<Math.abs(k-g)?(e.x=f,e.y=h):(e.x=f,e.y=k)}m=!0}N.free(b)}else if(l.type===ud){p=I.alloc();var q=h-f;var u=k-g,v=q*q+u*u,w=f,y=g;if(0<v&&r.contains(w,y)&&(p.x=w,p.y=y,this.$(p)))for(0!==q&&.5>Math.abs(q)?(u*=.5/q,q=.5):0!==u&&.5>Math.abs(u)&&(q*=.5/u,u=.5),w-=q,y-=u;r.contains(w, y);)w-=q,y-=u;e.x=h;e.y=k;for(u=0;u<l.figures.count;u++){var z=l.figures.j[u],A=z.isFilled?w:f,C=z.isFilled?y:g,F=z.segments;r=z.startX;q=z.startY;for(var Q=r,K=q,T=0;T<F.count;T++){var P=F.j[T],J=P.type;var ka=P.endX;var ba=P.endY;var qa=!1;switch(J){case ae:Q=ka;K=ba;break;case yd:qa=xn(r,q,ka,ba,A,C,h,k,p);break;case be:qa=L.tq(r,q,P.point1X,P.point1Y,P.point2X,P.point2Y,ka,ba,A,C,h,k,.6,p);break;case ce:qa=L.tq(r,q,r+2/3*(P.point1X-r),q+2/3*(P.point1Y-q),ka+2/3*(P.point1X-ka),ba+2/3*(P.point1Y- ba),ka,ba,A,C,h,k,.6,p);break;case de:case ee:J=P.type===de?fe(P,z):ge(P,z,r,q);var Ma=J.length;if(0===Ma){qa=xn(r,q,P.type===de?P.centerX:P.endX,P.type===de?P.centerY:P.endY,A,C,h,k,p);break}ba=null;for(ka=0;ka<Ma;ka++){ba=J[ka];if(0===ka&&xn(r,q,ba[0],ba[1],A,C,h,k,p)){var eb=yn(A,C,p,v,e);eb<v&&(v=eb,m=!0)}L.tq(ba[0],ba[1],ba[2],ba[3],ba[4],ba[5],ba[6],ba[7],A,C,h,k,.6,p)&&(eb=yn(A,C,p,v,e),eb<v&&(v=eb,m=!0))}ka=ba[6];ba=ba[7];break;default:B("Unknown Segment type: "+J)}r=ka;q=ba;qa&&(qa=yn(A, C,p,v,e),qa<v&&(v=qa,m=!0));P.isClosed&&(ka=Q,ba=K,xn(r,q,ka,ba,A,C,h,k,p)&&(P=yn(A,C,p,v,e),P<v&&(v=P,m=!0)))}}f=c-a;g=d-b;h=Math.sqrt(f*f+g*g);0!==h&&(f/=h,g/=h);e.x-=f*n;e.y-=g*n;I.free(p)}else B("Unknown Geometry type: "+l.type);if(!m)return!1;this.transform.sa(e);return!0};function yn(a,b,c,d,e){a=c.x-a;b=c.y-b;b=a*a+b*b;return b<d?(e.x=c.x,e.y=c.y,b):d} function xn(a,b,c,d,e,f,g,h,k){var l=!1,m=(e-g)*(b-d)-(f-h)*(a-c);if(0===m)return!1;k.x=((e*h-f*g)*(a-c)-(e-g)*(a*d-b*c))/m;k.y=((e*h-f*g)*(b-d)-(f-h)*(a*d-b*c))/m;(a>c?a-c:c-a)<(b>d?b-d:d-b)?(a=b<d?b:d,b=b<d?d:b,(k.y>a||L.aa(k.y,a))&&(k.y<b||L.aa(k.y,b))&&(l=!0)):(b=a<c?a:c,a=a<c?c:a,(k.x>b||L.aa(k.x,b))&&(k.x<a||L.aa(k.x,a))&&(l=!0));return l} t.Ih=function(a,b){if(void 0===b)return a.He(this.actualBounds);var c=this.na;null===c&&(this.measure(Infinity,Infinity),c=this.na);c=c.bounds;var d=this.strokeWidth/2,e=!1,f=I.alloc();f.h(c.x-d,c.y-d);a.$(b.sa(f))&&(f.h(c.x-d,c.bottom+d),a.$(b.sa(f))&&(f.h(c.right+d,c.bottom+d),a.$(b.sa(f))&&(f.h(c.right+d,c.y-d),a.$(b.sa(f))&&(e=!0))));I.free(f);return e}; t.Oc=function(a,b){if(this.Ih(a,b)||void 0===b&&(b=this.transform,a.He(this.actualBounds)))return!0;var c=rd.alloc();c.set(b);c.Tt();var d=a.left,e=a.right,f=a.top;a=a.bottom;var g=I.alloc();g.h(d,f);c.sa(g);if(this.Jh(g,!0))return I.free(g),!0;g.h(e,f);c.sa(g);if(this.Jh(g,!0))return I.free(g),!0;g.h(d,a);c.sa(g);if(this.Jh(g,!0))return I.free(g),!0;g.h(e,a);c.sa(g);if(this.Jh(g,!0))return I.free(g),!0;var h=I.alloc(),k=I.alloc();c.set(b);c.iw(this.transform);c.Tt();h.x=e;h.y=f;h.transform(c);g.x= d;g.y=f;g.transform(c);b=!1;zn(this,g,h,k)?b=!0:(g.x=e,g.y=a,g.transform(c),zn(this,g,h,k)?b=!0:(h.x=d,h.y=a,h.transform(c),zn(this,g,h,k)?b=!0:(g.x=d,g.y=f,g.transform(c),zn(this,g,h,k)&&(b=!0))));I.free(g);rd.free(c);I.free(h);I.free(k);return b};function zn(a,b,c,d){if(!a.Ot(b,c,d))return!1;a=b.x;b=b.y;var e=c.x,f=c.y;c=d.x;d=d.y;if(a===e)return b<f?(a=b,b=f):a=f,d>=a&&d<=b;a<e?(d=a,a=e):d=e;return c>=d&&c<=a} t.sy=function(a,b,c){function d(a,b){for(var c=a.length,d=0;d<c;d+=2)if(b.rd(a[d],a[d+1])>e)return!0;return!1}if(c&&null!==this.fill&&this.Jh(a,!0))return!0;var e=a.Ie(b),f=e;1.5<this.strokeWidth&&(e=this.strokeWidth/2+Math.sqrt(e),e*=e);b=this.na;if(null===b&&(this.measure(Infinity,Infinity),b=this.na,null===b))return!1;if(!c){var g=b.bounds,h=g.x,k=g.y,l=g.x+g.width;g=g.y+g.height;if(Ab(a.x,a.y,h,k)<=e&&Ab(a.x,a.y,l,k)<=e&&Ab(a.x,a.y,h,g)<=e&&Ab(a.x,a.y,l,g)<=e)return!0}h=b.startX;k=b.startY;l= b.endX;g=b.endY;if(b.type===wd){if(c=(h-l)*(a.x-l)+(k-g)*(a.y-g),zb(a.x,a.y,h,k,l,g)<=(0<=(l-h)*(a.x-h)+(g-k)*(a.y-k)&&0<=c?e:f))return!0}else{if(b.type===Dd)return b=!1,c&&(b=zb(a.x,a.y,h,k,h,g)<=e||zb(a.x,a.y,h,k,l,k)<=e||zb(a.x,a.y,l,k,l,g)<=e||zb(a.x,a.y,h,g,l,g)<=e),b;if(b.type===Ed){b=a.x-(h+l)/2;f=a.y-(k+g)/2;var m=Math.abs(l-h)/2,n=Math.abs(g-k)/2;if(0===m||0===n)return zb(a.x,a.y,h,k,l,g)<=e?!0:!1;if(c){if(a=L.Mz(m,n,b,f),a*a<=e)return!0}else return Ab(b,f,-m,0)>=e||Ab(b,f,0,-n)>=e||Ab(b, f,0,n)>=e||Ab(b,f,m,0)>=e?!1:!0}else if(b.type===ud){l=b.bounds;f=l.x;h=l.y;k=l.x+l.width;l=l.y+l.height;if(a.x>k&&a.x<f&&a.y>l&&a.y<h&&zb(a.x,a.y,f,h,f,l)>e&&zb(a.x,a.y,f,h,k,h)>e&&zb(a.x,a.y,k,l,f,l)>e&&zb(a.x,a.y,k,l,k,h)>e)return!1;f=Math.sqrt(e);if(c){if(null===this.fill?je(b,a.x,a.y,f):he(b,a,f,!0,!1))return!0}else{c=b.figures;for(b=0;b<c.count;b++){f=c.j[b];g=f.startX;m=f.startY;if(a.rd(g,m)>e)return!1;h=f.segments.j;k=h.length;for(l=0;l<k;l++)switch(n=h[l],n.type){case ae:case yd:g=n.endX; m=n.endY;if(a.rd(g,m)>e)return!1;break;case be:var p=Ea();L.Ge(g,m,n.point1X,n.point1Y,n.point2X,n.point2Y,n.endX,n.endY,.8,p);g=d(p,a);Ia(p);if(g)return!1;g=n.endX;m=n.endY;if(a.rd(g,m)>e)return!1;break;case ce:p=Ea();L.Vq(g,m,n.point1X,n.point1Y,n.endX,n.endY,.8,p);g=d(p,a);Ia(p);if(g)return!1;g=n.endX;m=n.endY;if(a.rd(g,m)>e)return!1;break;case de:case ee:p=n.type===de?fe(n,f):ge(n,f,g,m);var r=p.length;if(0===r){g=n.type===de?n.centerX:n.endX;m=n.type===de?n.centerY:n.endY;if(a.rd(g,m)>e)return!1; break}n=null;for(var q=Ea(),u=0;u<r;u++)if(n=p[u],q.length=0,L.Ge(n[0],n[1],n[2],n[3],n[4],n[5],n[6],n[7],.8,q),d(q,a))return Ia(q),!1;Ia(q);null!==n&&(g=n[6],m=n[7]);break;default:B("Unknown Segment type: "+n.type)}}return!0}}}return!1};t.dc=function(){this.na=null};function An(a){var b=a.diagram;null!==b&&b.undoManager.isUndoingRedoing||(a.segmentOrientation=Wm,"None"!==a.qm?(a.segmentIndex=-1,a.alignmentFocus=fd):"None"!==a.ul&&(a.segmentIndex=0,a.alignmentFocus=new O(1-fd.x,fd.y)))} Mf.makeGeometry=function(a,b,c){if("None"!==a.toArrow)var d=Kn[a.toArrow];else"None"!==a.fromArrow?d=Kn[a.fromArrow]:(d=L.Re[a.figure],"string"===typeof d&&(d=L.Re[d]),void 0===d&&B("Unknown Shape.figure: "+a.figure),d=d(a,b,c),d.El=b,d.Dl=c);if(null===d){var e=L.Re.Rectangle;"function"===typeof e&&(d=e(a,b,c))}return d}; function Ln(a){var b=Kn[a];if(void 0===b){var c=a.toLowerCase();if("none"===c)return"None";b=Kn[c];if(void 0===b){var d=null,e;for(e in L.bn)if(e.toLowerCase()===c){d=e;break}if(null!==d)return a=Fd(L.bn[d],!1),Kn[d]=a,c!==d&&(Kn[c]=d),d}}return"string"===typeof b?b:b instanceof td?a:null} na.Object.defineProperties(Mf.prototype,{geometry:{get:function(){return null!==this.na?this.na:this.Ed},set:function(a){var b=this.na,c=this.Ed;if(b!==a){null!==a?this.Ed=this.na=a.freeze():this.Ed=this.na=null;var d=this.part;null!==d&&(d.kh=NaN);this.o();this.g("geometry",b||c,a);hl(this)&&(a=this.part,null!==a&&il(this,a,"geometryString"))}}},geometryString:{get:function(){return null===this.geometry?"":this.geometry.toString()},set:function(a){a= Fd(a);var b=a.normalize();this.geometry=a;this.position=a=I.allocAt(-b.x,-b.y);I.free(a)}},isGeometryPositioned:{get:function(){return this.qo},set:function(a){var b=this.qo;b!==a&&(this.qo=a,this.o(),this.g("isGeometryPositioned",b,a))}},fill:{get:function(){return this.tl},set:function(a){var b=this.tl;b!==a&&(null!==a&&Tl(a,"Shape.fill"),a instanceof wl&&a.freeze(),this.tl=a,this.M(),this.g("fill",b,a))}},stroke:{ get:function(){return this.Jc},set:function(a){var b=this.Jc;b!==a&&(null!==a&&Tl(a,"Shape.stroke"),a instanceof wl&&a.freeze(),this.Jc=a,this.M(),this.g("stroke",b,a))}},strokeWidth:{get:function(){return this.wh},set:function(a){var b=this.wh;if(b!==a)if(0<=a){this.wh=a;this.o();var c=this.part;null!==c&&(c.kh=NaN);this.g("strokeWidth",b,a)}else wa(a,"value >= 0",Mf,"strokeWidth:value")}},strokeCap:{get:function(){return this.jm},set:function(a){var b= this.jm;b!==a&&("string"!==typeof a||"butt"!==a&&"round"!==a&&"square"!==a?wa(a,'"butt", "round", or "square"',Mf,"strokeCap"):(this.jm=a,this.M(),this.g("strokeCap",b,a)))}},strokeJoin:{get:function(){return this.km},set:function(a){var b=this.km;b!==a&&("string"!==typeof a||"miter"!==a&&"bevel"!==a&&"round"!==a?wa(a,'"miter", "bevel", or "round"',Mf,"strokeJoin"):(this.km=a,this.M(),this.g("strokeJoin",b,a)))}},strokeMiterLimit:{get:function(){return this.gk}, set:function(a){var b=this.gk;if(b!==a&&1<=a){this.gk=a;this.M();var c=this.part;null!==c&&(c.kh=NaN);this.g("strokeMiterLimit",b,a)}}},strokeDashArray:{get:function(){return this.uh},set:function(a){var b=this.uh;if(b!==a){if(null!==a){for(var c=a.length,d=0,e=0;e<c;e++){var f=a[e];0<=f&&isFinite(f)||B("strokeDashArray:value "+f+" at index "+e+" must be a positive number or zero.");d+=f}if(0===d){if(null===b)return;a=null}}this.uh=a;this.M();this.g("strokeDashArray", b,a)}}},strokeDashOffset:{get:function(){return this.vh},set:function(a){var b=this.vh;b!==a&&0<=a&&(this.vh=a,this.M(),this.g("strokeDashOffset",b,a))}},figure:{get:function(){return this.Wn},set:function(a){var b=this.Wn;if(b!==a){var c=L.Re[a];"function"===typeof c?c=a:(c=L.Re[a.toLowerCase()])||B("Unknown Shape.figure: "+a);b!==c&&(a=this.part,null!==a&&(a.kh=NaN),this.Wn=c,this.Ed=null,this.dc(),this.o(),this.g("figure",b,c))}}},toArrow:{ get:function(){return this.qm},set:function(a){var b=this.qm;!0===a?a="Standard":!1===a&&(a="");if(b!==a){var c=Ln(a);null===c?B("Unknown Shape.toArrow: "+a):b!==c&&(this.qm=c,this.Ed=null,this.dc(),this.o(),An(this),this.g("toArrow",b,c))}}},fromArrow:{get:function(){return this.ul},set:function(a){var b=this.ul;!0===a?a="Standard":!1===a&&(a="");if(b!==a){var c=Ln(a);null===c?B("Unknown Shape.fromArrow: "+a):b!==c&&(this.ul=c,this.Ed=null,this.dc(),this.o(), An(this),this.g("fromArrow",b,c))}}},spot1:{get:function(){return this.qf},set:function(a){var b=this.qf;b.w(a)||(this.qf=a=a.G(),this.o(),this.g("spot1",b,a))}},spot2:{get:function(){return this.rf},set:function(a){var b=this.rf;b.w(a)||(this.rf=a=a.G(),this.o(),this.g("spot2",b,a))}},parameter1:{get:function(){return this.np},set:function(a){var b=this.np;b!==a&&(this.np=a,this.dc(),this.o(),this.g("parameter1", b,a))}},parameter2:{get:function(){return this.op},set:function(a){var b=this.op;b!==a&&(this.op=a,this.dc(),this.o(),this.g("parameter2",b,a))}},naturalBounds:{get:function(){var a=this.desiredSize;return a.s()||null===this.na?new N(0,0,a.width,a.height):(this.rc.assign(this.na.bounds),this.rc)}},pathPattern:{get:function(){return this.qp},set:function(a){var b=this.qp;b!==a&&(this.qp=a,this.M(),this.g("pathPattern", b,a))}},geometryStretch:{get:function(){return this.eo},set:function(a){var b=this.eo;b!==a&&(this.eo=a,this.g("geometryStretch",b,a))}},interval:{get:function(){return this.Yd},set:function(a){var b=this.Yd;a=Math.round(a);if(b!==a&&0!==a&&isFinite(a)){this.Yd=a;var c=this.diagram;null!==c&&this.panel===c.grid&&qj(c);this.o();c=this.panel;null!==c&&(c.eh=null);this.g("interval",b,a)}}},graduatedStart:{get:function(){return this.Wd}, set:function(a){var b=this.Wd;b!==a&&(0>a?a=0:1<a&&(a=1),this.Wd=a,this.o(),this.g("graduatedStart",b,a))}},graduatedEnd:{get:function(){return this.Ud},set:function(a){var b=this.Ud;b!==a&&(0>a?a=0:1<a&&(a=1),this.Ud=a,this.o(),this.g("graduatedEnd",b,a))}},graduatedSkip:{get:function(){return this.Vd},set:function(a){var b=this.Vd;b!==a&&(this.Vd=a,this.o(),this.g("graduatedSkip",b,a))}}});Mf.prototype.intersectsRect=Mf.prototype.Oc; Mf.prototype.containedInRect=Mf.prototype.Ih;Mf.prototype.getNearestIntersectionPoint=Mf.prototype.Ot;Mf.prototype.getDocumentBounds=Mf.prototype.mj;Mf.prototype.getDocumentPoint=Mf.prototype.da;var Kn=new cb,wn=new cb;Mf.className="Shape";Mf.getFigureGenerators=function(){var a=new H,b;for(b in L.Re)b!==b.toLowerCase()&&a.add(b,L.Re[b]);a.freeze();return a};Mf.defineFigureGenerator=function(a,b){var c=a.toLowerCase(),d=L.Re;d[a]=b;d[c]=a}; Mf.getArrowheadGeometries=function(){var a=new H;for(d in L.bn)if(void 0===Kn[d]){var b=Fd(L.bn[d],!1);Kn[d]=b;b=d.toLowerCase();b!==d&&(Kn[b]=d)}for(var c in Kn)if(c!==c.toLowerCase()){var d=Kn[c];d instanceof td&&a.add(c,d)}a.freeze();return a};Mf.defineArrowheadGeometry=function(a,b){var c=null;"string"===typeof b?c=Fd(b,!1):c=b;b=a.toLowerCase();"none"!==b&&a!==b||B("Shape.defineArrowheadGeometry name must not be empty or None or all-lower-case: "+a);var d=Kn;d[a]=c;d[b]=a}; function Yg(){Y.call(this);Mn||(Nn=Wg?(new Ek(null)).context:null,Mn=!0);this.Kx=this.Ub="";this.Jc="black";this.oe="13px sans-serif";this.Vi="start";this.Td=Bg;this.aj=bd;this.Pj=!0;this.zi=this.Ai=!1;this.og=On;this.Ag=Pn;this.vs=this.ub=this.ad=0;this.dv=this.ev=null;this.Tn=!1;this.Ec=this.vn=this.fq=this.Wi=this.gq=null;this.pf=this.nf=0;this.si=Qn;this.we=Infinity;this.Di=0;this.pe=null;this.Ce=0;this.ne=this.lb=this.Qb=null;this.Yd=1;this.Wd=0;this.Ud=1;this.Vd=this.Lj=null}ma(Yg,Y); Yg.prototype.cloneProtected=function(a){Y.prototype.cloneProtected.call(this,a);a.Ub=this.Ub;a.Kx=this.Kx;a.Jc=this.Jc;a.oe=this.oe;a.Vi=this.Vi;a.Td=this.Td;a.aj=this.aj;a.Pj=this.Pj;a.Ai=this.Ai;a.zi=this.zi;a.og=this.og;a.Ag=this.Ag;a.ad=this.ad;a.vs=this.vs;a.ub=this.ub;a.ev=this.ev;a.dv=this.dv;a.Tn=this.Tn;a.gq=this.gq;a.Wi=this.Wi;a.fq=this.fq;a.vn=this.vn;a.Ec=this.Ec;a.nf=this.nf;a.pf=this.pf;a.si=this.si;a.we=this.we;a.pe=this.pe;a.Ce=this.Ce;a.Qb=this.Qb;a.lb=this.lb;a.ne=this.ne;a.Di= this.Di;a.Yd=this.Yd;a.Wd=this.Wd;a.Ud=this.Ud;a.Lj=this.Lj;a.Vd=this.Vd}; function Vm(a,b){a.F=b.F|6144;a.hb=b.opacity;a.mb=b.background;a.ec=b.areaBackground;a.Zc=b.desiredSize.G();a.hg=b.minSize.G();a.gg=b.maxSize.G();a.eg=b.eg.copy();a.ya=b.scale;a.Yb=b.angle;a.Ee=b.stretch;a.jh=b.margin.G();a.zb=b.alignment.G();a.$k=b.alignmentFocus.G();a.$l=b.segmentFraction;a.am=b.segmentOffset.G();a.bm=b.segmentOrientation;null!==b.Ya&&(a.Ya=b.Ya.copy());a.dm=b.shadowVisible;b instanceof Yg&&(a.Ub=b.Ub,a.Jc=b.Jc,a.oe=b.oe,a.Vi=b.Vi,a.Td=b.Td,a.aj=b.aj,a.Pj=b.Pj,a.Ai=b.Ai,a.zi=b.zi, a.og=b.og,a.Ag=b.Ag,a.pe=null,a.nf=b.nf,a.pf=b.pf,a.we=b.we,a.Di=b.Di,a.Yd=b.Yd,a.Wd=b.Wd,a.Ud=b.Ud,a.Lj=b.Lj,a.Vd=b.Vd)}t=Yg.prototype;t.jb=function(a){a.classType===Yg?this.wrap=a:Y.prototype.jb.call(this,a)};t.toString=function(){return 22<this.Ub.length?'TextBlock("'+this.Ub.substring(0,20)+'"...)':'TextBlock("'+this.Ub+'")'};t.o=function(){Y.prototype.o.call(this);this.dv=this.ev=null}; t.ej=function(a,b){if(null!==this.Jc&&0!==this.Ub.length&&null!==this.oe){var c=this.naturalBounds,d=this.actualBounds,e=c.width,f=c.height,g=Rn(this),h=a.textAlign=this.Vi,k=b.Hl;"start"===h?h=k?"right":"left":"end"===h&&(h=k?"left":"right");k=this.Ai;var l=this.zi;oi(this,a,this.Jc,!0,!1,c,d);(k||l)&&oi(this,a,this.Jc,!1,!1,c,d);d=0;c=!1;var m=I.allocAt(0,0);this.Fd.sa(m);var n=I.allocAt(0,g);this.Fd.sa(n);var p=m.Ie(n);I.free(m);I.free(n);m=b.scale;8>p*m*m&&(c=!0);b.Hb!==a&&(c=!1);!1===b.Ke("textGreeking")&& (c=!1);b=this.nf;p=this.pf;switch(this.flip){case cl:a.translate(e,0);a.scale(-1,1);break;case bl:a.translate(0,f);a.scale(1,-1);break;case dl:a.translate(e,f),a.scale(-1,-1)}m=this.ad;n=(b+g+p)*m;f>n&&(d=this.aj,d=d.y*f-d.y*n+d.offsetY);if(1===m&&null!==this.ne)p=this.ub,p>e&&(p=e),this.dj(this.ne,a,0,d+b,e,g,p,c,h,k,l);else if(null!==this.Qb&&null!==this.lb)for(n=0;n<m;n++){var r=this.Qb[n];r>e&&(r=e);d+=b;this.dj(this.lb[n],a,0,d,e,g,r,c,h,k,l);d+=g+p}switch(this.flip){case cl:a.scale(-1,1);a.translate(-e, 0);break;case bl:a.scale(1,-1);a.translate(0,-f);break;case dl:a.scale(-1,-1),a.translate(-e,-f)}}}; t.dj=function(a,b,c,d,e,f,g,h,k,l,m){var n=0;h?("left"===k?n=0:"right"===k?n=e-g:"center"===k&&(n=(e-g)/2),b.fillRect(c+n,d+.25*f,g,1)):("left"===k?n=0:"right"===k?n=e:"center"===k&&(n=e/2),e=null!==Sn?Sn(this,f):.75*f,b.fillText(a,c+n,d+e),a=f/20|0,0===a&&(a=1),"right"===k?n-=g:"center"===k&&(n-=g/2),l&&(k=null!==Tn?Tn(this,f):.8*f,b.beginPath(),b.lineWidth=a,b.moveTo(c+n,d+k),b.lineTo(c+n+g,d+k),b.stroke()),m&&(b.beginPath(),b.lineWidth=a,d=d+f-f/2.2|0,0!==a%2&&(d+=.5),b.moveTo(c+n,d),b.lineTo(c+ n+g,d),b.stroke()))}; t.Gm=function(a,b,c,d){this.Di=a;var e=this.oe;null!==Nn&&Un!==e&&(Un=Nn.font=e);this.ub=this.Ce=0;this.ne=this.lb=this.Qb=this.pe=null;var f;if(isNaN(this.desiredSize.width)){e=this.Ub.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(0===e.length)e=0;else if(this.isMultiline){for(var g=f=0,h=!1;!h;){var k=e.indexOf("\n",g);-1===k&&(k=e.length,h=!0);g=e.substr(g,k-g);this.si===Qn&&(g=g.trim());f=Math.max(f,Vn(g));g=k+1}e=f}else f=e.indexOf("\n",0),0<=f&&(e=e.substr(0,f)),e=Vn(e);e=Math.min(e,a/this.scale); e=Math.max(8,e)}else e=this.desiredSize.width;null!==this.panel&&(e=Math.min(e,this.panel.maxSize.width));f=Wn(this,e);isNaN(this.desiredSize.height)?f=Math.min(f,b/this.scale):f=this.desiredSize.height;h=f;if(0!==this.ub&&null!==this.Qb&&null!==this.lb&&this.og===Xn&&(b=this.oe,b=this.og===Xn?Yn(b):0,k=this.nf+this.pf,k=Math.max(0,Rn(this)+k),h=Math.min(this.maxLines-1,Math.max(Math.floor(h/k+.01)-1,0)),!(h+1>=this.lb.length))){k=this.lb[h];for(b=Math.max(1,a-b);Vn(k)>b&&1<k.length;)k=k.substr(0, k.length-1);k+=Zn;b=Vn(k);this.lb[h]=k;this.lb=this.lb.slice(0,h+1);this.Qb[h]=b;this.Qb=this.Qb.slice(0,h+1);this.Ce=this.lb.length;this.ub=Math.max(this.ub,b);this.ad=this.Ce;1===this.ad&&(this.ne=this.lb[0])}if(this.wrap===$n||isNaN(this.desiredSize.width))e=isNaN(a)?this.ub:Math.min(a,this.ub),isNaN(this.desiredSize.width)&&(e=Math.max(8,e));e=Math.max(c,e);f=Math.max(d,f);Ub(this.rc,e,f);kl(this,0,0,e,f)};t.Hh=function(a,b,c,d){pl(this,a,b,c,d)}; function ao(a,b,c){if(null===a.ne)a.ne=b,a.ub=c;else{if(null===a.lb||null===a.Qb)a.lb=[],a.Qb=[],a.lb.push(a.ne),a.Qb.push(a.ub);a.lb.push(b);a.Qb.push(c)}} function bo(a,b,c,d){var e=a.si===Qn;e&&(b=b.trim());var f=0,g=a.oe,h=a.nf+a.pf;h=Math.max(0,Rn(a)+h);var k=a.og===Xn?Yn(g):0;if(a.ad>=a.we)null!==d&&d.h(0,h);else if(g=b,a.Ag===co){a.Ce=1;var l=Vn(b);if(0===k||l<=c)a.ub=Math.max(a.ub,l),ao(a,b,a.ub),null!==d&&d.h(l,h);else{f=eo(a,g);g=g.substr(f.length);b=eo(a,g);for(l=Vn(f+b);0<b.length&&l<=c;)f+=b,g=g.substr(b.length),b=eo(a,g),l=f+b,e&&(l=l.trim()),l=Vn(l);e&&(b=b.trim());f+=b;for(c=Math.max(1,c-k);Vn(f)>c&&1<f.length;)f=f.substr(0,f.length-1); f+=Zn;var m=Vn(f);a.ub=m;ao(a,f,m);null!==d&&d.h(m,h)}}else{k=0;0===g.length&&(k=1,ao(a,g,0));for(;0<g.length;){b=eo(a,g);for(g=g.substr(b.length);Vn(b)>c;){var n=1;l=Vn(b.substr(0,n));for(m=0;l<=c;)n++,m=l,l=Vn(b.substr(0,n));if(1===n){var p=l;f=Math.max(f,l)}else p=m,f=Math.max(f,m);n--;1>n&&(n=1);ao(a,b.substr(0,n),p);k++;b=b.substr(n);if(a.ad+k>a.we)break}m=eo(a,g);for(l=Vn(b+m);0<m.length&&l<=c;)b+=m,g=g.substr(m.length),m=eo(a,g),l=b+m,e&&(l=l.trim()),l=Vn(l);e&&(b=b.trim());if(""!==b&&("\u00ad"=== b[b.length-1]&&(b=b.substring(0,b.length-1)+"\u2010"),0===m.length?(n=l,f=Math.max(f,l)):(n=m=Vn(b),f=Math.max(f,m)),ao(a,b,n),k++,a.ad+k>a.we))break}a.Ce=Math.min(a.we,k);a.ub=Math.max(a.ub,f);null!==d&&d.h(a.ub,h*a.Ce)}}function eo(a,b){if(a.Ag===fo)return b.substr(0,1);for(var c=b.length,d=0,e=go;d<c&&!e.test(b.charAt(d));)d++;for(a.si===ho&&(c=Math.min(c,d+1));d<c&&e.test(b.charAt(d));)d++;return d>=b.length?b:b.substr(0,d)}function Vn(a){return null===Nn?8*a.length:Nn.measureText(a).width} function Rn(a){if(null!==a.pe)return a.pe;var b=a.oe;if(null===Nn){var c=16;return a.pe=c}void 0!==io[b]&&5E3>jo?c=io[b]:(c=1.3*Nn.measureText("M").width,io[b]=c,jo++);return a.pe=c}function Yn(a){if(null===Nn)return 6;if(void 0!==ko[a]&&5E3>lo)var b=ko[a];else b=Nn.measureText(Zn).width,ko[a]=b,lo++;return b} function Wn(a,b){var c=a.Ub.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),d=a.nf+a.pf;d=Math.max(0,Rn(a)+d);if(0===c.length)return a.ub=0,a.ad=1,d;if(!a.isMultiline){var e=c.indexOf("\n",0);0<=e&&(c=c.substr(0,e))}e=0;for(var f=a.ad=0,g,h=!1;!h;){g=c.indexOf("\n",f);-1===g&&(g=c.length,h=!0);if(f<=g){f=c.substr(f,g-f);if(a.Ag!==co){a.Ce=0;var k=M.alloc();bo(a,f,b,k);e+=k.height;M.free(k);a.ad+=a.Ce}else bo(a,f,b,null),e+=d,a.ad++;a.ad===a.we&&(h=!0)}f=g+1}return a.vs=e} na.Object.defineProperties(Yg.prototype,{font:{get:function(){return this.oe},set:function(a){var b=this.oe;b!==a&&(this.oe=a,this.pe=null,this.o(),this.g("font",b,a))}},text:{get:function(){return this.Ub},set:function(a){var b=this.Ub;null!==a&&void 0!==a?a=a.toString():a="";b!==a&&(this.Ub=a,this.o(),this.g("text",b,a))}},textAlign:{get:function(){return this.Vi},set:function(a){var b=this.Vi;b===a||"start"!== a&&"end"!==a&&"left"!==a&&"right"!==a&&"center"!==a||(this.Vi=a,this.M(),this.g("textAlign",b,a))}},flip:{get:function(){return this.Td},set:function(a){var b=this.Td;b!==a&&(this.Td=a,this.M(),this.g("flip",b,a))}},verticalAlignment:{get:function(){return this.aj},set:function(a){var b=this.aj;b.w(a)||(this.aj=a=a.G(),Fl(this),this.g("verticalAlignment",b,a))}},naturalBounds:{get:function(){if(!this.rc.s()){var a= M.alloc();bo(this,this.Ub,999999,a);var b=a.width;M.free(a);a=Wn(this,b);var c=this.desiredSize;isNaN(c.width)||(b=c.width);isNaN(c.height)||(a=c.height);Ub(this.rc,b,a)}return this.rc}},isMultiline:{get:function(){return this.Pj},set:function(a){var b=this.Pj;b!==a&&(this.Pj=a,this.o(),this.g("isMultiline",b,a))}},isUnderline:{get:function(){return this.Ai},set:function(a){var b=this.Ai;b!==a&&(this.Ai=a,this.M(),this.g("isUnderline",b, a))}},isStrikethrough:{get:function(){return this.zi},set:function(a){var b=this.zi;b!==a&&(this.zi=a,this.M(),this.g("isStrikethrough",b,a))}},wrap:{get:function(){return this.Ag},set:function(a){var b=this.Ag;b!==a&&(this.Ag=a,this.o(),this.g("wrap",b,a))}},overflow:{get:function(){return this.og},set:function(a){var b=this.og;b!==a&&(this.og=a,this.o(),this.g("overflow",b,a))}},stroke:{ get:function(){return this.Jc},set:function(a){var b=this.Jc;b!==a&&(null!==a&&Tl(a,"TextBlock.stroke"),a instanceof wl&&a.freeze(),this.Jc=a,this.M(),this.g("stroke",b,a))}},lineCount:{get:function(){return this.ad}},editable:{get:function(){return this.Tn},set:function(a){var b=this.Tn;b!==a&&(this.Tn=a,this.g("editable",b,a))}},textEditor:{get:function(){return this.gq},set:function(a){var b=this.gq;b!==a&& (this.gq=a,this.g("textEditor",b,a))}},errorFunction:{get:function(){return this.Ec},set:function(a){var b=this.Ec;b!==a&&(this.Ec=a,this.g("errorFunction",b,a))}},interval:{get:function(){return this.Yd},set:function(a){var b=this.Yd;a=Math.round(a);if(b!==a&&0!==a&&isFinite(a)){this.Yd=a;this.o();var c=this.panel;null!==c&&(c.eh=null);this.g("interval",b,a)}}},graduatedStart:{get:function(){return this.Wd}, set:function(a){var b=this.Wd;b!==a&&(0>a?a=0:1<a&&(a=1),this.Wd=a,this.o(),this.g("graduatedStart",b,a))}},graduatedEnd:{get:function(){return this.Ud},set:function(a){var b=this.Ud;b!==a&&(0>a?a=0:1<a&&(a=1),this.Ud=a,this.o(),this.g("graduatedEnd",b,a))}},graduatedFunction:{get:function(){return this.Lj},set:function(a){var b=this.Lj;b!==a&&(this.Lj=a,this.o(),this.g("graduatedFunction",b,a))}},graduatedSkip:{ get:function(){return this.Vd},set:function(a){var b=this.Vd;b!==a&&(this.Vd=a,this.o(),this.g("graduatedSkip",b,a))}},textValidation:{get:function(){return this.Wi},set:function(a){var b=this.Wi;b!==a&&(this.Wi=a,this.g("textValidation",b,a))}},textEdited:{get:function(){return this.fq},set:function(a){var b=this.fq;b!==a&&(this.fq=a,this.g("textEdited",b,a))}},spacingAbove:{get:function(){return this.nf},set:function(a){var b= this.nf;b!==a&&(this.nf=a,this.g("spacingAbove",b,a))}},spacingBelow:{get:function(){return this.pf},set:function(a){var b=this.pf;b!==a&&(this.pf=a,this.g("spacingBelow",b,a))}},formatting:{get:function(){return this.si},set:function(a){var b=this.si;b!==a&&(this.si=a,this.g("formatting",b,a))}},maxLines:{get:function(){return this.we},set:function(a){var b=this.we;b!==a&&(a=Math.floor(a),0>=a&&wa(a,"> 0",Yg, "maxLines"),this.we=a,this.g("maxLines",b,a),this.o())}},metrics:{get:function(){return{arrSize:null!==this.Qb?this.Qb:[this.ub],arrText:null!==this.lb?this.lb:[this.ne],maxLineWidth:this.ub,fontHeight:this.pe}}},choices:{get:function(){return this.vn},set:function(a){var b=this.vn;b!==a&&(this.vn=a,this.g("choices",b,a))}}}); var Sn=null,Tn=null,co=new D(Yg,"None",0),$n=new D(Yg,"WrapFit",1),Pn=new D(Yg,"WrapDesiredSize",2),fo=new D(Yg,"WrapBreakAll",3),On=new D(Yg,"OverflowClip",0),Xn=new D(Yg,"OverflowEllipsis",1),Qn=new D(Yg,"FormatTrim",0),ho=new D(Yg,"FormatNone",0),go=/[ \u200b\u00ad]/,io=new cb,jo=0,ko=new cb,lo=0,Zn="...",Un="",Nn=null,Mn=!1;Yg.className="TextBlock";Yg.getEllipsis=function(){return Zn};Yg.setEllipsis=function(a){Zn=a;ko=new cb;lo=0};Yg.getBaseline=function(){return Sn}; Yg.setBaseline=function(a){Sn=a;a=Qa();for(var b=a.length,c=0;c<b;c++)a[c].Ne()};Yg.getUnderline=function(){return Tn};Yg.setUnderline=function(a){Tn=a;a=Qa();for(var b=a.length,c=0;c<b;c++)a[c].Ne()}; Yg.isValidFont=function(a){Mn||(Nn=Wg?(new Ek(null)).context:null,Mn=!0);if(null===Nn)return!0;var b=Nn.font;if(a===b||"10px sans-serif"===a)return!0;Nn.font="10px sans-serif";Nn.font=a;var c=Nn.font;if("10px sans-serif"!==c)return Nn.font=b,!0;Nn.font="19px serif";var d=Nn.font;Nn.font=a;c=Nn.font;Nn.font=b;return c!==d};Yg.None=co;Yg.WrapFit=$n;Yg.WrapDesiredSize=Pn;Yg.WrapBreakAll=fo;Yg.OverflowClip=On;Yg.OverflowEllipsis=Xn;function mo(){this.Qb=[];this.lb=[]} mo.prototype.reset=function(){this.Qb=[];this.lb=[]};mo.prototype.Dt=function(a){this.Qb=Ba(a.Qb);this.lb=Ba(a.lb)};mo.className="TextBlockMetrics";function bk(){Y.call(this);this.Zg=null;this.Xp="";this.th=lc;this.zl=vd;this.sf=this.Ec=null;this.yl=Bc;this.Td=Bg;this.mm=null;this.Su=!1;this.Zr=!0;this.Pl=!1;this.fm=null}ma(bk,Y); bk.prototype.cloneProtected=function(a){Y.prototype.cloneProtected.call(this,a);a.element=this.Zg;a.Xp=this.Xp;a.th=this.th.G();a.zl=this.zl;a.Td=this.Td;a.Ec=this.Ec;a.sf=this.sf;a.yl=this.yl.G();a.Zr=this.Zr;a.fm=this.fm};t=bk.prototype;t.jb=function(a){a===Bg||a===Dg||a===al?this.imageStretch=a:Y.prototype.jb.call(this,a)};t.toString=function(){return"Picture("+this.source+")#"+mb(this)};function dk(a){void 0===a&&(a="");""!==a?no[a]&&(delete no[a],oo--):(no=new cb,oo=0)} function po(a,b){a.ms=!0;a.vl=!1;for(var c,d=Qa(),e=d.length,f=0;f<e;f++){var g=d[f];c=a.getAttribute("src");var h=g.Pi.H(c);if(null!==h)for(var k=h.length,l=0;l<k;l++)c=h[l],g.Ms.add(c),g.Eb(),void 0===a.nv&&(a.nv=b,null!==c.sf&&c.sf(c,b))}}function qo(a,b){a.vl=b;for(var c,d=Qa(),e=d.length,f=0;f<e;f++){var g=d[f],h=a.getAttribute("src");c=g.Pi.H(h);if(null!==c){g=c.length;h=Ea();for(var k=0;k<g;k++)h.push(c[k]);for(k=0;k<g;k++)c=h[k],null!==c.Ec&&c.Ec(c,b);Ia(h)}}} t.QA=function(){if(""!==this.source){dk(this.source);var a=this.source;this.source="";this.source=a}};t.Ne=function(){this.M()}; t.ej=function(a,b){var c=this.Zg;if(null!==c){var d=c.getAttribute("src");if(!(c instanceof HTMLImageElement&&(null===d||""===d)||c.vl instanceof Event&&a instanceof Al)){d=this.naturalBounds;var e=0,f=0,g=this.Su,h=g?+c.width:c.naturalWidth;g=g?+c.height:c.naturalHeight;void 0===h&&c.videoWidth&&(h=c.videoWidth);void 0===g&&c.videoHeight&&(g=c.videoHeight);h=h||d.width;g=g||d.height;if(0!==h&&0!==g){var k=h,l=g;this.sourceRect.s()&&(e=this.th.x,f=this.th.y,h=this.th.width,g=this.th.height);var m= h,n=g,p=this.zl,r=this.yl;switch(p){case Bg:if(this.sourceRect.s())break;m>=d.width&&(e=e+r.offsetX+(m*r.x-d.width*r.x));n>=d.height&&(f=f+r.offsetY+(n*r.y-d.height*r.y));h=Math.min(d.width,m);g=Math.min(d.height,n);break;case vd:m=d.width;n=d.height;break;case Dg:case al:p===Dg?(p=Math.min(d.height/n,d.width/m),m*=p,n*=p):p===al&&(p=Math.max(d.height/n,d.width/m),m*=p,n*=p,m>=d.width&&(e=(e+r.offsetX+(m*r.x-d.width*r.x)/m)*h),n>=d.height&&(f=(f+r.offsetY+(n*r.y-d.height*r.y)/n)*g),h*=1/(m/d.width), g*=1/(n/d.height),m=d.width,n=d.height)}p=this.Cf()*b.scale;var q=m*p*n*p,u=h*g/q,v=c.__goCache;p=null;var w=ro;if(c.ms&&void 0!==v&&4<q&&u>w*w)for(null===v.cj&&(so(v,4,k,l,c),so(v,16,k,l,c)),k=v.cj,l=k.length,q=0;q<l;q++)if(k[q].ratio*k[q].ratio<u)p=k[q];else break;if(!b.rl){if(null===this.mm)if(null===this.Zg)this.mm=!1;else{k=(new Ek(null)).context;k.drawImage(this.Zg,0,0);try{k.getImageData(0,0,1,1).data[3]&&(this.mm=!1),this.mm=!1}catch(y){this.mm=!0}}if(this.mm)return}k=0;m<d.width&&(k=r.offsetX+ (d.width*r.x-m*r.x));l=0;n<d.height&&(l=r.offsetY+(d.height*r.y-n*r.y));switch(this.flip){case cl:a.translate(Math.min(d.width,m),0);a.scale(-1,1);break;case bl:a.translate(0,Math.min(d.height,n));a.scale(1,-1);break;case dl:a.translate(Math.min(d.width,m),Math.min(d.height,n)),a.scale(-1,-1)}if(b.Ke("pictureRatioOptimization")&&!b.xi&&void 0!==v&&null!==p&&1!==p.ratio){a.save();b=p.ratio;try{a.drawImage(p.source,e/b,f/b,Math.min(p.source.width,h/b),Math.min(p.source.height,g/b),k,l,Math.min(d.width, m),Math.min(d.height,n))}catch(y){this.Zr=!1}a.restore()}else try{a.drawImage(c,e,f,h,g,k,l,Math.min(d.width,m),Math.min(d.height,n))}catch(y){this.Zr=!1}switch(this.flip){case cl:a.scale(-1,1);a.translate(-Math.min(d.width,m),0);break;case bl:a.scale(1,-1);a.translate(0,-Math.min(d.height,n));break;case dl:a.scale(-1,-1),a.translate(-Math.min(d.width,m),-Math.min(d.height,n))}}}}}; t.Gm=function(a,b,c,d){var e=this.desiredSize,f=nl(this,!0),g=this.Zg,h=this.Su;if(h||!this.Pl&&g&&g.complete)this.Pl=!0;null===g&&(isFinite(e.width)||(a=0),isFinite(e.height)||(b=0));isFinite(e.width)||f===vd||f===Zk?(isFinite(a)||(a=this.sourceRect.s()?this.sourceRect.width:h?+g.width:g.naturalWidth),c=0):null!==g&&!1!==this.Pl&&(a=this.sourceRect.s()?this.sourceRect.width:h?+g.width:g.naturalWidth);isFinite(e.height)||f===vd||f===$k?(isFinite(b)||(b=this.sourceRect.s()?this.sourceRect.height:h? +g.height:g.naturalHeight),d=0):null!==g&&!1!==this.Pl&&(b=this.sourceRect.s()?this.sourceRect.height:h?+g.height:g.naturalHeight);isFinite(e.width)&&(a=e.width);isFinite(e.height)&&(b=e.height);e=this.maxSize;f=this.minSize;c=Math.max(c,f.width);d=Math.max(d,f.height);a=Math.min(e.width,a);b=Math.min(e.height,b);a=Math.max(c,a);b=Math.max(d,b);null===g||g.complete||(isFinite(a)||(a=0),isFinite(b)||(b=0));Ub(this.rc,a,b);kl(this,0,0,a,b)};t.Hh=function(a,b,c,d){pl(this,a,b,c,d)}; na.Object.defineProperties(bk.prototype,{element:{get:function(){return this.Zg},set:function(a){var b=this.Zg;if(b!==a){null===a||a instanceof HTMLImageElement||a instanceof HTMLVideoElement||a instanceof HTMLCanvasElement||B("Picture.element must be an instance of Image, Canvas, or Video, not: "+a);this.Su=a instanceof HTMLCanvasElement;this.Zg=a;if(null!==a)if(a instanceof HTMLCanvasElement||!0===a.complete)a.vl instanceof Event&&null!==this.Ec&&this.Ec(this,a.vl), !0===a.ms&&null!==this.sf&&this.sf(this,a.nv),a.ms=!0,this.desiredSize.s()||(pj(this,!1),this.o());else{var c=this;a.zx||(a.addEventListener("load",function(b){po(a,b);c.desiredSize.s()||(pj(c,!1),c.o())}),a.addEventListener("error",function(b){qo(a,b)}),a.zx=!0)}this.g("element",b,a);this.M()}}},source:{get:function(){return this.Xp},set:function(a){var b=this.Xp;if(b!==a){this.Xp=a;var c=no,d=this.diagram;if(Wg){var e=null;if(void 0!==c[a])e=c[a];else if(""!==a){30< oo&&(dk(),c=no);e=ua("img");var f=this;e.addEventListener("load",function(a){po(e,a);f.desiredSize.s()||(pj(f,!1),f.o())});e.addEventListener("error",function(a){qo(e,a)});e.zx=!0;var g=this.fm;null!==g&&(e.crossOrigin=g(this));e.src=a;c[a]=e;oo++}null!==d&&ck(d,this);this.element=e;null!==d&&null!==e&&ak(d,this);null!==e&&void 0===e.__goCache&&(e.__goCache=new to);this.o();this.M()}this.g("source",b,a)}}},sourceCrossOrigin:{get:function(){return this.fm},set:function(a){if(this.fm!== a&&(this.fm=a,null!==this.element)){var b=this.element.getAttribute("src");null===a&&"string"===typeof b?this.element.crossOrigin=null:null!==a&&(this.element.crossOrigin=a(this));this.element.src=b}}},sourceRect:{get:function(){return this.th},set:function(a){var b=this.th;b.w(a)||(this.th=a=a.G(),this.M(),this.g("sourceRect",b,a))}},imageStretch:{get:function(){return this.zl},set:function(a){var b=this.zl;b!==a&&(this.zl=a,this.M(),this.g("imageStretch", b,a))}},flip:{get:function(){return this.Td},set:function(a){var b=this.Td;b!==a&&(this.Td=a,this.M(),this.g("flip",b,a))}},imageAlignment:{get:function(){return this.yl},set:function(a){var b=this.yl;b.w(a)||(this.yl=a=a.G(),this.o(),this.g("imageAlignment",b,a))}},errorFunction:{get:function(){return this.Ec},set:function(a){var b=this.Ec;b!==a&&(this.Ec=a,this.g("errorFunction",b,a))}},successFunction:{ get:function(){return this.sf},set:function(a){var b=this.sf;b!==a&&(this.sf=a,this.g("successFunction",b,a))}},naturalBounds:{get:function(){return this.rc}}});bk.prototype.redraw=bk.prototype.Ne;bk.prototype.reloadSource=bk.prototype.QA;var no=null,oo=0,ro=4;bk.className="Picture";no=new cb;bk.clearCache=dk;function to(){this.cj=null} function so(a,b,c,d,e){null===a.cj&&(a.cj=[]);var f=new Ek(null),g=f.context,h=1/b;f.width=c/b;f.height=d/b;0!==f.width&&0!==f.height&&(b=new uo(f.Ga,b),c=1,0<a.cj.length&&(c=a.cj[a.cj.length-1],e=c.source,c=c.ratio),g.setTransform(h*c,0,0,h*c,0,0),g.drawImage(e,0,0),a.cj.push(b))}to.className="PictureCacheArray";function uo(a,b){this.source=a;this.ratio=b}uo.className="PictureCacheInstance";function vo(){this.Lt=new td;this.ic=null}t=vo.prototype; t.reset=function(a){null!==a?(a.ea(),this.Lt=a,a.figures.clear()):this.Lt=new td;this.ic=null};function Id(a,b,c,d,e){a.ic=new se;a.ic.startX=b;a.ic.startY=c;a.ic.isFilled=d;a.Lt.figures.add(a.ic);void 0!==e&&(a.ic.isShadowed=e)}function Xd(a){var b=a.ic.segments.length;0<b&&a.ic.segments.J(b-1).close()}t.fr=function(a){this.ic.isShadowed=a};t.moveTo=function(a,b,c){void 0===c&&(c=!1);var d=new te(ae);d.endX=a;d.endY=b;c&&d.close();this.ic.segments.add(d)}; t.lineTo=function(a,b,c){void 0===c&&(c=!1);var d=new te(yd);d.endX=a;d.endY=b;c&&d.close();this.ic.segments.add(d)};function Ud(a,b,c,d,e,f,g){var h;void 0===h&&(h=!1);var k=new te(be);k.point1X=b;k.point1Y=c;k.point2X=d;k.point2Y=e;k.endX=f;k.endY=g;h&&k.close();a.ic.segments.add(k)}function Vd(a,b,c,d,e){var f;void 0===f&&(f=!1);var g=new te(ce);g.point1X=b;g.point1Y=c;g.endX=d;g.endY=e;f&&g.close();a.ic.segments.add(g)} t.arcTo=function(a,b,c,d,e,f,g){void 0===f&&(f=0);void 0===g&&(g=!1);var h=new te(de);h.startAngle=a;h.sweepAngle=b;h.centerX=c;h.centerY=d;h.radiusX=e;h.radiusY=0!==f?f:e;g&&h.close();this.ic.segments.add(h)};function Wd(a,b,c,d,e,f,g,h){var k;void 0===k&&(k=!1);b=new te(ee,g,h,b,c,d,e,f);k&&b.close();a.ic.segments.add(b)}function Hd(a){var b=Yd;if(null!==b)return Yd=null,b.reset(a),b;b=new vo;b.reset(a);return b}var Yd=null;vo.className="StreamGeometryContext"; function wo(a,b){var c=a.toLowerCase(),d=L.Re;d[a]=b;d[c]=a}wo("Rectangle",function(a,b,c){a="r"+b+","+c;var d=L.Th[a];if(void 0!==d)return d;d=new td(Dd);d.endX=b;d.endY=c;50>L.Uh&&(L.Th[a]=d,L.Uh++);return d});wo("Square",function(a,b,c){a="s"+b+","+c;var d=L.Th[a];if(void 0!==d)return d;d=new td(Dd);d.endX=b;d.endY=c;d.defaultStretch=Dg;50>L.Uh&&(L.Th[a]=d,L.Uh++);return d}); wo("RoundedRectangle",function(a,b,c){var d=a?a.parameter1:NaN;if(isNaN(d)||0>d)d=5;d=Math.min(d,b/3);d=Math.min(d,c/3);a=d*L.Lg;b=(new td).add((new se(d,0,!0)).add(new te(yd,b-d,0)).add(new te(be,b,d,b-a,0,b,a)).add(new te(yd,b,c-d)).add(new te(be,b-d,c,b,c-a,b-a,c)).add(new te(yd,d,c)).add(new te(be,0,c-d,a,c,0,c-a)).add(new te(yd,0,d)).add((new te(be,d,0,0,a,a,0)).close()));1<a&&(b.spot1=new O(0,0,a,a),b.spot2=new O(1,1,-a,-a));return b});wo("Border","RoundedRectangle"); wo("Ellipse",function(a,b,c){a="e"+b+","+c;var d=L.Th[a];if(void 0!==d)return d;d=new td(Ed);d.endX=b;d.endY=c;d.spot1=hd;d.spot2=id;50>L.Uh&&(L.Th[a]=d,L.Uh++);return d});wo("Circle",function(a,b,c){a="c"+b+","+c;var d=L.Th[a];if(void 0!==d)return d;d=new td(Ed);d.endX=b;d.endY=c;d.spot1=hd;d.spot2=id;d.defaultStretch=Dg;50>L.Uh&&(L.Th[a]=d,L.Uh++);return d});wo("TriangleRight",function(a,b,c){return(new td).add((new se(0,0)).add(new te(yd,b,.5*c)).add((new te(yd,0,c)).close())).Xm(0,.25,.5,.75)}); wo("TriangleDown",function(a,b,c){return(new td).add((new se(0,0)).add(new te(yd,b,0)).add((new te(yd,.5*b,c)).close())).Xm(.25,0,.75,.5)});wo("TriangleLeft",function(a,b,c){return(new td).add((new se(b,c)).add(new te(yd,0,.5*c)).add((new te(yd,b,0)).close())).Xm(.5,.25,1,.75)});wo("TriangleUp",function(a,b,c){return(new td).add((new se(b,c)).add(new te(yd,0,c)).add((new te(yd,.5*b,0)).close())).Xm(.25,.5,.75,1)});wo("Triangle","TriangleUp"); wo("Diamond",function(a,b,c){return(new td).add((new se(.5*b,0)).add(new te(yd,0,.5*c)).add(new te(yd,.5*b,c)).add((new te(yd,b,.5*c)).close())).Xm(.25,.25,.75,.75)});wo("LineH",function(a,b,c){a=new td(wd);a.startX=0;a.startY=c/2;a.endX=b;a.endY=c/2;return a});wo("LineV",function(a,b,c){a=new td(wd);a.startX=b/2;a.startY=0;a.endX=b/2;a.endY=c;return a});wo("None","Rectangle");wo("BarH","Rectangle");wo("BarV","Rectangle");wo("MinusLine","LineH"); wo("PlusLine",function(a,b,c){return(new td).add((new se(0,c/2,!1)).add(new te(yd,b,c/2)).add(new te(ae,b/2,0)).add(new te(yd,b/2,c)))});wo("XLine",function(a,b,c){return(new td).add((new se(0,c,!1)).add(new te(yd,b,0)).add(new te(ae,0,0)).add(new te(yd,b,c)))}); L.bn={"":"",Standard:"F1 m 0,0 l 8,4 -8,4 2,-4 z",Backward:"F1 m 8,0 l -2,4 2,4 -8,-4 z",Triangle:"F1 m 0,0 l 8,4.62 -8,4.62 z",BackwardTriangle:"F1 m 8,4 l 0,4 -8,-4 8,-4 0,4 z",Boomerang:"F1 m 0,0 l 8,4 -8,4 4,-4 -4,-4 z",BackwardBoomerang:"F1 m 8,0 l -8,4 8,4 -4,-4 4,-4 z",SidewaysV:"m 0,0 l 8,4 -8,4 0,-1 6,-3 -6,-3 0,-1 z",BackwardV:"m 8,0 l -8,4 8,4 0,-1 -6,-3 6,-3 0,-1 z",OpenTriangle:"m 0,0 l 8,4 -8,4",BackwardOpenTriangle:"m 8,0 l -8,4 8,4",OpenTriangleLine:"m 0,0 l 8,4 -8,4 m 8.5,0 l 0,-8", BackwardOpenTriangleLine:"m 8,0 l -8,4 8,4 m -8.5,0 l 0,-8",OpenTriangleTop:"m 0,0 l 8,4 m 0,4",BackwardOpenTriangleTop:"m 8,0 l -8,4 m 0,4",OpenTriangleBottom:"m 0,8 l 8,-4",BackwardOpenTriangleBottom:"m 0,4 l 8,4",HalfTriangleTop:"F1 m 0,0 l 0,4 8,0 z m 0,8",BackwardHalfTriangleTop:"F1 m 8,0 l 0,4 -8,0 z m 0,8",HalfTriangleBottom:"F1 m 0,4 l 0,4 8,-4 z",BackwardHalfTriangleBottom:"F1 m 8,4 l 0,4 -8,-4 z",ForwardSemiCircle:"m 4,0 b 270 180 0 4 4",BackwardSemiCircle:"m 4,8 b 90 180 0 -4 4",Feather:"m 0,0 l 3,4 -3,4", BackwardFeather:"m 3,0 l -3,4 3,4",DoubleFeathers:"m 0,0 l 3,4 -3,4 m 3,-8 l 3,4 -3,4",BackwardDoubleFeathers:"m 3,0 l -3,4 3,4 m 3,-8 l -3,4 3,4",TripleFeathers:"m 0,0 l 3,4 -3,4 m 3,-8 l 3,4 -3,4 m 3,-8 l 3,4 -3,4",BackwardTripleFeathers:"m 3,0 l -3,4 3,4 m 3,-8 l -3,4 3,4 m 3,-8 l -3,4 3,4",ForwardSlash:"m 0,8 l 5,-8",BackSlash:"m 0,0 l 5,8",DoubleForwardSlash:"m 0,8 l 4,-8 m -2,8 l 4,-8",DoubleBackSlash:"m 0,0 l 4,8 m -2,-8 l 4,8",TripleForwardSlash:"m 0,8 l 4,-8 m -2,8 l 4,-8 m -2,8 l 4,-8", TripleBackSlash:"m 0,0 l 4,8 m -2,-8 l 4,8 m -2,-8 l 4,8",Fork:"m 0,4 l 8,0 m -8,0 l 8,-4 m -8,4 l 8,4",BackwardFork:"m 8,4 l -8,0 m 8,0 l -8,-4 m 8,4 l -8,4",LineFork:"m 0,0 l 0,8 m 0,-4 l 8,0 m -8,0 l 8,-4 m -8,4 l 8,4",BackwardLineFork:"m 8,4 l -8,0 m 8,0 l -8,-4 m 8,4 l -8,4 m 8,-8 l 0,8",CircleFork:"F1 m 6,4 b 0 360 -3 0 3 z m 0,0 l 6,0 m -6,0 l 6,-4 m -6,4 l 6,4",BackwardCircleFork:"F1 m 0,4 l 6,0 m -6,-4 l 6,4 m -6,4 l 6,-4 m 6,0 b 0 360 -3 0 3",CircleLineFork:"F1 m 6,4 b 0 360 -3 0 3 z m 1,-4 l 0,8 m 0,-4 l 6,0 m -6,0 l 6,-4 m -6,4 l 6,4", BackwardCircleLineFork:"F1 m 0,4 l 6,0 m -6,-4 l 6,4 m -6,4 l 6,-4 m 0,-4 l 0,8 m 7,-4 b 0 360 -3 0 3",Circle:"F1 m 8,4 b 0 360 -4 0 4 z",Block:"F1 m 0,0 l 0,8 8,0 0,-8 z",StretchedDiamond:"F1 m 0,3 l 5,-3 5,3 -5,3 -5,-3 z",Diamond:"F1 m 0,4 l 4,-4 4,4 -4,4 -4,-4 z",Chevron:"F1 m 0,0 l 5,0 3,4 -3,4 -5,0 3,-4 -3,-4 z",StretchedChevron:"F1 m 0,0 l 8,0 3,4 -3,4 -8,0 3,-4 -3,-4 z",NormalArrow:"F1 m 0,2 l 4,0 0,-2 4,4 -4,4 0,-2 -4,0 z",X:"m 0,0 l 8,8 m 0,-8 l -8,8",TailedNormalArrow:"F1 m 0,0 l 2,0 1,2 3,0 0,-2 2,4 -2,4 0,-2 -3,0 -1,2 -2,0 1,-4 -1,-4 z", DoubleTriangle:"F1 m 0,0 l 4,4 -4,4 0,-8 z m 4,0 l 4,4 -4,4 0,-8 z",BigEndArrow:"F1 m 0,0 l 5,2 0,-2 3,4 -3,4 0,-2 -5,2 0,-8 z",ConcaveTailArrow:"F1 m 0,2 h 4 v -2 l 4,4 -4,4 v -2 h -4 l 2,-2 -2,-2 z",RoundedTriangle:"F1 m 0,1 a 1,1 0 0 1 1,-1 l 7,3 a 0.5,1 0 0 1 0,2 l -7,3 a 1,1 0 0 1 -1,-1 l 0,-6 z",SimpleArrow:"F1 m 1,2 l -1,-2 2,0 1,2 -1,2 -2,0 1,-2 5,0 0,-2 2,2 -2,2 0,-2 z",AccelerationArrow:"F1 m 0,0 l 0,8 0.2,0 0,-8 -0.2,0 z m 2,0 l 0,8 1,0 0,-8 -1,0 z m 3,0 l 2,0 2,4 -2,4 -2,0 0,-8 z",BoxArrow:"F1 m 0,0 l 4,0 0,2 2,0 0,-2 2,4 -2,4 0,-2 -2,0 0,2 -4,0 0,-8 z", TriangleLine:"F1 m 8,4 l -8,-4 0,8 8,-4 z m 0.5,4 l 0,-8",CircleEndedArrow:"F1 m 10,4 l -2,-3 0,2 -2,0 0,2 2,0 0,2 2,-3 z m -4,0 b 0 360 -3 0 3 z",DynamicWidthArrow:"F1 m 0,3 l 2,0 2,-1 2,-2 2,4 -2,4 -2,-2 -2,-1 -2,0 0,-2 z",EquilibriumArrow:"m 0,3 l 8,0 -3,-3 m 3,5 l -8,0 3,3",FastForward:"F1 m 0,0 l 3.5,4 0,-4 3.5,4 0,-4 1,0 0,8 -1,0 0,-4 -3.5,4 0,-4 -3.5,4 0,-8 z",Kite:"F1 m 0,4 l 2,-4 6,4 -6,4 -2,-4 z",HalfArrowTop:"F1 m 0,0 l 4,4 4,0 -8,-4 z m 0,8",HalfArrowBottom:"F1 m 0,8 l 4,-4 4,0 -8,4 z", OpposingDirectionDoubleArrow:"F1 m 0,4 l 2,-4 0,2 4,0 0,-2 2,4 -2,4 0,-2 -4,0 0,2 -2,-4 z",PartialDoubleTriangle:"F1 m 0,0 4,3 0,-3 4,4 -4,4 0,-3 -4,3 0,-8 z",LineCircle:"F1 m 0,0 l 0,8 m 7 -4 b 0 360 -3 0 3 z",DoubleLineCircle:"F1 m 0,0 l 0,8 m 2,-8 l 0,8 m 7 -4 b 0 360 -3 0 3 z",TripleLineCircle:"F1 m 0,0 l 0,8 m 2,-8 l 0,8 m 2,-8 l 0,8 m 7 -4 b 0 360 -3 0 3 z",CircleLine:"F1 m 6 4 b 0 360 -3 0 3 z m 1,-4 l 0,8",DiamondCircle:"F1 m 8,4 l -4,4 -4,-4 4,-4 4,4 m 8,0 b 0 360 -4 0 4 z",PlusCircle:"F1 m 8,4 b 0 360 -4 0 4 l -8 0 z m -4 -4 l 0 8", OpenRightTriangleTop:"m 8,0 l 0,4 -8,0 m 0,4",OpenRightTriangleBottom:"m 8,8 l 0,-4 -8,0",Line:"m 0,0 l 0,8",DoubleLine:"m 0,0 l 0,8 m 2,0 l 0,-8",TripleLine:"m 0,0 l 0,8 m 2,0 l 0,-8 m 2,0 l 0,8",PentagonArrow:"F1 m 8,4 l -4,-4 -4,0 0,8 4,0 4,-4 z"}; function V(a){X.call(this,a);this.D=2408959;this.ih=this.Pf="";this.Bp=this.xp=this.Mp=this.Co=null;this.Op="";this.Nf=this.oo=this.Np=this.sh=null;this.zp="";this.yp=Qb;this.Ub=this.Cp="";this.Ei=this.yn=this.li=null;this.fg=(new I(NaN,NaN)).freeze();this.Jo="";this.df=null;this.Ko=vc;this.Dp=Zc;this.To=Gb;this.Lo=Hb;this.Qn=null;this.Do=127;this.Sp=Ib;this.Rp="gray";this.lf=4;this.Bx=-1;this.qq=NaN;this.fz=new N;this.Xj=null;this.kh=NaN}ma(V,X); V.prototype.cloneProtected=function(a){X.prototype.cloneProtected.call(this,a);a.D=this.D&-4097|49152;a.Pf=this.Pf;a.ih=this.ih;a.Co=this.Co;a.Mp=this.Mp;a.xp=this.xp;a.Bp=this.Bp;a.Op=this.Op;a.Np=this.Np;a.oo=this.oo;a.Nf=null;a.zp=this.zp;a.yp=this.yp.G();a.Cp=this.Cp;a.Dp=this.Dp.G();a.Ub=this.Ub;a.yn=this.yn;a.fg.assign(this.fg);a.Jo=this.Jo;a.Ko=this.Ko.G();a.To=this.To.G();a.Lo=this.Lo.G();a.Qn=this.Qn;a.Do=this.Do;a.Sp=this.Sp.G();a.Rp=this.Rp;a.lf=this.lf;a.qq=this.qq}; V.prototype.Af=function(a){X.prototype.Af.call(this,a);a.Nh();a.sh=null;a.df=null;a.Xj=null};V.prototype.toString=function(){var a=Ja(this.constructor)+"#"+mb(this);null!==this.data&&(a+="("+Ka(this.data)+")");return a};V.prototype.Rk=function(a,b,c,d,e,f,g){var h=this.diagram;null!==h&&(a===Be&&"elements"===b?e instanceof X?Hj(e,function(a){Jj(h.partManager,a);Ij(h,a)}):ak(h,e):a===Ce&&"elements"===b&&(e instanceof X?Hj(e,function(a){Mj(h.partManager,a,h)}):ck(h,e)),h.bb(a,b,c,d,e,f,g))}; V.prototype.Ca=function(a){X.prototype.Ca.call(this,a);if(null!==this.data){for(var b=this.W.j,c=b.length,d=0;d<c;d++){var e=b[d];e instanceof X&&Hj(e,function(a){null!==a.data&&a.Ca()})}for(b=this.adornments;b.next();)b.value.Ca(a)}};V.prototype.updateRelationshipsFromData=function(){null!==this.data&&this.diagram.partManager.updateRelationshipsFromData(this)};V.prototype.wk=function(a){var b=this.Nf;return null===b?null:b.H(a)}; V.prototype.Fh=function(a,b){if(null!==b){var c=null,d=this.Nf;null!==d&&(c=d.H(a));if(c!==b){if(null!==c){var e=c.diagram;null!==e&&e.remove(c)}null===d&&(this.Nf=d=new H);b.Pf!==a&&(b.category=a);d.add(a,b);a=this.diagram;null!==a&&(a.add(b),a=b.adornedObject,null!==a&&(a=a.ij(),null!==a&&(b.data=a.data)))}}};V.prototype.Jf=function(a){var b=this.Nf;if(null!==b){var c=b.H(a);if(null!==c){var d=c.diagram;null!==d&&d.remove(c)}b.remove(a);0===b.count&&(this.Nf=null)}}; V.prototype.nk=function(){var a=this.Nf;if(null!==a){var b=Ea();for(a=a.iterator;a.next();)b.push(a.key);a=b.length;for(var c=0;c<a;c++)this.Jf(b[c]);Ia(b)}}; V.prototype.updateAdornments=function(){var a=this.diagram;if(null!==a){for(var b=this.adornments;b.next();){var c=b.value;c.o();c.placeholder&&c.placeholder.o()}a:{if(this.isSelected&&this.selectionAdorned&&(b=this.selectionObject,null!==b&&this.actualBounds.s()&&this.isVisible()&&b.If()&&b.actualBounds.s())){c=this.wk("Selection");if(null===c){c=this.selectionAdornmentTemplate;null===c&&(c=this.Oh()?a.linkSelectionAdornmentTemplate:this instanceof U?a.groupSelectionAdornmentTemplate:a.nodeSelectionAdornmentTemplate); if(!(c instanceof Qe))break a;Ag(c);c=c.copy();null!==c&&(this.Oh()&&this.selectionObject===this.path&&(c.type=X.Link),c.adornedObject=b)}if(null!==c){c.type===X.Link&&c.o();this.Fh("Selection",c);break a}}this.Jf("Selection")}xo(this,a);for(b=this.adornments;b.next();)b.value.Ca()}};V.prototype.Mb=function(){var a=this.diagram;null!==a&&(Vi(a),0!==(this.D&16384)!==!0&&(this.D|=16384,a.Eb()))};function mi(a){0!==(a.D&16384)!==!1&&(a.updateAdornments(),a.D&=-16385)} function xo(a,b){b.toolManager.mouseDownTools.each(function(b){b.isEnabled&&b.updateAdornments(a)});b.toolManager.updateAdornments(a)}function yo(a){if(!1===wj(a)){zo(a,!0);a.Gl();var b=a.diagram;null!==b&&(b.wd.add(a),b.Eb())}}function Ao(a){a.D|=2097152;if(!1!==wj(a)){var b=a.position,c=a.location;c.s()&&b.s()||Bo(a,b,c);c=a.yb;var d=N.alloc().assign(c);c.ea();c.x=b.x;c.y=b.y;c.freeze();a.Hm(d,c);N.free(d);zo(a,!1)}}V.prototype.move=function(a,b){!0===b?this.location=a:this.position=a}; V.prototype.moveTo=function(a,b,c){a=I.allocAt(a,b);this.move(a,c);I.free(a)};V.prototype.isVisible=function(){if(!this.visible)return!1;var a=this.layer;if(null!==a){if(!a.visible)return!1;a=a.diagram;if(null!==a&&a.animationManager.cu(this))return!0}a=this.containingGroup;return null===a||a.isSubGraphExpanded&&a.isVisible()?!0:!1};t=V.prototype;t.Pb=function(a){var b=this.diagram;a?(this.C(4),this.Mb(),null!==b&&b.wd.add(this)):(this.C(8),this.nk());this.Nh();null!==b&&(b.Oa(),b.M())}; t.ab=function(a){if(this.name===a)return this;var b=this.Xj;null===b&&(this.Xj=b=new H);if(null!==b.H(a))return b.H(a);var c=X.prototype.ab.call(this,a);if(null!==c)return b.set(a,c),c;b.set(a,null);return null};t.Ff=function(a,b,c){void 0===c&&(c=new I);b=b.nc()?Bc:b;var d=a.naturalBounds;c.h(d.width*b.x+b.offsetX,d.height*b.y+b.offsetY);if(null===a||a===this)return c;a.transform.sa(c);for(a=a.panel;null!==a&&a!==this;)a.transform.sa(c),a=a.panel;this.eg.sa(c);c.offset(-this.qc.x,-this.qc.y);return c}; t.mj=function(a){void 0===a&&(a=new N);return a.assign(this.actualBounds)};t.Ta=function(){!0===uj(this)&&this.measure(Infinity,Infinity);this.arrange()};function Fj(a,b){var c=a.fz;isNaN(a.kh)&&(a.kh=gn(a));var d=a.kh;var e=2*d;if(!a.isShadowed)return c.h(b.x-1-d,b.y-1-d,b.width+2+e,b.height+2+e),c;d=b.x;e=b.y;var f=b.width;b=b.height;var g=a.shadowBlur;a=a.shadowOffset;f+=g;b+=g;d-=g/2;e-=g/2;0<a.x?f+=a.x:(d+=a.x,f-=a.x);0<a.y?b+=a.y:(e+=a.y,b-=a.y);c.h(d-1,e-1,f+2,b+2);return c} V.prototype.arrange=function(){if(!1===vj(this))Ao(this);else{ol(this,!1);var a=this.yb,b=N.alloc();b.assign(a);var c=yg(this);this.Hh(0,0,this.qc.width,this.qc.height);var d=this.position;Bo(this,d,this.location);a.ea();a.x=d.x;a.y=d.y;a.freeze();this.Hm(b,a);b.w(a)?this.Nd(c):!this.Pc()||L.A(b.width,a.width)&&L.A(b.height,a.height)||0<=this.Bx&&this.C(16);N.free(b);zo(this,!1)}};t=V.prototype; t.Hm=function(a,b){var c=this.diagram;if(null!==c){var d=!1;if(!1===c.ui&&a.s()){var e=N.alloc();e.assign(c.documentBounds);e.Kw(c.padding);a.x>e.x&&a.y>e.y&&a.right<e.right&&a.bottom<e.bottom&&b.x>e.x&&b.y>e.y&&b.right<e.right&&b.bottom<e.bottom&&(d=!0);N.free(e)}0!==(this.D&65536)!==!0&&a.w(b)||Kj(this,d,c);c.M();$b(a,b)||(this instanceof W&&!c.undoManager.isUndoingRedoing&&this.td(),this.Nh())}}; t.Fw=function(a,b){if(this.Oh()||!a.s())return!1;var c=this.diagram;null!==c&&Co(this,c,a,b);this.la=a;this.D&=-2097153;var d=this.fg;!d.s()||null!==c&&!c.animationManager.isTicking&&c.undoManager.isUndoingRedoing||(c=d.copy(),d.h(d.x+(a.x-b.x),d.y+(a.y-b.y)),this.g("location",c,d.copy()));!1===wj(this)&&!1===vj(this)&&(yo(this),Ao(this));return!0};function Co(a,b,c,d){null===b||a instanceof Qe||(b=b.animationManager,b.ff&&Qh(b,a,d.copy(),c.copy()))} t.er=function(a,b,c){var d=this.fg,e=this.la;if(c){if(d.x===a&&d.y===b)return;wj(this)||vj(this)?e.h(NaN,NaN):e.h(e.x+a-d.x,e.y+b-d.y);d.h(a,b)}else{if(e.x===a&&e.y===b)return;wj(this)||vj(this)?this.lu():d.h(d.x+a-e.x,d.y+b-e.y);e.h(a,b)}yo(this)};t.lu=function(){this.D&=-2097153;yo(this)}; function Bo(a,b,c){var d=I.alloc(),e=a.locationSpot,f=a.locationObject;e.nc()&&B("determineOffset: Part's locationSpot must be real: "+e.toString());var g=f.naturalBounds,h=f instanceof Mf?f.strokeWidth:0;d.Tk(0,0,g.width+h,g.height+h,e);if(f!==a)for(d.offset(-h/2,-h/2),f.transform.sa(d),e=f.panel;null!==e&&e!==a;)e.transform.sa(d),e=e.panel;a.eg.sa(d);d.offset(-a.qc.x,-a.qc.y);e=a.diagram;f=c.s();g=b.s();f&&g?0!==(a.D&2097152)?Do(a,b,c,e,d):Eo(a,b,c,e,d):f?Do(a,b,c,e,d):g&&Eo(a,b,c,e,d);a.D|=2097152; I.free(d);a.Gl()}function Do(a,b,c,d,e){var f=b.x,g=b.y;b.h(c.x-e.x,c.y-e.y);null!==d&&(c=d.animationManager,(d=c.defaultAnimation.isAnimating)||!c.ff||a instanceof Qe||Qh(c,a,new I(f,g),b),d||b.x===f&&b.y===g||a.g("position",new I(f,g),b.copy()))}function Eo(a,b,c,d,e){var f=c.copy();c.h(b.x+e.x,b.y+e.y);c.w(f)||null===d||a.g("location",f,c.copy())} function Kj(a,b,c){ql(a,!1);a instanceof W&&zk(c,a);a.layer.isTemporary||b||c.Oa();b=a.yb;var d=c.viewportBounds;d.s()?yg(a)?(cc(b,d)||a.Nd(!1),a.updateAdornments()):b.Oc(d)?(a.Nd(!0),a.updateAdornments()):a.Mb():c.wi=!0}t.rj=function(){return!0};t.Pc=function(){return!0};t.Oh=function(){return!1};t.Hf=function(){return!0}; function Fo(a,b,c,d){b.constructor===a.constructor||Go||(Go=!0,xa('Should not change the class of the Part when changing category from "'+c+'" to "'+d+'"'),xa(" Old class: "+Ja(a.constructor)+", new class: "+Ja(b.constructor)+", part: "+a.toString()));a.nk();var e=a.data;c=a.layerName;var f=a.isSelected,g=a.isHighlighted,h=!0,k=!0,l=!1;a instanceof W&&(h=a.isTreeLeaf,k=a.isTreeExpanded,l=a.wasTreeExpanded);b.Af(a);b.cloneProtected(a);a.Pf=d;a.o();a.M();b=a.diagram;d=!0;null!==b&&(d=b.skipsUndoManager, b.skipsUndoManager=!0);a.nb=e;a.D=f?a.D|4096:a.D&-4097;a.D=g?a.D|524288:a.D&-524289;a instanceof W&&(a.P=h?a.P|4:a.P&-5,a.P=k?a.P|1:a.P&-2,a.P=l?a.P|2:a.P&-3);null!==e&&a.Ca();e=a.layerName;e!==c&&(a.ih=c,a.layerName=e);null!==b&&(b.skipsUndoManager=d);a.Pc()&&a.C(64)}V.prototype.canCopy=function(){if(!this.copyable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowCopy)return!1;a=a.diagram;return null===a?!0:a.allowCopy?!0:!1}; V.prototype.canDelete=function(){if(!this.deletable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowDelete)return!1;a=a.diagram;return null===a?!0:a.allowDelete?!0:!1};V.prototype.canEdit=function(){if(!this.textEditable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowTextEdit)return!1;a=a.diagram;return null===a?!0:a.allowTextEdit?!0:!1}; V.prototype.canGroup=function(){if(!this.groupable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowGroup)return!1;a=a.diagram;return null===a?!0:a.allowGroup?!0:!1};V.prototype.canMove=function(){if(!this.movable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowMove)return!1;a=a.diagram;return null===a?!0:a.allowMove?!0:!1}; V.prototype.canReshape=function(){if(!this.reshapable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowReshape)return!1;a=a.diagram;return null===a?!0:a.allowReshape?!0:!1};V.prototype.canResize=function(){if(!this.resizable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowResize)return!1;a=a.diagram;return null===a?!0:a.allowResize?!0:!1}; V.prototype.canRotate=function(){if(!this.rotatable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowRotate)return!1;a=a.diagram;return null===a?!0:a.allowRotate?!0:!1};V.prototype.canSelect=function(){if(!this.selectable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowSelect)return!1;a=a.diagram;return null===a?!0:a.allowSelect?!0:!1};function wj(a){return 0!==(a.D&32768)}function zo(a,b){a.D=b?a.D|32768:a.D&-32769}function ql(a,b){a.D=b?a.D|65536:a.D&-65537} function yg(a){return 0!==(a.D&131072)}t=V.prototype;t.Nd=function(a){this.D=a?this.D|131072:this.D&-131073};function Ho(a,b){a.D=b?a.D|1048576:a.D&-1048577}t.Nh=function(){var a=this.containingGroup;null!==a&&(a.o(),null!==a.placeholder&&a.placeholder.o(),a.td())};t.M=function(){var a=this.diagram;null!==a&&!vj(this)&&!wj(this)&&this.isVisible()&&this.yb.s()&&a.M(Fj(this,this.yb))}; t.o=function(){X.prototype.o.call(this);var a=this.diagram;null!==a&&(a.wd.add(this),this instanceof W&&null!==this.labeledLink&&Fl(this.labeledLink),a.Eb(!0))};t.Jq=function(a){a||(a=this.li,null!==a&&Io(a,this))};t.Kq=function(a){a||(a=this.li,null!==a&&Jo(a,this))};t.uk=function(){var a=this.data;if(null!==a){var b=this.diagram;null!==b&&(b=b.model,null!==b&&b.Mm(a))}};t.bA=function(){return Ko(this,this)}; function Ko(a,b){var c=b.containingGroup;return null!==c?1+Ko(a,c):b instanceof W&&(b=b.labeledLink,null!==b)?Ko(a,b):0}t.eA=function(){return Lo(this,this)};function Lo(a,b){var c=b.containingGroup;return null!==c||b instanceof W&&(c=b.labeledLink,null!==c)?Lo(a,c):b}t.Kd=function(a){return a instanceof U?Mo(this,this,a):!1};function Mo(a,b,c){if(b===c||null===c)return!1;var d=b.containingGroup;return null===d||d!==c&&!Mo(a,d,c)?b instanceof W&&(b=b.labeledLink,null!==b)?Mo(a,b,c):!1:!0} t.oy=function(a){if(null===a)return null;if(this===a)return this.containingGroup;for(var b=this;null!==b;){b instanceof U&&Ho(b,!0);if(b instanceof W){var c=b.labeledLink;null!==c&&(b=c)}b=b.containingGroup}c=null;for(b=a;null!==b;){if(0!==(b.D&1048576)){c=b;break}b instanceof W&&(a=b.labeledLink,null!==a&&(b=a));b=b.containingGroup}for(b=this;null!==b;)b instanceof U&&Ho(b,!1),b instanceof W&&(a=b.labeledLink,null!==a&&(b=a)),b=b.containingGroup;return c}; V.prototype.canLayout=function(){if(!this.isLayoutPositioned||!this.isVisible())return!1;var a=this.layer;return null!==a&&a.isTemporary||this instanceof W&&this.isLinkLabel?!1:!0}; V.prototype.C=function(a){void 0===a&&(a=16777215);if(this.isLayoutPositioned&&0!==(a&this.layoutConditions)){var b=this.layer;null!==b&&b.isTemporary||this instanceof W&&this.isLinkLabel?b=!1:(b=this.diagram,b=null!==b&&b.undoManager.isUndoingRedoing?!1:!0)}else b=!1;if(b)if(b=this.li,null!==b){var c=b.layout;null!==c?c.C():b.C(a)}else a=this.diagram,null!==a&&(a=a.layout,null!==a&&a.C())};function Lj(a){if(!a.isVisible())return!1;a=a.layer;return null!==a&&a.isTemporary?!1:!0} function Vk(a,b,c,d,e,f){void 0===f&&(f=null);if(!(a.contains(b)||null!==f&&!f(b)||b instanceof Qe))if(a.add(b),b instanceof W){if(c&&b instanceof U)for(var g=b.memberParts;g.next();)Vk(a,g.value,c,d,e,f);if(!1!==e)for(g=b.linksConnected;g.next();){var h=g.value;if(!a.contains(h)){var k=h.fromNode,l=h.toNode;k=null===k||a.contains(k);l=null===l||a.contains(l);(e?k&&l:k||l)&&Vk(a,h,c,d,e,f)}}if(1<d)for(b=b.Vv();b.next();)Vk(a,b.value,c,d-1,e,f)}else if(b instanceof S)for(b=b.labelNodes;b.next();)Vk(a, b.value,c,d,e,f)} na.Object.defineProperties(V.prototype,{key:{get:function(){var a=this.diagram;if(null!==a)return a.model.ja(this.data)}},adornments:{get:function(){return null===this.Nf?ib:this.Nf.iteratorValues}},layer:{get:function(){return this.Ei}},diagram:{get:function(){var a=this.Ei;return null!==a?a.diagram:null}},layerName:{get:function(){return this.ih},set:function(a){var b= this.ih;if(b!==a){var c=this.diagram;if(null===c||null!==c.ym(a)&&!c.partManager.addsToTemporaryLayer)if(this.ih=a,null!==c&&c.Oa(),this.g("layerName",b,a),b=this.layer,null!==b&&b.name!==a&&(c=b.diagram,null!==c&&(a=c.ym(a),null!==a&&a!==b))){var d=b.Nc(-1,this,!0);0<=d&&c.bb(Ce,"parts",b,this,null,d,!0);d=a.oj(99999999,this,!0);b.visible!==a.visible&&this.Pb(a.visible);0<=d&&c.bb(Be,"parts",a,null,this,!0,d);d=this.layerChanged;if(null!==d){var e=c.Z;c.Z=!0;d(this,b,a);c.Z=e}}}}},layerChanged:{ get:function(){return this.Co},set:function(a){var b=this.Co;b!==a&&(this.Co=a,this.g("layerChanged",b,a))}},zOrder:{get:function(){return this.qq},set:function(a){var b=this.qq;if(b!==a){this.qq=a;var c=this.layer;null!==c&&pi(c,-1,this);this.g("zOrder",b,a);a=this.diagram;null!==a&&a.M()}}},locationObject:{get:function(){if(null===this.df){var a=this.locationObjectName;""!==a?(a=this.ab(a),null!==a?this.df=a:this.df=this): this instanceof Qe?this.type!==X.Link&&null!==this.placeholder?this.df=this.placeholder:this.df=this:this.df=this}return this.df.visible?this.df:this}},minLocation:{get:function(){return this.To},set:function(a){var b=this.To;b.w(a)||(this.To=a=a.G(),this.g("minLocation",b,a))}},maxLocation:{get:function(){return this.Lo},set:function(a){var b=this.Lo;b.w(a)||(this.Lo=a=a.G(),this.g("maxLocation",b,a))}},locationObjectName:{ get:function(){return this.Jo},set:function(a){var b=this.Jo;b!==a&&(this.Jo=a,this.df=null,this.o(),this.g("locationObjectName",b,a))}},locationSpot:{get:function(){return this.Ko},set:function(a){var b=this.Ko;b.w(a)||(this.Ko=a=a.G(),this.o(),this.g("locationSpot",b,a))}},location:{get:function(){return this.fg},set:function(a){var b=a.x,c=a.y,d=this.fg,e=d.x,f=d.y;(e===b||isNaN(e)&&isNaN(b))&&(f===c||isNaN(f)&&isNaN(c))|| (a=a.copy(),b=a,this.Oh()?b=!1:(this.fg=b,this.D|=2097152,!1===vj(this)&&(yo(this),c=this.la,c.s()&&(e=this.diagram,null===e||e.animationManager.isTicking||!e.undoManager.isUndoingRedoing))&&(f=c.copy(),c.h(c.x+(b.x-d.x),c.y+(b.y-d.y)),Co(this,e,c,f),this.g("position",f,c.copy())),b=!0),b&&this.g("location",d.copy(),a.copy()))}},category:{get:function(){return this.Pf},set:function(a){var b=this.Pf;if(b!==a){var c=this.diagram,d=this.data,e=null;if(null!==c&&null!==d&& !(this instanceof Qe)){var f=c.model.undoManager;f.isEnabled&&!f.isUndoingRedoing&&(e=this.clone(),e.W.addAll(this.W))}this.Pf=a;this.g("category",b,a);null===c||null===d||this instanceof Qe?this instanceof Qe&&(e=this.adornedPart,null!==e&&(a=e.Nf,null!==a&&a.remove(b),e.Fh(this.category,this))):(f=c.model,f.undoManager.isUndoingRedoing||(this.Oh()?(c.partManager.setLinkCategoryForData(d,a),c=c.partManager.findLinkTemplateForCategory(a),null!==c&&(Ag(c),c=c.copy(),null!==c&&Fo(this,c,b,a))):(null!== f&&f.Tm(d,a),c=No(c.partManager,d,a),null!==c&&(Ag(c),c=c.copy(),null===c||c instanceof S||(d=this.location.copy(),Fo(this,c,b,a),this.location.s()||(this.location=d)))),null!==e&&(b=this.clone(),b.W.addAll(this.W),this.g("self",e,b))))}}},self:{get:function(){return this},set:function(a){Fo(this,a,this.category,a.category)}},copyable:{get:function(){return 0!==(this.D&1)},set:function(a){var b=0!==(this.D&1);b!==a&&(this.D^=1,this.g("copyable", b,a))}},deletable:{get:function(){return 0!==(this.D&2)},set:function(a){var b=0!==(this.D&2);b!==a&&(this.D^=2,this.g("deletable",b,a))}},textEditable:{get:function(){return 0!==(this.D&4)},set:function(a){var b=0!==(this.D&4);b!==a&&(this.D^=4,this.g("textEditable",b,a),this.Mb())}},groupable:{get:function(){return 0!==(this.D&8)},set:function(a){var b=0!==(this.D&8);b!==a&&(this.D^=8,this.g("groupable",b, a))}},movable:{get:function(){return 0!==(this.D&16)},set:function(a){var b=0!==(this.D&16);b!==a&&(this.D^=16,this.g("movable",b,a))}},selectionAdorned:{get:function(){return 0!==(this.D&32)},set:function(a){var b=0!==(this.D&32);b!==a&&(this.D^=32,this.g("selectionAdorned",b,a),this.Mb())}},isInDocumentBounds:{get:function(){return 0!==(this.D&64)},set:function(a){var b=0!==(this.D&64);if(b!==a){this.D^=64; var c=this.diagram;null!==c&&c.Oa();this.g("isInDocumentBounds",b,a)}}},isLayoutPositioned:{get:function(){return 0!==(this.D&128)},set:function(a){var b=0!==(this.D&128);b!==a&&(this.D^=128,this.g("isLayoutPositioned",b,a),this.C(a?4:8))}},selectable:{get:function(){return 0!==(this.D&256)},set:function(a){var b=0!==(this.D&256);b!==a&&(this.D^=256,this.g("selectable",b,a),this.Mb())}},reshapable:{get:function(){return 0!== (this.D&512)},set:function(a){var b=0!==(this.D&512);b!==a&&(this.D^=512,this.g("reshapable",b,a),this.Mb())}},resizable:{get:function(){return 0!==(this.D&1024)},set:function(a){var b=0!==(this.D&1024);b!==a&&(this.D^=1024,this.g("resizable",b,a),this.Mb())}},rotatable:{get:function(){return 0!==(this.D&2048)},set:function(a){var b=0!==(this.D&2048);b!==a&&(this.D^=2048,this.g("rotatable",b,a),this.Mb())}},isSelected:{ get:function(){return 0!==(this.D&4096)},set:function(a){var b=0!==(this.D&4096);if(b!==a){var c=this.diagram;if(!a||this.canSelect()&&!(null!==c&&c.selection.count>=c.maxSelectionCount)){this.D^=4096;var d=!1;if(null!==c){d=c.skipsUndoManager;c.skipsUndoManager=!0;var e=c.selection;e.ea();a?e.add(this):e.remove(this);e.freeze()}this.g("isSelected",b,a);this.Mb();a=this.selectionChanged;null!==a&&a(this);null!==c&&(c.Eb(),c.skipsUndoManager=d)}}}},isHighlighted:{get:function(){return 0!== (this.D&524288)},set:function(a){var b=0!==(this.D&524288);if(b!==a){this.D^=524288;var c=this.diagram;null!==c&&(c=c.highlighteds,c.ea(),a?c.add(this):c.remove(this),c.freeze());this.g("isHighlighted",b,a);this.M();a=this.highlightedChanged;null!==a&&a(this)}}},isShadowed:{get:function(){return 0!==(this.D&8192)},set:function(a){var b=0!==(this.D&8192);b!==a&&(this.D^=8192,this.g("isShadowed",b,a),this.M())}},isAnimated:{get:function(){return 0!== (this.D&262144)},set:function(a){var b=0!==(this.D&262144);b!==a&&(this.D^=262144,this.g("isAnimated",b,a))}},highlightedChanged:{get:function(){return this.oo},set:function(a){var b=this.oo;b!==a&&(this.oo=a,this.g("highlightedChanged",b,a))}},selectionObjectName:{get:function(){return this.Op},set:function(a){var b=this.Op;b!==a&&(this.Op=a,this.sh=null,this.g("selectionObjectName",b,a))}},selectionAdornmentTemplate:{ get:function(){return this.Mp},set:function(a){var b=this.Mp;b!==a&&(this.Mp=a,this.g("selectionAdornmentTemplate",b,a))}},selectionObject:{get:function(){if(null===this.sh){var a=this.selectionObjectName;null!==a&&""!==a?(a=this.ab(a),null!==a?this.sh=a:this.sh=this):this instanceof S?(a=this.path,null!==a?this.sh=a:this.sh=this):this.sh=this}return this.sh}},selectionChanged:{get:function(){return this.Np},set:function(a){var b=this.Np; b!==a&&(this.Np=a,this.g("selectionChanged",b,a))}},resizeAdornmentTemplate:{get:function(){return this.xp},set:function(a){var b=this.xp;b!==a&&(this.xp=a,this.g("resizeAdornmentTemplate",b,a))}},resizeObjectName:{get:function(){return this.zp},set:function(a){var b=this.zp;b!==a&&(this.zp=a,this.g("resizeObjectName",b,a))}},resizeObject:{get:function(){var a=this.resizeObjectName;return""!==a&&(a=this.ab(a), null!==a)?a:this}},resizeCellSize:{get:function(){return this.yp},set:function(a){var b=this.yp;b.w(a)||(this.yp=a=a.G(),this.g("resizeCellSize",b,a))}},rotateAdornmentTemplate:{get:function(){return this.Bp},set:function(a){var b=this.Bp;b!==a&&(this.Bp=a,this.g("rotateAdornmentTemplate",b,a))}},rotateObjectName:{get:function(){return this.Cp},set:function(a){var b=this.Cp;b!==a&&(this.Cp=a,this.g("rotateObjectName", b,a))}},rotateObject:{get:function(){var a=this.rotateObjectName;return""!==a&&(a=this.ab(a),null!==a)?a:this}},rotationSpot:{get:function(){return this.Dp},set:function(a){var b=this.Dp;b.w(a)||(this.Dp=a=a.G(),this.g("rotationSpot",b,a))}},text:{get:function(){return this.Ub},set:function(a){var b=this.Ub;b!==a&&(this.Ub=a,this.g("text",b,a))}},containingGroup:{get:function(){return this.li}, set:function(a){if(this.Pc()){var b=this.li;if(b!==a){null===a||this!==a&&!a.Kd(this)||(this===a&&B("Cannot make a Group a member of itself: "+this.toString()),B("Cannot make a Group indirectly contain itself: "+this.toString()+" already contains "+a.toString()));this.C(2);var c=this.diagram;null!==b?Jo(b,this):this instanceof U&&null!==c&&c.Ch.remove(this);this.li=a;null!==a?Io(a,this):this instanceof U&&null!==c&&c.Ch.add(this);this.C(1);if(null!==c&&c.Z){var d=this.data,e=c.model;if(null!==d&& e.Ck()){var f=e.ja(null!==a?a.data:null);e.dr(d,f)}}d=this.containingGroupChanged;null!==d&&(e=!0,null!==c&&(e=c.Z,c.Z=!0),d(this,b,a),null!==c&&(c.Z=e));if(this instanceof U)for(c=new G,Vk(c,this,!0,0,!0),c=c.iterator;c.next();)if(d=c.value,d instanceof W)for(d=d.linksConnected;d.next();)Oo(d.value);if(this instanceof W){for(c=this.linksConnected;c.next();)Oo(c.value);c=this.labeledLink;null!==c&&Oo(c)}this.g("containingGroup",b,a);null!==a&&(b=a.layer,null!==b&&pi(b,-1,a))}}else B("cannot set the Part.containingGroup of a Link or Adornment")}}, containingGroupChanged:{get:function(){return this.yn},set:function(a){var b=this.yn;b!==a&&(this.yn=a,this.g("containingGroupChanged",b,a))}},isTopLevel:{get:function(){return null!==this.containingGroup||this instanceof W&&null!==this.labeledLink?!1:!0}},layoutConditions:{get:function(){return this.Do},set:function(a){var b=this.Do;b!==a&&(this.Do=a,this.g("layoutConditions",b,a))}},dragComputation:{ get:function(){return this.Qn},set:function(a){var b=this.Qn;b!==a&&(this.Qn=a,this.g("dragComputation",b,a))}},shadowOffset:{get:function(){return this.Sp},set:function(a){var b=this.Sp;b.w(a)||(this.Sp=a=a.G(),this.M(),this.g("shadowOffset",b,a))}},shadowColor:{get:function(){return this.Rp},set:function(a){var b=this.Rp;b!==a&&(this.Rp=a,this.M(),this.g("shadowColor",b,a))}},shadowBlur:{get:function(){return this.lf}, set:function(a){var b=this.lf;b!==a&&(this.lf=a,this.M(),this.g("shadowBlur",b,a))}}});V.prototype.invalidateLayout=V.prototype.C;V.prototype.findCommonContainingGroup=V.prototype.oy;V.prototype.isMemberOf=V.prototype.Kd;V.prototype.findTopLevelPart=V.prototype.eA;V.prototype.findSubGraphLevel=V.prototype.bA;V.prototype.ensureBounds=V.prototype.Ta;V.prototype.getDocumentBounds=V.prototype.mj;V.prototype.getRelativePoint=V.prototype.Ff;V.prototype.findObject=V.prototype.ab;V.prototype.moveTo=V.prototype.moveTo; V.prototype.invalidateAdornments=V.prototype.Mb;V.prototype.clearAdornments=V.prototype.nk;V.prototype.removeAdornment=V.prototype.Jf;V.prototype.addAdornment=V.prototype.Fh;V.prototype.findAdornment=V.prototype.wk;V.prototype.updateTargetBindings=V.prototype.Ca;var Go=!1;V.className="Part";V.LayoutNone=0;V.LayoutAdded=1;V.LayoutRemoved=2;V.LayoutShown=4;V.LayoutHidden=8;V.LayoutNodeSized=16;V.LayoutGroupLayout=32;V.LayoutNodeReplaced=64;V.LayoutStandard=127;V.LayoutAll=16777215; function Qe(a){V.call(this,a);this.D&=-257;this.ih="Adornment";this.je=null;this.Fx=0;this.Tx=!1;this.l=a instanceof Nm?[]:Po;this.Ra=null}ma(Qe,V);Qe.prototype.toString=function(){var a=this.adornedPart;return"Adornment("+this.category+")"+(null!==a?a.toString():"")};Qe.prototype.updateRelationshipsFromData=function(){}; Qe.prototype.Fk=function(a){var b=this.adornedObject.part;if(b instanceof S&&this.adornedObject instanceof Mf){var c=b.path;b.Fk(a);a=c.geometry;b=this.W.j;c=b.length;for(var d=0;d<c;d++){var e=b[d];e.isPanelMain&&e instanceof Mf&&(e.na=a)}}};Qe.prototype.rj=function(){var a=this.je;if(null===a)return!0;a=a.part;return null===a||!vj(a)};Qe.prototype.Pc=function(){return!1}; Qe.prototype.Rk=function(a,b,c,d,e,f,g){if(a===Be&&"elements"===b)if(e instanceof zg)null===this.Ra&&(this.Ra=e);else{if(e instanceof X){var h=e.xm(function(a){return a instanceof zg});h instanceof zg&&null===this.Ra&&(this.Ra=h)}}else a===Ce&&"elements"===b&&null!==this.Ra&&(d===this.Ra?this.Ra=null:d instanceof X&&this.Ra.Hg(d)&&(this.Ra=null));V.prototype.Rk.call(this,a,b,c,d,e,f,g)};Qe.prototype.updateAdornments=function(){};Qe.prototype.uk=function(){}; na.Object.defineProperties(Qe.prototype,{placeholder:{get:function(){return this.Ra}},adornedObject:{get:function(){return this.je},set:function(a){var b=this.adornedPart,c=null;null!==a&&(c=a.part);null===b||null!==a&&b===c||b.Jf(this.category);this.je=a;null!==c&&c.Fh(this.category,this)}},adornedPart:{get:function(){var a=this.je;return null!==a?a.part:null}},containingGroup:{ get:function(){return null}}});var Po=[];Qe.className="Adornment";function W(a){V.call(this,a);this.P=13;this.Za=new E;this.kq=this.Ll=this.Hi=this.Fo=this.Eo=null;this.cl=tc;this.tc=this.Te=null;this.tp=Qo;this.Dh=!1}ma(W,V);W.prototype.cloneProtected=function(a){V.prototype.cloneProtected.call(this,a);a.P=this.P;a.P=this.P&-17;a.Eo=this.Eo;a.Fo=this.Fo;a.Hi=this.Hi;a.kq=this.kq;a.cl=this.cl.G();a.tp=this.tp};t=W.prototype;t.Af=function(a){V.prototype.Af.call(this,a);a.td();a.Te=this.Te;a.tc=null}; function Ro(a,b){null!==b&&(null===a.Te&&(a.Te=new G),a.Te.add(b))}function So(a,b,c,d){if(null===b||null===a.Te)return null;for(var e=a.Te.iterator;e.next();){var f=e.value;if(f.au===a&&f.kw===b&&f.Ny===c&&f.Oy===d||f.au===b&&f.kw===a&&f.Ny===d&&f.Oy===c)return f}return null}t.xA=function(a,b,c){if(void 0===b||null===b)b="";if(void 0===c||null===c)c="";a=So(this,a,b,c);null!==a&&a.Cm()}; t.Rk=function(a,b,c,d,e,f,g){a===Be&&"elements"===b?this.tc=null:a===Ce&&"elements"===b&&(this.tc=null);V.prototype.Rk.call(this,a,b,c,d,e,f,g)};t.td=function(a){void 0===a&&(a=null);for(var b=this.linksConnected;b.next();){var c=b.value;null!==a&&a.contains(c)||(To(c.fromPort),To(c.toPort),c.Ua())}};function rl(a,b){for(a=a.linksConnected;a.next();){var c=a.value;if(c.fromPort===b||c.toPort===b)To(c.fromPort),To(c.toPort),c.Ua()}} function To(a){if(null!==a){var b=a.sp;null!==b&&b.Cm();a=a.part;b=a.containingGroup;null===b||a.isVisible()||To(b.port)}}t.rj=function(){return!0};W.prototype.getAvoidableRect=function(a){a.set(this.actualBounds);a.rq(this.cl);return a};W.prototype.findVisibleNode=function(){for(var a=this;null!==a&&!a.isVisible();)a=a.containingGroup;return a}; W.prototype.isVisible=function(){if(!V.prototype.isVisible.call(this))return!1;var a=!0,b=ui,c=this.diagram;if(null!==c){if(c.animationManager.cu(this))return!0;a=c.isTreePathToChildren;b=c.treeCollapsePolicy}if(b===ui){if(a=this.Gg(),null!==a&&!a.isTreeExpanded)return!1}else if(b===Gk){if(a=a?this.Sv():this.Tv(),0<a.count&&a.all(function(a){return!a.isTreeExpanded}))return!1}else if(b===Hk&&(a=a?this.Sv():this.Tv(),0<a.count&&a.any(function(a){return!a.isTreeExpanded})))return!1;a=this.labeledLink; return null!==a?a.isVisible():!0};W.prototype.Pb=function(a){V.prototype.Pb.call(this,a);for(var b=this.linksConnected;b.next();){var c=b.value;if(a&&null!==this.containingGroup){var d=c.Hq(this);null===d||d.Kd(this.containingGroup)||c.Ua()}c.Pb(a)}};W.prototype.py=function(){var a=new G,b=new G;Uo(this,this,a,b);return b.iterator}; function Uo(a,b,c,d){if(null!==b&&!c.has(b)){c.add(b);var e=!0,f=a.diagram;null!==f&&(e=f.isTreePathToChildren);b.linksConnected.each(function(f){f.isTreeLink?(e?f.fromNode===b:f.toNode===b)&&Uo(a,e?f.toNode:f.fromNode,c,d):d.add(f)})}}W.prototype.findLinksConnected=function(a){void 0===a&&(a=null);if(null===a)return this.Za.iterator;var b=new kb(this.Za),c=this;b.predicate=function(b){return b.fromNode===c&&b.fromPortId===a||b.toNode===c&&b.toPortId===a};return b};t=W.prototype; t.Cq=function(a){void 0===a&&(a=null);var b=new kb(this.Za),c=this;b.predicate=function(b){return b.fromNode!==c?!1:null===a?!0:b.fromPortId===a};return b};t.Hd=function(a){void 0===a&&(a=null);var b=new kb(this.Za),c=this;b.predicate=function(b){return b.toNode!==c?!1:null===a?!0:b.toPortId===a};return b}; t.Rv=function(a){void 0===a&&(a=null);for(var b=null,c=null,d=this.Za.iterator;d.next();){var e=d.value;if(e.fromNode===this){if(null===a||e.fromPortId===a)e=e.toNode,null!==b?b.add(e):null!==c&&c!==e?(b=new G,b.add(c),b.add(e)):c=e}else e.toNode!==this||null!==a&&e.toPortId!==a||(e=e.fromNode,null!==b?b.add(e):null!==c&&c!==e?(b=new G,b.add(c),b.add(e)):c=e)}return null!==b?b.iterator:null!==c?new jb(c):ib}; t.Tv=function(a){void 0===a&&(a=null);for(var b=null,c=null,d=this.Za.iterator;d.next();){var e=d.value;e.fromNode!==this||null!==a&&e.fromPortId!==a||(e=e.toNode,null!==b?b.add(e):null!==c&&c!==e?(b=new G,b.add(c),b.add(e)):c=e)}return null!==b?b.iterator:null!==c?new jb(c):ib}; t.Sv=function(a){void 0===a&&(a=null);for(var b=null,c=null,d=this.Za.iterator;d.next();){var e=d.value;e.toNode!==this||null!==a&&e.toPortId!==a||(e=e.fromNode,null!==b?b.add(e):null!==c&&c!==e?(b=new G,b.add(c),b.add(e)):c=e)}return null!==b?b.iterator:null!==c?new jb(c):ib}; t.Xz=function(a,b,c){void 0===b&&(b=null);void 0===c&&(c=null);var d=new kb(this.Za),e=this;d.predicate=function(d){return(d.fromNode!==e||d.toNode!==a||null!==b&&d.fromPortId!==b||null!==c&&d.toPortId!==c)&&(d.fromNode!==a||d.toNode!==e||null!==c&&d.fromPortId!==c||null!==b&&d.toPortId!==b)?!1:!0};return d}; t.Yz=function(a,b,c){void 0===b&&(b=null);void 0===c&&(c=null);var d=new kb(this.Za),e=this;d.predicate=function(d){return d.fromNode!==e||d.toNode!==a||null!==b&&d.fromPortId!==b||null!==c&&d.toPortId!==c?!1:!0};return d}; function Vo(a,b,c){To(c);var d=a.Za.contains(b);d||a.Za.add(b);if(!d||b.fromNode===b.toNode){var e=a.linkConnected;if(null!==e){var f=!0,g=a.diagram;null!==g&&(f=g.Z,g.Z=!0);e(a,b,c);null!==g&&(g.Z=f)}}!d&&b.isTreeLink&&(c=b.fromNode,b=b.toNode,null!==c&&null!==b&&c!==b&&(d=!0,a=a.diagram,null!==a&&(d=a.isTreePathToChildren),e=d?b:c,f=d?c:b,e.Dh||(e.Dh=f),!f.isTreeLeaf||null!==a&&a.undoManager.isUndoingRedoing||(d?c===f&&(f.isTreeLeaf=!1):b===f&&(f.isTreeLeaf=!1))))} function Wo(a,b,c){To(c);var d=a.Za.remove(b),e=null;if(d||b.toNode===b.fromNode){var f=a.linkDisconnected;e=a.diagram;if(null!==f){var g=!0;null!==e&&(g=e.Z,e.Z=!0);f(a,b,c);null!==e&&(e.Z=g)}}d&&b.isTreeLink&&(c=!0,null!==e&&(c=e.isTreePathToChildren),a=c?b.toNode:b.fromNode,b=c?b.fromNode:b.toNode,null!==a&&(a.Dh=!1),null===b||b.isTreeLeaf||(0===b.Za.count?(b.Dh=null,null!==e&&e.undoManager.isUndoingRedoing||(b.isTreeLeaf=!0)):Fk(b)))} function Fk(a){a.Dh=!1;if(0!==a.Za.count){var b=!0,c=a.diagram;if(null===c||!c.undoManager.isUndoingRedoing){null!==c&&(b=c.isTreePathToChildren);for(c=a.Za.iterator;c.next();){var d=c.value;if(d.isTreeLink)if(b){if(d.fromNode===a){a.isTreeLeaf=!1;return}}else if(d.toNode===a){a.isTreeLeaf=!1;return}}a.isTreeLeaf=!0}}}W.prototype.updateRelationshipsFromData=function(){var a=this.diagram;null!==a&&a.partManager.updateRelationshipsFromData(this)};t=W.prototype; t.Jq=function(a){V.prototype.Jq.call(this,a);a||(Fk(this),a=this.Ll,null!==a&&Xo(a,this))};t.Kq=function(a){V.prototype.Kq.call(this,a);a||(a=this.Ll,null!==a&&null!==a.od&&(a.od.remove(this),a.o()))}; t.uk=function(){if(0<this.Za.count){var a=this.diagram;if(null!==a)for(var b=null!==a.commandHandler?a.commandHandler.deletesConnectedLinks:!0,c=this.Za.copy().iterator;c.next();){var d=c.value;b?a.remove(d):(d.fromNode===this&&(d.fromNode=null),d.toNode===this&&(d.toNode=null))}}this.labeledLink=null;V.prototype.uk.call(this)};t.Kt=function(a){if(null===this.tc){if(""===a&&!1===this.Mh)return this;Yo(this)}var b=this.tc.H(a);return null!==b||""!==a&&(b=this.tc.H(""),null!==b)?b:this}; function Yo(a){null===a.tc?a.tc=new H:a.tc.clear();a.Zm(a,function(a,c){Vl(a,c)});0===a.tc.count&&a.tc.add("",a)}function Vl(a,b){var c=b.portId;null!==c&&null!==a.tc&&a.tc.add(c,b)}function Ul(a,b,c){var d=b.portId;if(null!==d&&(null!==a.tc&&a.tc.remove(d),b=a.diagram,null!==b&&c)){c=null;for(a=a.findLinksConnected(d);a.next();)d=a.value,null===c&&(c=Ea()),c.push(d);if(null!==c){for(a=0;a<c.length;a++)b.remove(c[a]);Ia(c)}}} t.zA=function(a){if(null===a||a===this)return!1;var b=!0,c=this.diagram;null!==c&&(b=c.isTreePathToChildren);c=this;if(b)for(;c!==a;){b=null;for(var d=c.Za.iterator;d.next();){var e=d.value;if(e.isTreeLink&&(b=e.fromNode,b!==c&&b!==this))break}if(b===this||null===b||b===c)return!1;c=b}else for(;c!==a;){b=null;for(d=c.Za.iterator;d.next()&&(e=d.value,!e.isTreeLink||(b=e.toNode,b===c||b===this)););if(b===this||null===b||b===c)return!1;c=b}return!0}; t.iA=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);b=this;if(a)for(;;){a=null;for(var c=b.Za.iterator;c.next();){var d=c.value;if(d.isTreeLink&&(a=d.fromNode,a!==b&&a!==this))break}if(a===this)return this;if(null===a||a===b)return b;b=a}else for(;;){a=null;for(c=b.Za.iterator;c.next()&&(d=c.value,!d.isTreeLink||(a=d.toNode,a===b||a===this)););if(a===this)return this;if(null===a||a===b)return b;b=a}}; t.Uz=function(a){if(null===a)return null;if(this===a)return this;for(var b=this;null!==b;)Ho(b,!0),b=b.Gg();var c=null;for(b=a;null!==b;){if(0!==(b.D&1048576)){c=b;break}b=b.Gg()}for(b=this;null!==b;)Ho(b,!1),b=b.Gg();return c};t.jj=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);b=this.Za.iterator;if(a)for(;b.next();){if(a=b.value,a.isTreeLink&&a.fromNode!==this)return a}else for(;b.next();)if(a=b.value,a.isTreeLink&&a.toNode!==this)return a;return null}; t.Gg=function(){var a=this.Dh;if(null===a)return null;if(a instanceof W)return a;var b=!0;a=this.diagram;null!==a&&(b=a.isTreePathToChildren);a=this.Za.iterator;if(b)for(;a.next();){if(b=a.value,b.isTreeLink&&(b=b.fromNode,b!==this))return this.Dh=b}else for(;a.next();)if(b=a.value,b.isTreeLink&&(b=b.toNode,b!==this))return this.Dh=b;return this.Dh=null};t.gA=function(){function a(b,d){if(null!==b){d.add(b);var c=b.jj();null!==c&&(d.add(c),a(b.Gg(),d))}}var b=new G;a(this,b);return b}; t.fA=function(){return Zo(this,this)};function Zo(a,b){b=b.Gg();return null===b?0:1+Zo(a,b)}t.Eq=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);b=new kb(this.Za);var c=this;b.predicate=a?function(a){return a.isTreeLink&&a.fromNode===c?!0:!1}:function(a){return a.isTreeLink&&a.toNode===c?!0:!1};return b}; t.Vv=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);var c=b=null,d=this.Za.iterator;if(a)for(;d.next();)a=d.value,a.isTreeLink&&a.fromNode===this&&(a=a.toNode,null!==b?b.add(a):null!==c&&c!==a?(b=new E,b.add(c),b.add(a)):c=a);else for(;d.next();)a=d.value,a.isTreeLink&&a.toNode===this&&(a=a.fromNode,null!==b?b.add(a):null!==c&&c!==a?(b=new E,b.add(c),b.add(a)):c=a);return null!==b?b.iterator:null!==c?new jb(c):ib}; t.hA=function(a){void 0===a&&(a=Infinity);var b=new G;Vk(b,this,!1,a,!0);return b};W.prototype.collapseTree=function(a){void 0===a&&(a=1);1>a&&(a=1);var b=this.diagram;if(null!==b&&!b.Le){b.Le=!0;var c=new G;c.add(this);$o(this,c,b.isTreePathToChildren,a,b,this,b.treeCollapsePolicy===ui);b.Le=!1}};function $o(a,b,c,d,e,f,g){if(1<d)for(var h=c?a.Cq():a.Hd();h.next();){var k=h.value;k.isTreeLink&&(k=k.Hq(a),null===k||k===a||b.contains(k)||(b.add(k),$o(k,b,c,d-1,e,f,g)))}else ap(a,b,c,e,f,g)} function ap(a,b,c,d,e,f){for(var g=e===a?!0:a.isTreeExpanded,h=c?a.Cq():a.Hd();h.next();){var k=h.value;if(k.isTreeLink&&(k=k.Hq(a),null!==k&&k!==a)){var l=b.contains(k);l||b.add(k);g&&(f&&d.jk(k,e),k.Nh(),k.Pb(!1));k.isTreeExpanded&&(k.wasTreeExpanded=k.isTreeExpanded,l||ap(k,b,c,d,e,f))}}a.isTreeExpanded=!1} W.prototype.expandTree=function(a){void 0===a&&(a=2);2>a&&(a=2);var b=this.diagram;if(null!==b&&!b.Le){b.Le=!0;var c=new G;c.add(this);bp(this,c,b.isTreePathToChildren,a,b,this,b.treeCollapsePolicy===ui);b.Le=!1}}; function bp(a,b,c,d,e,f,g){for(var h=f===a?!1:a.isTreeExpanded,k=c?a.Cq():a.Hd();k.next();){var l=k.value;l.isTreeLink&&(h||l.kd||l.Ua(),l=l.Hq(a),null!==l&&l!==a&&!b.contains(l)&&(b.add(l),h||(l.Pb(!0),l.Nh(),g&&e.lk(l,f)),2<d||l.wasTreeExpanded))&&(l.wasTreeExpanded=!1,bp(l,b,c,d-1,e,f,g))}a.isTreeExpanded=!0} na.Object.defineProperties(W.prototype,{portSpreading:{get:function(){return this.tp},set:function(a){var b=this.tp;b!==a&&(this.tp=a,this.g("portSpreading",b,a),a=this.diagram,null!==a&&a.undoManager.isUndoingRedoing||this.td())}},avoidable:{get:function(){return 0!==(this.P&8)},set:function(a){var b=0!==(this.P&8);if(b!==a){this.P^=8;var c=this.diagram;null!==c&&zk(c,this);this.g("avoidable",b,a)}}},avoidableMargin:{ get:function(){return this.cl},set:function(a){"number"===typeof a&&(a=new oc(a));var b=this.cl;if(!b.w(a)){this.cl=a=a.G();var c=this.diagram;null!==c&&zk(c,this);this.g("avoidableMargin",b,a)}}},linksConnected:{get:function(){return this.Za.iterator}},linkConnected:{get:function(){return this.Eo},set:function(a){var b=this.Eo;b!==a&&(this.Eo=a,this.g("linkConnected",b,a))}},linkDisconnected:{get:function(){return this.Fo}, set:function(a){var b=this.Fo;b!==a&&(this.Fo=a,this.g("linkDisconnected",b,a))}},linkValidation:{get:function(){return this.Hi},set:function(a){var b=this.Hi;b!==a&&(this.Hi=a,this.g("linkValidation",b,a))}},isLinkLabel:{get:function(){return null!==this.Ll}},labeledLink:{get:function(){return this.Ll},set:function(a){var b=this.Ll;if(b!==a){var c=this.diagram,d=this.data;if(null!==b){null!==b.od&&(b.od.remove(this), b.o());if(null!==c&&null!==d&&!c.undoManager.isUndoingRedoing){var e=b.data,f=c.model;if(null!==e&&f.qj()){var g=f.ja(d);void 0!==g&&f.Py(e,g)}}this.containingGroup=null}this.Ll=a;null!==a&&(Xo(a,this),null===c||null===d||c.undoManager.isUndoingRedoing||(e=a.data,c=c.model,null!==e&&c.qj()&&(d=c.ja(d),void 0!==d&&c.Cv(e,d))),this.containingGroup=a.containingGroup);Fl(this);this.g("labeledLink",b,a)}}},port:{get:function(){return this.Kt("")}},ports:{ get:function(){null===this.tc&&Yo(this);return this.tc.iteratorValues}},isTreeExpanded:{get:function(){return 0!==(this.P&1)},set:function(a){var b=0!==(this.P&1);if(b!==a){this.P^=1;var c=this.diagram;this.g("isTreeExpanded",b,a);b=this.treeExpandedChanged;if(null!==b){var d=!0;null!==c&&(d=c.Z,c.Z=!0);b(this);null!==c&&(c.Z=d)}null!==c&&c.undoManager.isUndoingRedoing?this.Pb(a):a?this.expandTree():this.collapseTree()}}},wasTreeExpanded:{ get:function(){return 0!==(this.P&2)},set:function(a){var b=0!==(this.P&2);b!==a&&(this.P^=2,this.g("wasTreeExpanded",b,a))}},treeExpandedChanged:{get:function(){return this.kq},set:function(a){var b=this.kq;b!==a&&(this.kq=a,this.g("treeExpandedChanged",b,a))}},isTreeLeaf:{get:function(){return 0!==(this.P&4)},set:function(a){var b=0!==(this.P&4);b!==a&&(this.P^=4,this.g("isTreeLeaf",b,a))}}});W.prototype.expandTree=W.prototype.expandTree; W.prototype.collapseTree=W.prototype.collapseTree;W.prototype.findTreeParts=W.prototype.hA;W.prototype.findTreeChildrenNodes=W.prototype.Vv;W.prototype.findTreeChildrenLinks=W.prototype.Eq;W.prototype.findTreeLevel=W.prototype.fA;W.prototype.findTreeParentChain=W.prototype.gA;W.prototype.findTreeParentNode=W.prototype.Gg;W.prototype.findTreeParentLink=W.prototype.jj;W.prototype.findCommonTreeParent=W.prototype.Uz;W.prototype.findTreeRoot=W.prototype.iA;W.prototype.isInTreeOf=W.prototype.zA; W.prototype.findPort=W.prototype.Kt;W.prototype.findLinksTo=W.prototype.Yz;W.prototype.findLinksBetween=W.prototype.Xz;W.prototype.findNodesInto=W.prototype.Sv;W.prototype.findNodesOutOf=W.prototype.Tv;W.prototype.findNodesConnected=W.prototype.Rv;W.prototype.findLinksInto=W.prototype.Hd;W.prototype.findLinksOutOf=W.prototype.Cq;W.prototype.findExternalTreeLinksConnected=W.prototype.py;W.prototype.invalidateConnectedLinks=W.prototype.td;W.prototype.invalidateLinkBundle=W.prototype.xA; var cp=new D(W,"SpreadingNone",10),Qo=new D(W,"SpreadingEvenly",11),dp=new D(W,"SpreadingPacked",12);W.className="Node";W.SpreadingNone=cp;W.SpreadingEvenly=Qo;W.SpreadingPacked=dp;function U(a){W.call(this,a);this.P|=4608;this.Qo=new G;this.Tl=new G;this.Ra=this.aq=this.Ji=this.Ro=this.Po=this.Ya=null;this.lc=new Bi;this.lc.group=this}ma(U,W); U.prototype.cloneProtected=function(a){W.prototype.cloneProtected.call(this,a);this.P=this.P&-32769;null!==this.Ya&&(a.Ya=this.Ya.copy());a.Po=this.Po;a.Ro=this.Ro;a.Ji=this.Ji;a.aq=this.aq;var b=a.xm(function(a){return a instanceof zg});b instanceof zg?a.Ra=b:a.Ra=null;null!==this.lc?(a.lc=this.lc.copy(),a.lc.group=a):(null!==a.lc&&(a.lc.group=null),a.lc=null)};t=U.prototype; t.Af=function(a){W.prototype.Af.call(this,a);var b=a.xk();for(a=a.memberParts;a.next();){var c=a.value;c.o();c.C(8);c.nk();if(c instanceof W)c.td(b);else if(c instanceof S)for(c=c.labelNodes;c.next();)c.value.td(b)}}; t.Rk=function(a,b,c,d,e,f,g){if(a===Be&&"elements"===b)if(e instanceof zg)null===this.Ra?this.Ra=e:this.Ra!==e&&B("Cannot insert a second Placeholder into the visual tree of a Group.");else{if(e instanceof X){var h=e.xm(function(a){return a instanceof zg});h instanceof zg&&(null===this.Ra?this.Ra=h:this.Ra!==h&&B("Cannot insert a second Placeholder into the visual tree of a Group."))}}else a===Ce&&"elements"===b&&null!==this.Ra&&(d===this.Ra?this.Ra=null:d instanceof X&&this.Ra.Hg(d)&&(this.Ra=null)); W.prototype.Rk.call(this,a,b,c,d,e,f,g)};t.Hm=function(a,b){W.prototype.Hm.call(this,a,b);this.isClipping&&this.type!==X.Spot&&(a=this.resizeObject,a instanceof X&&(a=a.rb()),null===this.Ya&&(this.Ya=new N),a.mj(this.Ya),a instanceof Mf&&this.Ya.Lc(-a.strokeWidth,-a.strokeWidth))};t.Hh=function(a,b,c,d){this.df=this.Ra;W.prototype.Hh.call(this,a,b,c,d)};t.Ta=function(){var a=this;a.isSubGraphExpanded&&this.memberParts.each(function(b){!a.computesBoundsIncludingLinks&&b instanceof S||b.Ta()});W.prototype.Ta.call(this)}; t.rj=function(){if(!W.prototype.rj.call(this))return!1;for(var a=this.memberParts;a.next();){var b=a.value;if(b instanceof W){if(b.isVisible()&&vj(b))return!1}else if(b instanceof S&&b.isVisible()&&vj(b)&&b.fromNode!==this&&b.toNode!==this)return!1}return!0}; function Io(a,b){if(a.Qo.add(b)){b instanceof U&&a.Tl.add(b);var c=a.memberAdded;if(null!==c){var d=!0,e=a.diagram;null!==e&&(d=e.Z,e.Z=!0);c(a,b);null!==e&&(e.Z=d)}a.isVisible()&&a.isSubGraphExpanded||b.Pb(!1)}b instanceof S&&!a.computesBoundsIncludingLinks||(b=a.Ra,null===b&&(b=a),b.o())} function Jo(a,b){if(a.Qo.remove(b)){b instanceof U&&a.Tl.remove(b);var c=a.memberRemoved;if(null!==c){var d=!0,e=a.diagram;null!==e&&(d=e.Z,e.Z=!0);c(a,b);null!==e&&(e.Z=d)}a.isVisible()&&a.isSubGraphExpanded||b.Pb(!0)}b instanceof S&&!a.computesBoundsIncludingLinks||(b=a.Ra,null===b&&(b=a),b.o())}t.uk=function(){if(0<this.Qo.count){var a=this.diagram;if(null!==a)for(var b=this.Qo.copy().iterator;b.next();)a.remove(b.value)}W.prototype.uk.call(this)}; U.prototype.canAddMembers=function(a){var b=this.diagram;if(null===b)return!1;b=b.commandHandler;for(a=Xk(a).iterator;a.next();)if(!b.isValidMember(this,a.value))return!1;return!0};U.prototype.addMembers=function(a,b){var c=this.diagram;if(null===c)return!1;c=c.commandHandler;var d=!0;for(a=Xk(a).iterator;a.next();){var e=a.value;!b||c.isValidMember(this,e)?e.containingGroup=this:d=!1}return d}; U.prototype.canUngroup=function(){if(!this.ungroupable)return!1;var a=this.layer;if(null!==a&&!a.allowUngroup)return!1;a=a.diagram;return null===a||a.allowUngroup?!0:!1};t=U.prototype; t.td=function(a){void 0===a&&(a=null);var b=0!==(this.P&65536);W.prototype.td.call(this,a);if(!b)for(0!==(this.P&65536)!==!0&&(this.P=this.P^65536),b=this.Qv();b.next();){var c=b.value;if(null===a||!a.contains(c)){var d=c.fromNode;null!==d&&d!==this&&d.Kd(this)&&!d.isVisible()?(To(c.fromPort),To(c.toPort),c.Ua()):(d=c.toNode,null!==d&&d!==this&&d.Kd(this)&&!d.isVisible()&&(To(c.fromPort),To(c.toPort),c.Ua()))}}}; t.Qv=function(){var a=this.xk();a.add(this);for(var b=new G,c=a.iterator;c.next();){var d=c.value;if(d instanceof W)for(d=d.linksConnected;d.next();){var e=d.value;a.contains(e)||b.add(e)}}return b.iterator};t.Wz=function(){var a=this.xk();a.add(this);for(var b=new G,c=a.iterator;c.next();){var d=c.value;if(d instanceof W)for(d=d.linksConnected;d.next();){var e=d.value,f=e.fromNode;null===f||a.contains(f)&&f!==this||b.add(f);e=e.toNode;null===e||a.contains(e)&&e!==this||b.add(e)}}return b.iterator}; t.Vz=function(){function a(b,d){null!==b&&(d.add(b),a(b.containingGroup,d))}var b=new G;a(this,b);return b};t.xk=function(){var a=new G;Vk(a,this,!0,0,!0);a.remove(this);return a};t.Pb=function(a){W.prototype.Pb.call(this,a);for(var b=this.memberParts;b.next();)b.value.Pb(a)};U.prototype.collapseSubGraph=function(){var a=this.diagram;if(null!==a&&!a.Le){a.Le=!0;var b=this.xk();ep(this,b,a,this);a.Le=!1}}; function ep(a,b,c,d){for(var e=a.memberParts;e.next();){var f=e.value;f.Pb(!1);f instanceof U&&f.isSubGraphExpanded&&(f.wasSubGraphExpanded=f.isSubGraphExpanded,ep(f,b,c,d));if(f instanceof W)f.td(b),c.jk(f,d);else if(f instanceof S)for(f=f.labelNodes;f.next();)f.value.td(b)}a.isSubGraphExpanded=!1}U.prototype.expandSubGraph=function(){var a=this.diagram;if(null!==a&&!a.Le){a.Le=!0;var b=this.xk();fp(this,b,a,this);a.Le=!1}}; function fp(a,b,c,d){for(var e=a.memberParts;e.next();){var f=e.value;f.Pb(!0);f instanceof U&&f.wasSubGraphExpanded&&(f.wasSubGraphExpanded=!1,fp(f,b,c,d));if(f instanceof W)f.td(b),c.lk(f,d);else if(f instanceof S)for(f=f.labelNodes;f.next();)f.value.td(b)}a.isSubGraphExpanded=!0} U.prototype.move=function(a,b){void 0===b&&(b=!1);var c=b?this.location:this.position,d=c.x;c=c.y;var e=a.x,f=a.y;if(!(d===e||isNaN(d)&&isNaN(e))||!(c===f||isNaN(c)&&isNaN(f))){d=e-(isNaN(d)?0:d);c=f-(isNaN(c)?0:c);f=I.alloc();W.prototype.move.call(this,a,b);a=new G;for(b=this.xk().iterator;b.next();)if(e=b.value,e instanceof S&&(e.suspendsRouting&&a.add(e),e.kd||e.fromNode!==this&&e.toNode!==this))e.suspendsRouting=!0;for(b.reset();b.next();)if(e=b.value,!(e.Oh()||e instanceof W&&e.isLinkLabel)){var g= e.position,h=e.location;g.s()?(f.x=g.x+d,f.y=g.y+c,e.position=f):h.s()&&(f.x=h.x+d,f.y=h.y+c,e.location=f)}for(b.reset();b.next();)if(e=b.value,e instanceof S&&(e.suspendsRouting=a.contains(e),e.kd||e.fromNode!==this&&e.toNode!==this))g=e.position,f.x=g.x+d,f.y=g.y+c,f.s()?e.move(f):e.Ua(),Sj(e)&&e.Ua();I.free(f)}}; na.Object.defineProperties(U.prototype,{placeholder:{get:function(){return this.Ra}},computesBoundsAfterDrag:{get:function(){return 0!==(this.P&2048)},set:function(a){var b=0!==(this.P&2048);b!==a&&(this.P^=2048,this.g("computesBoundsAfterDrag",b,a))}},computesBoundsIncludingLinks:{get:function(){return 0!==(this.P&4096)},set:function(a){var b=0!==(this.P&4096);b!==a&&(this.P^=4096,this.g("computesBoundsIncludingLinks", b,a))}},computesBoundsIncludingLocation:{get:function(){return 0!==(this.P&8192)},set:function(a){var b=0!==(this.P&8192);b!==a&&(this.P^=8192,this.g("computesBoundsIncludingLocation",b,a))}},handlesDragDropForMembers:{get:function(){return 0!==(this.P&16384)},set:function(a){var b=0!==(this.P&16384);b!==a&&(this.P^=16384,this.g("handlesDragDropForMembers",b,a))}},memberParts:{get:function(){return this.Qo.iterator}}, layout:{get:function(){return this.lc},set:function(a){var b=this.lc;if(b!==a){null!==b&&(b.diagram=null,b.group=null);this.lc=a;var c=this.diagram;null!==a&&(a.diagram=c,a.group=this);null!==c&&(c.Og=!0);this.g("layout",b,a);null!==c&&c.Eb()}}},memberAdded:{get:function(){return this.Po},set:function(a){var b=this.Po;b!==a&&(this.Po=a,this.g("memberAdded",b,a))}},memberRemoved:{get:function(){return this.Ro}, set:function(a){var b=this.Ro;b!==a&&(this.Ro=a,this.g("memberRemoved",b,a))}},memberValidation:{get:function(){return this.Ji},set:function(a){var b=this.Ji;b!==a&&(this.Ji=a,this.g("memberValidation",b,a))}},ungroupable:{get:function(){return 0!==(this.P&256)},set:function(a){var b=0!==(this.P&256);b!==a&&(this.P^=256,this.g("ungroupable",b,a))}},isSubGraphExpanded:{get:function(){return 0!==(this.P&512)}, set:function(a){var b=0!==(this.P&512);if(b!==a){this.P^=512;var c=this.diagram;this.g("isSubGraphExpanded",b,a);b=this.subGraphExpandedChanged;if(null!==b){var d=!0;null!==c&&(d=c.Z,c.Z=!0);b(this);null!==c&&(c.Z=d)}null!==c&&c.undoManager.isUndoingRedoing?(null!==this.Ra&&this.Ra.o(),this.memberParts.each(function(a){a.updateAdornments()})):a?this.expandSubGraph():this.collapseSubGraph()}}},wasSubGraphExpanded:{get:function(){return 0!==(this.P&1024)},set:function(a){var b= 0!==(this.P&1024);b!==a&&(this.P^=1024,this.g("wasSubGraphExpanded",b,a))}},subGraphExpandedChanged:{get:function(){return this.aq},set:function(a){var b=this.aq;b!==a&&(this.aq=a,this.g("subGraphExpandedChanged",b,a))}},Qh:{get:function(){return 0!==(this.P&32768)},set:function(a){0!==(this.P&32768)!==a&&(this.P^=32768)}}});U.prototype.expandSubGraph=U.prototype.expandSubGraph;U.prototype.collapseSubGraph=U.prototype.collapseSubGraph; U.prototype.findSubGraphParts=U.prototype.xk;U.prototype.findContainingGroupChain=U.prototype.Vz;U.prototype.findExternalNodesConnected=U.prototype.Wz;U.prototype.findExternalLinksConnected=U.prototype.Qv;U.prototype.ensureBounds=U.prototype.Ta;U.className="Group";function zg(){Y.call(this);this.ib=sc;this.Ip=new N(NaN,NaN,NaN,NaN)}ma(zg,Y);zg.prototype.cloneProtected=function(a){Y.prototype.cloneProtected.call(this,a);a.ib=this.ib.G();a.Ip=this.Ip.copy()}; zg.prototype.Jh=function(a){if(null===this.background&&null===this.areaBackground)return!1;var b=this.naturalBounds;return hc(0,0,b.width,b.height,a.x,a.y)}; zg.prototype.Gm=function(){var a=this.part;null!==a&&(a instanceof U||a instanceof Qe)||B("Placeholder is not inside a Group or Adornment.");if(a instanceof U){var b=this.computeBorder(this.Ip),c=this.minSize,d=this.rc;Ub(d,(isFinite(c.width)?Math.max(c.width,b.width):b.width)||0,(isFinite(c.height)?Math.max(c.height,b.height):b.height)||0);kl(this,0,0,d.width,d.height);d=a.memberParts;for(c=!1;d.next();)if(d.value.isVisible()){c=!0;break}d=a.diagram;!c||null===d||d.animationManager.dw(a)||isNaN(b.x)|| isNaN(b.y)||(c=I.alloc(),c.tj(b,a.locationSpot),c.w(a.location)||(a.location=new I(c.x,c.y)),I.free(c))}else{b=this.rc;c=this.ib;d=c.left+c.right;var e=c.top+c.bottom,f=a.adornedObject;a.angle=f.lj();var g=0;f instanceof Mf&&(g=f.strokeWidth);var h=f.Cf(),k=f.naturalBounds,l=(k.width+g)*h;g=(k.height+g)*h;a.type!==X.Link&&(f=f.da("Selection"===a.category?vc:a.locationSpot,I.alloc()),a.location=f,I.free(f));isNaN(l)||isNaN(g)?(a=a.adornedObject,l=a.da(vc,I.alloc()),f=N.allocAt(l.x,l.y,0,0),f.Pe(a.da(Gc, l)),f.Pe(a.da(zc,l)),f.Pe(a.da(Dc,l)),Ub(b,f.width+d||0,f.height+e||0),kl(this,-c.left,-c.top,b.width,b.height),I.free(l),N.free(f)):(Ub(b,l+d||0,g+e||0),kl(this,-c.left,-c.top,b.width,b.height))}};zg.prototype.Hh=function(a,b,c,d){this.actualBounds.h(a,b,c,d)}; zg.prototype.computeBorder=function(a){var b=this.part,c=b.diagram;if(null!==c&&b instanceof U&&!b.layer.isTemporary&&b.computesBoundsAfterDrag&&this.Ip.s()){var d=c.toolManager.findTool("Dragging");if(d===c.currentTool&&(c=d.computeBorder(b,this.Ip,a),null!==c))return c}c=N.alloc();d=this.computeMemberBounds(c);var e=this.ib;b instanceof U&&!b.isSubGraphExpanded?a.h(d.x-e.left,d.y-e.top,0,0):a.h(d.x-e.left,d.y-e.top,Math.max(d.width+e.left+e.right,0),Math.max(d.height+e.top+e.bottom,0));N.free(c); b instanceof U&&b.computesBoundsIncludingLocation&&b.location.s()&&a.Pe(b.location);return a}; zg.prototype.computeMemberBounds=function(a){if(!(this.part instanceof U))return a.h(0,0,0,0),a;for(var b=this.part,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=b.memberParts;g.next();){var h=g.value;if(h.isVisible()){if(h instanceof S){if(!b.computesBoundsIncludingLinks)continue;if(uj(h))continue;if(h.fromNode===b||h.toNode===b)continue}h=h.actualBounds;h.left<c&&(c=h.left);h.top<d&&(d=h.top);h.right>e&&(e=h.right);h.bottom>f&&(f=h.bottom)}}isFinite(c)&&isFinite(d)?a.h(c,d,e-c,f-d):(b=b.location, a.h(b.x,b.y,0,0));return a};na.Object.defineProperties(zg.prototype,{padding:{get:function(){return this.ib},set:function(a){"number"===typeof a&&(a=new oc(a));var b=this.ib;b.w(a)||(this.ib=a=a.G(),this.g("padding",b,a),this.o())}}});zg.className="Placeholder"; function S(){V.call(this,X.Link);this.Fa=8;this.Xe=null;this.Ye="";this.tf=this.co=null;this.uf="";this.jq=null;this.Yk=cg;this.Fn=0;this.Hn=cg;this.In=NaN;this.ck=gp;this.Wp=.5;this.od=null;this.Bb=(new E).freeze();this.sg=this.ph=null;this.Yl=new N;this.na=new td;this.I=this.v=this.Of=this.Xf=null;this.l=[];this.uv=new I;this.bs=this.Ox=this.Nx=null;this.Pu=NaN;this.O=null}ma(S,V); S.prototype.cloneProtected=function(a){V.prototype.cloneProtected.call(this,a);a.Fa=this.Fa&-113;a.Ye=this.Ye;a.co=this.co;a.uf=this.uf;a.jq=this.jq;a.Yk=this.Yk;a.Fn=this.Fn;a.Hn=this.Hn;a.In=this.In;a.ck=this.ck;a.Wp=this.Wp;null!==this.O&&(a.O=this.O.copy())};t=S.prototype;t.Af=function(a){V.prototype.Af.call(this,a);this.Ye=a.Ye;this.uf=a.uf;a.ph=null;a.Ua();a.Of=this.Of;var b=a.fromPort;null!==b&&To(b);a=a.toPort;null!==a&&To(a)}; t.jb=function(a){a.classType===S?2===(a.value&2)?this.routing=a:a===sg||a===bg||a===ag?this.curve=a:a===hp||a===ip||a===jp?this.adjusting=a:a!==gp&&a!==cg&&B("Unknown Link enum value for a Link property: "+a):V.prototype.jb.call(this,a)};t.Mc=function(){null===this.O&&(this.O=new gl)};t.rj=function(){var a=this.fromNode;if(null!==a){var b=a.findVisibleNode();null!==b&&(a=b);if(vj(a)||wj(a))return!1}a=this.toNode;return null!==a&&(b=a.findVisibleNode(),null!==b&&(a=b),vj(a)||wj(a))?!1:!0};t.Fw=function(){return!1}; t.lu=function(){};t.Pc=function(){return!1};S.prototype.computeAngle=function(a,b,c){return S.computeAngle(b,c)};S.computeAngle=function(a,b){switch(a){default:case cg:a=0;break;case Wm:a=b;break;case Pm:a=b+90;break;case Rm:a=b-90;break;case kp:a=b+180;break;case Xm:a=L.Sq(b);90<a&&270>a&&(a-=180);break;case Qm:a=L.Sq(b+90);90<a&&270>a&&(a-=180);break;case Sm:a=L.Sq(b-90);90<a&&270>a&&(a-=180);break;case Tm:a=L.Sq(b);if(45<a&&135>a||225<a&&315>a)return 0;90<a&&270>a&&(a-=180)}return L.Sq(a)}; function Oo(a){var b=a.fromNode,c=a.toNode,d=null;null!==b?d=null!==c?b.oy(c):b.containingGroup:null!==c?d=c.containingGroup:d=null;b=d;c=a.li;if(c!==b){null!==c&&Jo(c,a);a.li=b;null!==b&&Io(b,a);var e=a.containingGroupChanged;if(null!==e){var f=!0,g=a.diagram;null!==g&&(f=g.Z,g.Z=!0);e(a,c,b);null!==g&&(g.Z=f)}!a.kd||a.Nx!==c&&a.Ox!==c||a.Ua()}if(a.isLabeledLink)for(a=a.labelNodes;a.next();)a.value.containingGroup=d}t=S.prototype; t.Nh=function(){var a=this.containingGroup;null!==a&&this.fromNode!==a&&this.toNode!==a&&a.computesBoundsIncludingLinks&&V.prototype.Nh.call(this)};t.Hq=function(a){var b=this.fromNode;return a===b?this.toNode:b};t.nA=function(a){var b=this.fromPort;return a===b?this.toPort:b};function Xo(a,b){null===a.od&&(a.od=new G);a.od.add(b);a.o()} t.Jq=function(a){V.prototype.Jq.call(this,a);lp(this)&&this.Mq(this.actualBounds);if(!a){a=this.Xe;var b=null;null!==a&&(b=this.fromPort,Vo(a,this,b));var c=this.tf;if(null!==c){var d=this.toPort;c===a&&d===b||Vo(c,this,d)}mp(this)}};t.Kq=function(a){V.prototype.Kq.call(this,a);lp(this)&&this.Mq(this.actualBounds);if(!a){a=this.Xe;var b=null;null!==a&&(b=this.fromPort,Wo(a,this,b));var c=this.tf;if(null!==c){var d=this.toPort;c===a&&d===b||Wo(c,this,d)}np(this)}}; t.uk=function(){this.kd=!0;if(null!==this.od){var a=this.diagram;if(null!==a)for(var b=this.od.copy().iterator;b.next();)a.remove(b.value)}null!==this.data&&(a=this.diagram,null!==a&&a.partManager.removeDataForLink(this))};S.prototype.updateRelationshipsFromData=function(){if(null!==this.data){var a=this.diagram;null!==a&&a.partManager.updateRelationshipsFromData(this)}}; S.prototype.move=function(a,b){var c=b?this.location:this.position,d=c.x;isNaN(d)&&(d=0);var e=c.y;isNaN(e)&&(e=0);d=a.x-d;e=a.y-e;!0===b?V.prototype.move.call(this,a,!1):(a=I.allocAt(c.x+d,c.y+e),V.prototype.move.call(this,a,!1),I.free(a));tf(this,d,e);for(a=this.labelNodes;a.next();)b=a.value,c=b.position,b.moveTo(c.x+d,c.y+e)}; S.prototype.canRelinkFrom=function(){if(!this.relinkableFrom)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowRelink)return!1;a=a.diagram;return null===a||a.allowRelink?!0:!1};S.prototype.canRelinkTo=function(){if(!this.relinkableTo)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowRelink)return!1;a=a.diagram;return null===a||a.allowRelink?!0:!1}; S.prototype.computeMidPoint=function(a){var b=this.pointsCount;if(0===b)return a.assign(Jb),a;if(1===b)return a.assign(this.i(0)),a;if(2===b){var c=this.i(0),d=this.i(1);a.h((c.x+d.x)/2,(c.y+d.y)/2);return a}if(this.isOrthogonal&&(15<=this.computeCorner()||this.computeCurve()===sg))return this.na.Wv(.5,a),a.add(this.i(0)),c=this.na.figures.first(),a.offset(-c.startX,-c.startY),a;if(this.computeCurve()===sg){if(3===b)return this.i(1);d=(b-1)/3|0;c=3*(d/2|0);if(1===d%2){d=this.i(c);var e=this.i(c+1), f=this.i(c+2);c=this.i(c+3);L.yz(d.x,d.y,e.x,e.y,f.x,f.y,c.x,c.y,a)}else a.assign(this.i(c));return a}var g=this.flattenedLengths;c=this.flattenedTotalLength;for(e=f=d=0;d<c/2&&f<b;){e=g[f];if(d+e>c/2)break;d+=e;f++}b=this.i(f);f=this.i(f+1);1>Math.abs(b.x-f.x)?b.y>f.y?a.h(b.x,b.y-(c/2-d)):a.h(b.x,b.y+(c/2-d)):1>Math.abs(b.y-f.y)?b.x>f.x?a.h(b.x-(c/2-d),b.y):a.h(b.x+(c/2-d),b.y):(c=(c/2-d)/e,a.h(b.x+c*(f.x-b.x),b.y+c*(f.y-b.y)));return a}; S.prototype.computeMidAngle=function(){var a=this.pointsCount;if(2>a)return NaN;if(2===a)return this.i(0).Sa(this.i(1));if(this.isOrthogonal&&(15<=this.computeCorner()||this.computeCurve()===sg))return this.na.vy(.5);if(this.computeCurve()===sg&&4<=a){var b=(a-1)/3|0,c=3*(b/2|0);if(1===b%2){c=Math.floor(c);a=this.i(c);b=this.i(c+1);var d=this.i(c+2);c=this.i(c+3);return L.xz(a.x,a.y,b.x,b.y,d.x,d.y,c.x,c.y)}if(0<c&&c+1<a)return this.i(c-1).Sa(this.i(c+1))}b=this.flattenedLengths;d=this.flattenedTotalLength; var e=0;c=0;for(var f;e<d/2&&c<a;){f=b[c];if(e+f>d/2)break;e+=f;c++}b=this.i(c);d=this.i(c+1);if(1>Math.abs(b.x-d.x)&&1>Math.abs(b.y-d.y)){if(0<c&&c+2<a)return this.i(c-1).Sa(this.i(c+2))}else{if(1>Math.abs(b.x-d.x))return b.y>d.y?270:90;if(1>Math.abs(b.y-d.y))return b.x>d.x?180:0}return b.Sa(d)};t=S.prototype;t.i=function(a){return this.Bb.j[a]};t.Sc=function(a,b){this.Bb.Rc(a,b)};t.L=function(a,b,c){this.Bb.Rc(a,new I(b,c))};t.wA=function(a,b){this.Bb.wb(a,b)}; t.m=function(a,b,c){this.Bb.wb(a,new I(b,c))};t.ce=function(a){this.Bb.add(a)};t.xf=function(a,b){this.Bb.add(new I(a,b))};t.uw=function(a){this.Bb.cb(a)};t.pk=function(){this.Bb.clear()}; function tf(a,b,c){if(0!==b||0!==c)if(0===a.pointsCount)a.defaultFromPoint&&a.defaultFromPoint.copy().offset(b,c),a.defaultToPoint&&a.defaultToPoint.copy().offset(b,c);else{for(var d=a.kd,e=new E,f=a.Bb.iterator;f.next();){var g=f.value;e.add((new I(g.x+b,g.y+c)).freeze())}e.freeze();f=a.Bb;a.Bb=e;g=a.diagram;isNaN(b)||isNaN(c)||null!==g&&g.animationManager.sc?a.o():(a.fg.h(a.fg.x+b,a.fg.y+c),a.la.h(a.la.x+b,a.la.y+c),Fl(a));d?op(a):(a.defaultFromPoint&&(a.defaultFromPoint=a.i(0)),a.defaultToPoint&& (a.defaultToPoint=a.i(a.pointsCount-1)));null!==g&&g.animationManager.sc&&(a.sg=e);a.g("points",f,e)}}t.Sh=function(){null===this.ph&&(this.ph=this.Bb,this.Bb=this.Bb.copy())}; t.zf=function(){if(null!==this.ph){for(var a=this.ph,b=this.Bb,c=Infinity,d=Infinity,e=a.j,f=e.length,g=0;g<f;g++){var h=e[g];c=Math.min(h.x,c);d=Math.min(h.y,d)}h=g=Infinity;for(var k=b.j,l=k.length,m=0;m<l;m++){var n=k[m];g=Math.min(n.x,g);h=Math.min(n.y,h);n.freeze()}b.freeze();if(l===f)for(f=0;f<l;f++){if(m=e[f],n=k[f],m.x-c!==n.x-g||m.y-d!==n.y-h){this.dc();break}}else this.dc();this.ph=null;c=this.diagram;null!==c&&c.animationManager.sc&&(this.sg=b);op(this);this.g("points",a,b)}}; t.zw=function(){null!==this.ph&&(this.Bb=this.ph,this.ph=null)};function op(a){0===a.Bb.count?a.kd=!1:(a.kd=!0,a.bs=null,a.Pu=NaN,a.defaultFromPoint=a.i(0),a.defaultToPoint=a.i(a.pointsCount-1),pp(a,!1))} t.Ua=function(){if(!this.suspendsRouting){var a=this.diagram;if(a){if(a.Yt.contains(this)||a.undoManager.isUndoingRedoing)return;a=a.animationManager;if(a.isTicking&&!a.defaultAnimation.isAnimating)return;null!==this.sg&&!a.isTicking&&a.defaultAnimation.isAnimating&&(this.sg=null)}a=this.path;null!==a&&(this.kd=!1,this.o(),a.o())}};t.xj=function(){if(!this.kd&&!this.Ct){var a=!0;try{this.Ct=!0,this.Sh(),a=this.computePoints()}catch(b){this.Ct=!1,this.zw()}finally{this.Ct=!1,a?this.zf():this.zw()}}}; S.prototype.computePoints=function(){if(null===this.diagram)return!1;var a=this.fromNode,b=null;null===a?(qp||(qp=new W,qp.desiredSize=Kb,qp.Ta()),this.defaultFromPoint&&(qp.location=this.defaultFromPoint,qp.Ta(),b=a=qp)):b=this.fromPort;if(null!==b&&!a.isVisible()){var c=a.findVisibleNode();null!==c&&c!==a?(a=c,b=c.port):a=c}this.Nx=a;if(null===a||!a.location.s())return!1;for(;!(null===b||b.actualBounds.s()&&b.If());)b=b.panel;if(null===b)return!1;var d=this.toNode,e=null;null===d?(rp||(rp=new W, rp.desiredSize=Kb,rp.Ta()),this.defaultToPoint&&(rp.location=this.defaultToPoint,rp.Ta(),e=d=rp)):e=this.toPort;null===e||d.isVisible()||(c=d.findVisibleNode(),null!==c&&c!==d?(d=c,e=c.port):d=c);this.Ox=d;if(null===d||!d.location.s())return!1;for(;!(null===e||e.actualBounds.s()&&e.If());)e=e.panel;if(null===e)return!1;var f=this.pointsCount,g=this.computeSpot(!0,b);c=this.computeSpot(!1,e);var h=sp(g),k=sp(c),l=b===e&&null!==b,m=this.isOrthogonal,n=this.curve===sg;this.Xf=l&&!m?n=!0:!1;var p=this.computeAdjusting()=== cg||l;if(!m&&!l&&h&&k){if(h=!1,!p&&3<=f&&(p=this.getLinkPoint(a,b,g,!0,!1,d,e),k=this.getLinkPoint(d,e,c,!1,!1,a,b),h=this.adjustPoints(0,p,f-1,k))&&(p=this.getLinkPoint(a,b,g,!0,!1,d,e),k=this.getLinkPoint(d,e,c,!1,!1,a,b),this.adjustPoints(0,p,f-1,k)),!h)if(this.pk(),n){f=this.getLinkPoint(a,b,g,!0,!1,d,e);p=this.getLinkPoint(d,e,c,!1,!1,a,b);h=p.x-f.x;k=p.y-f.y;l=this.computeCurviness();n=m=0;var r=f.x+h/3,q=f.y+k/3,u=r,v=q;L.A(k,0)?v=0<h?v-l:v+l:(m=-h/k,n=Math.sqrt(l*l/(m*m+1)),0>l&&(n=-n),u= (0>k?-1:1)*n+r,v=m*(u-r)+q);r=f.x+2*h/3;q=f.y+2*k/3;var w=r,y=q;L.A(k,0)?y=0<h?y-l:y+l:(w=(0>k?-1:1)*n+r,y=m*(w-r)+q);this.pk();this.ce(f);this.xf(u,v);this.xf(w,y);this.ce(p);this.Sc(0,this.getLinkPoint(a,b,g,!0,!1,d,e));this.Sc(3,this.getLinkPoint(d,e,c,!1,!1,a,b))}else if(f=d,p=e,d=this.getLinkPoint(a,b,g,!0,!1,f,p),e=this.getLinkPoint(f,p,c,!1,!1,a,b),this.hasCurviness())p=e.x-d.x,c=e.y-d.y,g=this.computeCurviness(),a=d.x+p/2,b=d.y+c/2,f=a,h=b,L.A(c,0)?h=0<p?h-g:h+g:(p=-p/c,f=Math.sqrt(g*g/(p* p+1)),0>g&&(f=-f),f=(0>c?-1:1)*f+a,h=p*(f-a)+b),this.ce(d),this.xf(f,h),this.ce(e);else{this.ce(d);this.ce(e);h=N.alloc();b.mj(h);k=h.$(e);p.mj(h);l=h.$(d);if(k||l)g=b.da(tp(g),new I),this.Sc(0,this.getLinkPointFromPoint(a,b,g,e,!0,g)),c=p.da(tp(c),new I),this.Sc(1,this.getLinkPointFromPoint(f,p,c,d,!1,c));N.free(h)}}else{n=this.isAvoiding;p&&(m&&n||l)&&this.pk();var z=l?this.computeCurviness():0;n=this.getLinkPoint(a,b,g,!0,m,d,e);r=u=q=0;if(m||!h||l)v=this.computeEndSegmentLength(a,b,g,!0),r=this.getLinkDirection(a, b,n,g,!0,m,d,e),l&&(h||g.w(c)||!m&&1===g.x+c.x&&1===g.y+c.y)&&(r-=m?90:30,0>z&&(r-=180)),0>r?r+=360:360<=r&&(r-=360),l&&(v+=Math.abs(z)*(m?1:2)),0===r?q=v:90===r?u=v:180===r?q=-v:270===r?u=-v:(q=v*Math.cos(r*Math.PI/180),u=v*Math.sin(r*Math.PI/180)),g.nc()&&l&&(v=b.da(Bc,I.alloc()),w=I.allocAt(v.x+1E3*q,v.y+1E3*u),this.getLinkPointFromPoint(a,b,v,w,!0,n),I.free(v),I.free(w));v=this.getLinkPoint(d,e,c,!1,m,a,b);var A=y=w=0;if(m||!k||l){var C=this.computeEndSegmentLength(d,e,c,!1);A=this.getLinkDirection(d, e,v,c,!1,m,a,b);l&&(k||g.w(c)||!m&&1===g.x+c.x&&1===g.y+c.y)&&(A+=m?0:30,0>z&&(A+=180));0>A?A+=360:360<=A&&(A-=360);l&&(C+=Math.abs(z)*(m?1:2));0===A?w=C:90===A?y=C:180===A?w=-C:270===A?y=-C:(w=C*Math.cos(A*Math.PI/180),y=C*Math.sin(A*Math.PI/180));c.nc()&&l&&(c=e.da(Bc,I.alloc()),g=I.allocAt(c.x+1E3*w,c.y+1E3*y),this.getLinkPointFromPoint(d,e,c,g,!1,v),I.free(c),I.free(g))}c=n;if(m||!h||l)c=new I(n.x+q,n.y+u);g=v;if(m||!k||l)g=new I(v.x+w,v.y+y);!p&&!m&&h&&3<f&&this.adjustPoints(0,n,f-2,g)?this.Sc(f- 1,v):!p&&!m&&k&&3<f&&this.adjustPoints(1,c,f-1,v)?this.Sc(0,n):!p&&(m?6<=f:4<f)&&this.adjustPoints(1,c,f-2,g)?(this.Sc(0,n),this.Sc(f-1,v)):(this.pk(),this.ce(n),(m||!h||l)&&this.ce(c),m&&this.addOrthoPoints(c,r,g,A,a,d),(m||!k||l)&&this.ce(g),this.ce(v))}return!0};function up(a,b){Math.abs(b.x-a.x)>Math.abs(b.y-a.y)?(b.x>=a.x?b.x=a.x+9E9:b.x=a.x-9E9,b.y=a.y):(b.y>=a.y?b.y=a.y+9E9:b.y=a.y-9E9,b.x=a.x);return b} S.prototype.getLinkPointFromPoint=function(a,b,c,d,e,f){void 0===f&&(f=new I);if(null===a||null===b)return f.assign(c),f;a.isVisible()||(e=a.findVisibleNode(),null!==e&&e!==a&&(b=e.port));a=null;e=b.panel;null===e||e.ie()||(e=e.panel);if(null===e){e=d.x;d=d.y;var g=c.x;c=c.y}else{a=e.Fd;e=1/(a.m11*a.m22-a.m12*a.m21);g=a.m22*e;var h=-a.m12*e,k=-a.m21*e,l=a.m11*e,m=e*(a.m21*a.dy-a.m22*a.dx),n=e*(a.m12*a.dx-a.m11*a.dy);e=d.x*g+d.y*k+m;d=d.x*h+d.y*l+n;g=c.x*g+c.y*k+m;c=c.x*h+c.y*l+n}b.yk(e,d,g,c,f);null!== a&&f.transform(a);return f};function vp(a,b){var c=b.sp;null===c&&(c=new wp,c.port=b,c.node=b.part,b.sp=c);return xp(c,a)} S.prototype.getLinkPoint=function(a,b,c,d,e,f,g,h){void 0===h&&(h=new I);if(c.kb()&&!sp(c))return b.da(c,h),h;if(c.Qc()){var k=vp(this,b);if(null!==k){h.assign(k.Pq);if(e&&this.routing===yp){var l=vp(this,g);if(null!==l&&k.vm<l.vm){k=I.alloc();l=I.alloc();var m=new N(b.da(vc,k),b.da(Gc,l)),n=this.computeSpot(!d,g);a=this.getLinkPoint(f,g,n,!d,e,a,b,l);(c.Gf(Ic)||c.Gf(Jc))&&a.y>=m.y&&a.y<=m.y+m.height?h.y=a.y:(c.Gf(Hc)||c.Gf(Kc))&&a.x>=m.x&&a.x<=m.x+m.width&&(h.x=a.x);I.free(k);I.free(l)}}return h}}c= b.da(tp(c),I.alloc());this.pointsCount>(e?6:2)?(g=d?this.i(1):this.i(this.pointsCount-2),e&&(g=up(c,g.copy()))):(k=this.computeSpot(!d,g),f=I.alloc(),g=g.da(tp(k),f),e&&(g=up(c,g)),I.free(f));this.getLinkPointFromPoint(a,b,c,g,d,h);I.free(c);return h}; S.prototype.getLinkDirection=function(a,b,c,d,e,f,g,h){a:if(d.kb())var k=d.x>d.y?d.x>1-d.y?0:d.x<1-d.y?270:315:d.x<d.y?d.x>1-d.y?90:d.x<1-d.y?180:135:.5>d.x?225:.5<d.x?45:0;else{if(d.Qc()&&(k=vp(this,b),null!==k))switch(k.Bc){case 1:k=270;break a;case 2:k=180;break a;default:case 4:k=0;break a;case 8:k=90;break a}k=b.da(Bc,I.alloc());this.pointsCount>(f?6:2)?(h=e?this.i(1):this.i(this.pointsCount-2),h=f?up(k,h.copy()):c):(c=I.alloc(),h=h.da(Bc,c),I.free(c));c=Math.abs(h.x-k.x)>Math.abs(h.y-k.y)?h.x>= k.x?0:180:h.y>=k.y?90:270;I.free(k);k=c}d.nc()&&g.Kd(a)&&(k+=180,360<=k&&(k-=360));if(sp(d))return k;a=b.lj();if(0===a)return k;45<=a&&135>a?k+=90:135<=a&&225>a?k+=180:225<=a&&315>a&&(k+=270);360<=k&&(k-=360);return k};S.prototype.computeEndSegmentLength=function(a,b,c,d){if(null!==b&&c.Qc()&&(a=vp(this,b),null!==a))return a.Ov;a=d?this.fromEndSegmentLength:this.toEndSegmentLength;null!==b&&isNaN(a)&&(a=d?b.fromEndSegmentLength:b.toEndSegmentLength);isNaN(a)&&(a=10);return a}; S.prototype.computeSpot=function(a,b){void 0===b&&(b=null);a?(a=b?b:this.fromPort,null===a?a=Bc:(b=this.fromSpot,b.Nb()&&(b=a.fromSpot),a=b===Zc?uc:b)):(a=b?b:this.toPort,null===a?a=Bc:(b=this.toSpot,b.Nb()&&(b=a.toSpot),a=b===Zc?uc:b));return a};function sp(a){return a===uc||.5===a.x&&.5===a.y}function tp(a){return.5===a.x&&.5===a.y?a:Bc} S.prototype.computeOtherPoint=function(a,b){if(this.computeAdjusting()!==cg&&4<this.pointsCount)return this.computeMidPoint(new I);a=b.da(Bc);b=b.sp;b=null!==b?xp(b,this):null;null!==b&&(a=b.Pq);return a};S.prototype.computeShortLength=function(a){if(a){a=this.fromShortLength;if(isNaN(a)){var b=this.fromPort;null!==b&&(a=b.fromShortLength)}return isNaN(a)?0:a}a=this.toShortLength;isNaN(a)&&(b=this.toPort,null!==b&&(a=b.toShortLength));return isNaN(a)?0:a}; S.prototype.Bf=function(a,b,c,d,e,f){if(!1===this.pickable)return!1;void 0===b&&(b=null);void 0===c&&(c=null);var g=f;void 0===f&&(g=rd.alloc(),g.reset());g.multiply(this.transform);if(this.Ih(a,g))return hn(this,b,c,e),void 0===f&&rd.free(g),!0;if(this.Oc(a,g)){var h=!1;if(!this.isAtomic)for(var k=this.W.j,l=k.length;l--;){var m=k[l];if(m.visible||m===this.locationObject){var n=m.actualBounds,p=this.naturalBounds;if(!(n.x>p.width||n.y>p.height||0>n.x+n.width||0>n.y+n.height)){n=rd.alloc();n.set(g); if(m instanceof X)h=m.Bf(a,b,c,d,e,n);else if(this.path===m){if(m instanceof Mf)if(h=a,p=d,!1===m.pickable)h=!1;else if(n.multiply(m.transform),p)b:{var r=h,q=n;if(m.Ih(r,q))h=!0;else{if(void 0===q&&(q=m.transform,r.He(m.actualBounds))){h=!0;break b}h=r.left;p=r.right;var u=r.top;r=r.bottom;var v=I.alloc(),w=I.alloc(),y=I.alloc(),z=rd.alloc();z.set(q);z.iw(m.transform);z.Tt();w.x=p;w.y=u;w.transform(z);v.x=h;v.y=u;v.transform(z);q=!1;zn(m,v,w,y)?q=!0:(v.x=p,v.y=r,v.transform(z),zn(m,v,w,y)?q=!0:(w.x= h,w.y=r,w.transform(z),zn(m,v,w,y)?q=!0:(v.x=h,v.y=u,v.transform(z),zn(m,v,w,y)&&(q=!0))));rd.free(z);I.free(v);I.free(w);I.free(y);h=q}}else h=m.Ih(h,n)}else h=ml(m,a,d,n);h&&(p=m,null!==b&&(p=b(m)),p&&(null===c||c(p))&&e.add(p));rd.free(n)}}}void 0===f&&rd.free(g);return h||null!==this.background||null!==this.areaBackground}void 0===f&&rd.free(g);return!1}; S.prototype.computeCurve=function(){if(null===this.Xf){var a=this.fromPort,b=this.isOrthogonal;this.Xf=null!==a&&a===this.toPort&&!b}return this.Xf?sg:this.curve};S.prototype.computeCorner=function(){if(this.curve===sg)return 0;var a=this.corner;if(isNaN(a)||0>a)a=10;return a}; S.prototype.findMidLabel=function(){for(var a=this.path,b=this.W.j,c=b.length,d=0;d<c;d++){var e=b[d];if(e!==a&&!e.isPanelMain&&(-Infinity===e.segmentIndex||isNaN(e.segmentIndex)))return e}for(a=this.labelNodes;a.next();)if(b=a.value,-Infinity===b.segmentIndex||isNaN(b.segmentIndex))return b;return null}; S.prototype.computeSpacing=function(){if(!this.isVisible())return 0;var a=zp;a=Math.max(a,this.computeThickness());var b=this.fromPort,c=this.toPort;if(null!==b&&null!==c){var d=this.findMidLabel();if(null!==d){var e=d.naturalBounds,f=d.margin,g=isNaN(e.width)?30:e.width*d.scale+f.left+f.right;e=isNaN(e.height)?14:e.height*d.scale+f.top+f.bottom;d=d.segmentOrientation;d===Wm||d===Xm||d===kp?a=Math.max(a,e):d===Rm||d===Sm||d===Pm||d===Qm?a=Math.max(a,g):(b=b.da(Bc).Sa(c.da(Bc))/180*Math.PI,a=Math.max(a, Math.abs(Math.sin(b)*g)+Math.abs(Math.cos(b)*e)+1));this.curve===sg&&(a*=1.333)}}return a};S.prototype.arrangeBundledLinks=function(a,b){if(b)for(b=0;b<a.length;b++){var c=a[b];c.computeAdjusting()===cg&&c.Ua()}}; S.prototype.computeCurviness=function(){var a=this.curviness;if(isNaN(a)){a=Ap;var b=this.Of;if(null!==b){for(var c=Ea(),d=0,e=b.links,f=0;f<e.length;f++){var g=e[f].computeSpacing();c.push(g);d+=g}d=-d/2;for(f=0;f<e.length;f++){if(e[f]===this){a=d+c[f]/2;break}d+=c[f]}b.au===this.fromNode&&(a=-a);Ia(c)}}return a};S.prototype.computeThickness=function(){if(!this.isVisible())return 0;var a=this.path;return null!==a?Math.max(a.strokeWidth,1):1}; S.prototype.hasCurviness=function(){return!isNaN(this.curviness)||null!==this.Of}; S.prototype.adjustPoints=function(a,b,c,d){var e=this.computeAdjusting();if(this.isOrthogonal){if(e===ip)return!1;e===jp&&(e=hp)}switch(e){case ip:var f=this.i(a),g=this.i(c);if(!f.Na(b)||!g.Na(d)){e=f.x;f=f.y;var h=g.x-e,k=g.y-f,l=Math.sqrt(h*h+k*k);if(!L.aa(l,0)){if(L.aa(h,0))var m=0>k?-Math.PI/2:Math.PI/2;else m=Math.atan(k/Math.abs(h)),0>h&&(m=Math.PI-m);g=b.x;var n=b.y;h=d.x-g;var p=d.y-n;k=Math.sqrt(h*h+p*p);L.aa(h,0)?p=0>p?-Math.PI/2:Math.PI/2:(p=Math.atan(p/Math.abs(h)),0>h&&(p=Math.PI-p)); l=k/l;m=p-m;this.Sc(a,b);for(a+=1;a<c;a++)b=this.i(a),h=b.x-e,k=b.y-f,b=Math.sqrt(h*h+k*k),L.aa(b,0)||(L.aa(h,0)?k=0>k?-Math.PI/2:Math.PI/2:(k=Math.atan(k/Math.abs(h)),0>h&&(k=Math.PI-k)),h=k+m,b*=l,this.L(a,g+b*Math.cos(h),n+b*Math.sin(h)));this.Sc(c,d)}}return!0;case jp:f=this.i(a);n=this.i(c);if(!f.Na(b)||!n.Na(d)){e=f.x;f=f.y;g=n.x;n=n.y;l=(g-e)*(g-e)+(n-f)*(n-f);h=b.x;m=b.y;k=d.x;p=d.y;var r=1;if(0!==k-h){var q=(p-m)/(k-h);r=Math.sqrt(1+1/(q*q))}else q=9E9;this.Sc(a,b);for(a+=1;a<c;a++){b=this.i(a); var u=b.x,v=b.y,w=.5;0!==l&&(w=((e-u)*(e-g)+(f-v)*(f-n))/l);var y=e+w*(g-e),z=f+w*(n-f);b=Math.sqrt((u-y)*(u-y)+(v-z)*(v-z));v<q*(u-y)+z&&(b=-b);0<q&&(b=-b);u=h+w*(k-h);w=m+w*(p-m);0!==q?(b=u+b/r,this.L(a,b,w-(b-u)/q)):this.L(a,u,w+b)}this.Sc(c,d)}return!0;case hp:a:{if(this.isOrthogonal&&(e=this.i(a),f=this.i(a+1),g=this.i(a+2),h=f.x,m=f.y,n=h,l=m,L.A(e.y,f.y)?L.A(f.x,g.x)?m=b.y:L.A(f.y,g.y)&&(h=b.x):L.A(e.x,f.x)&&(L.A(f.y,g.y)?h=b.x:L.A(f.x,g.x)&&(m=b.y)),this.L(a+1,h,m),e=this.i(c),f=this.i(c- 1),g=this.i(c-2),h=f.x,m=f.y,k=h,p=m,L.A(e.y,f.y)?L.A(f.x,g.x)?m=d.y:L.A(f.y,g.y)&&(h=d.x):L.A(e.x,f.x)&&(L.A(f.y,g.y)?h=d.x:L.A(f.x,g.x)&&(m=d.y)),this.L(c-1,h,m),Sj(this))){this.L(a+1,n,l);this.L(c-1,k,p);c=!1;break a}this.Sc(a,b);this.Sc(c,d);c=!0}return c;default:return!1}}; S.prototype.addOrthoPoints=function(a,b,c,d,e,f){b=-45<=b&&45>b?0:45<=b&&135>b?90:135<=b&&225>b?180:270;d=-45<=d&&45>d?0:45<=d&&135>d?90:135<=d&&225>d?180:270;var g=e.actualBounds.copy(),h=f.actualBounds.copy();if(g.s()&&h.s()){g.Lc(Bp,Bp);h.Lc(Bp,Bp);g.Pe(a);h.Pe(c);if(0===b)if(c.x>a.x||270===d&&c.y<a.y&&h.right>a.x||90===d&&c.y>a.y&&h.right>a.x){var k=new I(c.x,a.y);var l=new I(c.x,(a.y+c.y)/2);180===d?(k.x=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1),l.x=k.x,l.y=c.y):270===d&&c.y<a.y||90=== d&&c.y>a.y?(k.x=a.x<h.left?this.computeMidOrthoPosition(a.x,a.y,h.left,c.y,!1):a.x<h.right&&(270===d&&a.y<h.top||90===d&&a.y>h.bottom)?this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1):h.right,l.x=k.x,l.y=c.y):0===d&&a.x<h.left&&a.y>h.top&&a.y<h.bottom&&(k.x=a.x,k.y=a.y<c.y?Math.min(c.y,h.top):Math.max(c.y,h.bottom),l.y=k.y)}else{k=new I(a.x,c.y);l=new I((a.x+c.x)/2,c.y);if(180===d||90===d&&c.y<g.top||270===d&&c.y>g.bottom)180===d&&(h.$(a)||g.$(c))?k.y=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y, !0):c.y<a.y&&(180===d||90===d)?k.y=this.computeMidOrthoPosition(a.x,g.top,c.x,Math.max(c.y,h.bottom),!0):c.y>a.y&&(180===d||270===d)&&(k.y=this.computeMidOrthoPosition(a.x,g.bottom,c.x,Math.min(c.y,h.top),!0)),l.x=c.x,l.y=k.y;if(k.y>g.top&&k.y<g.bottom)if(c.x>=g.left&&c.x<=a.x||a.x<=h.right&&a.x>=c.x){if(90===d||270===d)k=new I(Math.max((a.x+c.x)/2,a.x),a.y),l=new I(k.x,c.y)}else k.y=270===d||(0===d||180===d)&&c.y<a.y?Math.min(c.y,0===d?g.top:Math.min(g.top,h.top)):Math.max(c.y,0===d?g.bottom:Math.max(g.bottom, h.bottom)),l.x=c.x,l.y=k.y}else if(180===b)if(c.x<a.x||270===d&&c.y<a.y&&h.left<a.x||90===d&&c.y>a.y&&h.left<a.x)k=new I(c.x,a.y),l=new I(c.x,(a.y+c.y)/2),0===d?(k.x=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1),l.x=k.x,l.y=c.y):270===d&&c.y<a.y||90===d&&c.y>a.y?(k.x=a.x>h.right?this.computeMidOrthoPosition(a.x,a.y,h.right,c.y,!1):a.x>h.left&&(270===d&&a.y<h.top||90===d&&a.y>h.bottom)?this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1):h.left,l.x=k.x,l.y=c.y):180===d&&a.x>h.right&&a.y>h.top&&a.y< h.bottom&&(k.x=a.x,k.y=a.y<c.y?Math.min(c.y,h.top):Math.max(c.y,h.bottom),l.y=k.y);else{k=new I(a.x,c.y);l=new I((a.x+c.x)/2,c.y);if(0===d||90===d&&c.y<g.top||270===d&&c.y>g.bottom)0===d&&(h.$(a)||g.$(c))?k.y=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0):c.y<a.y&&(0===d||90===d)?k.y=this.computeMidOrthoPosition(a.x,g.top,c.x,Math.max(c.y,h.bottom),!0):c.y>a.y&&(0===d||270===d)&&(k.y=this.computeMidOrthoPosition(a.x,g.bottom,c.x,Math.min(c.y,h.top),!0)),l.x=c.x,l.y=k.y;if(k.y>g.top&&k.y<g.bottom)if(c.x<= g.right&&c.x>=a.x||a.x>=h.left&&a.x<=c.x){if(90===d||270===d)k=new I(Math.min((a.x+c.x)/2,a.x),a.y),l=new I(k.x,c.y)}else k.y=270===d||(0===d||180===d)&&c.y<a.y?Math.min(c.y,180===d?g.top:Math.min(g.top,h.top)):Math.max(c.y,180===d?g.bottom:Math.max(g.bottom,h.bottom)),l.x=c.x,l.y=k.y}else if(90===b)if(c.y>a.y||180===d&&c.x<a.x&&h.bottom>a.y||0===d&&c.x>a.x&&h.bottom>a.y)k=new I(a.x,c.y),l=new I((a.x+c.x)/2,c.y),270===d?(k.y=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0),l.x=c.x,l.y=k.y):180=== d&&c.x<a.x||0===d&&c.x>a.x?(k.y=a.y<h.top?this.computeMidOrthoPosition(a.x,a.y,c.x,h.top,!0):a.y<h.bottom&&(180===d&&a.x<h.left||0===d&&a.x>h.right)?this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0):h.bottom,l.x=c.x,l.y=k.y):90===d&&a.y<h.top&&a.x>h.left&&a.x<h.right&&(k.x=a.x<c.x?Math.min(c.x,h.left):Math.max(c.x,h.right),k.y=a.y,l.x=k.x);else{k=new I(c.x,a.y);l=new I(c.x,(a.y+c.y)/2);if(270===d||0===d&&c.x<g.left||180===d&&c.x>g.right)270===d&&(h.$(a)||g.$(c))?k.x=this.computeMidOrthoPosition(a.x, a.y,c.x,c.y,!1):c.x<a.x&&(270===d||0===d)?k.x=this.computeMidOrthoPosition(g.left,a.y,Math.max(c.x,h.right),c.y,!1):c.x>a.x&&(270===d||180===d)&&(k.x=this.computeMidOrthoPosition(g.right,a.y,Math.min(c.x,h.left),c.y,!1)),l.x=k.x,l.y=c.y;if(k.x>g.left&&k.x<g.right)if(c.y>=g.top&&c.y<=a.y||a.y<=h.bottom&&a.y>=c.y){if(0===d||180===d)k=new I(a.x,Math.max((a.y+c.y)/2,a.y)),l=new I(c.x,k.y)}else k.x=180===d||(90===d||270===d)&&c.x<a.x?Math.min(c.x,90===d?g.left:Math.min(g.left,h.left)):Math.max(c.x,90=== d?g.right:Math.max(g.right,h.right)),l.x=k.x,l.y=c.y}else if(c.y<a.y||180===d&&c.x<a.x&&h.top<a.y||0===d&&c.x>a.x&&h.top<a.y)k=new I(a.x,c.y),l=new I((a.x+c.x)/2,c.y),90===d?(k.y=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0),l.x=c.x,l.y=k.y):180===d&&c.x<a.x||0===d&&c.x>=a.x?(k.y=a.y>h.bottom?this.computeMidOrthoPosition(a.x,a.y,c.x,h.bottom,!0):a.y>h.top&&(180===d&&a.x<h.left||0===d&&a.x>h.right)?this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0):h.top,l.x=c.x,l.y=k.y):270===d&&a.y>h.bottom&&a.x> h.left&&a.x<h.right&&(k.x=a.x<c.x?Math.min(c.x,h.left):Math.max(c.x,h.right),k.y=a.y,l.x=k.x);else{k=new I(c.x,a.y);l=new I(c.x,(a.y+c.y)/2);if(90===d||0===d&&c.x<g.left||180===d&&c.x>g.right)90===d&&(h.$(a)||g.$(c))?k.x=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1):c.x<a.x&&(90===d||0===d)?k.x=this.computeMidOrthoPosition(g.left,a.y,Math.max(c.x,h.right),c.y,!1):c.x>a.x&&(90===d||180===d)&&(k.x=this.computeMidOrthoPosition(g.right,a.y,Math.min(c.x,h.left),c.y,!1)),l.x=k.x,l.y=c.y;if(k.x>g.left&& k.x<g.right)if(c.y<=g.bottom&&c.y>=a.y||a.y>=h.top&&a.y<=c.y){if(0===d||180===d)k=new I(a.x,Math.min((a.y+c.y)/2,a.y)),l=new I(c.x,k.y)}else k.x=180===d||(90===d||270===d)&&c.x<a.x?Math.min(c.x,270===d?g.left:Math.min(g.left,h.left)):Math.max(c.x,270===d?g.right:Math.max(g.right,h.right)),l.x=k.x,l.y=c.y}var m=k,n=l,p=c;if(this.isAvoiding){var r=this.diagram;if(null===r||!pk(r)||g.$(p)&&!f.Kd(e)||h.$(a)&&!e.Kd(f)||e===f||this.layer.isTemporary)b=!1;else{var q=tk(r,!0,this.containingGroup,null);if(17!== this.segmentIndex&&q.Dk(Math.min(a.x,m.x),Math.min(a.y,m.y),Math.abs(a.x-m.x),Math.abs(a.y-m.y))&&q.Dk(Math.min(m.x,n.x),Math.min(m.y,n.y),Math.abs(m.x-n.x),Math.abs(m.y-n.y))&&q.Dk(Math.min(n.x,p.x),Math.min(n.y,p.y),Math.abs(n.x-p.x),Math.abs(n.y-p.y)))b=!1;else{e=a;f=p;var u=c=null;if(r.isVirtualized){r=q.bounds.copy();r.Lc(-q.wq,-q.vq);var v=I.alloc();xk(q,a.x,a.y)||(L.Ef(r.x,r.y,r.x+r.width,r.y+r.height,a.x,a.y,m.x,m.y,v)?(c=a=v.copy(),b=v.Sa(m)):L.Ef(r.x,r.y,r.x+r.width,r.y+r.height,m.x,m.y, n.x,n.y,v)?(c=a=v.copy(),b=v.Sa(n)):L.Ef(r.x,r.y,r.x+r.width,r.y+r.height,n.x,n.y,p.x,p.y,v)&&(c=a=v.copy(),b=v.Sa(p)));xk(q,p.x,p.y)||(L.Ef(r.x,r.y,r.x+r.width,r.y+r.height,p.x,p.y,n.x,n.y,v)?(u=p=v.copy(),d=n.Sa(v)):L.Ef(r.x,r.y,r.x+r.width,r.y+r.height,n.x,n.y,m.x,m.y,v)?(u=p=v.copy(),d=m.Sa(v)):L.Ef(r.x,r.y,r.x+r.width,r.y+r.height,m.x,m.y,a.x,a.y,v)&&(u=p=v.copy(),d=a.Sa(v)));I.free(v)}g=g.copy().Tc(h);g.Lc(q.wq*q.Xy,q.vq*q.Xy);Cp(q,a,b,p,d,g,!0);h=Dp(q,p.x,p.y);!q.abort&&h>=Ep&&(wk(q),g.Lc(q.wq* q.Hy,q.vq*q.Hy),Cp(q,a,b,p,d,g,!1),h=Dp(q,p.x,p.y));if(!q.abort&&h<Ep&&Dp(q,p.x,p.y)!==yk){Fp(this,q,p.x,p.y,d,!0);h=this.i(2);if(4>this.pointsCount)0===b||180===b?(h.x=a.x,h.y=p.y):(h.x=p.x,h.y=a.y),this.L(2,h.x,h.y),this.m(3,h.x,h.y);else if(g=this.i(3),0===b||180===b)L.A(h.x,g.x)?(h=0===b?Math.max(h.x,a.x):Math.min(h.x,a.x),this.L(2,h,a.y),this.L(3,h,g.y)):L.A(h.y,g.y)?(Math.abs(a.y-h.y)<=q.vq/2&&(this.L(2,h.x,a.y),this.L(3,g.x,a.y)),this.m(2,h.x,a.y)):this.L(2,a.x,h.y);else if(90===b||270===b)L.A(h.y, g.y)?(h=90===b?Math.max(h.y,a.y):Math.min(h.y,a.y),this.L(2,a.x,h),this.L(3,g.x,h)):L.A(h.x,g.x)?(Math.abs(a.x-h.x)<=q.wq/2&&(this.L(2,a.x,h.y),this.L(3,a.x,g.y)),this.m(2,a.x,h.y)):this.L(2,h.x,a.y);null!==c&&(a=this.i(1),g=this.i(2),a.x!==g.x&&a.y!==g.y?0===b||180===b?this.m(2,a.x,g.y):this.m(2,g.x,a.y):0===b||180===b?this.m(2,e.x,c.y):this.m(2,c.x,e.y));null!==u&&(0===d||180===d?this.xf(f.x,u.y):this.xf(u.x,f.y));b=!0}else b=!1}}}else b=!1;b||(this.ce(k),this.ce(l))}}; S.prototype.computeMidOrthoPosition=function(a,b,c,d,e){var f=0;!this.hasCurviness()||this.computeSpot(!0,this.fromPort).Qc()||this.computeSpot(!1,this.toPort).Qc()||(f=this.computeCurviness());return e?(b+d)/2+f:(a+c)/2+f}; function Sj(a){if(null===a.diagram||!a.isAvoiding||!pk(a.diagram))return!1;var b=a.points.j,c=b.length;if(4>c)return!1;a=tk(a.diagram,!0,a.containingGroup,null);for(var d=1;d<c-2;d++){var e=b[d],f=b[d+1];if(!a.Dk(Math.min(e.x,f.x),Math.min(e.y,f.y),Math.abs(e.x-f.x),Math.abs(e.y-f.y)))return!0}return!1} function Fp(a,b,c,d,e,f){var g=b.wq,h=b.vq,k=Dp(b,c,d),l=c,m=d;for(0===e?l+=g:90===e?m+=h:180===e?l-=g:m-=h;k>Gp&&Dp(b,l,m)===k-1;)c=l,d=m,0===e?l+=g:90===e?m+=h:180===e?l-=g:m-=h,--k;if(f){if(k>Gp)if(180===e||0===e)c=Math.floor(c/g)*g+g/2;else if(90===e||270===e)d=Math.floor(d/h)*h+h/2}else c=Math.floor(c/g)*g+g/2,d=Math.floor(d/h)*h+h/2;k>Gp&&(f=e,l=c,m=d,0===e?(f=90,m+=h):90===e?(f=180,l-=g):180===e?(f=270,m-=h):270===e&&(f=0,l+=g),Dp(b,l,m)===k-1?Fp(a,b,l,m,f,!1):(l=c,m=d,0===e?(f=270,m-=h):90=== e?(f=0,l+=g):180===e?(f=90,m+=h):270===e&&(f=180,l-=g),Dp(b,l,m)===k-1&&Fp(a,b,l,m,f,!1)));a.xf(c,d)}S.prototype.Sz=function(a){var b=a.x;a=a.y;for(var c=this.i(0),d=this.i(1),e=zb(b,a,c.x,c.y,d.x,d.y),f=0,g=1;g<this.pointsCount-1;g++){c=this.i(g+1);var h=zb(b,a,d.x,d.y,c.x,c.y);d=c;h<e&&(f=g,e=h)}return f};S.prototype.dc=function(){this.Ym=!1;this.o()}; S.prototype.Fk=function(a){if(!a){if(!1===this.kd)return;a=this.rb();if(this.Ym&&(null===a||null!==a.geometry))return}this.na=this.makeGeometry();a=this.path;if(null!==a){a.na=this.na;for(var b=this.W.j,c=b.length,d=0;d<c;d++){var e=b[d];e!==a&&e.isPanelMain&&e instanceof Mf&&(e.na=this.na)}}}; S.prototype.makeGeometry=function(){var a=this.na,b=this.pointsCount;if(2>b)return a.type=wd,this.Ym=!0,a;var c=!1,d=this.diagram;null!==d&&lp(this)&&d.Wg.contains(this)&&(0!==this.Yl.width||0!==this.Yl.height)&&(c=!0);var e=this.i(0).copy(),f=e.copy();d=this.Bb.j;var g=this.computeCurve();if(g===sg&&3<=b&&!L.aa(this.smoothness,0))if(3===b){var h=this.i(1);d=Math.min(e.x,h.x);var k=Math.min(e.y,h.y);h=this.i(2);d=Math.min(d,h.x);k=Math.min(k,h.y)}else{if(this.isOrthogonal)for(k=0;k<b;k++)h=d[k],f.x= Math.min(h.x,f.x),f.y=Math.min(h.y,f.y);else for(d=3;d<b;d+=3)d+3>=b&&(d=b-1),k=this.i(d),f.x=Math.min(k.x,f.x),f.y=Math.min(k.y,f.y);d=f.x;k=f.y}else{for(k=0;k<b;k++)h=d[k],f.x=Math.min(h.x,f.x),f.y=Math.min(h.y,f.y);d=f.x;k=f.y}d-=this.uv.x;k-=this.uv.y;e.x-=d;e.y-=k;if(2!==b||lp(this)){a.type=ud;h=Hd(a);0!==this.computeShortLength(!0)&&(e=Hp(this,e,!0,f));Id(h,e.x,e.y,!1);if(g===sg&&3<=b&&!L.aa(this.smoothness,0))if(3===b)c=this.i(1),b=c.x-d,c=c.y-k,e=this.i(2).copy(),e.x-=d,e.y-=k,0!==this.computeShortLength(!1)&& (e=Hp(this,e,!1,f)),Ud(h,b,c,b,c,e.x,e.y);else if(this.isOrthogonal){f=new I(d,k);e=this.i(1).copy();g=new I(d,k);b=new I(d,k);c=this.i(0);for(var l,m=this.smoothness/3,n=1;n<this.pointsCount-1;n++){l=this.i(n);var p=c,r=l,q=this.i(Ip(this,l,n,!1));if(!L.aa(p.x,r.x)||!L.aa(r.x,q.x))if(!L.aa(p.y,r.y)||!L.aa(r.y,q.y)){var u=m;isNaN(u)&&(u=this.smoothness/3);var v=p.x;p=p.y;var w=r.x;r=r.y;var y=q.x;q=q.y;var z=u*Jp(v,p,w,r);u*=Jp(w,r,y,q);L.aa(p,r)&&L.aa(w,y)&&(w>v?q>r?(g.x=w-z,g.y=r-z,b.x=w+u,b.y= r+u):(g.x=w-z,g.y=r+z,b.x=w+u,b.y=r-u):q>r?(g.x=w+z,g.y=r-z,b.x=w-u,b.y=r+u):(g.x=w+z,g.y=r+z,b.x=w-u,b.y=r-u));L.aa(v,w)&&L.aa(r,q)&&(r>p?(y>w?(g.x=w-z,g.y=r-z,b.x=w+u):(g.x=w+z,g.y=r-z,b.x=w-u),b.y=r+u):(y>w?(g.x=w-z,g.y=r+z,b.x=w+u):(g.x=w+z,g.y=r+z,b.x=w-u),b.y=r-u));if(L.aa(v,w)&&L.aa(w,y)||L.aa(p,r)&&L.aa(r,q))v=.5*(v+y),p=.5*(p+q),g.x=v,g.y=p,b.x=v,b.y=p;1===n?(e.x=.5*(c.x+l.x),e.y=.5*(c.y+l.y)):2===n&&L.aa(c.x,this.i(0).x)&&L.aa(c.y,this.i(0).y)&&(e.x=.5*(c.x+l.x),e.y=.5*(c.y+l.y));Ud(h,e.x- d,e.y-k,g.x-d,g.y-k,l.x-d,l.y-k);f.set(g);e.set(b);c=l}}f=c.x;c=c.y;e=this.i(this.pointsCount-1);0!==this.computeShortLength(!1)&&(e=Hp(this,e.copy(),!1,Fb));f=.5*(f+e.x);c=.5*(c+e.y);Ud(h,b.x-d,b.y-k,f-d,c-k,e.x-d,e.y-k)}else for(c=3;c<b;c+=3)f=this.i(c-2),c+3>=b&&(c=b-1),e=this.i(c-1),g=this.i(c),c===b-1&&0!==this.computeShortLength(!1)&&(g=Hp(this,g.copy(),!1,Fb)),Ud(h,f.x-d,f.y-k,e.x-d,e.y-k,g.x-d,g.y-k);else{f=I.alloc();f.assign(this.i(0));e=I.alloc();e.assign(f);g=this.computeCorner();n=1;for(l= 0;n<b;){n=Ip(this,f,n,1<n);m=this.i(n);if(n>=b-1){if(!f.w(m))0!==this.computeShortLength(!1)&&(m=Hp(this,m.copy(),!1,Fb)),Kp(this,h,-d,-k,f,m,c);else if(0===l)for(n=1;n<b;)e.assign(f),m=this.i(n++),Kp(this,h,-d,-k,f,m,c),f.assign(m);break}l=Ip(this,m,n+1,n<b-3);n=-d;v=-k;p=m;u=this.i(l);w=c;if(L.A(f.y,p.y)&&L.A(p.x,u.x))if(r=Math.min(g,Math.abs(p.x-e.x)/2),r=y=Math.min(r,Math.abs(u.y-p.y)/2),L.A(r,0))Kp(this,h,n,v,f,p,w),f.assign(p);else{q=p.x;z=p.y;var A=q,C=z;p.x>f.x?q=p.x-r:q=p.x+r;u.y>p.y?C=p.y+ y:C=p.y-y;Kp(this,h,n,v,f,new I(q,z),w);Vd(h,p.x+n,p.y+v,A+n,C+v);f.h(A,C)}else L.A(f.x,p.x)&&L.A(p.y,u.y)?(r=Math.min(g,Math.abs(p.y-e.y)/2),r=y=Math.min(r,Math.abs(u.x-p.x)/2),L.A(y,0)?(Kp(this,h,n,v,f,p,w),f.assign(p)):(q=p.x,z=p.y,A=q,C=z,p.y>f.y?z=p.y-r:z=p.y+r,u.x>p.x?A=p.x+y:A=p.x-y,Kp(this,h,n,v,f,new I(q,z),w),Vd(h,p.x+n,p.y+v,A+n,C+v),f.h(A,C))):(Kp(this,h,n,v,f,p,w),f.assign(p));e.assign(m);n=l}I.free(f)}Yd=h}else h=this.i(1).copy(),h.x-=d,h.y-=k,0!==this.computeShortLength(!0)&&(e=Hp(this, e,!0,f)),0!==this.computeShortLength(!1)&&(h=Hp(this,h,!1,f)),a.type=wd,a.startX=e.x,a.startY=e.y,a.endX=h.x,a.endY=h.y;this.Ym=!0;return a};function Jp(a,b,c,d){a=c-a;if(isNaN(a)||Infinity===a||-Infinity===a)return NaN;0>a&&(a=-a);b=d-b;if(isNaN(b)||Infinity===b||-Infinity===b)return NaN;0>b&&(b=-b);return L.aa(a,0)?b:L.aa(b,0)?a:Math.sqrt(a*a+b*b)} function Hp(a,b,c,d){var e=a.pointsCount;if(2>e)return b;if(c){var f=a.i(1);c=f.x-d.x;f=f.y-d.y;d=Jp(b.x,b.y,c,f);if(0===d)return b;e=2===e?.5*d:d;a=a.computeShortLength(!0);a>e&&(a=e);e=a*(f-b.y)/d;b.x+=a*(c-b.x)/d;b.y+=e}else{f=a.i(e-2);c=f.x-d.x;f=f.y-d.y;d=Jp(b.x,b.y,c,f);if(0===d)return b;e=2===e?.5*d:d;a=a.computeShortLength(!1);a>e&&(a=e);e=a*(b.y-f)/d;b.x-=a*(b.x-c)/d;b.y-=e}return b} function Ip(a,b,c,d){for(var e=a.pointsCount,f=b;L.aa(b.x,f.x)&&L.aa(b.y,f.y);){if(c>=e)return e-1;f=a.i(c++)}if(!L.aa(b.x,f.x)&&!L.aa(b.y,f.y))return c-1;for(var g=f;L.aa(b.x,f.x)&&L.aa(f.x,g.x)&&(!d||(b.y>=f.y?f.y>=g.y:f.y<=g.y))||L.aa(b.y,f.y)&&L.aa(f.y,g.y)&&(!d||(b.x>=f.x?f.x>=g.x:f.x<=g.x));){if(c>=e)return e-1;g=a.i(c++)}return c-2} function Kp(a,b,c,d,e,f,g){if(!g&&lp(a)){g=[];var h=0;a.isVisible()&&(h=Lp(a,e,f,g));if(0<h)if(L.A(e.y,f.y))if(e.x<f.x)for(var k=0;k<h;){var l=Math.max(e.x,Math.min(g[k++]-5,f.x-10));b.lineTo(l+c,f.y+d);var m=l+c;for(var n=Math.min(l+10,f.x);k<h;)if(l=g[k],l<n+10)k++,n=Math.min(l+5,f.x);else break;l=f.y-10+d;n+=c;var p=f.y+d;a.curve===bg?Id(b,n,p,!1):Ud(b,m,l,n,l,n,p)}else for(--h;0<=h;){k=Math.min(e.x,Math.max(g[h--]+5,f.x+10));b.lineTo(k+c,f.y+d);m=k+c;for(l=Math.max(k-10,f.x);0<=h;)if(k=g[h],k> l-10)h--,l=Math.max(k-5,f.x);else break;k=f.y-10+d;l+=c;n=f.y+d;a.curve===bg?Id(b,l,n,!1):Ud(b,m,k,l,k,l,n)}else if(L.A(e.x,f.x))if(e.y<f.y)for(k=0;k<h;){l=Math.max(e.y,Math.min(g[k++]-5,f.y-10));b.lineTo(f.x+c,l+d);m=l+d;for(l=Math.min(l+10,f.y);k<h;)if(n=g[k],n<l+10)k++,l=Math.min(n+5,f.y);else break;n=f.x-10+c;p=f.x+c;l+=d;a.curve===bg?Id(b,p,l,!1):Ud(b,n,m,n,l,p,l)}else for(--h;0<=h;){k=Math.min(e.y,Math.max(g[h--]+5,f.y+10));b.lineTo(f.x+c,k+d);m=k+d;for(k=Math.max(k-10,f.y);0<=h;)if(l=g[h], l>k-10)h--,k=Math.max(l-5,f.y);else break;l=f.x-10+c;n=f.x+c;k+=d;a.curve===bg?Id(b,n,k,!1):Ud(b,l,m,l,k,n,k)}}b.lineTo(f.x+c,f.y+d)} function Lp(a,b,c,d){var e=a.diagram;if(null===e||b.w(c))return 0;for(e=e.layers;e.next();){var f=e.value;if(null!==f&&f.visible){f=f.Da.j;for(var g=f.length,h=0;h<g;h++){var k=f[h];if(k instanceof S){if(k===a)return 0<d.length&&d.sort(function(a,b){return a-b}),d.length;if(k.isVisible()&&lp(k)){var l=k.routeBounds;l.s()&&a.routeBounds.Oc(l)&&!a.usesSamePort(k)&&(l=k.path,null!==l&&l.If()&&Mp(b,c,d,k))}}}}}0<d.length&&d.sort(function(a,b){return a-b});return d.length} function Mp(a,b,c,d){for(var e=L.A(a.y,b.y),f=d.pointsCount,g=d.i(0),h=I.alloc(),k=1;k<f;k++){var l=d.i(k);if(k<f-1){var m=d.i(k+1);if(g.y===l.y&&l.y===m.y){if(l.x>g.x&&m.x>=l.x||l.x<g.x&&m.x<=l.x)continue}else if(g.x===l.x&&l.x===m.x&&(l.y>g.y&&m.y>=l.y||l.y<g.y&&m.y<=l.y))continue}a:{m=a.x;var n=a.y,p=b.x,r=b.y,q=g.x;g=g.y;var u=l.x,v=l.y;if(!L.A(m,p)){if(L.A(n,r)&&L.A(q,u)&&Math.min(m,p)<q&&Math.max(m,p)>q&&Math.min(g,v)<n&&Math.max(g,v)>n&&!L.A(g,v)){h.x=q;h.y=n;m=!0;break a}}else if(!L.A(n,r)&& L.A(g,v)&&Math.min(n,r)<g&&Math.max(n,r)>g&&Math.min(q,u)<m&&Math.max(q,u)>m&&!L.A(q,u)){h.x=m;h.y=g;m=!0;break a}h.x=0;h.y=0;m=!1}m&&(e?c.push(h.x):c.push(h.y));g=l}I.free(h)}function lp(a){a=a.curve;return a===ag||a===bg}function pp(a,b){if(b||lp(a))b=a.diagram,null===b||b.animationManager.isTicking||b.Wg.contains(a)||0===a.Yl.width&&0===a.Yl.height||b.Wg.add(a,a.Yl.copy())} S.prototype.Mq=function(a){var b=this.layer;if(null!==b&&b.visible&&!b.isTemporary){var c=b.diagram;if(null!==c&&!c.animationManager.isTicking){var d=!1;for(c=c.layers;c.next();){var e=c.value;if(e.visible)if(e===b){d=!0;var f=!1;e=e.Da.j;for(var g=e.length,h=0;h<g;h++){var k=e[h];k instanceof S&&(k===this?f=!0:f&&Np(this,k,a))}}else if(d)for(f=e.Da.j,e=f.length,g=0;g<e;g++)h=f[g],h instanceof S&&Np(this,h,a)}}}}; function Np(a,b,c){if(null!==b&&b.Ym&&b.kd&&lp(b)){var d=b.routeBounds;d.s()&&(a.routeBounds.Oc(d)||c.Oc(d))&&(a.usesSamePort(b)||b.dc())}}S.prototype.usesSamePort=function(a){var b=this.pointsCount,c=a.pointsCount;if(0<b&&0<c){var d=this.i(0),e=a.i(0);if(d.Na(e))return!0;b=this.i(b-1);a=a.i(c-1);if(b.Na(a)||d.Na(a)||b.Na(e))return!0}else if(this.fromNode===a.fromNode||this.toNode===a.toNode||this.fromNode===a.toNode||this.toNode===a.fromNode)return!0;return!1}; S.prototype.isVisible=function(){if(!V.prototype.isVisible.call(this))return!1;var a=this.containingGroup,b=!0,c=this.diagram;null!==c&&(b=c.isTreePathToChildren);c=this.fromNode;if(null!==c){if(this.isTreeLink&&b&&!c.isTreeExpanded)return!1;if(c===a)return!0;for(var d=c;null!==d;){if(d.labeledLink===this)return!0;d=d.containingGroup}c=c.findVisibleNode();if(null===c||c===a)return!1}c=this.toNode;if(null!==c){if(this.isTreeLink&&!b&&!c.isTreeExpanded)return!1;if(c===a)return!0;for(b=c;null!==b;){if(b.labeledLink=== this)return!0;b=b.containingGroup}b=c.findVisibleNode();if(null===b||b===a)return!1}return!0};S.prototype.Pb=function(a){V.prototype.Pb.call(this,a);null!==this.Of&&this.Of.Cm();if(null!==this.od)for(var b=this.od.iterator;b.next();)b.value.Pb(a)};S.prototype.computeAdjusting=function(){return this.isAvoiding&&null!==this.diagram&&this.diagram.animationManager.defaultAnimation.isAnimating?hp:this.Yk}; function mp(a){var b=a.Xe;if(null!==b){var c=a.tf;if(null!==c&&isNaN(a.curviness)){for(var d=a.Ye,e=a.uf,f=a=null,g=b.Za.j,h=g.length,k=0;k<h;k++){var l=g[k];if(l.Xe===b&&l.Ye===d&&l.tf===c&&l.uf===e||l.Xe===c&&l.Ye===e&&l.tf===b&&l.uf===d)null===f?f=l:(null===a&&(a=[],a.push(f)),a.push(l))}if(null!==a){f=So(b,c,d,e);null===f&&(f=new Op(b,d,c,e),Ro(b,f),Ro(c,f));f.links=a;for(b=0;b<a.length;b++)a[b].Of=f;f.Cm()}}}} function np(a){var b=a.Of;null!==b&&isNaN(a.curviness)&&(a.Of=null,a=b.links.indexOf(a),0<=a&&(Da(b.links,a),b.Cm()))}S.prototype.Oh=function(){return!0}; na.Object.defineProperties(S.prototype,{fromNode:{get:function(){return this.Xe},set:function(a){var b=this.Xe;if(b!==a){var c=this.fromPort;null!==b&&(this.tf!==b&&Wo(b,this,c),np(this),this.C(2));this.Xe=a;null!==a&&this.Pb(a.isVisible());this.Xf=null;this.Ua();var d=this.diagram;null!==d&&d.Z&&d.partManager.setFromNodeForLink(this,a,b);var e=this.fromPort,f=this.fromPortChanged;if(null!==f){var g=!0;null!==d&&(g=d.Z,d.Z=!0);f(this,c,e);null!==d&&(d.Z=g)}null!==a&& (this.tf!==a&&Vo(a,this,e),mp(this),this.C(1));this.g("fromNode",b,a);Oo(this)}}},fromPortId:{get:function(){return this.Ye},set:function(a){var b=this.Ye;if(b!==a){var c=this.fromPort;null!==c&&To(c);np(this);this.Ye=a;var d=this.fromPort;null!==d&&To(d);var e=this.diagram;if(null!==e){var f=this.data,g=e.model;null!==f&&g.qj()&&g.Dw(f,a)}c!==d&&(this.Xf=null,this.Ua(),f=this.fromPortChanged,null!==f&&(g=!0,null!==e&&(g=e.Z,e.Z=!0),f(this,c,d),null!==e&&(e.Z=g)));mp(this); this.g("fromPortId",b,a)}}},fromPort:{get:function(){var a=this.Xe;return null===a?null:a.Kt(this.Ye)}},fromPortChanged:{get:function(){return this.co},set:function(a){var b=this.co;b!==a&&(this.co=a,this.g("fromPortChanged",b,a))}},toNode:{get:function(){return this.tf},set:function(a){var b=this.tf;if(b!==a){var c=this.toPort;null!==b&&(this.Xe!==b&&Wo(b,this,c),np(this),this.C(2));this.tf=a;null!==a&&this.Pb(a.isVisible()); this.Xf=null;this.Ua();var d=this.diagram;null!==d&&d.Z&&d.partManager.setToNodeForLink(this,a,b);var e=this.toPort,f=this.toPortChanged;if(null!==f){var g=!0;null!==d&&(g=d.Z,d.Z=!0);f(this,c,e);null!==d&&(d.Z=g)}null!==a&&(this.Xe!==a&&Vo(a,this,e),mp(this),this.C(1));this.g("toNode",b,a);Oo(this)}}},toPortId:{get:function(){return this.uf},set:function(a){var b=this.uf;if(b!==a){var c=this.toPort;null!==c&&To(c);np(this);this.uf=a;var d=this.toPort;null!==d&&To(d); var e=this.diagram;if(null!==e){var f=this.data,g=e.model;null!==f&&g.qj()&&g.Iw(f,a)}c!==d&&(this.Xf=null,this.Ua(),f=this.toPortChanged,null!==f&&(g=!0,null!==e&&(g=e.Z,e.Z=!0),f(this,c,d),null!==e&&(e.Z=g)));mp(this);this.g("toPortId",b,a)}}},toPort:{get:function(){var a=this.tf;return null===a?null:a.Kt(this.uf)}},toPortChanged:{get:function(){return this.jq},set:function(a){var b=this.jq;b!==a&&(this.jq=a,this.g("toPortChanged",b,a))}}, fromSpot:{get:function(){return null!==this.O?this.O.bh:Zc},set:function(a){this.Mc();var b=this.O.bh;b.w(a)||(a=a.G(),this.O.bh=a,this.g("fromSpot",b,a),(b.Qc()||a.Qc())&&null!==this.fromNode&&To(this.fromPort),this.Ua())}},fromEndSegmentLength:{get:function(){return null!==this.O?this.O.$g:NaN},set:function(a){this.Mc();var b=this.O.$g;b!==a&&(0>a&&wa(a,">= 0",S,"fromEndSegmentLength"),this.O.$g=a,this.g("fromEndSegmentLength",b,a),this.Ua())}}, fromShortLength:{get:function(){return null!==this.O?this.O.ah:NaN},set:function(a){this.Mc();var b=this.O.ah;b!==a&&(this.O.ah=a,this.dc(),this.g("fromShortLength",b,a))}},toSpot:{get:function(){return null!==this.O?this.O.Bh:Zc},set:function(a){this.Mc();var b=this.O.Bh;b.w(a)||(a=a.G(),this.O.Bh=a,this.g("toSpot",b,a),(b.Qc()||a.Qc())&&null!==this.toNode&&To(this.toPort),this.Ua())}},toEndSegmentLength:{get:function(){return null!== this.O?this.O.zh:NaN},set:function(a){this.Mc();var b=this.O.zh;b!==a&&(0>a&&wa(a,">= 0",S,"toEndSegmentLength"),this.O.zh=a,this.g("toEndSegmentLength",b,a),this.Ua())}},toShortLength:{get:function(){return null!==this.O?this.O.Ah:NaN},set:function(a){this.Mc();var b=this.O.Ah;b!==a&&(this.O.Ah=a,this.dc(),this.g("toShortLength",b,a))}},isLabeledLink:{get:function(){return null===this.od?!1:0<this.od.count}},labelNodes:{ get:function(){return null===this.od?ib:this.od.iterator}},relinkableFrom:{get:function(){return 0!==(this.Fa&1)},set:function(a){var b=0!==(this.Fa&1);b!==a&&(this.Fa^=1,this.g("relinkableFrom",b,a),this.Mb())}},relinkableTo:{get:function(){return 0!==(this.Fa&2)},set:function(a){var b=0!==(this.Fa&2);b!==a&&(this.Fa^=2,this.g("relinkableTo",b,a),this.Mb())}},resegmentable:{get:function(){return 0!== (this.Fa&4)},set:function(a){var b=0!==(this.Fa&4);b!==a&&(this.Fa^=4,this.g("resegmentable",b,a),this.Mb())}},isTreeLink:{get:function(){return 0!==(this.Fa&8)},set:function(a){var b=0!==(this.Fa&8);b!==a&&(this.Fa^=8,this.g("isTreeLink",b,a),null!==this.fromNode&&Fk(this.fromNode),null!==this.toNode&&Fk(this.toNode))}},path:{get:function(){var a=this.rb();return a instanceof Mf?a:null}},routeBounds:{get:function(){this.xj(); var a=this.Yl,b=Infinity,c=Infinity,d=this.pointsCount;if(0===d)a.h(NaN,NaN,0,0);else{if(1===d)d=this.i(0),b=Math.min(d.x,b),c=Math.min(d.y,c),a.h(d.x,d.y,0,0);else if(2===d){d=this.i(0);var e=this.i(1);b=Math.min(d.x,e.x);c=Math.min(d.y,e.y);a.h(d.x,d.y,0,0);a.Pe(e)}else if(this.computeCurve()===sg&&3<=d&&!this.isOrthogonal)if(e=this.i(0),b=e.x,c=e.y,a.h(b,c,0,0),3===d){d=this.i(1);b=Math.min(d.x,b);c=Math.min(d.y,c);var f=this.i(2);b=Math.min(f.x,b);c=Math.min(f.y,c);L.um(e.x,e.y,d.x,d.y,d.x,d.y, f.x,f.y,.5,a)}else for(f=3;f<d;f+=3){var g=this.i(f-2);f+3>=d&&(f=d-1);var h=this.i(f-1),k=this.i(f);L.um(e.x,e.y,g.x,g.y,h.x,h.y,k.x,k.y,.5,a);b=Math.min(k.x,b);c=Math.min(k.y,c);e=k}else for(e=this.i(0),f=this.i(1),b=Math.min(e.x,f.x),c=Math.min(e.y,f.y),a.h(e.x,e.y,0,0),a.Pe(f),e=2;e<d;e++)f=this.i(e),b=Math.min(f.x,b),c=Math.min(f.y,c),a.Pe(f);this.uv.h(b-a.x,c-a.y)}return a}},midPoint:{get:function(){this.xj();return this.computeMidPoint(new I)}},midAngle:{ get:function(){this.xj();return this.computeMidAngle()}},flattenedLengths:{get:function(){if(null===this.bs){this.kd||op(this);for(var a=this.bs=[],b=this.pointsCount,c=0;c<b-1;c++){var d=this.i(c);var e=this.i(c+1);L.aa(d.x,e.x)?(d=e.y-d.y,0>d&&(d=-d)):L.aa(d.y,e.y)?(d=e.x-d.x,0>d&&(d=-d)):d=Math.sqrt(d.Ie(e));a.push(d)}}return this.bs}},flattenedTotalLength:{get:function(){var a=this.Pu;if(isNaN(a)){for(var b=this.flattenedLengths, c=b.length,d=a=0;d<c;d++)a+=b[d];this.Pu=a}return a}},points:{get:function(){return this.Bb},set:function(a){var b=this.Bb;if(b!==a){var c=null;if(Array.isArray(a)){var d=0===a.length%2;if(d)for(var e=0;e<a.length;e++)if("number"!==typeof a[e]||isNaN(a[e])){d=!1;break}if(d)for(c=new E,d=0;d<a.length/2;d++)e=(new I(a[2*d],a[2*d+1])).freeze(),c.add(e);else{d=!0;for(e=0;e<a.length;e++){var f=a[e];if(!za(f)||"number"!==typeof f.x||isNaN(f.x)||"number"!==typeof f.y||isNaN(f.y)){d= !1;break}}if(d)for(c=new E,d=0;d<a.length;d++)e=a[d],c.add((new I(e.x,e.y)).freeze())}}else if(a instanceof E)for(c=a.copy(),a=c.iterator;a.next();)a.value.freeze();else B("Link.points value is not an instance of List or Array: "+a);c.freeze();this.Bb=c;this.dc();op(this);a=this.diagram;null!==a&&(a.pj||a.undoManager.isUndoingRedoing||a.Yt.add(this),a.animationManager.sc&&(this.sg=c));this.g("points",b,c)}}},pointsCount:{get:function(){return this.Bb.count}},kd:{ get:function(){return 0!==(this.Fa&16)},set:function(a){0!==(this.Fa&16)!==a&&(this.Fa^=16)}},suspendsRouting:{get:function(){return 0!==(this.Fa&32)},set:function(a){0!==(this.Fa&32)!==a&&(this.Fa^=32)}},Ct:{get:function(){return 0!==(this.Fa&64)},set:function(a){0!==(this.Fa&64)!==a&&(this.Fa^=64)}},defaultFromPoint:{get:function(){return this.v},set:function(a){this.v=a.copy()}},defaultToPoint:{ get:function(){return this.I},set:function(a){this.I=a.copy()}},isOrthogonal:{get:function(){return 2===(this.ck.value&2)}},isAvoiding:{get:function(){return 4===(this.ck.value&4)}},Ym:{get:function(){return 0!==(this.Fa&128)},set:function(a){0!==(this.Fa&128)!==a&&(this.Fa^=128)}},geometry:{get:function(){this.Ym||(this.xj(),this.na=this.makeGeometry());return this.na}}, firstPickIndex:{get:function(){return 2>=this.pointsCount?0:this.isOrthogonal||!sp(this.computeSpot(!0))?1:0}},lastPickIndex:{get:function(){var a=this.pointsCount;return 0===a?0:2>=a?a-1:this.isOrthogonal||!sp(this.computeSpot(!1))?a-2:a-1}},adjusting:{get:function(){return this.Yk},set:function(a){var b=this.Yk;b!==a&&(this.Yk=a,this.g("adjusting",b,a))}},corner:{get:function(){return this.Fn}, set:function(a){var b=this.Fn;b!==a&&(this.Fn=a,this.dc(),this.g("corner",b,a))}},curve:{get:function(){return this.Hn},set:function(a){var b=this.Hn;b!==a&&(this.Hn=a,this.Ua(),this.dc(),pp(this,b===bg||b===ag||a===bg||a===ag),this.g("curve",b,a))}},curviness:{get:function(){return this.In},set:function(a){var b=this.In;b!==a&&(this.In=a,this.Ua(),this.dc(),this.g("curviness",b,a))}},routing:{get:function(){return this.ck}, set:function(a){var b=this.ck;b!==a&&(this.ck=a,this.Xf=null,this.Ua(),pp(this,2===(b.value&2)||2===(a.value&2)),this.g("routing",b,a))}},smoothness:{get:function(){return this.Wp},set:function(a){var b=this.Wp;b!==a&&(this.Wp=a,this.dc(),this.g("smoothness",b,a))}},key:{get:function(){var a=this.diagram;if(null!==a&&a.model.qj())return a.model.Wb(this.data)}}});S.prototype.invalidateOtherJumpOvers=S.prototype.Mq; S.prototype.findClosestSegment=S.prototype.Sz;S.prototype.updateRoute=S.prototype.xj;S.prototype.invalidateRoute=S.prototype.Ua;S.prototype.rollbackRoute=S.prototype.zw;S.prototype.commitRoute=S.prototype.zf;S.prototype.startRoute=S.prototype.Sh;S.prototype.clearPoints=S.prototype.pk;S.prototype.removePoint=S.prototype.uw;S.prototype.addPointAt=S.prototype.xf;S.prototype.addPoint=S.prototype.ce;S.prototype.insertPointAt=S.prototype.m;S.prototype.insertPoint=S.prototype.wA;S.prototype.setPointAt=S.prototype.L; S.prototype.setPoint=S.prototype.Sc;S.prototype.getPoint=S.prototype.i;S.prototype.getOtherPort=S.prototype.nA;S.prototype.getOtherNode=S.prototype.Hq; var qp=null,rp=null,gp=new D(S,"Normal",1),Pp=new D(S,"Orthogonal",2),Qp=new D(S,"AvoidsNodes",6),yp=new D(S,"AvoidsNodesStraight",7),cg=new D(S,"None",0),sg=new D(S,"Bezier",9),bg=new D(S,"JumpGap",10),ag=new D(S,"JumpOver",11),hp=new D(S,"End",17),ip=new D(S,"Scale",18),jp=new D(S,"Stretch",19),Wm=new D(S,"OrientAlong",21),Pm=new D(S,"OrientPlus90",22),Rm=new D(S,"OrientMinus90",23),kp=new D(S,"OrientOpposite",24),Xm=new D(S,"OrientUpright",25),Qm=new D(S,"OrientPlus90Upright",26),Sm=new D(S,"OrientMinus90Upright", 27),Tm=new D(S,"OrientUpright45",28),Ap=16,zp=14,Bp=8;S.className="Link";S.Normal=gp;S.Orthogonal=Pp;S.AvoidsNodes=Qp;S.AvoidsNodesStraight=yp;S.None=cg;S.Bezier=sg;S.JumpGap=bg;S.JumpOver=ag;S.End=hp;S.Scale=ip;S.Stretch=jp;S.OrientAlong=Wm;S.OrientPlus90=Pm;S.OrientMinus90=Rm;S.OrientOpposite=kp;S.OrientUpright=Xm;S.OrientPlus90Upright=Qm;S.OrientMinus90Upright=Sm;S.OrientUpright45=Tm;S.EndSegmentStep=8;S.CurvinessStart=Ap;S.SpacingMin=zp;S.OrthoShortCut=Bp;S.AvoidanceCell=8;S.AvoidanceLimit=999; function Op(a,b,c,d){Za(this);this.te=this.js=!1;this.au=a;this.Ny=b;this.kw=c;this.Oy=d;this.links=[]}Op.prototype.Cm=function(){if(!this.js){var a=this.links;0<a.length&&(a=a[0].diagram,null!==a&&(a.Ru.add(this),this.te=a.undoManager.isUndoingRedoing))}this.js=!0}; Op.prototype.Ww=function(){if(this.js){this.js=!1;var a=this.links;if(0<a.length){var b=a[0],c=b.diagram;c=null===c||c.pj&&!this.te;this.te=!1;b.arrangeBundledLinks(a,c);1===a.length&&(b.Of=null,a.length=0)}0===a.length&&(a=this.au,null!==this&&null!==a.Te&&a.Te.remove(this),a=this.kw,null!==this&&null!==a.Te&&a.Te.remove(this))}};Op.className="LinkBundle"; function uk(){Za(this);this.Wy=this.group=null;this.St=!0;this.abort=!1;this.Bd=this.Ad=1;this.No=this.Mo=-1;this.gc=this.fc=8;this.Rb=null;this.$i=this.Zi=0;this.Xy=11;this.Hy=124} uk.prototype.initialize=function(a){if(!(0>=a.width||0>=a.height)){var b=a.y,c=a.x+a.width,d=a.y+a.height;this.Ad=Math.floor((a.x-this.fc)/this.fc)*this.fc;this.Bd=Math.floor((b-this.gc)/this.gc)*this.gc;this.Mo=Math.ceil((c+2*this.fc)/this.fc)*this.fc;this.No=Math.ceil((d+2*this.gc)/this.gc)*this.gc;a=1+(Math.ceil((this.Mo-this.Ad)/this.fc)|0);b=1+(Math.ceil((this.No-this.Bd)/this.gc)|0);if(null===this.Rb||this.Zi<a-1||this.$i<b-1){c=[];for(d=0;d<=a;d++)c[d]=new Uint32Array(b);this.Rb=c;this.Zi= a-1;this.$i=b-1}a=Rp;if(null!==this.Rb)for(b=0;b<=this.Zi;b++)if(c=this.Rb[b],c.fill)c.fill(a);else for(d=0;d<=this.$i;d++)c[d]=a}};function xk(a,b,c){return a.Ad<=b&&b<=a.Mo&&a.Bd<=c&&c<=a.No}function Dp(a,b,c){if(!xk(a,b,c))return Rp;b-=a.Ad;b/=a.fc;c-=a.Bd;c/=a.gc;return a.Rb[b|0][c|0]}function wk(a){if(null!==a.Rb)for(var b=0;b<=a.Zi;b++)for(var c=a.Rb[b],d=0;d<=a.$i;d++)c[d]>=Gp&&(c[d]=Rp)} uk.prototype.Dk=function(a,b,c,d){if(a>this.Mo||a+c<this.Ad||b>this.No||b+d<this.Bd)return!0;a=(a-this.Ad)/this.fc|0;b=(b-this.Bd)/this.gc|0;c=Math.max(0,c)/this.fc+1|0;var e=Math.max(0,d)/this.gc+1|0;0>a&&(c+=a,a=0);0>b&&(e+=b,b=0);if(0>c||0>e)return!0;d=Math.min(a+c-1,this.Zi)|0;for(c=Math.min(b+e-1,this.$i)|0;a<=d;a++){e=this.Rb[a];for(var f=b;f<=c;f++)if(e[f]===yk)return!1}return!0}; function Sp(a,b,c,d,e,f,g,h,k){if(!(b<f||b>g||c<h||c>k)){var l=b|0;var m=c|0;var n=a.Rb[l][m];if(n>=Gp&&n<Ep)for(e?m+=d:l+=d,n+=1;f<=l&&l<=g&&h<=m&&m<=k&&!(n>=a.Rb[l][m]);)a.Rb[l][m]=n,n+=1,e?m+=d:l+=d;l=e?m:l;if(e)if(0<d)for(c+=d;c<l;c+=d)Sp(a,b,c,1,!e,f,g,h,k),Sp(a,b,c,-1,!e,f,g,h,k);else for(c+=d;c>l;c+=d)Sp(a,b,c,1,!e,f,g,h,k),Sp(a,b,c,-1,!e,f,g,h,k);else if(0<d)for(b+=d;b<l;b+=d)Sp(a,b,c,1,!e,f,g,h,k),Sp(a,b,c,-1,!e,f,g,h,k);else for(b+=d;b>l;b+=d)Sp(a,b,c,1,!e,f,g,h,k),Sp(a,b,c,-1,!e,f,g,h, k)}}function Tp(a,b,c,d,e,f,g,h,k){b|=0;c|=0;var l=yk,m=Gp;for(a.Rb[b][c]=m;l===yk&&b>f&&b<g&&c>h&&c<k;)m+=1,a.Rb[b][c]=m,e?c+=d:b+=d,l=a.Rb[b][c]}function Up(a,b,c,d,e,f,g,h,k){b|=0;c|=0;var l=yk,m=Ep;for(a.Rb[b][c]=m;l===yk&&b>f&&b<g&&c>h&&c<k;)a.Rb[b][c]=m,e?c+=d:b+=d,l=a.Rb[b][c]} function Cp(a,b,c,d,e,f,g){if(null!==a.Rb){a.abort=!1;var h=b.x,k=b.y;if(xk(a,h,k)){h-=a.Ad;h/=a.fc;k-=a.Bd;k/=a.gc;var l=d.x,m=d.y;if(xk(a,l,m))if(l-=a.Ad,l/=a.fc,m-=a.Bd,m/=a.gc,1>=Math.abs(h-l)&&1>=Math.abs(k-m))a.abort=!0;else{var n=f.x;d=f.y;b=f.x+f.width;var p=f.y+f.height;n-=a.Ad;n/=a.fc;d-=a.Bd;d/=a.gc;b-=a.Ad;b/=a.fc;p-=a.Bd;p/=a.gc;f=Math.max(0,Math.min(a.Zi,n|0));b=Math.min(a.Zi,Math.max(0,b|0));n=Math.max(0,Math.min(a.$i,d|0));p=Math.min(a.$i,Math.max(0,p|0));d=a.Rb;h|=0;k|=0;l|=0;m|= 0;var r=0===c||90===c?1:-1;c=90===c||270===c;d[h][k]===yk?(Tp(a,h,k,r,c,f,b,n,p),Tp(a,h,k,1,!c,f,b,n,p),Tp(a,h,k,-1,!c,f,b,n,p)):Tp(a,h,k,r,c,h,k,h,k);d[l][m]===yk?(Up(a,l,m,0===e||90===e?1:-1,90===e||270===e,f,b,n,p),Up(a,l,m,1,!(90===e||270===e),f,b,n,p),Up(a,l,m,-1,!(90===e||270===e),f,b,n,p)):Up(a,l,m,r,c,l,m,l,m);c=Ea();if(g&&Vp(a,l,m,e,h,k,c)){if(c[0]!==l||c[1]!==m)c.unshift(m),c.unshift(l);if(c[c.length-2]!==h||c[c.length-1]!==k)c.push(h),c.push(k);a=Gp;e=c[c.length-2];g=c[c.length-1];d[e][g]= a++;for(f=c.length-4;0<=f;f-=2)for(e=c[f+2],g=c[f+3],b=c[f],l=c[f+1];b>e?e++:b<e?e--:l>g?g++:l<g&&g--,d[e][g]=a++,e!==b||g!==l;);}else Sp(a,h,k,1,!1,f,b,n,p),Sp(a,h,k,-1,!1,f,b,n,p),Sp(a,h,k,1,!0,f,b,n,p),Sp(a,h,k,-1,!0,f,b,n,p);Ia(c)}}}} function Vp(a,b,c,d,e,f,g){for(var h=a.Rb,k=b,l=c;;){if(k===e&&l===f)return!0;var m=k,n=l;if(0===d)if(m<e)m++;else break;else if(90===d)if(n<f)n++;else break;else if(180===d)if(m>e)m--;else break;else if(n>f)n--;else break;var p=h[m][n];if(0===p||p===Wp)break;k=m;l=n}for(;;){m=d;n=k;p=l;0===d?p<f?(m=90,p++):p>f&&(m=270,p--):90===d?n<e?(m=0,n++):n>e&&(m=180,n--):180===d?p<f?(m=90,p++):p>f&&(m=270,p--):n<e?(m=0,n++):n>e&&(m=180,n--);n=h[n][p];if(m!==d&&0!==n&&n!==Wp){g.push(k);g.push(l);if(Vp(a,k,l, m,e,f,g))return!0;g.pop();g.pop()}h[k][l]=Wp;if(0===d){if(k===b)return!1;k--}else if(90===d){if(l===c)return!1;l--}else if(180===d){if(k===b)return!1;k++}else{if(l===c)return!1;l++}}} na.Object.defineProperties(uk.prototype,{bounds:{get:function(){return new N(this.Ad,this.Bd,this.Mo-this.Ad,this.No-this.Bd)}},wq:{get:function(){return this.fc},set:function(a){0<a&&a!==this.fc&&(this.fc=a,this.initialize(this.bounds))}},vq:{get:function(){return this.gc},set:function(a){0<a&&a!==this.gc&&(this.gc=a,this.initialize(this.bounds))}}});var yk=0,Gp=1,Ep=999999,Rp=Ep+1,Wp=Ep+2;uk.className="PositionArray"; function wp(){Za(this);this.port=this.node=null;this.ee=[];this.Rq=!1}wp.prototype.toString=function(){for(var a=this.ee,b=this.node.toString()+" "+a.length.toString()+":",c=0;c<a.length;c++){var d=a[c];null!==d&&(b+="\n "+d.toString())}return b}; function Xp(a,b,c,d){b=b.offsetY;switch(b){case 8:return 90;case 2:return 180;case 1:return 270;case 4:return 0}switch(b){case 9:return 180<c?270:90;case 6:return 90<c&&270>=c?180:0}a=180*Math.atan2(a.height,a.width)/Math.PI;switch(b){case 3:return c>a&&c<=180+a?180:270;case 5:return c>180-a&&c<=360-a?270:0;case 12:return c>a&&c<=180+a?90:0;case 10:return c>180-a&&c<=360-a?180:90;case 7:return 90<c&&c<=180+a?180:c>180+a&&c<=360-a?270:0;case 13:return 180<c&&c<=360-a?270:c>a&&180>=c?90:0;case 14:return c> a&&c<=180-a?90:c>180-a&&270>=c?180:0;case 11:return c>180-a&&c<=180+a?180:c>180+a?270:90}d&&15!==b&&(c-=15,0>c&&(c+=360));return c>a&&c<180-a?90:c>=180-a&&c<=180+a?180:c>180+a&&c<360-a?270:0}wp.prototype.Cm=function(){this.ee.length=0}; function xp(a,b){var c=a.ee;if(0===c.length){a:if(!a.Rq){c=a.Rq;a.Rq=!0;var d=null,e=a.node,f=e instanceof U?e:null;if(null===f||f.isSubGraphExpanded)var g=e.isTreeExpanded?e.findLinksConnected(a.port.portId):e.py();else{if(!f.actualBounds.s()){a.Rq=c;break a}d=f;g=d.Qv()}f=a.ee.length=0;var h=a.port.da(vc,I.alloc()),k=a.port.da(Gc,I.alloc());e=N.allocAt(h.x,h.y,0,0);e.Pe(k);I.free(h);I.free(k);h=I.allocAt(e.x+e.width/2,e.y+e.height/2);k=a.port.lj();for(g=g.iterator;g.next();){var l=g.value;if(l.isVisible()&& l.fromPort!==l.toPort){var m=l.fromPort===a.port||null!==l.fromNode&&l.fromNode.Kd(d),n=l.computeSpot(m,a.port);if(n.Qc()&&(m=m?l.toPort:l.fromPort,null!==m)){var p=m.part;if(null!==p){var r=p.findVisibleNode();null!==r&&r!==p&&(p=r,m=p.port);m=l.computeOtherPoint(p,m);p=h.Sa(m);p-=k;0>p?p+=360:360<=p&&(p-=360);n=Xp(e,n,p,l.isOrthogonal);0===n?(n=4,180<p&&(p-=360)):90===n?(n=8,270<p&&(p-=360)):180===n?n=2:(n=1,90>p&&(p+=360));r=a.ee[f];void 0===r?(r=new Yp(l,p,n),a.ee[f]=r):(r.link=l,r.angle=p,r.Bc= n);r.nw.set(m);f++}}}}I.free(h);a.ee.sort(wp.prototype.l);k=a.ee.length;d=-1;for(f=h=0;f<k;f++)g=a.ee[f],void 0!==g&&(g.Bc!==d&&(d=g.Bc,h=0),g.Iq=h,h++);d=-1;h=0;for(f=k-1;0<=f;f--)k=a.ee[f],void 0!==k&&(k.Bc!==d&&(d=k.Bc,h=k.Iq+1),k.vm=h);f=a.ee;n=a.port;d=a.node.portSpreading;h=I.alloc();k=I.alloc();g=I.alloc();l=I.alloc();n.da(vc,h);n.da(zc,k);n.da(Gc,g);n.da(Dc,l);r=p=m=n=0;if(d===dp)for(var q=0;q<f.length;q++){var u=f[q];if(null!==u){var v=u.link.computeThickness();switch(u.Bc){case 8:p+=v;break; case 2:r+=v;break;case 1:n+=v;break;default:case 4:m+=v}}}var w=q=0,y=1,z=u=0;for(v=0;v<f.length;v++){var A=f[v];if(null!==A){if(q!==A.Bc){q=A.Bc;switch(q){case 8:var C=g;w=l;break;case 2:C=l;w=h;break;case 1:C=h;w=k;break;default:case 4:C=k,w=g}u=w.x-C.x;z=w.y-C.y;switch(q){case 8:p>Math.abs(u)?(y=Math.abs(u)/p,p=Math.abs(u)):y=1;break;case 2:r>Math.abs(z)?(y=Math.abs(z)/r,r=Math.abs(z)):y=1;break;case 1:n>Math.abs(u)?(y=Math.abs(u)/n,n=Math.abs(u)):y=1;break;default:case 4:m>Math.abs(z)?(y=Math.abs(z)/ m,m=Math.abs(z)):y=1}w=0}var F=A.Pq;if(d===dp){A=A.link.computeThickness();A*=y;F.set(C);switch(q){case 8:F.x=C.x+u/2+p/2-w-A/2;break;case 2:F.y=C.y+z/2+r/2-w-A/2;break;case 1:F.x=C.x+u/2-n/2+w+A/2;break;default:case 4:F.y=C.y+z/2-m/2+w+A/2}w+=A}else{var Q=.5;d===Qo&&(Q=(A.Iq+1)/(A.vm+1));F.x=C.x+u*Q;F.y=C.y+z*Q}}}I.free(h);I.free(k);I.free(g);I.free(l);C=a.ee;for(f=0;f<C.length;f++)d=C[f],null!==d&&(d.Ov=a.computeEndSegmentLength(d));a.Rq=c;N.free(e)}c=a.ee}for(a=0;a<c.length;a++)if(e=c[a],null!== e&&e.link===b)return e;return null}wp.prototype.l=function(a,b){return a===b?0:null===a?-1:null===b?1:a.Bc<b.Bc?-1:a.Bc>b.Bc?1:a.angle<b.angle?-1:a.angle>b.angle?1:0}; wp.prototype.computeEndSegmentLength=function(a){var b=a.link,c=b.computeEndSegmentLength(this.node,this.port,uc,b.fromPort===this.port),d=a.Iq;if(0>d)return c;var e=a.vm;if(1>=e||!b.isOrthogonal)return c;b=a.nw;var f=a.Pq;if(2===a.Bc||8===a.Bc)d=e-1-d;return((a=2===a.Bc||4===a.Bc)?b.y<f.y:b.x<f.x)?c+8*d:(a?b.y===f.y:b.x===f.x)?c:c+8*(e-1-d)};wp.className="Knot";function Yp(a,b,c){this.link=a;this.angle=b;this.Bc=c;this.nw=new I;this.vm=this.Iq=0;this.Pq=new I;this.Ov=0} Yp.prototype.toString=function(){return this.link.toString()+" "+this.angle.toString()+" "+this.Bc.toString()+":"+this.Iq.toString()+"/"+this.vm.toString()+" "+this.Pq.toString()+" "+this.Ov.toString()+" "+this.nw.toString()};Yp.className="LinkInfo";function gl(){this.Bh=this.bh=Zc;this.Ah=this.ah=this.zh=this.$g=NaN;this.hq=this.ao=null;this.iq=this.bo=Infinity} gl.prototype.copy=function(){var a=new gl;a.bh=this.bh.G();a.Bh=this.Bh.G();a.$g=this.$g;a.zh=this.zh;a.ah=this.ah;a.Ah=this.Ah;a.ao=this.ao;a.hq=this.hq;a.bo=this.bo;a.iq=this.iq;return a};gl.className="LinkSettings";function Bi(){Za(this);this.v=this.B=null;this.yi=this.so=!0;this.xo=!1;this.ln=(new I(0,0)).freeze();this.uo=!0;this.tn=this.to=null;this.wo=!1;this.l=null;this.I=0;this.Oo=this.nq=null;this.wt=!1;this.zg=this.ek=null;this.lt=!1} Bi.prototype.cloneProtected=function(a){a.so=this.so;a.yi=this.yi;a.xo=this.xo;a.ln.assign(this.ln);a.uo=this.uo;a.to=this.to;a.tn=this.tn;a.wo=!0;a.Oo=this.Oo;a.nq=this.nq};Bi.prototype.copy=function(){var a=new this.constructor;this.cloneProtected(a);return a};Bi.prototype.serializeLayoutProperties=function(a){a.arrangementOrigin={x:this.arrangementOrigin.x,y:this.arrangementOrigin.y};a.isRouting=this.isRouting}; Bi.prototype.deserializeLayoutProperties=function(a){null!==a&&(this.arrangementOrigin=new I(a.arrangementOrigin.x,a.arrangementOrigin.y),this.isRouting=a.isRouting)};Bi.prototype.jb=function(){};Bi.prototype.toString=function(){var a=Ja(this.constructor);a+="(";null!==this.group&&(a+=" in "+this.group);null!==this.diagram&&(a+=" for "+this.diagram);return a+")"}; Bi.prototype.C=function(){if(this.isValidLayout){var a=this.diagram;if(null!==a&&!a.undoManager.isUndoingRedoing){var b=a.animationManager;!b.isTicking&&(b.defaultAnimation.isAnimating&&b.Cc(),this.isOngoing&&a.pj||this.isInitial&&!a.pj)&&(this.isValidLayout=!1,a.Eb())}}};Bi.prototype.createNetwork=function(){return new Zp(this)};Bi.prototype.makeNetwork=function(a){var b=this.createNetwork();a instanceof R?(b.Bg(a.nodes,!0),b.Bg(a.links,!0)):a instanceof U?b.Bg(a.memberParts):b.Bg(a.iterator);return b}; Bi.prototype.updateParts=function(){this.isValidLayout=!0;if(!this.workerLayout()){var a=this.diagram;if(null===a&&null!==this.network)for(var b=this.network.vertexes.iterator;b.next();){var c=b.value.node;if(null!==c&&(a=c.diagram,null!==a))break}try{null!==a&&a.xa("Layout"),this.commitLayout()}finally{null!==a&&a.Wa("Layout")}}};Bi.prototype.commitLayout=function(){if(null!==this.network){for(var a=this.network.vertexes.iterator;a.next();)a.value.commit();if(this.isRouting)for(a=this.network.edges.iterator;a.next();)a.value.commit()}}; Bi.prototype.doLayout=function(a){var b=new G;a instanceof R?($p(this,b,a.nodes,!0,this.Qh,!0,!1,!0),$p(this,b,a.parts,!0,this.Qh,!0,!1,!0)):a instanceof U?$p(this,b,a.memberParts,!1,this.Qh,!0,!1,!0):b.addAll(a.iterator);0<b.count&&(a=this.diagram,null!==a&&a.xa("Layout"),this.doMinimalNoNetworkLayout(b),null!==a&&a.Wa("Layout"));this.isValidLayout=!0}; Bi.prototype.doMinimalNoNetworkLayout=function(a){var b=Math.ceil(Math.sqrt(a.count));this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin);var c=this.arrangementOrigin.x,d=c,e=this.arrangementOrigin.y,f=0,g=0;for(a=a.iterator;a.next();){var h=a.value;aq(h);var k=h.measuredBounds,l=k.width;k=k.height;h.moveTo(d,e);h instanceof U&&(h.Qh=!1);d+=Math.max(l,50)+20;g=Math.max(g,Math.max(k,50));f>=b-1?(f=0,d=c,e+=g+20,g=0):f++}}; Bi.prototype.doMinimalNetworkLayout=function(){var a=Math.ceil(Math.sqrt(this.network.vertexes.count));this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin);for(var b=this.arrangementOrigin.x,c=b,d=this.arrangementOrigin.y,e=0,f=0,g=this.network.vertexes.iterator;g.next();){var h=g.value.node;if(!(null===h||h instanceof S)&&(aq(h),this.Qh(h))){var k=h.measuredBounds,l=k.width;k=k.height;h.moveTo(c,d);h instanceof U&&(h.Qh=!1);c+=Math.max(l,50)+20;f=Math.max(f,Math.max(k,50));e>=a-1?(e= 0,c=b,d+=f+20,f=0):e++}}};Bi.prototype.Qh=function(a){return!a.location.s()||a instanceof U&&a.Qh?!0:!1};function $p(a,b,c,d,e,f,g,h){for(c=c.iterator;c.next();){var k=c.value;d&&!k.isTopLevel||null!==e&&!e(k)||!k.canLayout()||(f&&k instanceof W?k.isLinkLabel||(k instanceof U?null===k.layout?$p(a,b,k.memberParts,!1,e,f,g,h):(aq(k),b.add(k)):(aq(k),b.add(k))):g&&k instanceof S?b.add(k):!h||!k.Pc()||k instanceof W||(aq(k),b.add(k)))}} function aq(a){var b=a.actualBounds;(0===b.width||0===b.height||isNaN(b.width)||isNaN(b.height))&&a.Ta()}Bi.prototype.nj=function(a,b){var c=this.boundsComputation;if(null!==c)return b||(b=new N),c(a,this,b);if(!b)return a.actualBounds;b.set(a.actualBounds);return b}; Bi.prototype.ay=function(a){var b=new G;a instanceof R?($p(this,b,a.nodes,!0,null,!0,!0,!0),$p(this,b,a.links,!0,null,!0,!0,!0),$p(this,b,a.parts,!0,null,!0,!0,!0)):a instanceof U?$p(this,b,a.memberParts,!1,null,!0,!0,!0):$p(this,b,a.iterator,!1,null,!0,!0,!0);return b}; Bi.prototype.initialOrigin=function(a){var b=this.group;if(null!==b){var c=b.position.copy();(isNaN(c.x)||isNaN(c.y))&&c.set(a);b=b.placeholder;null!==b&&(c=b.da(vc),(isNaN(c.x)||isNaN(c.y))&&c.set(a),a=b.padding,c.x+=a.left,c.y+=a.top);return c}return a};Bi.prototype.mayUseWorker=function(){return this.mayUseWorkerFunction?this.mayUseWorkerFunction(this):!1};Bi.prototype.workerLayout=function(){return!1}; function bq(a,b){if(null!==a.workerStateChanged){var c={key:a.group?a.group.key:null};void 0!==b&&(c.time=b);null!==a.ek&&(c.running=cq(a.ek));null!==a.zg&&(c.waiting=cq(a.zg));a.workerStateChanged(c,a)}}function cq(a){return{vertexes:a.vertexes.count,edges:a.edges.count}}Bi.prototype.zz=function(){var a=dq(this.constructor);a&&(null!==a.Qe&&a.Qe.terminate(),a.Qe=null,a.Em.iteratorValues.each(function(a){a.wt=!1;a.ek=null;a.zg=null;a.lt=!1;bq(a)}),a.Em.clear())}; function eq(a,b){var c=dq(a);if(c){if(b)for(var d in b)c[d]=b[d]}else throw Error("Unknown Layout class: "+a);}function dq(a){var b=null;if("function"===typeof a){if(b=fq.get(a),!b){var c=Ja(a);b=fq.get(c);b||(b=new gq,b.Kv=a,b.name=c,b.l=a.name,b.Cy=hq,fq.set(c,b),fq.set(a,b),fq.set(a.name,b))}}else"string"===typeof a&&(b=fq.get(a));return b} Bi.prototype.Vw=function(){if("undefined"===typeof Worker||!iq||"undefined"===typeof self||"undefined"!==typeof self.DedicatedWorkerGlobalScope)return!1;if(!this.mayUseWorker())return this.wt&&(this.lt=!0,this.zg=this.ek=null,bq(this)),!1;var a=dq(this.constructor);if(null===a)return!1;null===a.Qe&&(a.Qe=new Worker(iq),a.Qe.onerror=function(a){a.preventDefault();xa("Worker Error at: "+a.filename+" "+a.lineno+" "+a.colno+"\n "+a.message)},a.Qe.l=function(a){xa("Worker serialization error: "+a)},a.Qe.onmessage= function(b){var c=b.data;if("_GoJS"===c._GoJS)if(c.version&&R.version&&c.version!==R.version)xa("Failure: GoJS v"+R.version+" Worker v"+c.version);else if(b=a.Em.get(c.id)){a.Em.remove(c.id);b.wt=!1;b.ek=null;if(b.lt)b.lt=!1,b.zg=null;else{var d=jq(b,c,!1);b.network=d;b.updateParts();b.network=null;b.isValidLayout=!0}bq(b,c.time);c=b.zg;if(null!==c)b.zg=null;else for(d=a.Em.iteratorValues;d.next();){var e=d.value;c=e.zg;if(null!==c){e.zg=null;break}}null!==c&&kq(b,c)}},a.Qe.postMessage({_GoJS:"_GoJS", url:a.Cy}),Array.isArray(a.scripts)&&a.scripts.forEach(function(b){a.Qe.postMessage({_GoJS:"_GoJS",url:b})}),a.Qe.postMessage({_GoJS:"_GoJS",version:-1}));null!==this.ek?this.zg=this.network:kq(this,this.network);bq(this);this.doMinimalNetworkLayout();this.network=null;return this.isValidLayout=!0};function kq(a,b){a.wt=!0;var c=dq(a.constructor),d=lq(a,b,!0);d._GoJS="_GoJS";c.Qe.postMessage(d);c.Em.set(mb(a),a);a.ek=b} function lq(a,b,c){a.onNetworkSerialization(1,c,b,null);var d={};a.serializeLayoutProperties(d,c);var e=[];b.vertexes.each(function(a){var b={};a.serializeVertexProperties(b,c);e.push(b)});var f=[];b.edges.each(function(a){var b={};a.serializeEdgeProperties(b,c);f.push(b)});d={id:c?mb(a):a.id,layout:Ja(a.constructor),p:d,hB:e,Qz:f};a.onNetworkSerialization(2,c,b,d);return d} function jq(a,b,c){c&&(a.id=b.id);var d=a.diagram,e=a.createNetwork();a.onNetworkSerialization(3,c,e,b);var f=b.hB,g=new H;f&&f.forEach(function(a){var b=null;null===a.key||null===d||c||(b=d.Db(a.key));null!==b?b=e.mk(b):(b=e.createVertex(),e.Cg(b));c&&null!==a.key&&(b.data={Ci:a.key});g.set(a.id,b)});var h=b.Qz,k=new H;h&&h.forEach(function(a){var b=null;null===a.key||null===d||c||(b=d.findLinkForKey(a.key));var f=e.createEdge();e.sm(f);f.link=b;c&&null!==a.key&&(f.data={Ci:a.key});k.set(a.id,f)}); f&&f.forEach(function(a){var b=g.get(a.id);b&&b.zq(a,g,k,c)});h&&h.forEach(function(a){var b=k.get(a.id);b&&b.deserializeEdgeProperties(a,g,k,c)});a.deserializeLayoutProperties(b.p,g,k,c,e);a.onNetworkSerialization(4,c,e,b);return e}Bi.prototype.onNetworkSerialization=function(){}; na.Object.defineProperties(Bi.prototype,{diagram:{get:function(){return this.B},set:function(a){this.B=a}},group:{get:function(){return this.v},set:function(a){this.v!==a&&(this.v=a,null!==a&&(this.B=a.diagram))}},isOngoing:{get:function(){return this.so},set:function(a){this.so!==a&&(this.so=a)}},isInitial:{get:function(){return this.yi},set:function(a){this.yi=a;a||(this.wo=!0)}}, isViewportSized:{get:function(){return this.xo},set:function(a){this.xo!==a&&(this.xo=a)&&this.C()}},isRouting:{get:function(){return this.uo},set:function(a){this.uo!==a&&(this.uo=a)}},isRealtime:{get:function(){return this.to},set:function(a){this.to!==a&&(this.to=a)}},isValidLayout:{get:function(){return this.wo},set:function(a){this.wo!==a&&(this.wo=a,a||(a=this.diagram,null!== a&&(a.Og=!0)))}},network:{get:function(){return this.l},set:function(a){this.l!==a&&(this.l=a,null!==a&&(a.layout=this))}},boundsComputation:{get:function(){return this.tn},set:function(a){this.tn!==a&&(this.tn=a,this.C())}},arrangementOrigin:{get:function(){return this.ln},set:function(a){this.ln.w(a)||(this.ln.assign(a),this.C())}},id:{get:function(){return this.I},set:function(a){this.I= a}},mayUseWorkerFunction:{get:function(){return this.Oo},set:function(a){this.Oo!==a&&(this.Oo=a)}},workerStateChanged:{get:function(){return this.nq},set:function(a){this.nq!==a&&(this.nq=a)}}});Bi.prototype.useWorker=Bi.prototype.Vw;Bi.declareWorkerLayout=eq;Bi.prototype.cancelWorker=Bi.prototype.zz;Bi.prototype.collectParts=Bi.prototype.ay;Bi.prototype.getLayoutBounds=Bi.prototype.nj;Bi.prototype.invalidateLayout=Bi.prototype.C; var fq=new H,hq="object"===typeof x.document&&x.document.currentScript?x.document.currentScript.src:"",iq="undefined"!==typeof URL&&"function"===typeof URL.createObjectURL&&"function"===typeof Blob?URL.createObjectURL(new Blob(["self.onmessage=function(e){if(e.data.url){\nimportScripts(e.data.url);}}"],{type:"text/javascript"})):"";Bi.className="Layout";Bi.GoJSScriptURL=hq;Bi.declareWorkerLayout=eq; "undefined"!==typeof self&&"undefined"!==typeof self.DedicatedWorkerGlobalScope&&"undefined"!==typeof self&&"undefined"!==typeof self.DedicatedWorkerGlobalScope&&(self.onmessage=function(a){a=a.data;if("_GoJS"===a._GoJS)if(a.url)importScripts(a.url);else if(a.version)self.postMessage({_GoJS:"_GoJS",version:R.version},void 0);else{var b=performance.now(),c=null;a.layout&&(c=dq(a.layout));var d=null;c&&c.Kv&&(d=new c.Kv);if(!d)throw Error("no registered Worker Layout: "+a.layout);d.network=jq(d,a,!0); d.workerLayout=function(){var a=lq(d,d.network,!1);a._GoJS="_GoJS";a.time=performance.now()-b;self.postMessage(a,void 0);return!0};d.doLayout(new E)}});function gq(){this.Kv=null;this.Cy=this.l=this.name="";this.scripts=[];this.Qe=null;this.Em=new H}function Zp(a){Za(this);this.lc=a;this.vf=new G;this.me=new G;this.bu=new H;this.Xt=new H} Zp.prototype.clear=function(){if(this.vf)for(var a=this.vf.iterator;a.next();)a.value.clear();if(this.me)for(a=this.me.iterator;a.next();)a.value.clear();this.vf=new G;this.me=new G;this.bu=new H;this.Xt=new H}; Zp.prototype.toString=function(a){void 0===a&&(a=0);var b="LayoutNetwork"+(null!==this.layout?"("+this.layout.toString()+")":"");if(0>=a)return b;b+=" vertexes: "+this.vf.count+" edges: "+this.me.count;if(1<a){for(var c=this.vf.iterator;c.next();)b+="\n "+c.value.toString(a-1);for(c=this.me.iterator;c.next();)b+="\n "+c.value.toString(a-1)}return b};Zp.prototype.createVertex=function(){return new mq(this)};Zp.prototype.createEdge=function(){return new nq(this)}; Zp.prototype.Bg=function(a,b,c){if(null!==a){void 0===b&&(b=!1);void 0===c&&(c=null);null===c&&(c=function(a){if(a instanceof W)return!a.isLinkLabel;if(a instanceof S){var b=a.fromNode;if(null===b||b.isLinkLabel)return!1;a=a.toNode;return null===a||a.isLinkLabel?!1:!0}return!1});for(a=a.iterator;a.next();){var d=a.value;if(d instanceof W&&(!b||d.isTopLevel)&&d.canLayout()&&c(d))if(d instanceof U&&null===d.layout)this.Bg(d.memberParts,!1);else if(null===this.kj(d)){var e=this.createVertex();e.node= d;this.Cg(e)}}for(a.reset();a.next();)if(d=a.value,d instanceof S&&(!b||d.isTopLevel)&&d.canLayout()&&c(d)&&null===this.Bq(d)){var f=d.fromNode;e=d.toNode;null!==f&&null!==e&&f!==e&&(f=this.findGroupVertex(f),e=this.findGroupVertex(e),null!==f&&null!==e&&this.Ek(f,e,d))}}};Zp.prototype.findGroupVertex=function(a){if(null===a)return null;var b=a.findVisibleNode();if(null===b)return null;a=this.kj(b);if(null!==a)return a;for(b=b.containingGroup;null!==b;){a=this.kj(b);if(null!==a)return a;b=b.containingGroup}return null}; t=Zp.prototype;t.Cg=function(a){if(null!==a){this.vf.add(a);var b=a.node;null!==b&&this.bu.add(b,a);a.network=this}};t.mk=function(a){if(null===a)return null;var b=this.kj(a);null===b&&(b=this.createVertex(),b.node=a,this.Cg(b));return b};t.Nv=function(a){if(null!==a&&oq(this,a)){for(var b=a.ud,c=b.count-1;0<=c;c--){var d=b.J(c);this.vk(d)}b=a.Gd;for(a=b.count-1;0<=a;a--)c=b.J(a),this.vk(c)}}; function oq(a,b){if(null===b)return!1;var c=a.vf.remove(b);c&&(b=b.node,null!==b&&a.bu.remove(b));return c}t.Lz=function(a){null!==a&&(a=this.kj(a),null!==a&&this.Nv(a))};t.kj=function(a){return null===a?null:this.bu.H(a)};t.sm=function(a){if(null!==a){pq(this,a);var b=a.toVertex;null!==b&&b.Dv(a);b=a.fromVertex;null!==b&&b.Bv(a)}};function pq(a,b){if(null!==b){a.me.add(b);var c=b.link;null!==c&&null===a.Bq(c)&&a.Xt.add(c,b);b.network=a}} t.oz=function(a){if(null===a)return null;var b=a.fromNode,c=a.toNode,d=this.Bq(a);null===d?(d=this.createEdge(),d.link=a,null!==b&&(d.fromVertex=this.mk(b)),null!==c&&(d.toVertex=this.mk(c)),this.sm(d)):(null!==b?d.fromVertex=this.mk(b):d.fromVertex=null,null!==c?d.toVertex=this.mk(c):d.toVertex=null);return d};t.vk=function(a){if(null!==a){var b=a.toVertex;null!==b&&b.Mv(a);b=a.fromVertex;null!==b&&b.Lv(a);qq(this,a)}}; function qq(a,b){null!==b&&a.me.remove(b)&&(b=b.link,null!==b&&a.Xt.remove(b))}t.Kz=function(a){null!==a&&(a=this.Bq(a),null!==a&&this.vk(a))};t.Bq=function(a){return null===a?null:this.Xt.H(a)};t.Ek=function(a,b,c){if(null===a||null===b)return null;if(a.network===this&&b.network===this){var d=this.createEdge();d.link=c;d.fromVertex=a;d.toVertex=b;this.sm(d);return d}return null};t.Qm=function(a){if(null!==a){var b=a.fromVertex,c=a.toVertex;null!==b&&null!==c&&(b.Lv(a),c.Mv(a),a.Qm(),b.Dv(a),c.Bv(a))}}; t.yq=function(){for(var a=Ea(),b=this.me.iterator;b.next();){var c=b.value;c.fromVertex===c.toVertex&&a.push(c)}b=a.length;for(c=0;c<b;c++)this.vk(a[c]);Ia(a)};Zp.prototype.deleteArtificialVertexes=function(){for(var a=Ea(),b=this.vf.iterator;b.next();){var c=b.value;null===c.node&&null===c.data&&a.push(c)}c=a.length;for(b=0;b<c;b++)this.Nv(a[b]);b=Ea();for(c=this.me.iterator;c.next();){var d=c.value;null===d.link&&null===d.data&&b.push(d)}c=b.length;for(d=0;d<c;d++)this.vk(b[d]);Ia(a);Ia(b)}; function rq(a){for(var b=Ea(),c=a.me.iterator;c.next();){var d=c.value;null!==d.fromVertex&&null!==d.toVertex||b.push(d)}c=b.length;for(d=0;d<c;d++)a.vk(b[d]);Ia(b)} Zp.prototype.Yy=function(a){void 0===a&&(a=!0);a&&(this.deleteArtificialVertexes(),rq(this),this.yq());a=new E;for(var b=!0;b;){b=!1;for(var c=this.vf.iterator;c.next();){var d=c.value;if(0<d.ud.count||0<d.Gd.count){b=this.layout.createNetwork();a.add(b);sq(this,b,d);b=!0;break}}}a.sort(function(a,b){return null===a||null===b||a===b?0:b.vertexes.count-a.vertexes.count});return a}; function sq(a,b,c){if(null!==c&&c.network!==b){oq(a,c);b.Cg(c);for(var d=c.sourceEdges;d.next();){var e=d.value;e.network!==b&&(qq(a,e),pq(b,e),sq(a,b,e.fromVertex))}for(d=c.destinationEdges;d.next();)c=d.value,c.network!==b&&(qq(a,c),pq(b,c),sq(a,b,c.toVertex))}}Zp.prototype.Rz=function(){for(var a=new G,b=this.vf.iterator;b.next();)a.add(b.value.node);for(b=this.me.iterator;b.next();)a.add(b.value.link);return a}; na.Object.defineProperties(Zp.prototype,{layout:{get:function(){return this.lc},set:function(a){null!==a&&(this.lc=a)}},vertexes:{get:function(){return this.vf}},edges:{get:function(){return this.me}}});Zp.prototype.findAllParts=Zp.prototype.Rz;Zp.prototype.splitIntoSubNetworks=Zp.prototype.Yy;Zp.prototype.deleteSelfEdges=Zp.prototype.yq;Zp.prototype.reverseEdge=Zp.prototype.Qm;Zp.prototype.linkVertexes=Zp.prototype.Ek; Zp.prototype.findEdge=Zp.prototype.Bq;Zp.prototype.deleteLink=Zp.prototype.Kz;Zp.prototype.deleteEdge=Zp.prototype.vk;Zp.prototype.addLink=Zp.prototype.oz;Zp.prototype.addEdge=Zp.prototype.sm;Zp.prototype.findVertex=Zp.prototype.kj;Zp.prototype.deleteNode=Zp.prototype.Lz;Zp.prototype.deleteVertex=Zp.prototype.Nv;Zp.prototype.addNode=Zp.prototype.mk;Zp.prototype.addVertex=Zp.prototype.Cg;Zp.prototype.addParts=Zp.prototype.Bg;Zp.className="LayoutNetwork"; function mq(a){Za(this);this.Vc=a;this.l=(new N(0,0,10,10)).freeze();this.v=(new I(5,5)).freeze();this.Li=this.nb=null;this.ud=new E;this.Gd=new E} mq.prototype.serializeVertexProperties=function(a){a.id=mb(this);a.key=this.node?this.node.key:this.data?this.data.Ci:void 0;void 0===a.key&&(a.key=null);a.x=this.bounds.x;a.y=this.bounds.y;a.iB=this.bounds.width;a.tA=this.bounds.height;a.fx=this.focus.x;a.fy=this.focus.y;var b=[];this.ud.each(function(a){b.push(mb(a))});a.Vy=b;var c=[];this.Gd.each(function(a){c.push(mb(a))});a.jy=c}; mq.prototype.zq=function(a,b,c){if(null!==a){this.x=a.x;this.y=a.y;this.width=a.iB;this.height=a.tA;this.focusX=a.fx;this.focusY=a.fy;var d=this;a.Vy&&a.Vy.forEach(function(a){(a=c.get(a))&&d.ud.add(a)});a.jy&&a.jy.forEach(function(a){(a=c.get(a))&&d.Gd.add(a)})}};mq.prototype.clear=function(){this.Li=this.nb=null;this.ud=new E;this.Gd=new E}; mq.prototype.toString=function(a){void 0===a&&(a=0);var b="LayoutVertex#"+mb(this);if(0<a&&(b+=null!==this.node?"("+this.node.toString()+")":"",1<a)){a="";for(var c=!0,d=this.ud.iterator;d.next();){var e=d.value;c?c=!1:a+=",";a+=e.toString(0)}e="";c=!0;for(d=this.Gd.iterator;d.next();){var f=d.value;c?c=!1:e+=",";e+=f.toString(0)}b+=" sources: "+a+" destinations: "+e}return b}; mq.prototype.commit=function(){var a=this.nb;if(null!==a){var b=this.bounds,c=a.bounds;za(c)?(c.x=b.x,c.y=b.y,c.width=b.width,c.height=b.height):a.bounds=b.copy()}else if(a=this.node,null!==a){b=this.bounds;if(!(a instanceof U)){c=N.alloc();var d=this.network.layout.nj(a,c),e=a.locationObject.da(Bc);if(d.s()&&e.s()){a.moveTo(b.x+this.focusX-(e.x-d.x),b.y+this.focusY-(e.y-d.y));N.free(c);return}N.free(c)}a.moveTo(b.x,b.y)}};mq.prototype.Dv=function(a){null!==a&&(this.ud.contains(a)||this.ud.add(a))}; mq.prototype.Mv=function(a){null!==a&&this.ud.remove(a)};mq.prototype.Bv=function(a){null!==a&&(this.Gd.contains(a)||this.Gd.add(a))};mq.prototype.Lv=function(a){null!==a&&this.Gd.remove(a)};function tq(a,b){a=a.Li;b=b.Li;return a?b?(a=a.text,b=b.text,a<b?-1:a>b?1:0):1:null!==b?-1:0} na.Object.defineProperties(mq.prototype,{sourceEdgesArrayAccess:{get:function(){return this.ud._dataArray}},destinationEdgesArrayAccess:{get:function(){return this.Gd._dataArray}},data:{get:function(){return this.nb},set:function(a){this.nb=a;if(null!==a&&a.bounds){var b=a.bounds;a=b.x;var c=b.y,d=b.width;b=b.height;this.v.h(d/2,b/2);this.l.h(a,c,d,b)}}},node:{get:function(){return this.Li}, set:function(a){if(this.Li!==a){this.Li=a;a.Ta();var b=this.network.layout,c=N.alloc(),d=b.nj(a,c);b=d.x;var e=d.y,f=d.width;d=d.height;isNaN(b)&&(b=0);isNaN(e)&&(e=0);this.l.h(b,e,f,d);N.free(c);if(!(a instanceof U)&&(a=a.locationObject.da(Bc),a.s())){this.v.h(a.x-b,a.y-e);return}this.v.h(f/2,d/2)}}},bounds:{get:function(){return this.l},set:function(a){this.l.w(a)||this.l.assign(a)}},focus:{get:function(){return this.v},set:function(a){this.v.w(a)|| this.v.assign(a)}},centerX:{get:function(){return this.l.x+this.v.x},set:function(a){var b=this.l;b.x+this.v.x!==a&&(b.ea(),b.x=a-this.v.x,b.freeze())}},centerY:{get:function(){return this.l.y+this.v.y},set:function(a){var b=this.l;b.y+this.v.y!==a&&(b.ea(),b.y=a-this.v.y,b.freeze())}},focusX:{get:function(){return this.v.x},set:function(a){var b=this.v;b.x!==a&&(b.ea(),b.x=a,b.freeze())}},focusY:{ get:function(){return this.v.y},set:function(a){var b=this.v;b.y!==a&&(b.ea(),b.y=a,b.freeze())}},x:{get:function(){return this.l.x},set:function(a){var b=this.l;b.x!==a&&(b.ea(),b.x=a,b.freeze())}},y:{get:function(){return this.l.y},set:function(a){var b=this.l;b.y!==a&&(b.ea(),b.y=a,b.freeze())}},width:{get:function(){return this.l.width},set:function(a){var b=this.l;b.width!==a&&(b.ea(),b.width= a,b.freeze())}},height:{get:function(){return this.l.height},set:function(a){var b=this.l;b.height!==a&&(b.ea(),b.height=a,b.freeze())}},network:{get:function(){return this.Vc},set:function(a){this.Vc=a}},sourceVertexes:{get:function(){for(var a=new G,b=this.sourceEdges;b.next();)a.add(b.value.fromVertex);return a.iterator}},destinationVertexes:{get:function(){for(var a=new G,b= this.destinationEdges;b.next();)a.add(b.value.toVertex);return a.iterator}},vertexes:{get:function(){for(var a=new G,b=this.sourceEdges;b.next();)a.add(b.value.fromVertex);for(b=this.destinationEdges;b.next();)a.add(b.value.toVertex);return a.iterator}},sourceEdges:{get:function(){return this.ud.iterator}},destinationEdges:{get:function(){return this.Gd.iterator}},edges:{get:function(){for(var a= new E,b=this.sourceEdges;b.next();)a.add(b.value);for(b=this.destinationEdges;b.next();)a.add(b.value);return a.iterator}},edgesCount:{get:function(){return this.ud.count+this.Gd.count}}});mq.prototype.deleteDestinationEdge=mq.prototype.Lv;mq.prototype.addDestinationEdge=mq.prototype.Bv;mq.prototype.deleteSourceEdge=mq.prototype.Mv;mq.prototype.addSourceEdge=mq.prototype.Dv;mq.className="LayoutVertex";mq.standardComparer=tq; mq.smartComparer=function(a,b){if(null!==a){if(null!==b){a=a.Li;var c=b.Li;if(null!==a){if(null!==c){b=a.text.toLocaleLowerCase().split(/([+\-]?[\.]?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/);a=c.text.toLocaleLowerCase().split(/([+\-]?[\.]?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/);for(c=0;c<b.length;c++)if(""!==a[c]&&void 0!==a[c]){var d=parseFloat(b[c]),e=parseFloat(a[c]);if(isNaN(d))if(isNaN(e)){if(0!==b[c].localeCompare(a[c]))return b[c].localeCompare(a[c])}else return 1;else{if(isNaN(e))return-1;if(0!==d-e)return d- e}}else if(""!==b[c])return 1;return""!==a[c]&&void 0!==a[c]?-1:0}return 1}return null!==c?-1:0}return 1}return null!==b?-1:0};function nq(a){Za(this);this.Uc=a;this.gd=this.$c=this.Ol=this.nb=null}nq.prototype.clear=function(){this.gd=this.$c=this.Ol=this.nb=null}; nq.prototype.serializeEdgeProperties=function(a){a.id=mb(this);a.key=this.link?this.link.key:this.data?this.data.Ci:void 0;void 0===a.key&&(a.key=null);a.from=this.fromVertex?mb(this.fromVertex):null;a.dB=this.toVertex?mb(this.toVertex):null};nq.prototype.deserializeEdgeProperties=function(a,b){if(null!==a){var c=b.get(a.from);c&&(this.fromVertex=c);if(a=b.get(a.dB))this.toVertex=a}}; nq.prototype.toString=function(a){void 0===a&&(a=0);var b="LayoutEdge#"+mb(this);0<a&&(b+=null!==this.Ol?"("+this.Ol.toString()+")":"",1<a&&(b+=" "+(this.$c?this.$c.toString():"null")+" --\x3e "+(this.gd?this.gd.toString():"null")));return b};nq.prototype.Qm=function(){var a=this.$c;this.$c=this.gd;this.gd=a};nq.prototype.commit=function(){};nq.prototype.zy=function(a){return this.gd===a?this.$c:this.$c===a?this.gd:null}; na.Object.defineProperties(nq.prototype,{network:{get:function(){return this.Uc},set:function(a){this.Uc=a}},data:{get:function(){return this.nb},set:function(a){this.nb!==a&&(this.nb=a)}},link:{get:function(){return this.Ol},set:function(a){this.Ol!==a&&(this.Ol=a)}},fromVertex:{get:function(){return this.$c},set:function(a){this.$c!==a&&(this.$c=a)}},toVertex:{ get:function(){return this.gd},set:function(a){this.gd!==a&&(this.gd=a)}}});nq.prototype.getOtherVertex=nq.prototype.zy;nq.className="LayoutEdge";function Pk(){Bi.call(this);this.isViewportSized=!0;this.oq=this.pq=NaN;this.Rg=(new M(NaN,NaN)).freeze();this.mf=(new M(10,10)).freeze();this.zb=uq;this.Fb=vq;this.dd=wq;this.Yc=xq}ma(Pk,Bi); Pk.prototype.cloneProtected=function(a){Bi.prototype.cloneProtected.call(this,a);a.pq=this.pq;a.oq=this.oq;a.Rg.assign(this.Rg);a.mf.assign(this.mf);a.zb=this.zb;a.Fb=this.Fb;a.dd=this.dd;a.Yc=this.Yc};Pk.prototype.jb=function(a){a.classType===Pk?a===wq||a===yq||a===zq||a===Aq?this.sorting=a:a===vq||a===Bq?this.arrangement=a:a===uq||a===Cq?this.alignment=a:B("Unknown enum value: "+a):Bi.prototype.jb.call(this,a)}; Pk.prototype.doLayout=function(a){this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin);var b=this.ay(a);a=this.diagram;for(var c=b.copy().iterator;c.next();){var d=c.value;if(!d.Oh()||null===d.fromNode&&null===d.toNode){if(d.Ta(),d instanceof U)for(d=d.memberParts;d.next();)b.remove(d.value)}else b.remove(d)}var e=b.ma();if(0!==e.length){switch(this.sorting){case Aq:e.reverse();break;case wq:e.sort(this.comparer);break;case yq:e.sort(this.comparer),e.reverse()}var f=this.wrappingColumn; isNaN(f)&&(f=0);var g=this.wrappingWidth;isNaN(g)&&null!==a?(b=a.padding,g=Math.max(a.viewportBounds.width-b.left-b.right,0)):g=Math.max(this.wrappingWidth,0);0>=f&&0>=g&&(f=1);b=this.spacing.width;isFinite(b)||(b=0);c=this.spacing.height;isFinite(c)||(c=0);null!==a&&a.xa("Layout");d=[];switch(this.alignment){case Cq:var h=b,k=c,l=N.alloc(),m=Math.max(this.cellSize.width,1);if(!isFinite(m))for(var n=m=0;n<e.length;n++){var p=this.nj(e[n],l);m=Math.max(m,p.width)}m=Math.max(m+h,1);n=Math.max(this.cellSize.height, 1);if(!isFinite(n))for(p=n=0;p<e.length;p++){var r=this.nj(e[p],l);n=Math.max(n,r.height)}n=Math.max(n+k,1);p=this.arrangement;for(var q=r=this.arrangementOrigin.x,u=this.arrangementOrigin.y,v=0,w=0,y=0;y<e.length;y++){var z=e[y],A=this.nj(z,l),C=Math.ceil((A.width+h)/m)*m,F=Math.ceil((A.height+k)/n)*n;switch(p){case Bq:var Q=Math.abs(q-A.width);break;default:Q=q+A.width}if(0<f&&v>f-1||0<g&&0<v&&Q-r>g)d.push(new N(0,u,g+h,w)),v=0,q=r,u+=w,w=0;w=Math.max(w,F);switch(p){case Bq:A=-A.width;break;default:A= 0}z.moveTo(q+A,u);switch(p){case Bq:q-=C;break;default:q+=C}v++}d.push(new N(0,u,g+h,w));N.free(l);break;case uq:k=g;m=f;n=b;p=c;g=N.alloc();r=Math.max(this.cellSize.width,1);f=u=l=0;h=I.alloc();for(q=0;q<e.length;q++)w=e[q],v=this.nj(w,g),w=w.Ff(w.locationObject,w.locationSpot,h),l=Math.max(l,w.x),u=Math.max(u,v.width-w.x),f=Math.max(f,w.y);q=this.arrangement;switch(q){case Bq:l+=n;break;default:u+=n}r=isFinite(r)?Math.max(r+n,1):Math.max(l+u,1);var K=w=this.arrangementOrigin.x;y=this.arrangementOrigin.y; u=0;k>=l&&(k-=l);l=z=0;C=Math.max(this.cellSize.height,1);A=f=0;F=!0;v=I.alloc();for(Q=0;Q<e.length;Q++){var T=e[Q],P=this.nj(T,g),J=T.Ff(T.locationObject,T.locationSpot,h);if(0<u)switch(q){case Bq:K=(K-w-(P.width-J.x))/r;K=L.aa(Math.round(K),K)?Math.round(K):Math.floor(K);K=K*r+w;break;default:K=(K-w+J.x)/r,K=L.aa(Math.round(K),K)?Math.round(K):Math.ceil(K),K=K*r+w}else switch(q){case Bq:z=K+J.x+P.width;break;default:z=K-J.x}switch(q){case Bq:var ka=-(K+J.x)+z;break;default:ka=K+P.width-J.x-z}if(0< m&&u>m-1||0<k&&0<u&&ka>k){d.push(new N(0,F?y-f:y,k+n,A+f+p));for(K=0;K<u&&Q!==u;K++){ka=e[Q-u+K];var ba=ka.Ff(ka.locationObject,ka.locationSpot,v);ka.moveTo(ka.position.x,ka.position.y+f-ba.y)}A+=p;y=F?y+A:y+(A+f);u=A=f=0;K=w;F=!1}K===w&&(l=q===Bq?Math.max(l,P.width-J.x):Math.min(l,-J.x));f=Math.max(f,J.y);A=Math.max(A,P.height-J.y);isFinite(C)&&(A=Math.max(A,Math.max(P.height,C)-J.y));F?T.moveTo(K-J.x,y-J.y):T.moveTo(K-J.x,y);switch(q){case Bq:K-=J.x+n;break;default:K+=P.width-J.x+n}u++}d.push(new N(0, y,k+n,(F?A:A+f)+p));if(e.length!==u)for(k=0;k<u;k++)m=e[e.length-u+k],n=m.Ff(m.locationObject,m.locationSpot,h),m.moveTo(m.position.x,m.position.y+f-n.y);I.free(h);I.free(v);if(q===Bq)for(e=0;e<d.length;e++)f=d[e],f.width+=l,f.x-=l;else for(e=0;e<d.length;e++)f=d[e],f.x>l&&(f.width+=f.x-l,f.x=l);N.free(g)}for(h=f=g=e=0;h<d.length;h++)k=d[h],e=Math.min(e,k.x),g=Math.min(g,k.y),f=Math.max(f,k.x+k.width);this.arrangement===Bq?this.commitLayers(d,new I(e+b/2-(f+e),g-c/2)):this.commitLayers(d,new I(e- b/2,g-c/2));null!==a&&a.Wa("Layout");this.isValidLayout=!0}};Pk.prototype.commitLayers=function(){};function xq(a,b){a=a.text;b=b.text;return a<b?-1:a>b?1:0} na.Object.defineProperties(Pk.prototype,{wrappingWidth:{get:function(){return this.pq},set:function(a){this.pq!==a&&(0<a||isNaN(a))&&(this.pq=a,this.isViewportSized=isNaN(a),this.C())}},wrappingColumn:{get:function(){return this.oq},set:function(a){this.oq!==a&&(0<a||isNaN(a))&&(this.oq=a,this.C())}},cellSize:{get:function(){return this.Rg},set:function(a){this.Rg.w(a)||(this.Rg.assign(a),this.C())}},spacing:{ get:function(){return this.mf},set:function(a){this.mf.w(a)||(this.mf.assign(a),this.C())}},alignment:{get:function(){return this.zb},set:function(a){this.zb===a||a!==uq&&a!==Cq||(this.zb=a,this.C())}},arrangement:{get:function(){return this.Fb},set:function(a){this.Fb===a||a!==vq&&a!==Bq||(this.Fb=a,this.C())}},sorting:{get:function(){return this.dd},set:function(a){this.dd===a||a!==zq&&a!==Aq&& a!==wq&&a!==yq||(this.dd=a,this.C())}},comparer:{get:function(){return this.Yc},set:function(a){this.Yc!==a&&(this.Yc=a,this.C())}}});var Cq=new D(Pk,"Position",0),uq=new D(Pk,"Location",1),vq=new D(Pk,"LeftToRight",2),Bq=new D(Pk,"RightToLeft",3),zq=new D(Pk,"Forward",4),Aq=new D(Pk,"Reverse",5),wq=new D(Pk,"Ascending",6),yq=new D(Pk,"Descending",7);Pk.className="GridLayout";Pk.standardComparer=xq; Pk.smartComparer=function(a,b){if(null!==a){if(null!==b){a=a.text.toLocaleLowerCase().split(/([+\-]?[\.]?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/);b=b.text.toLocaleLowerCase().split(/([+\-]?[\.]?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/);for(var c=0;c<a.length;c++)if(""!==b[c]&&void 0!==b[c]){var d=parseFloat(a[c]),e=parseFloat(b[c]);if(isNaN(d))if(isNaN(e)){if(0!==a[c].localeCompare(b[c]))return a[c].localeCompare(b[c])}else return 1;else{if(isNaN(e))return-1;if(0!==d-e)return d-e}}else if(""!==a[c])return 1;return""!== b[c]&&void 0!==b[c]?-1:0}return 1}return null!==b?-1:0};Pk.Position=Cq;Pk.Location=uq;Pk.LeftToRight=vq;Pk.RightToLeft=Bq;Pk.Forward=zq;Pk.Reverse=Aq;Pk.Ascending=wq;Pk.Descending=yq;function wi(){this.gp=new G;this.Io=new G;this.Da=new G;this.Ve=new H;this.Ue=new H;this.Qj=new H;this.B=null;this.nr=!1}t=wi.prototype;t.clear=function(){this.gp.clear();this.Io.clear();this.Da.clear();this.Ve.clear();this.Ue.clear();this.Qj.clear()};t.fe=function(a){this.B=a}; t.oj=function(a){if(a instanceof W){if(this.gp.add(a),a instanceof U){var b=a.containingGroup;null===b?this.B.Ch.add(a):b.Tl.add(a);b=a.layout;null!==b&&(b.diagram=this.B)}}else a instanceof S?this.Io.add(a):a instanceof Qe||this.Da.add(a);b=a.data;null===b||a instanceof Qe||(a instanceof S?this.Ue.add(b,a):this.Ve.add(b,a))}; t.Nc=function(a){a.nk();if(a instanceof W){if(this.gp.remove(a),a instanceof U){var b=a.containingGroup;null===b?this.B.Ch.remove(a):b.Tl.remove(a);b=a.layout;null!==b&&(b.diagram=null)}}else a instanceof S?this.Io.remove(a):a instanceof Qe||this.Da.remove(a);b=a.data;null===b||a instanceof Qe||(a instanceof S?this.Ue.remove(b):this.Ve.remove(b))}; t.Md=function(){for(var a=this.B.nodeTemplateMap.iterator;a.next();){var b=a.value,c=a.key;(!b.Pc()||b instanceof U)&&B('Invalid node template in Diagram.nodeTemplateMap: template for "'+c+'" must be a Node or a simple Part, not a Group or Link: '+b)}for(a=this.B.groupTemplateMap.iterator;a.next();)b=a.value,c=a.key,b instanceof U||B('Invalid group template in Diagram.groupTemplateMap: template for "'+c+'" must be a Group, not a normal Node or Link: '+b);for(a=this.B.linkTemplateMap.iterator;a.next();)b= a.value,c=a.key,b instanceof S||B('Invalid link template in Diagram.linkTemplateMap: template for "'+c+'" must be a Link, not a normal Node or simple Part: '+b);a=Ea();for(b=this.B.selection.iterator;b.next();)(c=b.value.data)&&a.push(c);b=Ea();for(c=this.B.highlighteds.iterator;c.next();){var d=c.value.data;d&&b.push(d)}c=Ea();for(d=this.nodes.iterator;d.next();){var e=d.value;null!==e.data&&(c.push(e.data),c.push(e.location))}for(d=this.links.iterator;d.next();)e=d.value,null!==e.data&&(c.push(e.data), c.push(e.location));for(d=this.parts.iterator;d.next();)e=d.value,null!==e.data&&(c.push(e.data),c.push(e.location));this.removeAllModeledParts();this.addAllModeledParts();for(d=0;d<a.length;d++)e=this.zc(a[d]),null!==e&&(e.isSelected=!0);for(d=0;d<b.length;d++)e=this.zc(b[d]),null!==e&&(e.isHighlighted=!0);for(d=0;d<c.length;d+=2)e=this.zc(c[d]),null!==e&&(e.location=c[d+1]);Ia(a);Ia(b);Ia(c)};wi.prototype.addAllModeledParts=function(){this.addModeledParts(this.diagram.model.nodeDataArray)}; wi.prototype.addModeledParts=function(a,b){var c=this,d=this.diagram.model;a.forEach(function(a){d.$a(a)&&Dq(c,a,!1)});a.forEach(function(a){d.$a(a)&&c.resolveReferencesForData(a)});!1!==b&&ek(this.diagram,!1)}; function Dq(a,b,c){if(void 0!==b&&null!==b&&!a.diagram.undoManager.isUndoingRedoing&&!a.Ve.contains(b)){void 0===c&&(c=!0);a:{if(void 0!==b&&null!==b&&!a.B.undoManager.isUndoingRedoing&&!a.Ve.contains(b)){var d=a.Fq(b);var e=No(a,b,d);if(null!==e&&(Ag(e),e=e.copy(),null!==e)){var f=a.diagram.skipsModelSourceBindings;a.diagram.skipsModelSourceBindings=!0;e.Pf=d;e.nb=b;a.nr&&(e.ih="Tool");a.diagram.add(e);e.nb=null;e.data=b;a.diagram.skipsModelSourceBindings=f;d=e;break a}}d=null}null!==d&&c&&a.resolveReferencesForData(b)}} wi.prototype.insertLink=function(){return null};wi.prototype.resolveReferencesForData=function(){};wi.prototype.Fq=function(a){return this.B.model.Fq(a)}; function No(a,b,c){a=a.B;var d=a.model;d.Ck()&&d.ew(b)?(b=a.groupTemplateMap.H(c),null===b&&(b=a.groupTemplateMap.H(""),null===b&&(Eq||(Eq=!0,xa('No Group template found for category "'+c+'"'),xa(" Using default group template")),b=a.Du))):(b=a.nodeTemplateMap.H(c),null===b&&(b=a.nodeTemplateMap.H(""),null===b&&(Fq||(Fq=!0,xa('No Node template found for category "'+c+'"'),xa(" Using default node template")),b=a.Fu)));return b}wi.prototype.getLinkCategoryForData=function(){return""}; wi.prototype.setLinkCategoryForData=function(){};wi.prototype.setFromNodeForLink=function(){};wi.prototype.setToNodeForLink=function(){};wi.prototype.findLinkTemplateForCategory=function(a){var b=this.B.linkTemplateMap.H(a);null===b&&(b=this.B.linkTemplateMap.H(""),null===b&&(Gq||(Gq=!0,xa('No Link template found for category "'+a+'"'),xa(" Using default link template")),b=this.B.Eu));return b};wi.prototype.removeAllModeledParts=function(){this.fu(this.diagram.model.nodeDataArray)}; wi.prototype.fu=function(a){var b=this;a.forEach(function(a){b.$q(a)})};wi.prototype.$q=function(a){a=this.zc(a);null!==a&&(Nj(this.diagram,a,!1),this.unresolveReferencesForPart(a))};wi.prototype.unresolveReferencesForPart=function(){};wi.prototype.removeDataForLink=function(){};wi.prototype.findPartForKey=function(a){if(null===a||void 0===a)return null;a=this.B.model.Lb(a);return null!==a?this.Ve.H(a):null}; wi.prototype.Db=function(a){if(null===a||void 0===a)return null;a=this.B.model.Lb(a);if(null===a)return null;a=this.Ve.H(a);return a instanceof W?a:null};wi.prototype.findLinkForKey=function(){return null};t=wi.prototype;t.zc=function(a){if(null===a)return null;var b=this.Ve.H(a);return null!==b?b:b=this.Ue.H(a)};t.gj=function(a){if(null===a)return null;a=this.Ve.H(a);return a instanceof W?a:null};t.yc=function(a){return null===a?null:this.Ue.H(a)}; t.Jt=function(a){for(var b=0;b<arguments.length;++b);b=new G;for(var c=this.gp.iterator;c.next();){var d=c.value,e=d.data;if(null!==e)for(var f=0;f<arguments.length;f++){var g=arguments[f];if(za(g)&&Hq(this,e,g)){b.add(d);break}}}return b.iterator};t.It=function(a){for(var b=0;b<arguments.length;++b);b=new G;for(var c=this.Io.iterator;c.next();){var d=c.value,e=d.data;if(null!==e)for(var f=0;f<arguments.length;f++){var g=arguments[f];if(za(g)&&Hq(this,e,g)){b.add(d);break}}}return b.iterator}; function Hq(a,b,c){for(var d in c){var e=b[d],f=c[d];if(Aa(f)){if(!Aa(e)||e.length<f.length)return!1;for(var g=0;g<e.length;g++){var h=f[g];if(void 0!==h&&!Iq(a,e[g],h))return!1}}else if(!Iq(a,e,f))return!1}return!0}function Iq(a,b,c){if("function"===typeof c){if(!c(b))return!1}else if(c instanceof RegExp){if(!b||!c.test(b.toString()))return!1}else if(za(b)&&za(c)){if(!Hq(a,b,c))return!1}else if(b!==c)return!1;return!0} wi.prototype.doModelChanged=function(a){if(this.B){var b=this.B;if(a.model===b.model){var c=a.change;b.doModelChanged(a);if(b.Z){b.Z=!1;try{var d=a.modelChange;if(""!==d)if(c===ze){if("nodeCategory"===d){var e=this.zc(a.object),f=a.newValue;null!==e&&"string"===typeof f&&(e.category=f)}else"nodeDataArray"===d&&(this.fu(a.oldValue),this.addModeledParts(a.newValue));b.isModified=!0}else if(c===Be){var g=a.newValue;"nodeDataArray"===d&&za(g)&&Dq(this,g);b.isModified=!0}else if(c===Ce){var h=a.oldValue; "nodeDataArray"===d&&za(h)&&this.$q(h);b.isModified=!0}else c===Ae&&("SourceChanged"===d?null!==a.object?this.updateDataBindings(a.object,a.propertyName):(this.jr(),this.updateAllTargetBindings()):"ModelDisplaced"===d&&this.Md());else if(c===ze){var k=a.propertyName,l=a.object;if(l===b.model){if("nodeKeyProperty"===k||"nodeCategoryProperty"===k)b.undoManager.isUndoingRedoing||this.Md()}else this.updateDataBindings(l,k);b.isModified=!0}else if(c===Be||c===Ce){var m=a.change===Be,n=m?a.newParam:a.oldParam, p=m?a.newValue:a.oldValue,r=this.Qj.H(a.object);if(Array.isArray(r))for(a=0;a<r.length;a++){var q=r[a];if(m)nn(q,p,n);else if(!(0>n)){var u=n+fn(q);q.Nc(u,!0);rn(q,u,n)}}b.isModified=!0}}finally{b.Z=!0}}}}};wi.prototype.updateAllTargetBindings=function(a){void 0===a&&(a="");for(var b=this.parts.iterator;b.next();)b.value.Ca(a);for(b=this.nodes.iterator;b.next();)b.value.Ca(a);for(b=this.links.iterator;b.next();)b.value.Ca(a)}; wi.prototype.jr=function(){for(var a=this.B.model,b=new G,c=a.nodeDataArray,d=0;d<c.length;d++)b.add(c[d]);var e=[];this.nodes.each(function(a){null===a.data||b.contains(a.data)||e.push(a.data)});this.parts.each(function(a){null===a.data||b.contains(a.data)||e.push(a.data)});e.forEach(function(b){Jq(a,b,!1)});for(d=0;d<c.length;d++){var f=c[d];null===this.zc(f)&&Kq(a,f,!1)}this.refreshDataBoundLinks();for(c=this.parts.iterator;c.next();)c.value.updateRelationshipsFromData();for(c=this.nodes.iterator;c.next();)c.value.updateRelationshipsFromData(); for(c=this.links.iterator;c.next();)c.value.updateRelationshipsFromData()};wi.prototype.refreshDataBoundLinks=function(){};wi.prototype.updateRelationshipsFromData=function(){}; wi.prototype.updateDataBindings=function(a,b){if("string"===typeof b){var c=this.zc(a);if(null!==c)c.Ca(b);else{c=null;for(var d=this.Qj.iterator;d.next();){for(var e=d.value,f=0;f<e.length;f++){var g=e[f].qy(a);null!==g&&(null===c&&(c=Ea()),c.push(g))}if(null!==c)break}if(null!==c){for(d=0;d<c.length;d++)c[d].Ca(b);Ia(c)}}a===this.diagram.model.modelData&&this.updateAllTargetBindings(b)}}; function Jj(a,b){var c=b.Bi;if(Aa(c)){var d=a.Qj.H(c);if(null===d)d=[],d.push(b),a.Qj.add(c,d);else{for(a=0;a<d.length;a++)if(d[a]===b)return;d.push(b)}}}function Mj(a,b,c){Hj(b,function(a){a=a.W.j;for(var b=a.length,d=0;d<b;d++)ck(c,a[d])});var d=b.Bi;if(Aa(d)){var e=a.Qj.H(d);if(null!==e)for(var f=0;f<e.length;f++)if(e[f]===b){e.splice(f,1);0===e.length&&a.Qj.remove(d);break}}} wi.prototype.tk=function(a,b,c){void 0===c&&(c=!1);var d=new H;if(Aa(a))for(var e=0;e<a.length;e++)Lq(this,a[e],b,d,c);else for(a=a.iterator;a.next();)Lq(this,a.value,b,d,c);if(null!==b){c=b.model;a=b.toolManager.findTool("Dragging");a=null!==a?a.dragOptions.dragsLink:b.kl.dragsLink;e=new G;for(var f=new H,g=d.iterator;g.next();){var h=g.value;if(h instanceof S)a||null!==h.fromNode&&null!==h.toNode||e.add(h);else if(h instanceof W&&null!==h.data&&c.Dm()){var k=h;h=g.key;var l=h.Gg();null!==l&&(l= d.H(l),null!==l?(c.ge(k.data,c.ja(l.data)),k=b.yc(k.data),h=h.jj(),null!==h&&null!==k&&f.add(h,k)):c.ge(k.data,void 0))}}0<e.count&&b.gu(e,!1);if(0<f.count)for(c=f.iterator;c.next();)d.add(c.key,c.value)}if(null!==b&&null!==this.B&&(b=b.model,c=b.afterCopyFunction,null!==c)){var m=new H;d.each(function(a){null!==a.key.data&&m.add(a.key.data,a.value.data)});c(m,b,this.B.model)}for(b=d.iterator;b.next();)b.value.Ca();return d}; function Lq(a,b,c,d,e){if(null===b||e&&!b.canCopy())return null;if(d.contains(b))return d.H(b);var f=a.copyPartData(b,c);if(!(f instanceof V))return null;f.isSelected=!1;f.isHighlighted=!1;d.add(b,f);if(b instanceof W){for(var g=b.linksConnected;g.next();){var h=g.value;if(h.fromNode===b){var k=d.H(h);null!==k&&(k.fromNode=f)}h.toNode===b&&(h=d.H(h),null!==h&&(h.toNode=f))}if(b instanceof U&&f instanceof U)for(b=b.memberParts;b.next();)g=Lq(a,b.value,c,d,e),g instanceof S||null===g||(g.containingGroup= f)}else if(b instanceof S&&f instanceof S)for(g=b.fromNode,null!==g&&(g=d.H(g),null!==g&&(f.fromNode=g)),g=b.toNode,null!==g&&(g=d.H(g),null!==g&&(f.toNode=g)),b=b.labelNodes;b.next();)g=Lq(a,b.value,c,d,e),null!==g&&g instanceof W&&(g.labeledLink=f);return f} wi.prototype.copyPartData=function(a,b){var c=null,d=a.data;if(null!==d&&null!==b){var e=b.model;a instanceof S||(d=e.copyNodeData(d),za(d)&&(e.wf(d),c=b.zc(d)))}else Ag(a),c=a.copy(),null!==c&&(e=this.B,null!==b?b.add(c):null!==d&&null!==e&&null!==e.commandHandler&&e.commandHandler.copiesClipboardData&&(b=e.model,e=null,c instanceof S||(e=b.copyNodeData(d)),za(e)&&(c.data=e)));return c}; na.Object.defineProperties(wi.prototype,{nodes:{get:function(){return this.gp}},links:{get:function(){return this.Io}},parts:{get:function(){return this.Da}},diagram:{get:function(){return this.B}},addsToTemporaryLayer:{get:function(){return this.nr},set:function(a){this.nr=a}}});wi.prototype.updateAllRelationshipsFromData=wi.prototype.jr; wi.prototype.findLinksByExample=wi.prototype.It;wi.prototype.findNodesByExample=wi.prototype.Jt;wi.prototype.findLinkForData=wi.prototype.yc;wi.prototype.findNodeForData=wi.prototype.gj;wi.prototype.findPartForData=wi.prototype.zc;wi.prototype.findNodeForKey=wi.prototype.Db;wi.prototype.removeModeledPart=wi.prototype.$q;wi.prototype.removeModeledParts=wi.prototype.fu;wi.prototype.rebuildParts=wi.prototype.Md;var Fq=!1,Eq=!1,Gq=!1;wi.className="PartManager"; function Mq(a){wi.apply(this,arguments)}ma(Mq,wi);Mq.prototype.addAllModeledParts=function(){var a=this.diagram.model;this.addModeledParts(a.nodeDataArray);Nq(this,a.linkDataArray)};Mq.prototype.addModeledParts=function(a){wi.prototype.addModeledParts.call(this,a,!1);for(a=this.links.iterator;a.next();)Oo(a.value);ek(this.diagram,!1)};function Nq(a,b){b.forEach(function(b){Oq(a,b)});ek(a.diagram,!1)} function Oq(a,b){if(void 0!==b&&null!==b&&!a.diagram.undoManager.isUndoingRedoing&&!a.Ue.contains(b)){var c=a.getLinkCategoryForData(b),d=a.findLinkTemplateForCategory(c);if(null!==d){Ag(d);var e=d.copy();if(null!==e){d=a.diagram.skipsModelSourceBindings;a.diagram.skipsModelSourceBindings=!0;e.Pf=c;e.nb=b;c=a.diagram.model;var f=Pq(c,b,!0);""!==f&&(e.fromPortId=f);f=Qq(c,b,!0);void 0!==f&&(f=a.Db(f),f instanceof W&&(e.fromNode=f));f=Pq(c,b,!1);""!==f&&(e.toPortId=f);f=Qq(c,b,!1);void 0!==f&&(f=a.Db(f), f instanceof W&&(e.toNode=f));c=c.Df(b);Array.isArray(c)&&c.forEach(function(b){b=a.Db(b);null!==b&&(b.labeledLink=e)});a.nr&&(e.ih="Tool");a.diagram.add(e);e.nb=null;e.data=b;a.diagram.skipsModelSourceBindings=d}}}}Mq.prototype.removeAllModeledParts=function(){var a=this.diagram.model;Rq(this,a.linkDataArray);this.fu(a.nodeDataArray)};function Rq(a,b){b.forEach(function(b){a.$q(b)})}Mq.prototype.getLinkCategoryForData=function(a){return this.diagram.model.Mt(a)}; Mq.prototype.setLinkCategoryForData=function(a,b){return this.diagram.model.cr(a,b)};Mq.prototype.setFromNodeForLink=function(a,b){var c=this.diagram.model;c.Cw(a.data,c.ja(null!==b?b.data:null))};Mq.prototype.setToNodeForLink=function(a,b){var c=this.diagram.model;c.Hw(a.data,c.ja(null!==b?b.data:null))};Mq.prototype.removeDataForLink=function(a){this.diagram.model.Lm(a.data)}; Mq.prototype.findPartForKey=function(a){var b=wi.prototype.findPartForKey.call(this,a);return null===b&&(a=this.diagram.model.Eg(a),null!==a)?this.Ue.H(a):b};Mq.prototype.findLinkForKey=function(a){if(null===a||void 0===a)return null;a=this.diagram.model.Eg(a);return null!==a?this.Ue.H(a):null}; Mq.prototype.doModelChanged=function(a){var b=this;wi.prototype.doModelChanged.call(this,a);if(this.diagram){var c=this.diagram;if(a.model===c.model){var d=a.change;if(c.Z){c.Z=!1;try{var e=a.modelChange;if(""!==e)if(d===ze){if("linkFromKey"===e){var f=this.yc(a.object);if(null!==f){var g=this.Db(a.newValue);f.fromNode=g}}else if("linkToKey"===e){var h=this.yc(a.object);if(null!==h){var k=this.Db(a.newValue);h.toNode=k}}else if("linkFromPortId"===e){var l=this.yc(a.object);if(null!==l){var m=a.newValue; "string"===typeof m&&(l.fromPortId=m)}}else if("linkToPortId"===e){var n=this.yc(a.object);if(null!==n){var p=a.newValue;"string"===typeof p&&(n.toPortId=p)}}else if("nodeGroupKey"===e){var r=this.zc(a.object);if(null!==r){var q=a.newValue;if(void 0!==q){var u=this.Db(q);u instanceof U?r.containingGroup=u:r.containingGroup=null}else r.containingGroup=null}}else if("linkLabelKeys"===e){var v=this.yc(a.object);if(null!==v){var w=a.oldValue,y=a.newValue;Array.isArray(w)&&w.forEach(function(a){0<=y.indexOf(a)|| (a=b.Db(a),null!==a&&(a.labeledLink=null))});Array.isArray(y)&&y.forEach(function(a){a=b.Db(a);null!==a&&(a.labeledLink=v)})}}else if("linkCategory"===e){var z=this.yc(a.object),A=a.newValue;null!==z&&"string"===typeof A&&(z.category=A)}else"linkDataArray"===e&&(Rq(this,a.oldValue),Nq(this,a.newValue));c.isModified=!0}else if(d===Be){var C=a.newValue;if("linkDataArray"===e&&"object"===typeof C&&null!==C)Oq(this,C);else if("linkLabelKeys"===e&&Sq(C)){var F=this.yc(a.object),Q=this.Db(C);null!==F&& null!==Q&&(Q.labeledLink=F)}c.isModified=!0}else{if(d===Ce){var K=a.oldValue;if("linkDataArray"===e&&"object"===typeof K&&null!==K)this.$q(K);else if("linkLabelKeys"===e&&Sq(K)){var T=this.Db(K);null!==T&&(T.labeledLink=null)}c.isModified=!0}}else if(d===ze){var P=a.propertyName;a.object!==c.model||"linkFromKeyProperty"!==P&&"linkToKeyProperty"!==P&&"linkFromPortIdProperty"!==P&&"linkToPortIdProperty"!==P&&"linkLabelKeysProperty"!==P&&"nodeIsGroupProperty"!==P&&"nodeGroupKeyProperty"!==P&&"linkCategoryProperty"!== P||c.undoManager.isUndoingRedoing||this.Md();c.isModified=!0}}finally{c.Z=!0}}}}};Mq.prototype.refreshDataBoundLinks=function(){var a=this,b=this.diagram.model,c=new G,d=b.linkDataArray;d.forEach(function(a){c.add(a)});var e=[];this.links.each(function(a){null===a.data||c.contains(a.data)||e.push(a.data)});e.forEach(function(a){Tq(b,a,!1)});d.forEach(function(c){null===a.yc(c)&&Uq(b,c,!1)})}; Mq.prototype.updateRelationshipsFromData=function(a){var b=a.data;if(null!==b){var c=a.diagram;if(null!==c){var d=c.model;if(a instanceof S){var e=Qq(d,b,!0);e=c.Db(e);a.fromNode=e;e=Qq(d,b,!1);e=c.Db(e);a.toNode=e;b=d.Df(b);if(0<b.length||0<a.labelNodes.count){if(1===b.length&&1===a.labelNodes.count){e=b[0];var f=a.labelNodes.first();if(d.ja(f.data)===e)return}e=(new G).addAll(b);var g=new G;a.labelNodes.each(function(a){null!==a.data&&(a=d.ja(a.data),void 0!==a&&g.add(a))});b=g.copy();b.Zq(e);e= e.copy();e.Zq(g);if(0<b.count||0<e.count)b.each(function(b){b=c.Db(b);null!==b&&b.labeledLink===a&&(b.labeledLink=null)}),e.each(function(b){b=c.Db(b);null!==b&&b.labeledLink!==a&&(b.labeledLink=a)})}}else!(a instanceof Qe)&&(b=d.Kh(b),b=c.findPartForKey(b),null===b||b instanceof U)&&(a.containingGroup=b)}}}; Mq.prototype.resolveReferencesForData=function(a){var b=this.diagram.model,c=b.ja(a);if(void 0!==c){var d=Vq(b,c),e=this.zc(a);if(null!==d&&null!==e){d=d.iterator;for(var f={};d.next();){var g=d.value;b.$a(g)?e instanceof U&&b.Kh(g)===c&&(g=this.zc(g),null!==g&&(g.containingGroup=e)):(f.link=this.yc(g),null!==f.link&&e instanceof W&&(Qq(b,g,!0)===c&&(f.link.fromNode=e),Qq(b,g,!1)===c&&(f.link.toNode=e),g=b.Df(g),Array.isArray(g)&&g.some(function(a){return function(b){return b===c?(e.labeledLink=a.link, !0):!1}}(f))));f={link:f.link}}Wq(b,c)}a=b.Kh(a);void 0!==a&&(a=this.Db(a),a instanceof U&&(e.containingGroup=a))}};Mq.prototype.unresolveReferencesForPart=function(a){var b=this.diagram.model;if(a instanceof W){var c=b.ja(a.data);if(void 0!==c){for(var d=a.linksConnected;d.next();)Xq(b,c,d.value.data);a.isLinkLabel&&(d=a.labeledLink,null!==d&&Xq(b,c,d.data));if(a instanceof U)for(a=a.memberParts;a.next();)d=a.value.data,b.$a(d)&&Xq(b,c,d)}}}; Mq.prototype.copyPartData=function(a,b){var c=wi.prototype.copyPartData.call(this,a,b);if(a instanceof S)if(a=a.data,null!==a&&null!==b){var d=b.model;a=d.xq(a);"object"===typeof a&&null!==a&&(d.bj(a),c=b.yc(a))}else null!==c&&(b=this.diagram,null!==a&&null!==b&&null!==b.commandHandler&&b.commandHandler.copiesClipboardData&&(b=b.model.xq(a),"object"===typeof b&&null!==b&&(c.data=b)));return c}; Mq.prototype.insertLink=function(a,b,c,d){var e=this.diagram,f=e.model,g=e.toolManager.findTool("Linking"),h="";null!==a&&(null===b&&(b=a),h=b.portId,null===h&&(h=""));b="";null!==c&&(null===d&&(d=c),b=d.portId,null===b&&(b=""));d=g.archetypeLinkData;if(d instanceof S){if(Ag(d),f=d.copy(),null!==f)return f.fromNode=a,f.fromPortId=h,f.toNode=c,f.toPortId=b,e.add(f),a=g.archetypeLabelNodeData,a instanceof W&&(Ag(a),a=a.copy(),null!==a&&(a.labeledLink=f,e.add(a))),f}else if(null!==d&&(d=f.xq(d),"object"=== typeof d&&null!==d))return null!==a&&Yq(f,d,f.ja(a.data),!0),Zq(f,d,h,!0),null!==c&&Yq(f,d,f.ja(c.data),!1),Zq(f,d,b,!1),f.bj(d),a=g.archetypeLabelNodeData,null===a||a instanceof W||(a=f.copyNodeData(a),"object"===typeof a&&null!==a&&(f.wf(a),a=f.ja(a),void 0!==a&&f.Cv(d,a))),e.yc(d);return null};Mq.prototype.findLinkForKey=Mq.prototype.findLinkForKey;Mq.prototype.findPartForKey=Mq.prototype.findPartForKey;Mq.prototype.removeAllModeledParts=Mq.prototype.removeAllModeledParts; Mq.prototype.addModeledParts=Mq.prototype.addModeledParts;Mq.prototype.addAllModeledParts=Mq.prototype.addAllModeledParts;Mq.className="GraphLinksPartManager";function $q(){wi.apply(this,arguments);this.rh=null}ma($q,wi); function ar(a,b,c){if(null!==b&&null!==c){var d=a.diagram.toolManager.findTool("Linking"),e=b,f=c;if(a.diagram.isTreePathToChildren)for(b=f.linksConnected;b.next();){if(b.value.toNode===f)return}else for(e=c,f=b,b=e.linksConnected;b.next();)if(b.value.fromNode===e)return;if(null===d||!Qf(d,e,f,null,!0))if(d=a.getLinkCategoryForData(c.data),b=a.findLinkTemplateForCategory(d),null!==b&&(Ag(b),b=b.copy(),null!==b)){var g=a.diagram.skipsModelSourceBindings;a.diagram.skipsModelSourceBindings=!0;b.Pf=d; b.nb=c.data;b.fromNode=e;b.toNode=f;a.diagram.add(b);b.nb=null;b.data=c.data;a.diagram.skipsModelSourceBindings=g}}}$q.prototype.getLinkCategoryForData=function(a){return this.diagram.model.Pt(a)};$q.prototype.setLinkCategoryForData=function(a,b){this.diagram.model.ku(a,b)}; $q.prototype.setFromNodeForLink=function(a,b,c){var d=this.diagram.model;void 0===c&&(c=null);b=null!==b?b.data:null;if(this.diagram.isTreePathToChildren)d.ge(a.data,d.ja(b));else{var e=this.rh;this.rh=a;null!==c&&d.ge(c.data,void 0);d.ge(b,d.ja(null!==a.toNode?a.toNode.data:null));this.rh=e}}; $q.prototype.setToNodeForLink=function(a,b,c){var d=this.diagram.model;void 0===c&&(c=null);b=null!==b?b.data:null;if(this.diagram.isTreePathToChildren){var e=this.rh;this.rh=a;null!==c&&d.ge(c.data,void 0);d.ge(b,d.ja(null!==a.fromNode?a.fromNode.data:null));this.rh=e}else d.ge(a.data,d.ja(b))};$q.prototype.removeDataForLink=function(a){this.diagram.model.ge(a.data,void 0)}; $q.prototype.findLinkForKey=function(a){if(null===a||void 0===a)return null;a=this.diagram.model.Lb(a);return null!==a?this.Ue.H(a):null}; $q.prototype.doModelChanged=function(a){wi.prototype.doModelChanged.call(this,a);if(this.diagram){var b=this.diagram;if(a.model===b.model){var c=a.change;if(b.Z){b.Z=!1;try{var d=a.modelChange;if(""!==d){if(c===ze){if("nodeParentKey"===d){var e=a.object,f=this.Db(a.newValue),g=this.gj(e);if(null!==this.rh)null!==f&&(this.rh.data=e,this.rh.category=this.getLinkCategoryForData(e));else if(null!==g){var h=g.jj();null!==h?null===f?b.remove(h):b.isTreePathToChildren?h.fromNode=f:h.toNode=f:ar(this,f,g)}}else if("parentLinkCategory"=== d){var k=this.gj(a.object),l=a.newValue;if(null!==k&&"string"===typeof l){var m=k.jj();null!==m&&(m.category=l)}}b.isModified=!0}}else if(c===ze){var n=a.propertyName;a.object===b.model&&"nodeParentKeyProperty"===n&&(b.undoManager.isUndoingRedoing||this.Md());b.isModified=!0}}finally{b.Z=!0}}}}}; $q.prototype.updateRelationshipsFromData=function(a){var b=a.data;if(null!==b){var c=a.diagram;if(null!==c){var d=c.model;a instanceof W&&(b=d.Lh(b),b=c.Db(b),d=a.Gg(),b!==d&&(d=a.jj(),null!==b?null!==d?c.isTreePathToChildren?d.fromNode=b:d.toNode=b:ar(this,b,a):null!==d&&Nj(c,d,!1)))}}};$q.prototype.updateDataBindings=function(a,b){wi.prototype.updateDataBindings.call(this,a,b);"string"===typeof b&&null!==this.zc(a)&&(a=this.yc(a),null!==a&&a.Ca(b))}; $q.prototype.resolveReferencesForData=function(a){var b=this.diagram.model,c=b.ja(a);if(void 0!==c){var d=Vq(b,c),e=this.zc(a);if(null!==d&&null!==e){for(d=d.iterator;d.next();){var f=d.value;b.$a(f)&&e instanceof W&&b.Lh(f)===c&&ar(this,e,this.gj(f))}Wq(b,c)}a=b.Lh(a);void 0!==a&&e instanceof W&&(a=this.Db(a),ar(this,a,e))}}; $q.prototype.unresolveReferencesForPart=function(a){var b=this.diagram.model;if(a instanceof W){var c=b.ja(a.data),d=this.yc(a.data);if(null!==d){d.isSelected=!1;d.isHighlighted=!1;var e=d.layer;if(null!==e){var f=e.Nc(-1,d,!1);0<=f&&this.diagram.bb(Ce,"parts",e,d,null,f,null);f=d.layerChanged;null!==f&&f(d,e,null)}}d=this.diagram.isTreePathToChildren;for(a=a.linksConnected;a.next();)e=a.value,e=(d?e.toNode:e.fromNode).data,b.$a(e)&&Xq(b,c,e)}}; $q.prototype.insertLink=function(a,b,c){b=this.diagram.model;var d=a,e=c;this.diagram.isTreePathToChildren||(d=c,e=a);return null!==d&&null!==e?(b.ge(e.data,b.ja(d.data)),e.jj()):null};$q.prototype.findLinkForKey=$q.prototype.findLinkForKey;$q.className="TreePartManager"; function Z(a){this.Ni=new G;this.Ki=new G;this.su=',\n "insertedNodeKeys": ';this.mx=',\n "modifiedNodeData": ';this.uu=',\n "removedNodeKeys": ';this.Xh=null;Za(this);this.Jn=this.Qa="";this.bg=!1;this.l={};this.Hc=[];this.Va=new H;this.Mi="key";this.il=this.Ql=null;this.An=this.Bn=!1;this.Dn=!0;this.hn=null;this.Yj="category";this.Vf=new H;this.bv=new E;this.wg=!1;this.v=null;this.undoManager=new Ee;void 0!==a&&(this.nodeDataArray=a)} Z.prototype.cloneProtected=function(a){a.Qa=this.Qa;a.Jn=this.Jn;a.bg=this.bg;a.Mi=this.Mi;a.Ql=this.Ql;a.il=this.il;a.Bn=this.Bn;a.An=this.An;a.Dn=this.Dn;a.hn=this.hn;a.Yj=this.Yj};Z.prototype.copy=function(){var a=new this.constructor;this.cloneProtected(a);return a};Z.prototype.clear=function(){this.Hc=[];this.Va.clear();this.Vf.clear();this.undoManager.clear()}; Z.prototype.toString=function(a){void 0===a&&(a=0);if(1<a)return this.gr();var b=(""!==this.name?this.name:"")+" Model";if(0<a){b+="\n node data:";a=this.nodeDataArray;for(var c=a.length,d=0;d<c;d++){var e=a[d];b+=" "+this.ja(e)+":"+Ka(e)}}return b}; Z.prototype.eB=function(a){a.change!==Ae&&B("Model.toIncrementalData argument is not a Transaction ChangedEvent:"+a.toString());var b=a.object;if(!(a.isTransactionFinished&&b instanceof De))return null;br(this,b);a=this.Zw(b,"FinishedUndo"===a.propertyName);this.Xh=null;return a}; Z.prototype.Zw=function(a,b){var c=this,d=!1,e=new G,f=new G,g=new G,h=this.Xh;a.changes.each(function(a){a.model===c&&("nodeDataArray"===a.modelChange?a.change===Be?e.add(a.newValue):a.change===Ce&&g.add(a.oldValue):c.$a(a.object)?f.add(a.object):a.change!==ze||c.modelData!==a.object&&"modelData"!==a.propertyName?null!==a.object&&(h&&h.contains(a.object)?h.get(a.object).each(function(a){c.$a(a)&&f.add(a)}):a.object instanceof Z||c.qj()&&c.xc(a.object)||cr(c,a.object).each(function(a){f.add(a)})): d=!0)});var k=this.Ki;k.clear();e.each(function(a){k.add(c.ja(a));b||f.add(a)});var l=this.Ni;l.clear();g.each(function(a){l.add(c.ja(a));b&&f.add(a)});a=c.cloneDeep(f.ma());var m=null;d&&(null===m&&(m={}),m.modelData=this.cloneDeep(this.modelData));0<k.count&&(null===m&&(m={}),b?m.removedNodeKeys=k.ma():m.insertedNodeKeys=k.ma());0<a.length&&(null===m&&(m={}),m.modifiedNodeData=a);0<l.count&&(null===m&&(m={}),b?m.insertedNodeKeys=l.ma():m.removedNodeKeys=l.ma());l.clear();k.clear();return m}; Z.prototype.cloneDeep=function(a){return dr(this,a,!0)}; function dr(a,b,c,d,e,f){function g(a,c){h?(void 0===a.__gohashid&&f.push(a),d.set(a,c)):(a=qb++,d.set(a,c),e.set(a,b))}if(!za(b))return b;f||(f=[]);var h=Object.isExtensible(b);d||(d=new H);if(h){var k=d.get(b);if(k)return k}else for(e||(e=new H),k=e.iterator;k.next();){var l=k.key;if(k.value===b&&(l=d.get(l)))return l}if(Array.isArray(b)){k=[];g(b,k);for(var m=0;m<b.length;m++)k.push(dr(a,b[m],!1,d,e,f))}else if(b instanceof I||b instanceof M||b instanceof N||b instanceof oc||b instanceof O)k=b.copy(), g(b,k);else{if(b instanceof wl||b instanceof td||b instanceof D)return b;if(b instanceof E)k=(new E).addAll(dr(a,b.ma(),!1,d,e,f)),g(b,k);else if(b instanceof G)k=(new G).addAll(dr(a,b.ma(),!1,d,e,f)),g(b,k);else if(b instanceof H)k=(new H).addAll(dr(a,b.ma(),!1,d,e,f)),g(b,k);else if(b instanceof Date)k=new Date(b.getTime()),g(b,k);else if(b instanceof RegExp)k=new RegExp(b),g(b,k),k.lastIndex=b.lastIndex;else if("function"===typeof b.copy)k=b.copy(),g(b,k);else for(m in k={},g(b,k),b)"__gohashid"!== m&&(k[m]=dr(a,b[m],!1,d,e,f))}c&&f.forEach(function(a){delete a.__gohashid});return k}t=Z.prototype; t.Vk=function(){var a="";""!==this.name&&(a+=',\n "name": '+this.quote(this.name));""!==this.dataFormat&&(a+=',\n "dataFormat": '+this.quote(this.dataFormat));this.isReadOnly&&(a+=',\n "isReadOnly": '+this.isReadOnly);"key"!==this.nodeKeyProperty&&"string"===typeof this.nodeKeyProperty&&(a+=',\n "nodeKeyProperty": '+this.quote(this.nodeKeyProperty));this.copiesArrays&&(a+=',\n "copiesArrays": true');this.copiesArrayObjects&&(a+=',\n "copiesArrayObjects": true');this.copiesKey||(a+=',\n "copiesKey": false'); "category"!==this.nodeCategoryProperty&&"string"===typeof this.nodeCategoryProperty&&(a+=',\n "nodeCategoryProperty": '+this.quote(this.nodeCategoryProperty));return a}; t.Xq=function(a){a.name&&(this.name=a.name);a.dataFormat&&(this.dataFormat=a.dataFormat);a.isReadOnly&&(this.isReadOnly=!0);a.nodeKeyProperty&&(this.nodeKeyProperty=a.nodeKeyProperty);a.copiesArrays&&(this.copiesArrays=!0);a.copiesArrayObjects&&(this.copiesArrayObjects=!0);!1===a.copiesKey&&(this.copiesKey=!1);a.nodeCategoryProperty&&(this.nodeCategoryProperty=a.nodeCategoryProperty)};function er(a){return',\n "modelData": '+fr(a,a.modelData)} function gr(a,b){b=b.modelData;za(b)&&(a.Nm(b),a.modelData=b)}t.$w=function(){var a=this.modelData,b=!1,c;for(c in a)if(!hr(c,a[c])){b=!0;break}a="";b&&(a=er(this));return a+',\n "nodeDataArray": '+ir(this,this.nodeDataArray,!0)};t.qw=function(a){gr(this,a);a=a.nodeDataArray;Aa(a)&&(this.Nm(a),this.nodeDataArray=a)}; function jr(a,b,c,d){if(b===c)return!0;if(typeof b!==typeof c||"function"===typeof b||"function"===typeof c)return!1;if(Array.isArray(b)&&Array.isArray(c)){if(d.H(b)===c)return!0;d.add(b,c);if(b.length!==c.length)return!1;for(var e=0;e<b.length;e++)if(!jr(a,b[e],c[e],d))return!1;return!0}if(za(b)&&za(c)){if(d.H(b)===c)return!0;d.add(b,c);for(var f in b){var g=b[f];if(!hr(f,g)){var h=c[f];if(void 0===h||!jr(a,g,h,d))return!1}}for(e in c)if(f=c[e],!hr(e,f)&&(g=b[e],void 0===g||!jr(a,g,f,d)))return!1; return!0}return!1}function kr(a,b,c){a[c]!==b[c]&&B("Model.computeJsonDifference: Model."+c+' is not the same in both models: "'+a[c]+'" and "'+b[c]+'"')} t.lr=function(a){kr(this,a,"nodeKeyProperty");var b=this.Ki;b.clear();var c=new G,d=this.Ni;d.clear();d.addAll(this.Va.iteratorKeys);for(var e=new H,f=a.nodeDataArray,g=f.length,h=0;h<g;h++){var k=f[h],l=a.ja(k);if(void 0!==l){d.remove(l);var m=this.Lb(l);null===m?(b.add(l),c.add(k)):jr(this,m,k,e)||c.add(k)}else this.Zt(k),l=this.ja(k),b.add(l),c.add(k)}f="";jr(this,this.modelData,a.modelData,e)||(f+=er(this));0<b.count&&(f+=this.su+ir(this,b.ma(),!0));0<c.count&&(f+=this.mx+ir(this,c.ma(),!0)); 0<d.count&&(f+=this.uu+ir(this,d.ma(),!0));d.clear();b.clear();return f};t.Dz=function(a,b){void 0===b&&(b=lr(this,this));return'{ "class": '+this.quote(b)+', "incremental": 1'+this.Vk()+this.lr(a)+"}"}; function br(a,b){function c(a,b){if(b=b.part)if(b=b.data,a!==b){var c=d.get(a);null===c?(c=new G,c.add(b),d.add(a,c)):c.add(b)}}var d=a.Xh;null===d&&(d=new H,b.changes.each(function(a){if(null!==a.diagram){var b=a.change;if(b===ze)(a=a.object.panel)&&(b=a.data)&&c(b,a);else if(b===Be||b===Ce)a=a.object,(b=a.itemArray)&&c(b,a)}}),a.Xh=d)}function cr(a,b){for(var c=new G,d=0;d<a.nodeDataArray.length;d++){var e=a.nodeDataArray[d];mr(a,b,e,e,c)}return c} function mr(a,b,c,d,e){if(Array.isArray(c))for(var f=0;f<c.length;f++){var g=c[f];if(g===b)return e.add(d),!0;if(mr(a,b,g,d,e))return!0}else if(za(c)&&Object.getPrototypeOf(c)===Object.prototype)for(f in c){g=c[f];if(g===b)return e.add(d),!0;if(mr(a,b,g,d,e))return!0}return!1} t.Yw=function(a,b){var c=this,d=!1,e=new G,f=new G,g=new G,h=this.Xh;a.changes.each(function(a){a.model===c&&("nodeDataArray"===a.modelChange?a.change===Be?e.add(a.newValue):a.change===Ce&&g.add(a.oldValue):c.$a(a.object)?f.add(a.object):a.change!==ze||c.modelData!==a.object&&"modelData"!==a.propertyName?null!==a.object&&(h&&h.contains(a.object)?h.get(a.object).each(function(a){c.$a(a)&&f.add(a)}):a.object instanceof Z||c.qj()&&c.xc(a.object)||cr(c,a.object).each(function(a){f.add(a)})):d=!0)});var k= this.Ki;k.clear();e.each(function(a){k.add(c.ja(a));b||f.add(a)});var l=this.Ni;l.clear();g.each(function(a){l.add(c.ja(a));b&&f.add(a)});a="";d&&(a+=er(this));0<k.count&&(a+=(b?this.uu:this.su)+ir(this,k.ma(),!0));0<f.count&&(a+=this.mx+ir(this,f.ma(),!0));0<l.count&&(a+=(b?this.su:this.uu)+ir(this,l.ma(),!0));l.clear();k.clear();return a}; t.Wq=function(a){(void 0!==a.name&&a.name!==this.name||void 0!==a.dataFormat&&a.dataFormat!==this.dataFormat||void 0!==a.isReadOnly&&a.isReadOnly!==this.isReadOnly||void 0!==a.nodeKeyProperty&&a.nodeKeyProperty!==this.nodeKeyProperty||void 0!==a.copiesArrays&&a.copiesArrays!==this.copiesArrays||void 0!==a.copiesArrayObjects&&a.copiesArrayObjects!==this.copiesArrayObjects||void 0!==a.copiesKey&&a.copiesKey!==this.copiesKey||void 0!==a.nodeCategoryProperty&&a.nodeCategoryProperty!==this.nodeCategoryProperty)&& B("applyIncrementalJson cannot change Model properties");gr(this,a);var b=a.insertedNodeKeys,c=a.modifiedNodeData,d=new H;if(Array.isArray(c))for(var e=0;e<c.length;e++){var f=c[e],g=this.ja(f);void 0!==g&&null!==g&&d.set(g,f)}if(Array.isArray(b))for(e=b.length,f=0;f<e;f++){g=b[f];var h=this.Lb(g);null===h&&(h=(h=d.get(g))?h:this.copyNodeData({}),this.Um(h,g),this.wf(h))}if(Array.isArray(c))for(b=c.length,d=0;d<b;d++)if(e=c[d],f=this.ja(e),f=this.Lb(f),null!==f){for(var k in e)"__gohashid"===k||k=== this.nodeKeyProperty||this.Bk()&&k===this.nodeIsGroupProperty||this.setDataProperty(f,k,e[k]);this.Vm(e,f)}a=a.removedNodeKeys;if(Array.isArray(a))for(c=a.length,k=0;k<c;k++)b=this.Lb(a[k]),null!==b&&this.Mm(b)}; t.Zy=function(a,b){a.change!==Ae&&B("Model.toIncrementalJson argument is not a Transaction ChangedEvent:"+a.toString());var c=a.object;if(!(a.isTransactionFinished&&c instanceof De))return'{ "incremental": 0 }';void 0===b&&(b=lr(this,this));br(this,c);a=this.Yw(c,"FinishedUndo"===a.propertyName);this.Xh=null;return"2"===b?'{ "incremental": 2'+a+"}":'{ "class": '+this.quote(b)+', "incremental": 1'+this.Vk()+a+"}"};t.fB=function(a,b){return this.Zy(a,b)}; t.gr=function(a){void 0===a&&(a=lr(this,this));return'{ "class": '+this.quote(a)+this.Vk()+this.$w()+"}"};t.toJSON=function(a){return this.gr(a)};t.Yx=function(a){var b=null;if("string"===typeof a)try{b=x.JSON.parse(a)}catch(d){}else"object"===typeof a?b=a:B("Unable to modify a Model from: "+a);var c=b.incremental;"number"!==typeof c&&B("Unable to apply non-incremental changes to Model: "+a);0!==c&&(this.xa("applyIncrementalJson"),this.Wq(b),this.Wa("applyIncrementalJson"))};t.vz=function(a){return this.Yx(a)}; Z.constructGraphLinksModel=function(){return new Z};t=Z.prototype; t.Nm=function(a){if(Aa(a))for(var b=a.length,c=0;c<b;c++){var d=a[c];if(za(d)){var e=c;d=this.Nm(d);Array.isArray(a)?a[e]=d:B("Cannot replace an object in an HTMLCollection or NodeList at "+e)}}else if(za(a)){for(c in a)if(e=a[c],za(e)&&(e=this.Nm(e),a[c]=e,"points"===c&&Array.isArray(e))){d=0===e.length%2;for(var f=0;f<e.length;f++)if("number"!==typeof e[f]){d=!1;break}if(d){d=new E;for(f=0;f<e.length/2;f++)d.add(new I(e[2*f],e[2*f+1]));d.freeze();a[c]=d}}if("object"===typeof a){c=a;e=a["class"]|| "";0===e.indexOf("go.")&&(e=e.substr(3));if("NaN"===e)c=NaN;else if("Date"===e)c=new Date(a.value);else if("Point"===e)c=new I(nr(a.x),nr(a.y));else if("Size"===e)c=new M(nr(a.width),nr(a.height));else if("Rect"===e)c=new N(nr(a.x),nr(a.y),nr(a.width),nr(a.height));else if("Margin"===e)c=new oc(nr(a.top),nr(a.right),nr(a.bottom),nr(a.left));else if("Spot"===e)"string"===typeof a["enum"]?c=kd(a["enum"]):c=new O(nr(a.x),nr(a.y),nr(a.offsetX),nr(a.offsetY));else if("Brush"===e){if(c=new wl,c.type=$a(wl, a.type),"string"===typeof a.color&&(c.color=a.color),a.start instanceof O&&(c.start=a.start),a.end instanceof O&&(c.end=a.end),"number"===typeof a.startRadius&&(c.startRadius=nr(a.startRadius)),"number"===typeof a.endRadius&&(c.endRadius=nr(a.endRadius)),a=a.colorStops,za(a))for(b in a)c.addColorStop(parseFloat(b),a[b])}else"Geometry"===e?(b=null,"string"===typeof a.path?b=Fd(a.path):b=new td,b.type=$a(td,a.type),"number"===typeof a.startX&&(b.startX=nr(a.startX)),"number"===typeof a.startY&&(b.startY= nr(a.startY)),"number"===typeof a.endX&&(b.endX=nr(a.endX)),"number"===typeof a.endY&&(b.endY=nr(a.endY)),a.spot1 instanceof O&&(b.spot1=a.spot1),a.spot2 instanceof O&&(b.spot2=a.spot2),c=b):"EnumValue"===e&&(b=a.classType,0===b.indexOf("go.")&&(b=b.substr(3)),b=or(b),"function"===typeof b&&(c=$a(b,a.name)));a=c}}return a}; t.quote=function(a){for(var b="",c=a.length,d=0;d<c;d++){var e=a[d];if('"'===e||"\\"===e)b+="\\"+e;else if("\b"===e)b+="\\b";else if("\f"===e)b+="\\f";else if("\n"===e)b+="\\n";else if("\r"===e)b+="\\r";else if("\t"===e)b+="\\t";else{var f=a.charCodeAt(d);b=16>f?b+("\\u000"+a.charCodeAt(d).toString(16)):32>f?b+("\\u00"+a.charCodeAt(d).toString(16)):8232===f?b+"\\u2028":8233===f?b+"\\u2029":b+e}}return'"'+b+'"'}; t.$m=function(a){return void 0===a?"undefined":null===a?"null":!0===a?"true":!1===a?"false":"string"===typeof a?this.quote(a):"number"===typeof a?Infinity===a?"9e9999":-Infinity===a?"-9e9999":isNaN(a)?'{"class":"NaN"}':a.toString():a instanceof Date?'{"class":"Date", "value":"'+a.toJSON()+'"}':a instanceof Number?this.$m(a.valueOf()):Aa(a)?ir(this,a):za(a)?fr(this,a):"function"===typeof a?"null":a.toString()}; function ir(a,b,c){void 0===c&&(c=!1);var d=b.length;if(0>=d)return"[]";var e=new bb;e.add("[");c&&1<d&&e.add("\n");for(var f=0;f<d;f++){var g=b[f];void 0!==g&&(0<f&&(e.add(","),c&&e.add("\n")),e.add(a.$m(g)))}c&&1<d&&e.add("\n");e.add("]");return e.toString()}function hr(a,b){return void 0===b||"__gohashid"===a||"_"===a[0]||"function"===typeof b?!0:!1}function qr(a){return isNaN(a)?"NaN":Infinity===a?"9e9999":-Infinity===a?"-9e9999":a} function fr(a,b){var c=b;if(c instanceof I)b={"class":"go.Point",x:qr(c.x),y:qr(c.y)};else if(c instanceof M)b={"class":"go.Size",width:qr(c.width),height:qr(c.height)};else if(c instanceof N)b={"class":"go.Rect",x:qr(c.x),y:qr(c.y),width:qr(c.width),height:qr(c.height)};else if(c instanceof oc)b={"class":"go.Margin",top:qr(c.top),right:qr(c.right),bottom:qr(c.bottom),left:qr(c.left)};else if(c instanceof O)c.kb()?b={"class":"go.Spot",x:qr(c.x),y:qr(c.y),offsetX:qr(c.offsetX),offsetY:qr(c.offsetY)}: b={"class":"go.Spot","enum":c.toString()};else if(c instanceof wl){b={"class":"go.Brush",type:c.type.name};if(c.type===zl)b.color=c.color;else if(c.type===Cl||c.type===xl)b.start=c.start,b.end=c.end,c.type===xl&&(0!==c.startRadius&&(b.startRadius=qr(c.startRadius)),isNaN(c.endRadius)||(b.endRadius=qr(c.endRadius)));if(null!==c.colorStops){var d={};for(c=c.colorStops.iterator;c.next();)d[c.key]=c.value;b.colorStops=d}}else c instanceof td?(b={"class":"go.Geometry",type:c.type.name},0!==c.startX&&(b.startX= qr(c.startX)),0!==c.startY&&(b.startY=qr(c.startY)),0!==c.endX&&(b.endX=qr(c.endX)),0!==c.endY&&(b.endY=qr(c.endY)),c.spot1.w(vc)||(b.spot1=c.spot1),c.spot2.w(Gc)||(b.spot2=c.spot2),c.type===ud&&(b.path=zd(c))):c instanceof D&&(b={"class":"go.EnumValue",classType:lr(a,c.classType),name:c.name});d="{";c=!0;for(var e in b){var f=sn(b,e);if(!hr(e,f))if(c?c=!1:d+=",",d+='"'+e+'":',"points"===e&&f instanceof E){var g="[";for(f=f.iterator;f.next();){var h=f.value;1<g.length&&(g+=",");g+=a.$m(h.x);g+=","; g+=a.$m(h.y)}g+="]";d+=g}else d+=a.$m(f)}return d+"}"}function nr(a){return"number"===typeof a?a:"NaN"===a?NaN:"9e9999"===a?Infinity:"-9e9999"===a?-Infinity:parseFloat(a)}t.Gh=function(a){this.bv.add(a)};t.Sk=function(a){this.bv.remove(a)};t.zt=function(a){this.skipsUndoManager||this.undoManager.$v(a);for(var b=this.bv,c=b.length,d=0;d<c;d++)b.J(d)(a)};t.bb=function(a,b,c,d,e,f,g){rr(this,"",a,b,c,d,e,f,g)};t.g=function(a,b,c,d,e){rr(this,"",ze,a,this,b,c,d,e)}; t.du=function(a,b,c,d,e,f){rr(this,"",ze,b,a,c,d,e,f)};function rr(a,b,c,d,e,f,g,h,k){void 0===h&&(h=null);void 0===k&&(k=null);var l=new ye;l.model=a;l.change=c;l.modelChange=b;l.propertyName=d;l.object=e;l.oldValue=f;l.oldParam=h;l.newValue=g;l.newParam=k;a.zt(l)} Z.prototype.changeState=function(a,b){if(null!==a&&a.model===this)if(a.change===ze){var c=a.object,d=a.propertyName,e=a.H(b);d===this.nodeKeyProperty&&this.$a(c)&&(b=a.H(!b),void 0!==b&&this.Va.remove(b),void 0!==e&&this.Va.add(e,c));Uj(c,d,e)}else a.change===Be?(c=a.newParam,"nodeDataArray"===a.modelChange?(a=a.newValue,za(a)&&"number"===typeof c&&(d=this.ja(a),b?(this.Hc[c]===a&&Da(this.Hc,c),void 0!==d&&this.Va.remove(d)):(this.Hc[c]!==a&&Ca(this.Hc,c,a),void 0!==d&&this.Va.add(d,a)))):""===a.modelChange? ((d=a.object)&&!Aa(d)&&a.propertyName&&(d=sn(a.object,a.propertyName)),Aa(d)&&"number"===typeof c&&(a=a.newValue,b?Da(d,c):Ca(d,c,a))):B("unknown ChangedEvent.Insert modelChange: "+a.toString())):a.change===Ce?(c=a.oldParam,"nodeDataArray"===a.modelChange?(a=a.oldValue,za(a)&&"number"===typeof c&&(d=this.ja(a),b?(this.Hc[c]!==a&&Ca(this.Hc,c,a),void 0!==d&&this.Va.add(d,a)):(this.Hc[c]===a&&Da(this.Hc,c),void 0!==d&&this.Va.remove(d)))):""===a.modelChange?((d=a.object)&&!Aa(d)&&a.propertyName&&(d= sn(a.object,a.propertyName)),Aa(d)&&"number"===typeof c&&(a=a.oldValue,b?Ca(d,c,a):Da(d,c))):B("unknown ChangedEvent.Remove modelChange: "+a.toString())):a.change!==Ae&&B("unknown ChangedEvent: "+a.toString())};Z.prototype.xa=function(a){return this.undoManager.xa(a)};Z.prototype.Wa=function(a){return this.undoManager.Wa(a)};Z.prototype.Kf=function(){return this.undoManager.Kf()}; Z.prototype.commit=function(a,b){void 0===b&&(b="");var c=this.skipsUndoManager;null===b&&(this.skipsUndoManager=!0,b="");this.undoManager.xa(b);var d=!1;try{a(this),d=!0}finally{d?this.undoManager.Wa(b):this.undoManager.Kf(),this.skipsUndoManager=c}};t=Z.prototype;t.Ca=function(a,b){void 0===b&&(b="");rr(this,"SourceChanged",Ae,b,a,null,null)}; t.ja=function(a){if(null!==a){var b=this.Mi;if(""!==b&&(b=sn(a,b),void 0!==b)){if(Sq(b))return b;B("Key value for node data "+a+" is not a number or a string: "+b)}}};t.Um=function(a,b){if(null!==a){var c=this.Mi;if(""!==c)if(this.$a(a)){var d=sn(a,c);d!==b&&null===this.Lb(b)&&(Uj(a,c,b),void 0!==d&&this.Va.remove(d),this.Va.add(b,a),rr(this,"nodeKey",ze,c,a,d,b),"string"===typeof c&&this.Ca(a,c),this.ar(d,b))}else Uj(a,c,b)}};function Sq(a){return"number"===typeof a||"string"===typeof a} t.$a=function(a){var b=this.ja(a);return void 0===b?!1:this.Va.H(b)===a};t.Lb=function(a){null===a&&B("Model.findNodeDataForKey:key must not be null");return void 0!==a&&Sq(a)?this.Va.H(a):null}; t.Zt=function(a){if(null!==a){var b=this.Mi;if(""!==b){var c=this.ja(a);if(void 0===c||this.Va.contains(c)){var d=this.Ql;if(null!==d&&(c=d(this,a),void 0!==c&&null!==c&&!this.Va.contains(c))){Uj(a,b,c);return}if("string"===typeof c){for(d=2;this.Va.contains(c+d);)d++;Uj(a,b,c+d)}else if(void 0===c||"number"===typeof c){for(c=-this.Va.count-1;this.Va.contains(c);)c--;Uj(a,b,c)}}}}};t.wf=function(a){null!==a&&(ob(a),this.$a(a)||Kq(this,a,!0))}; function Kq(a,b,c){var d=a.ja(b);if(void 0===d||a.Va.H(d)!==b)a.Zt(b),d=a.ja(b),void 0===d?B("Model.makeNodeDataKeyUnique failed on "+b+". Data not added to Model."):(a.Va.add(d,b),d=null,c&&(d=a.Hc.length,Ca(a.Hc,d,b)),rr(a,"nodeDataArray",Be,"nodeDataArray",a,null,b,null,d),a.Pm(b),a.Om(b))}t.qz=function(a){if(Aa(a))for(var b=a.length,c=0;c<b;c++)this.wf(a[c]);else for(a=a.iterator;a.next();)this.wf(a.value)};t.Mm=function(a){null!==a&&Jq(this,a,!0)}; function Jq(a,b,c){var d=a.ja(b);void 0!==d&&a.Va.remove(d);d=null;if(c){a:if(c=a.Hc,Array.isArray(c))d=c.indexOf(b);else{d=c.length;for(var e=0;e<d;e++)if(c[e]===b){d=e;break a}d=-1}if(0>d)return;Da(a.Hc,d)}rr(a,"nodeDataArray",Ce,"nodeDataArray",a,b,null,d,null);a.ir(b)}t.VA=function(a){if(Aa(a))for(var b=a.length,c=0;c<b;c++)this.Mm(a[c]);else for(a=a.iterator;a.next();)this.Mm(a.value)}; t.KA=function(a){if(a!==this.nodeDataArray&&Aa(a)){var b=this.Ni;b.clear();b.addAll(this.Va.iteratorKeys);var c=this.Ki;c.clear();for(var d=a.length,e=0;e<d;e++){var f=a[e],g=this.ja(f);if(void 0!==g){c.add(g);var h=this.Lb(g);h!==f&&(null!==h?(this.sq(h,f),this.Vm(f,h)):(f=this.cloneDeep(f),this.Um(f,g),this.wf(f)))}else g=this.cloneDeep(f),this.wf(g),c.add(this.ja(g))}for(a=b.iterator;a.next();)d=a.value,c.contains(d)||(d=this.Lb(d))&&this.Mm(d);b.clear();c.clear()}}; t.ar=function(a,b){void 0!==b&&(a=Vq(this,a),a instanceof G&&this.Vf.add(b,a))};t.Tw=function(){};t.Pm=function(){};t.Om=function(){};t.ir=function(){};function Xq(a,b,c){if(void 0!==b){var d=a.Vf.H(b);null===d&&(d=new G,a.Vf.add(b,d));d.add(c)}}function Wq(a,b,c){if(void 0!==b){var d=a.Vf.H(b);d instanceof G&&(void 0===c||null===c?a.Vf.remove(b):(d.remove(c),0===d.count&&a.Vf.remove(b)))}}function Vq(a,b){if(void 0===b)return null;a=a.Vf.H(b);return a instanceof G?a:null} t.Cz=function(a){void 0===a?this.Vf.clear():this.Vf.remove(a)};Z.prototype.copyNodeData=function(a){if(null===a)return null;var b=this.il;a=null!==b?b(a,this):sr(this,a,!0);za(a)&&Za(a);return a}; function sr(a,b,c){if(a.copiesArrays&&Array.isArray(b)){var d=[];for(c=0;c<b.length;c++){var e=sr(a,b[c],a.copiesArrayObjects);d.push(e)}Za(d);return d}if(c&&za(b)){c=(c=b.constructor)?new c:{};e=a.copiesKey||"string"!==typeof a.nodeKeyProperty?null:a.nodeKeyProperty;for(d in b)if("__gohashid"===d)c.__gohashid=void 0;else if(d===e)c[e]=void 0;else{var f=sn(b,d),g=lr(a,f);"GraphObject"===g||"Diagram"===g||"Layer"===g||"RowColumnDefinition"===g||"AnimationManager"===g||"Tool"===g||"CommandHandler"=== g||"Layout"===g||"InputEvent"===g||"DiagramEvent"===g||f instanceof Z||f instanceof Ee||f instanceof De||f instanceof ye?Uj(c,d,f):(f=sr(a,f,!1),Uj(c,d,f))}Za(c);return c}return b instanceof I?b.copy():b instanceof M?b.copy():b instanceof N?b.copy():b instanceof O?b.copy():b instanceof oc?b.copy():b} Z.prototype.setDataProperty=function(a,b,c){if(this.$a(a)){if(b===this.nodeKeyProperty){this.Um(a,c);return}if(b===this.nodeCategoryProperty){this.Tm(a,c);return}}else!tr&&a instanceof Y&&(tr=!0,xa('Model.setDataProperty is modifying a GraphObject, "'+a.toString()+'"'),xa(" Is that really your intent?"));var d=sn(a,b);d!==c&&(Uj(a,b,c),this.du(a,b,d,c))};t=Z.prototype;t.set=function(a,b,c){this.setDataProperty(a,b,c)}; t.sq=function(a,b){if(b){var c=this.$a(a),d;for(d in b)"__gohashid"===d||c&&d===this.nodeKeyProperty||this.setDataProperty(a,d,b[d])}};t.mz=function(a,b){this.Qt(a,-1,b)};t.Qt=function(a,b,c){0>b&&(b=a.length);Ca(a,b,c);rr(this,"",Be,"",a,null,c,null,b)};t.sw=function(a,b){void 0===b&&(b=-1);a===this.Hc&&B("Model.removeArrayItem should not be called on the Model.nodeDataArray");-1===b&&(b=a.length-1);var c=a[b];Da(a,b);rr(this,"",Ce,"",a,c,null,b,null)}; t.Fq=function(a){if(null===a)return"";var b=this.Yj;if(""===b)return"";b=sn(a,b);if(void 0===b)return"";if("string"===typeof b)return b;B("getCategoryForNodeData found a non-string category for "+a+": "+b);return""};t.Tm=function(a,b){if(null!==a){var c=this.Yj;if(""!==c)if(this.$a(a)){var d=sn(a,c);void 0===d&&(d="");d!==b&&(Uj(a,c,b),rr(this,"nodeCategory",ze,c,a,d,b))}else Uj(a,c,b)}};t.Vm=function(a,b){this.Tm(b,this.Fq(a))};t.Dm=function(){return!1};t.Bk=function(){return!1};t.qj=function(){return!1}; t.Vt=function(){return!1};t.Ck=function(){return!1};function zi(){return new Z}function lr(a,b){if("function"===typeof b){if(b.className)return b.className;if(b.name)return b.name}else if("object"===typeof b&&null!==b&&b.constructor)return lr(a,b.constructor);return typeof b}function or(a){return ur[a]?ur[a]:void 0!==x.go&&x.go[a]?x.go[a]:null} function sn(a,b){if(!a||!b)return null;try{if("function"===typeof b)var c=b(a);else"function"===typeof a.getAttribute?(c=a.getAttribute(b),null===c&&(c=void 0)):c=a[b]}catch(d){}return c}function Uj(a,b,c){if(a&&b)try{"function"===typeof b?b(a,c):"function"===typeof a.setAttribute?a.setAttribute(b,c):a[b]=c}catch(d){}} na.Object.defineProperties(Z.prototype,{name:{get:function(){return this.Qa},set:function(a){var b=this.Qa;b!==a&&(this.Qa=a,this.g("name",b,a))}},dataFormat:{get:function(){return this.Jn},set:function(a){var b=this.Jn;b!==a&&(this.Jn=a,this.g("dataFormat",b,a))}},isReadOnly:{get:function(){return this.bg},set:function(a){var b=this.bg;b!==a&&(this.bg=a,this.g("isReadOnly",b,a))}},modelData:{ get:function(){return this.l},set:function(a){var b=this.l;b!==a&&(this.l=a,this.g("modelData",b,a),this.Ca(a))}},undoManager:{get:function(){return this.v},set:function(a){var b=this.v;b!==a&&(null!==b&&b.Qy(this),this.v=a,null!==a&&a.Wx(this))}},skipsUndoManager:{get:function(){return this.wg},set:function(a){this.wg=a}},nodeKeyProperty:{get:function(){return this.Mi},set:function(a){var b=this.Mi; b!==a&&(""===a&&B("Model.nodeKeyProperty may not be the empty string"),0<this.Va.count&&B("Cannot set Model.nodeKeyProperty when there is existing node data"),this.Mi=a,this.g("nodeKeyProperty",b,a))}},makeUniqueKeyFunction:{get:function(){return this.Ql},set:function(a){var b=this.Ql;b!==a&&(this.Ql=a,this.g("makeUniqueKeyFunction",b,a))}},nodeDataArray:{get:function(){return this.Hc},set:function(a){var b=this.Hc;if(b!==a){this.Va.clear(); this.Tw();for(var c=a.length,d=0;d<c;d++){var e=a[d];if(!za(e)){B("Model.nodeDataArray must only contain Objects, not: "+e);return}ob(e)}this.Hc=a;d=new E;for(e=0;e<c;e++){var f=a[e],g=this.ja(f);void 0===g?d.add(f):null!==this.Va.H(g)?d.add(f):this.Va.add(g,f)}for(d=d.iterator;d.next();)e=d.value,this.Zt(e),f=this.ja(e),void 0!==f&&this.Va.add(f,e);rr(this,"nodeDataArray",ze,"nodeDataArray",this,b,a);for(b=0;b<c;b++)d=a[b],this.Pm(d),this.Om(d);Array.isArray(a)||(this.isReadOnly=!0)}}},copyNodeDataFunction:{ get:function(){return this.il},set:function(a){var b=this.il;b!==a&&(this.il=a,this.g("copyNodeDataFunction",b,a))}},copiesArrays:{get:function(){return this.Bn},set:function(a){var b=this.Bn;b!==a&&(this.Bn=a,this.g("copiesArrays",b,a))}},copiesArrayObjects:{get:function(){return this.An},set:function(a){var b=this.An;b!==a&&(this.An=a,this.g("copiesArrayObjects",b,a))}},copiesKey:{get:function(){return this.Dn}, set:function(a){var b=this.Dn;b!==a&&(this.Dn=a,this.g("copiesKey",b,a))}},afterCopyFunction:{get:function(){return this.hn},set:function(a){var b=this.hn;b!==a&&(this.hn=a,this.g("afterCopyFunction",b,a))}},nodeCategoryProperty:{get:function(){return this.Yj},set:function(a){var b=this.Yj;b!==a&&(this.Yj=a,this.g("nodeCategoryProperty",b,a))}},type:{get:function(){return"Model"}}}); Z.prototype.setCategoryForNodeData=Z.prototype.Tm;Z.prototype.getCategoryForNodeData=Z.prototype.Fq;Z.prototype.removeArrayItem=Z.prototype.sw;Z.prototype.insertArrayItem=Z.prototype.Qt;Z.prototype.addArrayItem=Z.prototype.mz;Z.prototype.assignAllDataProperties=Z.prototype.sq;Z.prototype.set=Z.prototype.set;Z.prototype.clearUnresolvedReferences=Z.prototype.Cz;Z.prototype.mergeNodeDataArray=Z.prototype.KA;Z.prototype.removeNodeDataCollection=Z.prototype.VA;Z.prototype.removeNodeData=Z.prototype.Mm; Z.prototype.addNodeDataCollection=Z.prototype.qz;Z.prototype.addNodeData=Z.prototype.wf;Z.prototype.makeNodeDataKeyUnique=Z.prototype.Zt;Z.prototype.findNodeDataForKey=Z.prototype.Lb;Z.prototype.containsNodeData=Z.prototype.$a;Z.prototype.setKeyForNodeData=Z.prototype.Um;Z.prototype.getKeyForNodeData=Z.prototype.ja;Z.prototype.updateTargetBindings=Z.prototype.Ca;Z.prototype.commit=Z.prototype.commit;Z.prototype.rollbackTransaction=Z.prototype.Kf;Z.prototype.commitTransaction=Z.prototype.Wa; Z.prototype.startTransaction=Z.prototype.xa;Z.prototype.raiseDataChanged=Z.prototype.du;Z.prototype.raiseChanged=Z.prototype.g;Z.prototype.raiseChangedEvent=Z.prototype.bb;Z.prototype.removeChangedListener=Z.prototype.Sk;Z.prototype.addChangedListener=Z.prototype.Gh;Z.prototype.writeJsonValue=Z.prototype.$m;Z.prototype.replaceJsonObjects=Z.prototype.Nm;Z.prototype.applyIncrementalJSON=Z.prototype.vz;Z.prototype.applyIncrementalJson=Z.prototype.Yx;Z.prototype.toJSON=Z.prototype.toJSON; Z.prototype.toJson=Z.prototype.gr;Z.prototype.toIncrementalJSON=Z.prototype.fB;Z.prototype.toIncrementalJson=Z.prototype.Zy;Z.prototype.computeJsonDifference=Z.prototype.Dz;Z.prototype.toIncrementalData=Z.prototype.eB;Z.prototype.clear=Z.prototype.clear;var tr=!1,ur={};Z.className="Model"; Z.fromJSON=Z.fromJson=function(a,b){void 0===b&&(b=null);var c=null;if("string"===typeof a)try{c=x.JSON.parse(a)}catch(f){}else"object"===typeof a?c=a:B("Unable to construct a Model from: "+a);if(null===b){a=null;var d=c["class"];if("string"===typeof d)try{var e=null;0===d.indexOf("go.")?(d=d.substr(3),e=or(d)):(e=or(d),null===e&&(e=x[d]));"function"===typeof e&&(a=new e)}catch(f){}null===a||a instanceof Z?b=a:B("Unable to construct a Model of declared class: "+c["class"])}null===b&&(b=Z.constructGraphLinksModel()); b.Xq(c);b.qw(c);return b};Z.safePropertyValue=sn;Z.safePropertySet=Uj;ur.Brush=wl;ur.ChangedEvent=ye;ur.Geometry=td;ur.Margin=oc;ur.Panel=X;ur.Point=I;ur.Rect=N;ur.Size=M;ur.Spot=O;ur.Transaction=De;ur.UndoManager=Ee;function Ni(a,b,c){Za(this);this.u=!1;void 0===a&&(a="");void 0===b&&(b=a);void 0===c&&(c=null);this.l=-1;this.qd=null;this.om=a;this.nm=this.eq=0;this.ht=null;this.vo=!1;this.gm=b;this.zn=c;this.Uo=vr;this.sn=null;this.Nu=new G} Ni.prototype.copy=function(){var a=new Ni;a.om=this.om;a.eq=this.eq;a.nm=this.nm;a.ht=this.ht;a.vo=this.vo;a.gm=this.gm;a.zn=this.zn;a.Uo=this.Uo;a.sn=this.sn;return a};t=Ni.prototype;t.jb=function(a){a.classType===Ni&&(this.mode=a)};t.toString=function(){return"Binding("+this.targetProperty+":"+this.sourceProperty+(-1!==this.wj?" "+this.wj:"")+" "+this.mode.name+")"};t.freeze=function(){this.u=!0;return this};t.ea=function(){this.u=!1;return this}; t.Jy=function(a){void 0===a&&(a=null);this.mode=ln;this.backConverter=a;return this};t.Tq=function(a){void 0===a&&(a="");this.sourceName=a;this.isToModel=!1;return this};t.MA=function(){this.sourceName=null;this.isToModel=!0;return this};function jl(a,b,c){a=a.sourceName;return null===a||""===a?b:"/"===a?c.part:"."===a?c:".."===a?c.panel:b.ab(a)} t.Uw=function(a,b,c){var d=this.gm;if(void 0===c||""===d||d===c){c=this.om;var e=this.zn;if(null===e&&""===c)xa("Binding error: target property is the empty string: "+this.toString());else{var f=b;""!==d&&(f=sn(b,d));if(void 0!==f)if(null===e)""!==c&&Uj(a,c,f);else try{if(""!==c){var g=e(f,a);Uj(a,c,g)}else e(f,a)}catch(h){}}}}; t.kr=function(a,b,c,d){if(this.Uo===ln){var e=this.om;if(void 0===c||e===c){c=this.gm;var f=this.sn,g=a;""!==e&&(g=sn(a,e));if(void 0!==g&&!this.Nu.contains(a))try{this.Nu.add(a);var h=null!==d?d.diagram:null,k=null!==h?h.model:null;if(null===f)if(""!==c)null!==k?k.setDataProperty(b,c,g):Uj(b,c,g);else{if(null!==k&&null!==d&&0<=d.itemIndex&&null!==d.panel&&Array.isArray(d.panel.itemArray)){var l=d.itemIndex,m=d.panel.itemArray;k.sw(m,l);k.Qt(m,l,g)}}else try{if(""!==c){var n=f(g,b,k);null!==k?k.setDataProperty(b, c,n):Uj(b,c,n)}else{var p=f(g,b,k);if(void 0!==p&&null!==k&&null!==d&&0<=d.itemIndex&&null!==d.panel&&Array.isArray(d.panel.itemArray)){var r=d.itemIndex,q=d.panel.itemArray;k.sw(q,r);k.Qt(q,r,p)}}}catch(u){}}finally{this.Nu.remove(a)}}}}; na.Object.defineProperties(Ni.prototype,{wj:{get:function(){return this.l},set:function(a){this.u&&va(this);this.l=a}},targetProperty:{get:function(){return this.om},set:function(a){this.u&&va(this);this.om=a}},sourceName:{get:function(){return this.ht},set:function(a){this.u&&va(this);this.ht=a;null!==a&&(this.vo=!1)}},isToModel:{get:function(){return this.vo},set:function(a){this.u&& va(this);this.vo=a}},sourceProperty:{get:function(){return this.gm},set:function(a){this.u&&va(this);this.gm=a}},converter:{get:function(){return this.zn},set:function(a){this.u&&va(this);this.zn=a}},backConverter:{get:function(){return this.sn},set:function(a){this.u&&va(this);this.sn=a}},mode:{get:function(){return this.Uo},set:function(a){this.u&&va(this);this.Uo=a}}}); Ni.prototype.updateSource=Ni.prototype.kr;Ni.prototype.updateTarget=Ni.prototype.Uw;Ni.prototype.ofModel=Ni.prototype.MA;Ni.prototype.ofObject=Ni.prototype.Tq;Ni.prototype.makeTwoWay=Ni.prototype.Jy;var Mk="Binding",vr=new D(Ni,"OneWay",1),ln=new D(Ni,"TwoWay",2);Ni.className="Binding";Ni.parseEnum=function(a,b){return function(c){c=$a(a,c);return null===c?b:c}};Ni.toString=Ka;Ni.OneWay=vr;Ni.TwoWay=ln; function wr(a,b){Z.call(this);this.ru=',\n "insertedLinkKeys": ';this.lx=',\n "modifiedLinkData": ';this.tu=',\n "removedLinkKeys": ';this.bd=[];this.cg=new G;this.gb=new H;this.Gi="";this.Aj=this.hl=this.Rl=null;this.bf="from";this.cf="to";this.Vj=this.Uj="";this.Tj="category";this.ae="";this.Vl="isGroup";this.Ae="group";this.Cn=!1;void 0!==a&&(this.nodeDataArray=a);void 0!==b&&(this.linkDataArray=b)}ma(wr,Z);wr.constructGraphLinksModel=Z.constructGraphLinksModel; wr.prototype.cloneProtected=function(a){Z.prototype.cloneProtected.call(this,a);a.Gi=this.Gi;a.Rl=this.Rl;a.hl=this.hl;a.bf=this.bf;a.cf=this.cf;a.Uj=this.Uj;a.Vj=this.Vj;a.Tj=this.Tj;a.ae=this.ae;a.Vl=this.Vl;a.Ae=this.Ae;a.Cn=this.Cn};t=wr.prototype;t.clear=function(){Z.prototype.clear.call(this);this.bd=[];this.gb.clear();this.cg.clear()}; t.toString=function(a){void 0===a&&(a=0);if(2<=a)return this.gr();var b=(""!==this.name?this.name:"")+" GraphLinksModel";if(0<a){b+="\n node data:";a=this.nodeDataArray;var c=a.length,d;for(d=0;d<c;d++){var e=a[d];b+=" "+this.ja(e)+":"+Ka(e)}b+="\n link data:";a=this.linkDataArray;c=a.length;for(d=0;d<c;d++)e=a[d],b+=" "+Qq(this,e,!0)+"--\x3e"+Qq(this,e,!1)}return b}; t.Zw=function(a,b){""===this.linkKeyProperty&&B("GraphLinksModel.linkKeyProperty must not be an empty string for .toIncrementalData() to succeed.");var c=Z.prototype.Zw.call(this,a,b),d=this,e=new G,f=new G,g=new G,h=this.Xh;a.changes.each(function(a){a.model===d&&("linkDataArray"===a.modelChange?a.change===Be?e.add(a.newValue):a.change===Ce&&g.add(a.oldValue):d.xc(a.object)?f.add(a.object):null!==a.object&&(null!==a.object&&h&&h.contains(a.object)?h.get(a.object).each(function(a){d.xc(a)&&f.add(a)}): a.object instanceof Z||d.$a(a.object)||xr(d,a.object).each(function(a){f.add(a)})))});var k=this.Ki;k.clear();e.each(function(a){k.add(d.Wb(a));b||f.add(a)});var l=this.Ni;l.clear();g.each(function(a){l.add(d.Wb(a));b&&f.add(a)});a=d.cloneDeep(f.ma());0<k.count&&(null===c&&(c={}),b?c.removedLinkKeys=k.ma():c.insertedLinkKeys=k.ma());0<a.length&&(null===c&&(c={}),c.modifiedLinkData=a);0<l.count&&(null===c&&(c={}),b?c.insertedLinkKeys=l.ma():c.removedLinkKeys=l.ma());l.clear();k.clear();return c}; t.Vk=function(){var a=Z.prototype.Vk.call(this),b="";"category"!==this.linkCategoryProperty&&"string"===typeof this.linkCategoryProperty&&(b+=',\n "linkCategoryProperty": '+this.quote(this.linkCategoryProperty));""!==this.linkKeyProperty&&"string"===typeof this.linkKeyProperty&&(b+=',\n "linkKeyProperty": '+this.quote(this.linkKeyProperty));"from"!==this.linkFromKeyProperty&&"string"===typeof this.linkFromKeyProperty&&(b+=',\n "linkFromKeyProperty": '+this.quote(this.linkFromKeyProperty));"to"!== this.linkToKeyProperty&&"string"===typeof this.linkToKeyProperty&&(b+=',\n "linkToKeyProperty": '+this.quote(this.linkToKeyProperty));""!==this.linkFromPortIdProperty&&"string"===typeof this.linkFromPortIdProperty&&(b+=',\n "linkFromPortIdProperty": '+this.quote(this.linkFromPortIdProperty));""!==this.linkToPortIdProperty&&"string"===typeof this.linkToPortIdProperty&&(b+=',\n "linkToPortIdProperty": '+this.quote(this.linkToPortIdProperty));""!==this.linkLabelKeysProperty&&"string"===typeof this.linkLabelKeysProperty&& (b+=',\n "linkLabelKeysProperty": '+this.quote(this.linkLabelKeysProperty));"isGroup"!==this.nodeIsGroupProperty&&"string"===typeof this.nodeIsGroupProperty&&(b+=',\n "nodeIsGroupProperty": '+this.quote(this.nodeIsGroupProperty));"group"!==this.nodeGroupKeyProperty&&"string"===typeof this.nodeGroupKeyProperty&&(b+=',\n "nodeGroupKeyProperty": '+this.quote(this.nodeGroupKeyProperty));return a+b}; t.Xq=function(a){Z.prototype.Xq.call(this,a);a.linkKeyProperty&&(this.linkKeyProperty=a.linkKeyProperty);a.linkFromKeyProperty&&(this.linkFromKeyProperty=a.linkFromKeyProperty);a.linkToKeyProperty&&(this.linkToKeyProperty=a.linkToKeyProperty);a.linkFromPortIdProperty&&(this.linkFromPortIdProperty=a.linkFromPortIdProperty);a.linkToPortIdProperty&&(this.linkToPortIdProperty=a.linkToPortIdProperty);a.linkCategoryProperty&&(this.linkCategoryProperty=a.linkCategoryProperty);a.linkLabelKeysProperty&&(this.linkLabelKeysProperty= a.linkLabelKeysProperty);a.nodeIsGroupProperty&&(this.nodeIsGroupProperty=a.nodeIsGroupProperty);a.nodeGroupKeyProperty&&(this.nodeGroupKeyProperty=a.nodeGroupKeyProperty)};t.$w=function(){var a=Z.prototype.$w.call(this),b=',\n "linkDataArray": '+ir(this,this.linkDataArray,!0);return a+b};t.qw=function(a){Z.prototype.qw.call(this,a);a=a.linkDataArray;Array.isArray(a)&&(this.Nm(a),this.linkDataArray=a)}; t.lr=function(a){if(!(a instanceof wr))return B("Model.computeJsonDifference: newmodel must be a GraphLinksModel"),"";""===this.linkKeyProperty&&B("GraphLinksModel.linkKeyProperty must not be an empty string for .computeJsonDifference() to succeed.");var b=Z.prototype.lr.call(this,a);kr(this,a,"linkKeyProperty");kr(this,a,"linkFromKeyProperty");kr(this,a,"linkToKeyProperty");kr(this,a,"linkLabelKeysProperty");kr(this,a,"nodeIsGroupProperty");kr(this,a,"nodeGroupKeyProperty");var c=this.Ki;c.clear(); var d=new G,e=this.Ni;e.clear();e.addAll(this.gb.iteratorKeys);for(var f=new H,g=a.linkDataArray,h=g.length,k=0;k<h;k++){var l=g[k],m=a.Wb(l);if(void 0!==m){e.remove(m);var n=this.Eg(m);null===n?(c.add(m),d.add(l)):jr(this,n,l,f)||d.add(l)}else this.Qq(l),m=this.Wb(l),c.add(m),d.add(l)}a=b;0<c.count&&(a+=this.ru+ir(this,c.ma(),!0));0<d.count&&(a+=this.lx+ir(this,d.ma(),!0));0<e.count&&(a+=this.tu+ir(this,e.ma(),!0));e.clear();c.clear();return a}; function xr(a,b){for(var c=new G,d=0;d<a.linkDataArray.length;d++){var e=a.linkDataArray[d];mr(a,b,e,e,c)}return c} t.Yw=function(a,b){""===this.linkKeyProperty&&B("GraphLinksModel.linkKeyProperty must not be an empty string for .toIncrementalJson() to succeed.");var c=Z.prototype.Yw.call(this,a,b),d=this,e=new G,f=new G,g=new G,h=this.Xh;a.changes.each(function(a){a.model===d&&("linkDataArray"===a.modelChange?a.change===Be?e.add(a.newValue):a.change===Ce&&g.add(a.oldValue):d.xc(a.object)?f.add(a.object):null!==a.object&&(null!==a.object&&h&&h.contains(a.object)?h.get(a.object).each(function(a){d.xc(a)&&f.add(a)}): a.object instanceof Z||d.$a(a.object)||xr(d,a.object).each(function(a){f.add(a)})))});var k=this.Ki;k.clear();e.each(function(a){k.add(d.Wb(a));b||f.add(a)});var l=this.Ni;l.clear();g.each(function(a){l.add(d.Wb(a));b&&f.add(a)});a=c;0<k.count&&(a+=(b?this.tu:this.ru)+ir(this,k.ma(),!0));0<f.count&&(a+=this.lx+ir(this,f.ma(),!0));0<l.count&&(a+=(b?this.ru:this.tu)+ir(this,l.ma(),!0));l.clear();k.clear();return a}; t.Wq=function(a){(void 0!==a.linkCategoryProperty&&a.linkCategoryProperty!==this.linkCategoryProperty||void 0!==a.linkKeyProperty&&a.linkKeyProperty!==this.linkKeyProperty||void 0!==a.linkFromKeyProperty&&a.linkFromKeyProperty!==this.linkFromKeyProperty||void 0!==a.linkToKeyProperty&&a.linkToKeyProperty!==this.linkToKeyProperty||void 0!==a.linkFromPortIdProperty&&a.linkFromPortIdProperty!==this.linkFromPortIdProperty||void 0!==a.linkToPortIdProperty&&a.linkToPortIdProperty!==this.linkToPortIdProperty|| void 0!==a.linkLabelKeysProperty&&a.linkLabelKeysProperty!==this.linkLabelKeysProperty||void 0!==a.nodeIsGroupProperty&&a.nodeIsGroupProperty!==this.nodeIsGroupProperty||void 0!==a.nodeGroupKeyProperty&&a.nodeGroupKeyProperty!==this.nodeGroupKeyProperty)&&B("applyIncrementalJson cannot change Model properties");Z.prototype.Wq.call(this,a);var b=a.insertedLinkKeys;if(Array.isArray(b))for(var c=b.length,d=0;d<c;d++){var e=b[d],f=this.Eg(e);null===f&&(f=this.xq({}),this.iu(f,e),this.bj(f))}b=a.modifiedLinkData; if(Array.isArray(b))for(c=b.length,d=0;d<c;d++)if(e=b[d],f=this.Wb(e),f=this.Eg(f),null!==f){for(var g in e)"__gohashid"!==g&&g!==this.linkKeyProperty&&this.setDataProperty(f,g,e[g]);yr(this,e,f)}a=a.removedLinkKeys;if(Array.isArray(a))for(g=a.length,b=0;b<g;b++)c=this.Eg(a[b]),null!==c&&this.Lm(c)}; wr.prototype.changeState=function(a,b){if(null!==a&&a.model===this){if(a.change===ze){var c=a.object,d=a.propertyName;if(d===this.linkKeyProperty&&this.xc(c)){var e=a.H(b);b=a.H(!b);void 0!==b&&this.gb.remove(b);void 0!==e&&this.gb.add(e,c);Uj(c,d,e);return}}else if(a.change===Be){c=a.newParam;if("linkDataArray"===a.modelChange){a=a.newValue;za(a)&&"number"===typeof c&&(d=this.Wb(a),b?(this.cg.remove(a),this.bd[c]===a&&this.bd.splice(c,1),void 0!==d&&this.gb.remove(d)):(this.cg.add(a),this.bd[c]!== a&&this.bd.splice(c,0,a),void 0!==d&&this.gb.add(d,a)));return}if("linkLabelKeys"===a.modelChange){d=this.Df(a.object);Array.isArray(d)&&"number"===typeof c&&(b?(c=d.indexOf(a.newValue),0<=c&&d.splice(c,1)):0>d.indexOf(a.newValue)&&d.splice(c,0,a.newValue));return}}else if(a.change===Ce){c=a.oldParam;if("linkDataArray"===a.modelChange){a=a.oldValue;za(a)&&"number"===typeof c&&(d=this.Wb(a),b?(this.cg.add(a),this.bd[c]!==a&&this.bd.splice(c,0,a),void 0!==d&&this.gb.add(d,a)):(this.cg.remove(a),this.bd[c]=== a&&this.bd.splice(c,1),void 0!==d&&this.gb.remove(d)));return}if("linkLabelKeys"===a.modelChange){d=this.Df(a.object);Array.isArray(d)&&"number"===typeof c&&(b?0>d.indexOf(a.newValue)&&d.splice(c,0,a.newValue):(c=d.indexOf(a.newValue),0<=c&&d.splice(c,1)));return}}Z.prototype.changeState.call(this,a,b)}};t=wr.prototype;t.Fm=function(a){if(void 0!==a){var b=this.Aj;if(null!==b){var c=this.Lb(a);null===c&&(c=this.copyNodeData(b),Uj(c,this.nodeKeyProperty,a),this.wf(c))}return a}}; t.xy=function(a){return Qq(this,a,!0)};t.Cw=function(a,b){Yq(this,a,b,!0)};t.Ay=function(a){return Qq(this,a,!1)};t.Hw=function(a,b){Yq(this,a,b,!1)};function Qq(a,b,c){if(null!==b&&(a=c?a.bf:a.cf,""!==a&&(a=sn(b,a),void 0!==a))){if(Sq(a))return a;B((c?"FromKey":"ToKey")+" value for link data "+b+" is not a number or a string: "+a)}} function Yq(a,b,c,d){null===c&&(c=void 0);if(null!==b){var e=d?a.bf:a.cf;if(""!==e)if(c=a.Fm(c),a.xc(b)){var f=sn(b,e);f!==c&&(Wq(a,f,b),Uj(b,e,c),null===a.Lb(c)&&Xq(a,c,b),rr(a,d?"linkFromKey":"linkToKey",ze,e,b,f,c),"string"===typeof e&&a.Ca(b,e))}else Uj(b,e,c)}}t.yy=function(a){return Pq(this,a,!0)};t.Dw=function(a,b){Zq(this,a,b,!0)};t.By=function(a){return Pq(this,a,!1)};t.Iw=function(a,b){Zq(this,a,b,!1)}; function Pq(a,b,c){if(null===b)return"";a=c?a.Uj:a.Vj;if(""===a)return"";b=sn(b,a);return void 0===b?"":b}function Zq(a,b,c,d){if(null!==b){var e=d?a.Uj:a.Vj;if(""!==e)if(a.xc(b)){var f=sn(b,e);void 0===f&&(f="");f!==c&&(Uj(b,e,c),rr(a,d?"linkFromPortId":"linkToPortId",ze,e,b,f,c),"string"===typeof e&&a.Ca(b,e))}else Uj(b,e,c)}}t.Df=function(a){if(null===a)return zr;var b=this.ae;if(""===b)return zr;a=sn(a,b);return void 0===a?zr:a}; t.ju=function(a,b){if(null!==a){var c=this.ae;if(""!==c)if(this.xc(a)){var d=sn(a,c);void 0===d&&(d=zr);if(d!==b){if(Array.isArray(d))for(var e=d.length,f=0;f<e;f++)Wq(this,d[f],a);Uj(a,c,b);e=b.length;for(f=0;f<e;f++){var g=b[f];null===this.Lb(g)&&Xq(this,g,a)}rr(this,"linkLabelKeys",ze,c,a,d,b);"string"===typeof c&&this.Ca(a,c)}}else Uj(a,c,b)}}; t.Cv=function(a,b){if(null!==b&&void 0!==b&&null!==a){var c=this.ae;if(""!==c){var d=sn(a,c);if(void 0===d)c=[],c.push(b),this.ju(a,c);else if(Array.isArray(d)){var e=d.indexOf(b);0<=e||(e=d.length,d.push(b),this.xc(a)&&(null===this.Lb(b)&&Xq(this,b,a),rr(this,"linkLabelKeys",Be,c,a,null,b,null,e)))}else B(c+" property is not an Array; cannot addLabelKeyForLinkData: "+a)}}}; t.Py=function(a,b){if(null!==b&&void 0!==b&&null!==a){var c=this.ae;if(""!==c){var d=sn(a,c);if(Array.isArray(d)){var e=d.indexOf(b);0>e||(d.splice(e,1),this.xc(a)&&(Wq(this,b,a),rr(this,"linkLabelKeys",Ce,c,a,b,null,e,null)))}else void 0!==d&&B(c+" property is not an Array; cannot removeLabelKeyforLinkData: "+a)}}};t.Wb=function(a){if(null!==a){var b=this.Gi;if(""!==b&&(b=sn(a,b),void 0!==b)){if(Sq(b))return b;B("Key value for link data "+a+" is not a number or a string: "+b)}}}; t.iu=function(a,b){if(null!==a){var c=this.Gi;if(""!==c)if(this.xc(a)){var d=sn(a,c);d!==b&&null===this.Eg(b)&&(Uj(a,c,b),void 0!==d&&this.gb.remove(d),this.gb.add(b,a),rr(this,"linkKey",ze,c,a,d,b),"string"===typeof c&&this.Ca(a,c))}else Uj(a,c,b)}};t.Eg=function(a){null===a&&B("GraphLinksModel.findLinkDataForKey:key must not be null");return void 0!==a&&Sq(a)?this.gb.H(a):null}; t.Qq=function(a){if(null!==a){var b=this.Gi;if(""!==b){var c=this.Wb(a);if(void 0===c||this.gb.contains(c)){var d=this.Rl;if(null!==d&&(c=d(this,a),void 0!==c&&null!==c&&!this.gb.contains(c))){Uj(a,b,c);return}if("string"===typeof c){for(d=2;this.gb.contains(c+d);)d++;Uj(a,b,c+d)}else if(void 0===c||"number"===typeof c){for(c=-this.gb.count-1;this.gb.contains(c);)c--;Uj(a,b,c)}}}}};t.xc=function(a){return null===a?!1:this.cg.contains(a)};t.bj=function(a){null!==a&&(ob(a),this.xc(a)||Uq(this,a,!0))}; function Uq(a,b,c){if(""!==a.linkKeyProperty){var d=a.Wb(b);if(void 0!==d&&a.gb.H(d)===b)return;a.Qq(b);d=a.Wb(b);if(void 0===d){B("GraphLinksModel.makeLinkDataKeyUnique failed on "+b+". Data not added to model.");return}a.gb.add(d,b)}a.cg.add(b);d=null;c&&(d=a.bd.length,a.bd.splice(d,0,b));rr(a,"linkDataArray",Be,"linkDataArray",a,null,b,null,d);Ar(a,b)}t.pz=function(a){if(Array.isArray(a))for(var b=a.length,c=0;c<b;c++)this.bj(a[c]);else for(a=a.iterator;a.next();)this.bj(a.value)}; t.Lm=function(a){null!==a&&Tq(this,a,!0)};function Tq(a,b,c){a.cg.remove(b);var d=a.Wb(b);void 0!==d&&a.gb.remove(d);d=null;if(c){d=a.bd.indexOf(b);if(0>d)return;a.bd.splice(d,1)}rr(a,"linkDataArray",Ce,"linkDataArray",a,b,null,d,null);c=Qq(a,b,!0);Wq(a,c,b);c=Qq(a,b,!1);Wq(a,c,b);d=a.Df(b);if(Array.isArray(d))for(var e=d.length,f=0;f<e;f++)c=d[f],Wq(a,c,b)}t.TA=function(a){if(Array.isArray(a))for(var b=a.length,c=0;c<b;c++)this.Lm(a[c]);else for(a=a.iterator;a.next();)this.Lm(a.value)}; t.JA=function(a){""===this.linkKeyProperty&&B("GraphLinksModel.linkKeyProperty must not be an empty string for .mergeLinkDataArray() to succeed.");if(a!==this.linkDataArray&&Aa(a)){var b=this.Ni;b.clear();b.addAll(this.gb.iteratorKeys);var c=this.Ki;c.clear();for(var d=a.length,e=0;e<d;e++){var f=a[e],g=this.Wb(f);if(void 0!==g){c.add(g);var h=this.Eg(g);h!==f&&(null!==h?(this.sq(h,f),yr(this,f,h)):(f=this.cloneDeep(f),this.iu(f,g),this.bj(f)))}else g=this.cloneDeep(f),this.bj(g),c.add(this.Wb(g))}for(a= b.iterator;a.next();)d=a.value,c.contains(d)||(d=this.Eg(d))&&this.Lm(d);b.clear();c.clear()}};function Ar(a,b){var c=Qq(a,b,!0);c=a.Fm(c);null===a.Lb(c)&&Xq(a,c,b);c=Qq(a,b,!1);c=a.Fm(c);null===a.Lb(c)&&Xq(a,c,b);var d=a.Df(b);if(Array.isArray(d))for(var e=d.length,f=0;f<e;f++)c=d[f],null===a.Lb(c)&&Xq(a,c,b)} t.xq=function(a){if(null===a)return null;var b=this.hl;a=null!==b?b(a,this):sr(this,a,!0);za(a)&&(Za(a),""!==this.bf&&Uj(a,this.bf,void 0),""!==this.cf&&Uj(a,this.cf,void 0),""!==this.ae&&Uj(a,this.ae,[]));return a};t.ew=function(a){if(null===a)return!1;var b=this.Vl;return""===b?!1:sn(a,b)?!0:!1};t.Kh=function(a){if(null!==a){var b=this.Ae;if(""!==b&&(b=sn(a,b),void 0!==b)){if(Sq(b))return b;B("GroupKey value for node data "+a+" is not a number or a string: "+b)}}}; t.dr=function(a,b){null===b&&(b=void 0);if(null!==a){var c=this.Ae;if(""!==c)if(this.$a(a)){var d=sn(a,c);d!==b&&(Wq(this,d,a),Uj(a,c,b),null===this.Lb(b)&&Xq(this,b,a),rr(this,"nodeGroupKey",ze,c,a,d,b),"string"===typeof c&&this.Ca(a,c))}else Uj(a,c,b)}};wr.prototype.copyNodeData=function(a){if(null===a)return null;a=Z.prototype.copyNodeData.call(this,a);this.rk||""===this.Ae||void 0===sn(a,this.Ae)||Uj(a,this.Ae,void 0);return a}; wr.prototype.setDataProperty=function(a,b,c){if(this.$a(a)){if(b===this.nodeKeyProperty){this.Um(a,c);return}if(b===this.nodeCategoryProperty){this.Tm(a,c);return}if(b===this.nodeGroupKeyProperty){this.dr(a,c);return}}else if(this.xc(a)){if(b===this.linkFromKeyProperty){Yq(this,a,c,!0);return}if(b===this.linkToKeyProperty){Yq(this,a,c,!1);return}if(b===this.linkFromPortIdProperty){Zq(this,a,c,!0);return}if(b===this.linkToPortIdProperty){Zq(this,a,c,!1);return}if(b===this.linkKeyProperty){this.iu(a, c);return}if(b===this.linkCategoryProperty){this.cr(a,c);return}if(b===this.linkLabelKeysProperty){this.ju(a,c);return}}var d=sn(a,b);d!==c&&(Uj(a,b,c),this.du(a,b,d,c))};t=wr.prototype;t.sq=function(a,b){if(b){var c=this.$a(a),d=this.xc(a),e;for(e in b)"__gohashid"===e||c&&e===this.nodeKeyProperty||c&&e===this.nodeIsGroupProperty&&sn(a,e)===b[e]||d&&e===this.linkKeyProperty||this.setDataProperty(a,e,b[e])}}; t.ar=function(a,b){Z.prototype.ar.call(this,a,b);for(var c=this.Va.iterator;c.next();)this.ww(c.value,a,b);for(c=this.cg.iterator;c.next();){var d=c.value,e=a,f=b;if(Qq(this,d,!0)===e){var g=this.bf;Uj(d,g,f);rr(this,"linkFromKey",ze,g,d,e,f);"string"===typeof g&&this.Ca(d,g)}Qq(this,d,!1)===e&&(g=this.cf,Uj(d,g,f),rr(this,"linkToKey",ze,g,d,e,f),"string"===typeof g&&this.Ca(d,g));g=this.Df(d);if(Array.isArray(g))for(var h=g.length,k=this.ae,l=0;l<h;l++)g[l]===e&&(g[l]=f,rr(this,"linkLabelKeys",Be, k,d,e,f,l,l))}};t.ww=function(a,b,c){if(this.Kh(a)===b){var d=this.Ae;Uj(a,d,c);rr(this,"nodeGroupKey",ze,d,a,b,c);"string"===typeof d&&this.Ca(a,d)}};t.Tw=function(){Z.prototype.Tw.call(this);for(var a=this.linkDataArray,b=a.length,c=0;c<b;c++)Ar(this,a[c])}; t.Pm=function(a){Z.prototype.Pm.call(this,a);a=this.ja(a);var b=Vq(this,a);if(null!==b){var c=Ea();for(b=b.iterator;b.next();){var d=b.value;if(this.$a(d)){if(this.Kh(d)===a){var e=this.Ae;rr(this,"nodeGroupKey",ze,e,d,a,a);"string"===typeof e&&this.Ca(d,e);c.push(d)}}else if(Qq(this,d,!0)===a&&(e=this.bf,rr(this,"linkFromKey",ze,e,d,a,a),"string"===typeof e&&this.Ca(d,e),c.push(d)),Qq(this,d,!1)===a&&(e=this.cf,rr(this,"linkToKey",ze,e,d,a,a),"string"===typeof e&&this.Ca(d,e),c.push(d)),e=this.Df(d), Array.isArray(e))for(var f=e.length,g=this.ae,h=0;h<f;h++)e[h]===a&&(rr(this,"linkLabelKeys",Be,g,d,a,a,h,h),c.push(d))}for(b=0;b<c.length;b++)Wq(this,a,c[b]);Ia(c)}};t.Om=function(a){Z.prototype.Om.call(this,a);var b=this.Kh(a);null===this.Lb(b)&&Xq(this,b,a)};t.ir=function(a){Z.prototype.ir.call(this,a);var b=this.Kh(a);Wq(this,b,a)}; t.Mt=function(a){if(null===a)return"";var b=this.Tj;if(""===b)return"";b=sn(a,b);if(void 0===b)return"";if("string"===typeof b)return b;B("getCategoryForLinkData found a non-string category for "+a+": "+b);return""};wr.prototype.getLinkCategoryForData=function(a){return this.Mt(a)};wr.prototype.cr=function(a,b){if(null!==a){var c=this.Tj;if(""!==c)if(this.xc(a)){var d=sn(a,c);void 0===d&&(d="");d!==b&&(Uj(a,c,b),rr(this,"linkCategory",ze,c,a,d,b),"string"===typeof c&&this.Ca(a,c))}else Uj(a,c,b)}}; wr.prototype.setLinkCategoryForData=function(a,b){this.cr(a,b)};t=wr.prototype;t.Vm=function(a,b){Z.prototype.Vm.call(this,a,b);this.dr(b,this.Kh(a))};function yr(a,b,c){a.cr(c,a.Mt(b));a.Cw(c,a.xy(b));a.Hw(c,a.Ay(b));a.ju(c,a.Df(b));a.Dw(c,a.yy(b));a.Iw(c,a.By(b))}t.Bk=function(){return!0};t.qj=function(){return!0};t.Vt=function(){return!0};t.Ck=function(){return!0}; na.Object.defineProperties(wr.prototype,{archetypeNodeData:{get:function(){return this.Aj},set:function(a){var b=this.Aj;b!==a&&(this.Aj=a,this.g("archetypeNodeData",b,a))}},linkFromKeyProperty:{get:function(){return this.bf},set:function(a){var b=this.bf;b!==a&&(this.bf=a,this.g("linkFromKeyProperty",b,a))}},linkToKeyProperty:{get:function(){return this.cf},set:function(a){var b=this.cf;b!==a&&(this.cf=a,this.g("linkToKeyProperty", b,a))}},linkFromPortIdProperty:{get:function(){return this.Uj},set:function(a){var b=this.Uj;b!==a&&(this.Uj=a,this.g("linkFromPortIdProperty",b,a))}},linkToPortIdProperty:{get:function(){return this.Vj},set:function(a){var b=this.Vj;b!==a&&(this.Vj=a,this.g("linkToPortIdProperty",b,a))}},linkLabelKeysProperty:{get:function(){return this.ae},set:function(a){var b=this.ae;b!==a&&(this.ae=a,this.g("linkLabelKeysProperty", b,a))}},linkDataArray:{get:function(){return this.bd},set:function(a){var b=this.bd;if(b!==a){this.gb.clear();for(var c=a.length,d=0;d<c;d++){var e=a[d];if(!za(e)){B("GraphLinksModel.linkDataArray must only contain Objects, not: "+e);return}ob(e)}this.bd=a;if(""!==this.linkKeyProperty){d=new E;for(e=0;e<c;e++){var f=a[e],g=this.Wb(f);void 0===g?d.add(f):null!==this.gb.H(g)?d.add(f):this.gb.add(g,f)}for(d=d.iterator;d.next();)e=d.value,this.Qq(e),f=this.Wb(e),void 0!== f&&this.gb.add(f,e)}d=new G;for(e=0;e<c;e++)d.add(a[e]);this.cg=d;rr(this,"linkDataArray",ze,"linkDataArray",this,b,a);for(b=0;b<c;b++)Ar(this,a[b])}}},linkKeyProperty:{get:function(){return this.Gi},set:function(a){var b=this.Gi;if(b!==a){this.Gi=a;this.gb.clear();for(var c=this.linkDataArray.length,d=0;d<c;d++){var e=this.linkDataArray[d],f=this.Wb(e);void 0===f&&(this.Qq(e),f=this.Wb(e));void 0!==f&&this.gb.add(f,e)}this.g("linkKeyProperty",b,a)}}},makeUniqueLinkKeyFunction:{ get:function(){return this.Rl},set:function(a){var b=this.Rl;b!==a&&(this.Rl=a,this.g("makeUniqueLinkKeyFunction",b,a))}},copyLinkDataFunction:{get:function(){return this.hl},set:function(a){var b=this.hl;b!==a&&(this.hl=a,this.g("copyLinkDataFunction",b,a))}},nodeIsGroupProperty:{get:function(){return this.Vl},set:function(a){var b=this.Vl;b!==a&&(this.Vl=a,this.g("nodeIsGroupProperty",b,a))}},nodeGroupKeyProperty:{ get:function(){return this.Ae},set:function(a){var b=this.Ae;b!==a&&(this.Ae=a,this.g("nodeGroupKeyProperty",b,a))}},rk:{get:function(){return this.Cn},set:function(a){this.Cn!==a&&(this.Cn=a)}},linkCategoryProperty:{get:function(){return this.Tj},set:function(a){var b=this.Tj;b!==a&&(this.Tj=a,this.g("linkCategoryProperty",b,a))}},type:{get:function(){return"GraphLinksModel"}}}); wr.prototype.setCategoryForLinkData=wr.prototype.cr;wr.prototype.getCategoryForLinkData=wr.prototype.Mt;wr.prototype.assignAllDataProperties=wr.prototype.sq;wr.prototype.setGroupKeyForNodeData=wr.prototype.dr;wr.prototype.getGroupKeyForNodeData=wr.prototype.Kh;wr.prototype.isGroupForNodeData=wr.prototype.ew;wr.prototype.copyLinkData=wr.prototype.xq;wr.prototype.mergeLinkDataArray=wr.prototype.JA;wr.prototype.removeLinkDataCollection=wr.prototype.TA;wr.prototype.removeLinkData=wr.prototype.Lm; wr.prototype.addLinkDataCollection=wr.prototype.pz;wr.prototype.addLinkData=wr.prototype.bj;wr.prototype.containsLinkData=wr.prototype.xc;wr.prototype.makeLinkDataKeyUnique=wr.prototype.Qq;wr.prototype.findLinkDataForKey=wr.prototype.Eg;wr.prototype.setKeyForLinkData=wr.prototype.iu;wr.prototype.getKeyForLinkData=wr.prototype.Wb;wr.prototype.removeLabelKeyForLinkData=wr.prototype.Py;wr.prototype.addLabelKeyForLinkData=wr.prototype.Cv;wr.prototype.setLabelKeysForLinkData=wr.prototype.ju; wr.prototype.getLabelKeysForLinkData=wr.prototype.Df;wr.prototype.setToPortIdForLinkData=wr.prototype.Iw;wr.prototype.getToPortIdForLinkData=wr.prototype.By;wr.prototype.setFromPortIdForLinkData=wr.prototype.Dw;wr.prototype.getFromPortIdForLinkData=wr.prototype.yy;wr.prototype.setToKeyForLinkData=wr.prototype.Hw;wr.prototype.getToKeyForLinkData=wr.prototype.Ay;wr.prototype.setFromKeyForLinkData=wr.prototype.Cw;wr.prototype.getFromKeyForLinkData=wr.prototype.xy;wr.prototype.clear=wr.prototype.clear; var zr=Object.freeze([]);wr.className="GraphLinksModel";ur.GraphLinksModel=wr;Z.constructGraphLinksModel=Z.constructGraphLinksModel=function(){return new wr};Z.initDiagramModel=zi=function(){return new wr};function Br(a){Z.call(this);this.Be="parent";this.En=!1;this.$j="parentLinkCategory";void 0!==a&&(this.nodeDataArray=a)}ma(Br,Z);Br.constructGraphLinksModel=Z.constructGraphLinksModel; Br.prototype.cloneProtected=function(a){Z.prototype.cloneProtected.call(this,a);a.Be=this.Be;a.En=this.En;a.$j=this.$j};t=Br.prototype;t.toString=function(a){void 0===a&&(a=0);if(2<=a)return this.gr();var b=(""!==this.name?this.name:"")+" TreeModel";if(0<a){b+="\n node data:";a=this.nodeDataArray;for(var c=a.length,d=0;d<c;d++){var e=a[d];b+=" "+this.ja(e)+":"+Ka(e)}}return b}; t.Vk=function(){var a=Z.prototype.Vk.call(this),b="";"parent"!==this.nodeParentKeyProperty&&"string"===typeof this.nodeParentKeyProperty&&(b+=',\n "nodeParentKeyProperty": '+this.quote(this.nodeParentKeyProperty));return a+b};t.Xq=function(a){Z.prototype.Xq.call(this,a);a.nodeParentKeyProperty&&(this.nodeParentKeyProperty=a.nodeParentKeyProperty)};t.lr=function(a){kr(this,a,"nodeParentKeyProperty");return Z.prototype.lr.call(this,a)}; t.Wq=function(a){void 0!==a.nodeParentKeyProperty&&a.nodeParentKeyProperty!==this.nodeParentKeyProperty&&B("applyIncrementalJson cannot change Model properties");Z.prototype.Wq.call(this,a)};t.Fm=function(a){return a};t.Lh=function(a){if(null!==a){var b=this.Be;if(""!==b&&(b=sn(a,b),void 0!==b)){if(Sq(b))return b;B("ParentKey value for node data "+a+" is not a number or a string: "+b)}}}; t.ge=function(a,b){null===b&&(b=void 0);if(null!==a){var c=this.Be;if(""!==c)if(b=this.Fm(b),this.$a(a)){var d=sn(a,c);d!==b&&(Wq(this,d,a),Uj(a,c,b),null===this.Lb(b)&&Xq(this,b,a),rr(this,"nodeParentKey",ze,c,a,d,b),"string"===typeof c&&this.Ca(a,c))}else Uj(a,c,b)}};t.Pt=function(a){if(null===a)return"";var b=this.$j;if(""===b)return"";b=sn(a,b);if(void 0===b)return"";if("string"===typeof b)return b;B("getParentLinkCategoryForNodeData found a non-string category for "+a+": "+b);return""}; Br.prototype.getLinkCategoryForData=function(a){return this.Pt(a)};Br.prototype.ku=function(a,b){if(null!==a){var c=this.$j;if(""!==c)if(this.$a(a)){var d=sn(a,c);void 0===d&&(d="");d!==b&&(Uj(a,c,b),rr(this,"parentLinkCategory",ze,c,a,d,b),"string"===typeof c&&this.Ca(a,c))}else Uj(a,c,b)}};Br.prototype.setLinkCategoryForData=function(a,b){this.ku(a,b)}; Br.prototype.copyNodeData=function(a){if(null===a)return null;a=Z.prototype.copyNodeData.call(this,a);this.sk||""===this.Be||void 0===sn(a,this.Be)||Uj(a,this.Be,void 0);return a};Br.prototype.setDataProperty=function(a,b,c){if(this.$a(a)){if(b===this.nodeKeyProperty){this.Um(a,c);return}if(b===this.nodeCategoryProperty){this.Tm(a,c);return}if(b===this.nodeParentKeyProperty){this.ge(a,c);return}}var d=sn(a,b);d!==c&&(Uj(a,b,c),this.du(a,b,d,c))};t=Br.prototype; t.ar=function(a,b){Z.prototype.ar.call(this,a,b);for(var c=this.Va.iterator;c.next();)this.ww(c.value,a,b)};t.ww=function(a,b,c){if(this.Lh(a)===b){var d=this.Be;Uj(a,d,c);rr(this,"nodeParentKey",ze,d,a,b,c);"string"===typeof d&&this.Ca(a,d)}}; t.Pm=function(a){Z.prototype.Pm.call(this,a);a=this.ja(a);var b=Vq(this,a);if(null!==b){var c=Ea();for(b=b.iterator;b.next();){var d=b.value;if(this.$a(d)&&this.Lh(d)===a){var e=this.Be;rr(this,"nodeParentKey",ze,e,d,a,a);"string"===typeof e&&this.Ca(d,e);c.push(d)}}for(b=0;b<c.length;b++)Wq(this,a,c[b]);Ia(c)}};t.Om=function(a){Z.prototype.Om.call(this,a);var b=this.Lh(a);b=this.Fm(b);null===this.Lb(b)&&Xq(this,b,a)};t.ir=function(a){Z.prototype.ir.call(this,a);var b=this.Lh(a);Wq(this,b,a)}; t.Vm=function(a,b){Z.prototype.Vm.call(this,a,b);this.ku(b,this.Pt(a));this.ge(b,this.Lh(a))};t.Dm=function(){return!0};t.Vt=function(){return!0}; na.Object.defineProperties(Br.prototype,{nodeParentKeyProperty:{get:function(){return this.Be},set:function(a){var b=this.Be;b!==a&&(this.Be=a,this.g("nodeParentKeyProperty",b,a))}},sk:{get:function(){return this.En},set:function(a){this.En!==a&&(this.En=a)}},parentLinkCategoryProperty:{get:function(){return this.$j},set:function(a){var b=this.$j;b!==a&&(this.$j=a,this.g("parentLinkCategoryProperty",b,a))}}, linkCategoryProperty:{get:function(){return this.parentLinkCategoryProperty},set:function(a){this.parentLinkCategoryProperty=a}},type:{get:function(){return"TreeModel"}}});Br.prototype.setParentLinkCategoryForNodeData=Br.prototype.ku;Br.prototype.getParentLinkCategoryForNodeData=Br.prototype.Pt;Br.prototype.setParentKeyForNodeData=Br.prototype.ge;Br.prototype.getParentKeyForNodeData=Br.prototype.Lh;Br.className="TreeModel";ur.TreeModel=Br; function Cr(){Bi.call(this);this.xx=this.Sn=this.$b=0;this.Vr=360;this.wx=Dr;this.Ij=0;this.nx=new I;this.Hr=this.be=0;this.ut=new Er;this.Au=this.Zj=0;this.gz=600;this.vp=NaN;this.nn=1;this.Zp=0;this.lm=360;this.Fb=Dr;this.K=Fr;this.dd=Gr;this.Yc=tq;this.mf=6;this.ep=Hr}ma(Cr,Bi);Cr.prototype.cloneProtected=function(a){Bi.prototype.cloneProtected.call(this,a);a.vp=this.vp;a.nn=this.nn;a.Zp=this.Zp;a.lm=this.lm;a.Fb=this.Fb;a.K=this.K;a.dd=this.dd;a.Yc=this.Yc;a.mf=this.mf;a.ep=this.ep}; Cr.prototype.jb=function(a){if(a.classType===Cr)if(a===Ir||a===Jr||a===Kr||a===Lr||a===Gr)this.sorting=a;else if(a===Mr||a===Nr||a===Fr||a===Or)this.direction=a;else if(a===Pr||a===Qr||a===Dr||a===Rr)this.arrangement=a;else{if(a===Sr||a===Hr)this.nodeDiameterFormula=a}else Bi.prototype.jb.call(this,a)};Cr.prototype.createNetwork=function(){return new Tr(this)}; Cr.prototype.doLayout=function(a){null===this.network&&(this.network=this.makeNetwork(a));this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin);a=this.network.vertexes;if(1>=a.count)1===a.count&&(a=a.first(),a.centerX=0,a.centerY=0);else{var b=new E;b.addAll(a.iterator);a=new E;var c=new E;var d=this.sort(b);var e,f,g=this.Hr;var h=this.arrangement;var k=this.nodeDiameterFormula;var l=this.radius;if(!isFinite(l)||0>=l)l=NaN;var m=this.aspectRatio;if(!isFinite(m)||0>=m)m=1;var n=this.startAngle; isFinite(n)||(n=0);var p=this.sweepAngle;if(!isFinite(p)||360<p||1>p)p=360;b=this.spacing;isFinite(b)||(b=NaN);h===Rr&&k===Sr?h=Dr:h===Rr&&k!==Sr&&(h=this.arrangement);if((this.direction===Mr||this.direction===Nr)&&this.sorting!==Gr){for(k=0;!(k>=d.length);k+=2){a.add(d.J(k));if(k+1>=d.length)break;c.add(d.J(k+1))}this.direction===Mr?(this.arrangement===Rr&&a.reverse(),d=new E,d.addAll(a),d.addAll(c)):(this.arrangement===Rr&&c.reverse(),d=new E,d.addAll(c),d.addAll(a))}k=d.length;for(var r=f=e=0;r< d.length;r++){var q=n+p*f*(this.direction===Fr?1:-1)/k,u=d.J(r).diameter;isNaN(u)&&(u=Ur(d.J(r),q));360>p&&(0===r||r===d.length-1)&&(u/=2);e+=u;f++}if(isNaN(l)||h===Rr){isNaN(b)&&(b=6);if(h!==Dr&&h!==Rr){f=-Infinity;for(g=0;g<k;g++)r=d.J(g),e=d.J(g===k-1?0:g+1),isNaN(r.diameter)&&Ur(r,0),isNaN(e.diameter)&&Ur(e,0),f=Math.max(f,(r.diameter+e.diameter)/2);g=f+b;h===Pr?l=(f+b)/(2*Math.PI/k):l=Vr(this,g*(360<=p?k:k-1),m,n*Math.PI/180,p*Math.PI/180)}else l=Vr(this,e+(360<=p?k:k-1)*(h!==Rr?b:1.6*b),m,n* Math.PI/180,p*Math.PI/180);f=l*m}else if(f=l*m,r=Wr(this,l,f,n*Math.PI/180,p*Math.PI/180),isNaN(b)){if(h===Dr||h===Rr)b=(r-e)/(360<=p?k:k-1)}else if(h===Dr||h===Rr)r=(r-e)/(360<=p?k:k-1),r<b?(l=Vr(this,e+b*(360<=p?k:k-1),m,n*Math.PI/180,p*Math.PI/180),f=l*m):b=r;else{g=-Infinity;for(e=0;e<k;e++)q=d.J(e),u=d.J(e===k-1?0:e+1),isNaN(q.diameter)&&Ur(q,0),isNaN(u.diameter)&&Ur(u,0),g=Math.max(g,(q.diameter+u.diameter)/2);g+=b;e=Vr(this,g*(360<=p?k:k-1),m,n*Math.PI/180,p*Math.PI/180);e>l?(l=e,f=l*m):g= r/(360<=p?k:k-1)}this.wx=h;this.$b=l;this.Sn=m;this.xx=n;this.Vr=p;this.Ij=b;this.be=f;this.Hr=g;b=d;d=this.wx;h=this.$b;l=this.xx;m=this.Vr;n=this.Ij;p=this.be;k=this.Hr;if(this.direction!==Mr&&this.direction!==Nr||d!==Rr)if(this.direction===Mr||this.direction===Nr){g=0;switch(d){case Qr:g=180*Xr(this,h,p,l,k)/Math.PI;break;case Dr:k=b=0;g=a.first();null!==g&&(b=Ur(g,Math.PI/2));g=c.first();null!==g&&(k=Ur(g,Math.PI/2));g=180*Xr(this,h,p,l,n+(b+k)/2)/Math.PI;break;case Pr:g=m/b.length}if(this.direction=== Mr){switch(d){case Qr:Yr(this,a,l,Or);break;case Dr:Zr(this,a,l,Or);break;case Pr:$r(this,a,m/2,l,Or)}switch(d){case Qr:Yr(this,c,l+g,Fr);break;case Dr:Zr(this,c,l+g,Fr);break;case Pr:$r(this,c,m/2,l+g,Fr)}}else{switch(d){case Qr:Yr(this,c,l,Or);break;case Dr:Zr(this,c,l,Or);break;case Pr:$r(this,c,m/2,l,Or)}switch(d){case Qr:Yr(this,a,l+g,Fr);break;case Dr:Zr(this,a,l+g,Fr);break;case Pr:$r(this,a,m/2,l+g,Fr)}}}else switch(d){case Qr:Yr(this,b,l,this.direction);break;case Dr:Zr(this,b,l,this.direction); break;case Pr:$r(this,b,m,l,this.direction);break;case Rr:as(this,b,m,l,this.direction)}else as(this,b,m,l-m/2,Fr)}this.updateParts();this.network=null;this.isValidLayout=!0};function $r(a,b,c,d,e){var f=a.Vr,g=a.$b;a=a.be;d=d*Math.PI/180;c=c*Math.PI/180;for(var h=b.length,k=0;k<h;k++){var l=d+(e===Fr?k*c/(360<=f?h:h-1):-(k*c)/h),m=b.J(k),n=g*Math.tan(l)/a;n=Math.sqrt((g*g+a*a*n*n)/(1+n*n));m.centerX=n*Math.cos(l);m.centerY=n*Math.sin(l);m.actualAngle=180*l/Math.PI}} function Zr(a,b,c,d){var e=a.$b,f=a.be,g=a.Ij;c=c*Math.PI/180;for(var h=b.length,k=0;k<h;k++){var l=b.J(k),m=b.J(k===h-1?0:k+1),n=f*Math.sin(c);l.centerX=e*Math.cos(c);l.centerY=n;l.actualAngle=180*c/Math.PI;isNaN(l.diameter)&&Ur(l,0);isNaN(m.diameter)&&Ur(m,0);l=Xr(a,e,f,d===Fr?c:-c,(l.diameter+m.diameter)/2+g);c+=d===Fr?l:-l}} function Yr(a,b,c,d){var e=a.$b,f=a.be,g=a.Hr;c=c*Math.PI/180;for(var h=b.length,k=0;k<h;k++){var l=b.J(k);l.centerX=e*Math.cos(c);l.centerY=f*Math.sin(c);l.actualAngle=180*c/Math.PI;l=Xr(a,e,f,d===Fr?c:-c,g);c+=d===Fr?l:-l}}function as(a,b,c,d,e){var f=a.Vr;a.Zj=0;a.ut=new Er;if(360>c){for(f=d+(e===Fr?f:-f);0>f;)f+=360;f%=360;180<f&&(f-=360);f*=Math.PI/180;a.Au=f;bs(a,b,c,d,e)}else cs(a,b,c,d,e);a.ut.commit(b)} function cs(a,b,c,d,e){var f=a.$b,g=a.Ij,h=a.Sn,k=f*Math.cos(d*Math.PI/180),l=a.be*Math.sin(d*Math.PI/180),m=b.ma();if(3===m.length)m[0].centerX=f,m[0].centerY=0,m[1].centerX=m[0].centerX-m[0].width/2-m[1].width/2-g,m[1].y=m[0].y,m[2].centerX=(m[0].centerX+m[1].centerX)/2,m[2].y=m[0].y-m[2].height-g;else if(4===m.length)m[0].centerX=f,m[0].centerY=0,m[2].centerX=-m[0].centerX,m[2].centerY=m[0].centerY,m[1].centerX=0,m[1].y=Math.min(m[0].y,m[2].y)-m[1].height-g,m[3].centerX=0,m[3].y=Math.max(m[0].y+ m[0].height+g,m[2].y+m[2].height+g);else{f=I.alloc();for(var n=0;n<m.length;n++){m[n].centerX=k;m[n].centerY=l;if(n>=m.length-1)break;ds(a,k,l,m,n,e,f)||es(a,k,l,m,n,e,f);k=f.x;l=f.y}I.free(f);a.Zj++;if(!(23<a.Zj)){k=m[0].centerX;l=m[0].centerY;f=m[m.length-1].centerX;n=m[m.length-1].centerY;var p=Math.abs(k-f)-((m[0].width+m[m.length-1].width)/2+g),r=Math.abs(l-n)-((m[0].height+m[m.length-1].height)/2+g);g=0;1>Math.abs(r)?Math.abs(k-f)<(m[0].width+m[m.length-1].width)/2&&(g=0):g=0<r?r:1>Math.abs(p)? 0:p;k=Math.abs(f)>Math.abs(n)?0<f!==l>n:0<n!==k<f;if(k=e===Fr?k:!k)g=-Math.abs(g),g=Math.min(g,-m[m.length-1].width),g=Math.min(g,-m[m.length-1].height);a.ut.compare(g,m);1<Math.abs(g)&&(a.$b=8>a.Zj?a.$b-g/(2*Math.PI):5>m.length&&10<g?a.$b/2:a.$b-(0<g?1.7:-2.3),a.be=a.$b*h,cs(a,b,c,d,e))}}} function bs(a,b,c,d,e){for(var f=a.$b,g=a.be,h=a.Sn,k=f*Math.cos(d*Math.PI/180),l=g*Math.sin(d*Math.PI/180),m=I.alloc(),n=b.ma(),p=0;p<n.length;p++){n[p].centerX=k;n[p].centerY=l;if(p>=n.length-1)break;ds(a,k,l,n,p,e,m)||es(a,k,l,n,p,e,m);k=m.x;l=m.y}I.free(m);a.Zj++;if(!(23<a.Zj)){k=Math.atan2(l,k);k=e===Fr?a.Au-k:k-a.Au;k=Math.abs(k)<Math.abs(k-2*Math.PI)?k:k-2*Math.PI;f=k*(f+g)/2;g=a.ut;if(Math.abs(f)<Math.abs(g.Am))for(g.Am=f,g.Wk=[],g.an=[],k=0;k<n.length;k++)g.Wk[k]=n[k].bounds.x,g.an[k]=n[k].bounds.y; 1<Math.abs(f)&&(a.$b=8>a.Zj?a.$b-f/(2*Math.PI):a.$b-(0<f?1.7:-2.3),a.be=a.$b*h,bs(a,b,c,d,e))}}function ds(a,b,c,d,e,f,g){var h=a.$b,k=a.be,l=0;a=(d[e].width+d[e+1].width)/2+a.Ij;var m=!1;if(0<=c!==(f===Fr)){if(f=b+a,f>h){f=b-a;if(f<-h)return g.x=f,g.y=l,!1;m=!0}}else if(f=b-a,f<-h){f=b+a;if(f>h)return g.x=f,g.y=l,!1;m=!0}l=Math.sqrt(1-Math.min(1,f*f/(h*h)))*k;0>c!==m&&(l=-l);if(Math.abs(c-l)>(d[e].height+d[e+1].height)/2)return g.x=f,g.y=l,!1;g.x=f;g.y=l;return!0} function es(a,b,c,d,e,f,g){var h=a.$b,k=a.be,l=0;a=(d[e].height+d[e+1].height)/2+a.Ij;d=!1;if(0<=b!==(f===Fr)){if(f=c-a,f<-k){f=c+a;if(f>k){g.x=l;g.y=f;return}d=!0}}else if(f=c+a,f>k){f=c-a;if(f<-k){g.x=l;g.y=f;return}d=!0}l=Math.sqrt(1-Math.min(1,f*f/(k*k)))*h;0>b!==d&&(l=-l);g.x=l;g.y=f}Cr.prototype.commitLayout=function(){this.commitNodes();this.isRouting&&this.commitLinks()}; Cr.prototype.commitNodes=function(){var a=null!==this.group&&null!==this.group.placeholder&&this.group.isSubGraphExpanded,b=a?this.group.location.copy():null,c=this.actualCenter;a?c=new I(0,0):(c.x=this.arrangementOrigin.x+this.$b,c.y=this.arrangementOrigin.y+this.be);for(var d=this.network.vertexes.iterator;d.next();){var e=d.value;e.x+=c.x;e.y+=c.y;e.commit()}a&&(this.group.Ta(),a=this.group.position.copy(),c=this.group.location.copy(),b=b.he(c.he(a)),this.group.move(b),this.nx=b.he(a))}; Cr.prototype.commitLinks=function(){for(var a=this.network.edges.iterator;a.next();)a.value.commit()};function Wr(a,b,c,d,e){var f=a.gz;if(.001>Math.abs(a.Sn-1))return void 0!==d&&void 0!==e?e*b:2*Math.PI*b;a=b>c?Math.sqrt(b*b-c*c)/b:Math.sqrt(c*c-b*b)/c;var g=0;var h=void 0!==d&&void 0!==e?e/(f+1):Math.PI/(2*(f+1));for(var k=0,l=0;l<=f;l++){void 0!==d&&void 0!==e?k=d+l*e/f:k=l*Math.PI/(2*f);var m=Math.sin(k);g+=Math.sqrt(1-a*a*m*m)*h}return void 0!==d&&void 0!==e?(b>c?b:c)*g:4*(b>c?b:c)*g} function Vr(a,b,c,d,e){return b/(void 0!==d&&void 0!==e?Wr(a,1,c,d,e):Wr(a,1,c))}function Xr(a,b,c,d,e){if(.001>Math.abs(a.Sn-1))return e/b;var f=b>c?Math.sqrt(b*b-c*c)/b:Math.sqrt(c*c-b*b)/c,g=0;a=2*Math.PI/(700*a.network.vertexes.count);b>c&&(d+=Math.PI/2);for(var h=0;;h++){var k=Math.sin(d+h*a);g+=(b>c?b:c)*Math.sqrt(1-f*f*k*k)*a;if(g>=e)return h*a}} Cr.prototype.sort=function(a){switch(this.sorting){case Kr:break;case Lr:a.reverse();break;case Ir:a.sort(this.comparer);break;case Jr:a.sort(this.comparer);a.reverse();break;case Gr:return this.mw(fs(a));default:B("Invalid sorting type.")}return a}; function fs(a){for(var b=[],c=0;c<a.length;c++)b.push(0);c=new E;for(var d=0;d<a.length;d++){var e=-1,f=-1;if(0===d)for(var g=0;g<a.length;g++){var h=a.J(g).edgesCount;h>e&&(e=h,f=g)}else for(g=0;g<a.length;g++)h=b[g],h>e&&(e=h,f=g);c.add(a.J(f));b[f]=-1;f=a.J(f);for(g=f.sourceEdges;g.next();)e=a.indexOf(g.value.fromVertex),0>e||0<=b[e]&&b[e]++;for(f=f.destinationEdges;f.next();)e=a.indexOf(f.value.toVertex),0>e||0<=b[e]&&b[e]++}return c} Cr.prototype.mw=function(a){for(var b=[],c=0;c<a.length;c++){var d=a.J(c);b[c]=[];for(var e,f=d.destinationEdges;f.next();)e=a.indexOf(f.value.toVertex),e!==c&&0>b[c].indexOf(e)&&b[c].push(e);for(d=d.sourceEdges;d.next();)e=a.indexOf(d.value.fromVertex),e!==c&&0>b[c].indexOf(e)&&b[c].push(e)}f=[];for(c=0;c<b.length;c++)f[c]=0;c=[];var g=[],h=[];d=[];e=new E;for(var k=0,l=0;l<b.length;l++){var m=b[l].length;if(1===m)d.push(l);else if(0===m)e.add(a.J(l));else{if(0===k)c.push(l);else{for(var n=m=Infinity, p=-1,r=[],q=0;q<c.length;q++)0>b[c[q]].indexOf(c[q===c.length-1?0:q+1])&&r.push(q===c.length-1?0:q+1);if(0===r.length)for(q=0;q<c.length;q++)r.push(q);for(q=0;q<r.length;q++){for(var u=r[q],v=b[l],w=0,y=0;y<g.length;y++){var z=f[g[y]],A=f[h[y]];if(z<A){var C=z;z=A}else C=A;if(C<u&&u<=z)for(A=0;A<v.length;A++){var F=v[A];0>c.indexOf(F)||C<f[F]&&f[F]<z||C===f[F]||z===f[F]||w++}else for(A=0;A<v.length;A++)F=v[A],0>c.indexOf(F)||C<f[F]&&f[F]<z&&C!==f[F]&&z!==f[F]&&w++}v=w;for(y=w=0;y<b[l].length;y++)C= c.indexOf(b[l][y]),0<=C&&(C=Math.abs(u-(C>=u?C+1:C)),w+=C<c.length+1-C?C:c.length+1-C);for(y=0;y<g.length;y++)C=f[g[y]],z=f[h[y]],C>=u&&C++,z>=u&&z++,C>z&&(A=z,z=C,C=A),z-C<(c.length+2)/2===(C<u&&u<=z)&&w++;if(v<m||v===m&&w<n)m=v,n=w,p=u}c.splice(p,0,l);for(m=0;m<c.length;m++)f[c[m]]=m;for(m=0;m<b[l].length;m++)n=b[l][m],0<=c.indexOf(n)&&(g.push(l),h.push(n))}k++}}for(g=c.length;;){f=!0;for(h=0;h<d.length;h++)if(k=d[h],l=b[k][0],m=c.indexOf(l),0<=m){for(p=n=0;p<b[l].length;p++)r=c.indexOf(b[l][p]), 0>r||r===m||(q=r>m?r-m:m-r,n+=r<m!==q>g-q?1:-1);c.splice(0>n?m:m+1,0,k);d.splice(h,1);h--}else f=!1;if(f)break;else c.push(d[0]),d.splice(0,1)}for(b=0;b<c.length;b++)e.add(a.J(c[b]));return e}; na.Object.defineProperties(Cr.prototype,{radius:{get:function(){return this.vp},set:function(a){this.vp!==a&&(0<a||isNaN(a))&&(this.vp=a,this.C())}},aspectRatio:{get:function(){return this.nn},set:function(a){this.nn!==a&&0<a&&(this.nn=a,this.C())}},startAngle:{get:function(){return this.Zp},set:function(a){this.Zp!==a&&(this.Zp=a,this.C())}},sweepAngle:{get:function(){return this.lm}, set:function(a){this.lm!==a&&(0<a&&360>=a?this.lm=a:this.lm=360,this.C())}},arrangement:{get:function(){return this.Fb},set:function(a){this.Fb===a||a!==Rr&&a!==Dr&&a!==Qr&&a!==Pr||(this.Fb=a,this.C())}},direction:{get:function(){return this.K},set:function(a){this.K===a||a!==Fr&&a!==Or&&a!==Mr&&a!==Nr||(this.K=a,this.C())}},sorting:{get:function(){return this.dd},set:function(a){this.dd===a||a!==Kr&&a!==Lr&& a!==Ir&&!Jr&&a!==Gr||(this.dd=a,this.C())}},comparer:{get:function(){return this.Yc},set:function(a){this.Yc!==a&&(this.Yc=a,this.C())}},spacing:{get:function(){return this.mf},set:function(a){this.mf!==a&&(this.mf=a,this.C())}},nodeDiameterFormula:{get:function(){return this.ep},set:function(a){this.ep===a||a!==Hr&&a!==Sr||(this.ep=a,this.C())}},actualXRadius:{get:function(){return this.$b}}, actualYRadius:{get:function(){return this.be}},actualSpacing:{get:function(){return this.Ij}},actualCenter:{get:function(){return this.nx}}}); var Dr=new D(Cr,"ConstantSpacing",0),Qr=new D(Cr,"ConstantDistance",1),Pr=new D(Cr,"ConstantAngle",2),Rr=new D(Cr,"Packed",3),Fr=new D(Cr,"Clockwise",4),Or=new D(Cr,"Counterclockwise",5),Mr=new D(Cr,"BidirectionalLeft",6),Nr=new D(Cr,"BidirectionalRight",7),Kr=new D(Cr,"Forwards",8),Lr=new D(Cr,"Reverse",9),Ir=new D(Cr,"Ascending",10),Jr=new D(Cr,"Descending",11),Gr=new D(Cr,"Optimized",12),Hr=new D(Cr,"Pythagorean",13),Sr=new D(Cr,"Circular",14);Cr.className="CircularLayout";Cr.ConstantSpacing=Dr; Cr.ConstantDistance=Qr;Cr.ConstantAngle=Pr;Cr.Packed=Rr;Cr.Clockwise=Fr;Cr.Counterclockwise=Or;Cr.BidirectionalLeft=Mr;Cr.BidirectionalRight=Nr;Cr.Forwards=Kr;Cr.Reverse=Lr;Cr.Ascending=Ir;Cr.Descending=Jr;Cr.Optimized=Gr;Cr.Pythagorean=Hr;Cr.Circular=Sr;function Er(){this.Am=-Infinity;this.an=this.Wk=null} Er.prototype.compare=function(a,b){if(0<a&&0>this.Am||Math.abs(a)<Math.abs(this.Am)&&!(0>a&&0<this.Am))for(this.Am=a,this.Wk=[],this.an=[],a=0;a<b.length;a++)this.Wk[a]=b[a].bounds.x,this.an[a]=b[a].bounds.y};Er.prototype.commit=function(a){if(null!==this.Wk&&null!==this.an)for(var b=0;b<this.Wk.length;b++){var c=a.J(b);c.x=this.Wk[b];c.y=this.an[b]}};Er.className="VertexArrangement";function Tr(a){Zp.call(this,a)}ma(Tr,Zp);Tr.prototype.createVertex=function(){return new gs(this)}; Tr.prototype.createEdge=function(){return new hs(this)};Tr.className="CircularNetwork";function gs(a){mq.call(this,a);this.I=this.Gj=NaN}ma(gs,mq); function Ur(a,b){var c=a.network;if(null===c)return NaN;c=c.layout;if(null===c)return NaN;if(c.arrangement===Rr)if(c.nodeDiameterFormula===Sr)a.Gj=Math.max(a.width,a.height);else{c=Math.abs(Math.sin(b));b=Math.abs(Math.cos(b));if(0===c)return a.width;if(0===b)return a.height;a.Gj=Math.min(a.height/c,a.width/b)}else a.Gj=c.nodeDiameterFormula===Sr?Math.max(a.width,a.height):Math.sqrt(a.width*a.width+a.height*a.height);return a.Gj} na.Object.defineProperties(gs.prototype,{diameter:{get:function(){return this.Gj},set:function(a){this.Gj!==a&&(this.Gj=a)}},actualAngle:{get:function(){return this.I},set:function(a){this.I!==a&&(this.I=a)}}});gs.className="CircularVertex";function hs(a){nq.call(this,a)}ma(hs,nq);hs.className="CircularEdge"; function is(){Bi.call(this);this.Eh=null;this.zo=0;this.Pd=(new M(100,100)).freeze();this.mn=!1;this.kf=!0;this.ld=!1;this.Sl=100;this.Vn=1;this.Zf=1E3;this.Xo=10;this.wp=Math;this.ol=.05;this.nl=50;this.ll=150;this.ml=0;this.Mn=10;this.Ln=5}ma(is,Bi); is.prototype.cloneProtected=function(a){Bi.prototype.cloneProtected.call(this,a);a.Pd.assign(this.Pd);a.mn=this.mn;a.kf=this.kf;a.ld=this.ld;a.Sl=this.Sl;a.Vn=this.Vn;a.Zf=this.Zf;a.Xo=this.Xo;a.wp=this.wp;a.ol=this.ol;a.nl=this.nl;a.ll=this.ll;a.ml=this.ml;a.Mn=this.Mn;a.Ln=this.Ln}; is.prototype.serializeLayoutProperties=function(a,b){Bi.prototype.serializeLayoutProperties.call(this,a,b);a.arrangementSpacing={width:this.arrangementSpacing.width,height:this.arrangementSpacing.height};a.arrangesToOrigin=this.arrangesToOrigin;a.setsPortSpots=this.setsPortSpots;a.comments=this.comments;a.maxIterations=this.maxIterations;a.epsilonDistance=this.epsilonDistance;a.infinityDistance=this.infinityDistance;a.moveLimit=this.moveLimit;a.defaultSpringStiffness=this.defaultSpringStiffness;a.defaultSpringLength= this.defaultSpringLength;a.defaultElectricalCharge=this.defaultElectricalCharge;a.defaultGravitationalMass=this.defaultGravitationalMass;a.defaultCommentSpringLength=this.defaultCommentSpringLength;a.defaultCommentElectricalCharge=this.defaultCommentElectricalCharge}; is.prototype.deserializeLayoutProperties=function(a,b,c,d,e){Bi.prototype.deserializeLayoutProperties.call(this,a,b,c,d,e);this.arrangementSpacing=new M(a.arrangementSpacing.width,a.arrangementSpacing.height);this.arrangesToOrigin=a.arrangesToOrigin;this.setsPortSpots=a.setsPortSpots;this.comments=a.comments;this.maxIterations=a.maxIterations;this.epsilonDistance=a.epsilonDistance;this.infinityDistance=a.infinityDistance;this.moveLimit=a.moveLimit;this.defaultSpringStiffness=a.defaultSpringStiffness; this.defaultSpringLength=a.defaultSpringLength;this.defaultElectricalCharge=a.defaultElectricalCharge;this.defaultGravitationalMass=a.defaultGravitationalMass;this.defaultCommentSpringLength=a.defaultCommentSpringLength;this.defaultCommentElectricalCharge=a.defaultCommentElectricalCharge};is.prototype.createNetwork=function(){return new js(this)}; is.prototype.doLayout=function(a){null===this.network&&(this.network=this.makeNetwork(a));if(!this.Vw()){a=this.maxIterations;if(0<this.network.vertexes.count){this.network.yq();for(var b=this.network.vertexes.iterator;b.next();){var c=b.value;c.charge=this.electricalCharge(c);c.mass=this.gravitationalMass(c)}for(b=this.network.edges.iterator;b.next();)c=b.value,c.stiffness=this.springStiffness(c),c.length=this.springLength(c);this.Ev();this.zo=0;if(this.needsClusterLayout()){b=this.network;c=b.Yy(); for(var d=c.iterator;d.next();){this.network=d.value;for(var e=this.network.vertexes.iterator;e.next();){var f=e.value;f.Ld=f.vertexes.count;f.Rh=1;f.qk=null;f.Oe=null}ks(this,0,a)}this.network=b;var g=d=c.iterator;d=this.arrangementSpacing;var h=g.count,k=!0;f=e=0;for(var l=Ea(),m=0;m<h+b.vertexes.count+2;m++)l[m]=null;h=0;g.reset();for(var n=N.alloc();g.next();)if(m=g.value,this.computeBounds(m,n),k)k=!1,e=n.x+n.width/2,f=n.y+n.height/2,l[0]=new I(n.x+n.width+d.width,n.y),l[1]=new I(n.x,n.y+n.height+ d.height),h=2;else{var p=ls(l,h,e,f,n.width,n.height,d),r=l[p],q=new I(r.x+n.width+d.width,r.y),u=new I(r.x,r.y+n.height+d.height);p+1<h&&l.splice(p+1,0,null);l[p]=q;l[p+1]=u;h++;p=r.x-n.x;r=r.y-n.y;for(m=m.vertexes.iterator;m.next();)q=m.value,q.centerX+=p,q.centerY+=r}N.free(n);for(m=b.vertexes.iterator;m.next();)g=m.value,p=g.bounds,2>h?(e=p.x+p.width/2,f=p.y+p.height/2,l[0]=new I(p.x+p.width+d.width,p.y),l[1]=new I(p.x,p.y+p.height+d.height),h=2):(k=ls(l,h,e,f,p.width,p.height,d),n=l[k],r=new I(n.x+ p.width+d.width,n.y),p=new I(n.x,n.y+p.height+d.height),k+1<h&&l.splice(k+1,0,null),l[k]=r,l[k+1]=p,h++,g.centerX=n.x+g.width/2,g.centerY=n.y+g.height/2);Ia(l);for(d=c.iterator;d.next();){c=d.value;for(e=c.vertexes.iterator;e.next();)b.Cg(e.value);for(c=c.edges.iterator;c.next();)b.sm(c.value)}}ms(this,a);this.updateParts()}this.Sl=a;this.network=null;this.isValidLayout=!0}}; is.prototype.needsClusterLayout=function(){if(3>this.network.vertexes.count)return!1;for(var a=0,b=0,c=this.network.vertexes.first().bounds,d=this.network.vertexes.iterator;d.next();){if(d.value.bounds.Oc(c)&&(a++,2<a))return!0;if(10<b)break;b++}return!1};is.prototype.computeBounds=function(a,b){var c=!0;for(a=a.vertexes.iterator;a.next();){var d=a.value;c?(c=!1,b.set(d.bounds)):b.Tc(d.bounds)}return b}; function ks(a,b,c){if(ns(a,b)){var d=a.Zf;a.Zf*=1+1/(b+1);var e=os(a,b),f=Math.max(0,Math.max(Math.min(a.network.vertexes.count,c*(b+1)/11),10));a.maxIterations+=f;ks(a,b+1,c);ms(a,f);ps(a,e);b=e.vertexes.ma();b.sort(function(a,b){return null===a||null===b||a===b?0:b.Ld-a.Ld});for(c=0;c<b.length;c++)qs(a,b[c]);a.Zf=d}} function ns(a,b){if(10<b||3>a.network.vertexes.count)return!1;a.Eh=a.network.vertexes.ma();a=a.Eh;a.sort(function(a,b){return null===a||null===b||a===b?0:b.Ld-a.Ld});for(b=a.length-1;0<=b&&1>=a[b].Ld;)b--;return 1<a.length-b} function os(a,b){for(var c=a.network,d=new js(a),e=0;e<a.Eh.length;e++){var f=a.Eh[e];if(1<f.Ld){d.Cg(f);var g=new rs;g.pu=f.Ld;g.qu=f.width;g.ou=f.height;g.ax=f.focus.x;g.bx=f.focus.y;null===f.Oe&&(f.Oe=new E);f.Oe.add(g);f.Aw=f.Oe.count-1}else break}for(f=c.edges.iterator;f.next();){var h=f.value;e=h.fromVertex;g=h.toVertex;e.network===d&&g.network===d?d.sm(h):e.network===d?(h=e.qk,null===h&&(h=new E,e.qk=h),h.add(g),e.Ld--,e.Rh+=g.Rh):g.network===d&&(h=g.qk,null===h&&(h=new E,g.qk=h),h.add(e), g.Ld--,g.Rh+=e.Rh)}for(e=d.edges.iterator;e.next();)f=e.value,f.length*=Math.max(1,L.sqrt((f.fromVertex.Rh+f.toVertex.Rh)/(4*b+1)));for(b=d.vertexes.iterator;b.next();){e=b.value;var k=e.qk;if(null!==k&&0<k.count&&(g=e.Oe.J(e.Oe.count-1).pu-e.Ld,!(0>=g))){for(var l=h=0,m=k.count-g;m<k.count;m++){var n=k.J(m),p=null;for(f=n.edges.iterator;f.next();){var r=f.value;if(r.zy(n)===e){p=r;break}}null!==p&&(l+=p.length,h+=n.width*n.height)}f=e.centerX;k=e.centerY;m=e.width;n=e.height;p=e.focus;r=m*n;1>r&& (r=1);h=L.sqrt((h+r+l*l*4/(g*g))/r);g=(h-1)*m/2;h=(h-1)*n/2;e.bounds=new N(f-p.x-g,k-p.y-h,m+2*g,n+2*h);e.focus=new I(p.x+g,p.y+h)}}a.network=d;return c}function ps(a,b){for(var c=a.network.vertexes.iterator;c.next();){var d=c.value;d.network=b;if(null!==d.Oe){var e=d.Oe.J(d.Aw);d.Ld=e.pu;var f=e.ax,g=e.bx;d.bounds=new N(d.centerX-f,d.centerY-g,e.qu,e.ou);d.focus=new I(f,g);d.Aw--}}for(c=a.network.edges.iterator;c.next();)c.value.network=b;a.network=b} function qs(a,b){var c=b.qk;if(null!==c&&0!==c.count){var d=b.centerX,e=b.centerY,f=b.width,g=b.height;null!==b.Oe&&0<b.Oe.count&&(g=b.Oe.J(0),f=g.qu,g=g.ou);f=L.sqrt(f*f+g*g)/2;for(var h=!1,k=g=0,l=0,m=b.vertexes.iterator;m.next();){var n=m.value;1>=n.Ld?k++:(h=!0,l++,g+=Math.atan2(b.centerY-n.centerY,b.centerX-n.centerX))}if(0!==k)for(0<l&&(g/=l),l=b=0,b=h?2*Math.PI/(k+1):2*Math.PI/k,0===k%2&&(l=b/2),1<c.count&&c.sort(function(a,b){return null===a||null===b||a===b?0:b.width*b.height-a.width*a.height}), h=0===k%2?0:1,c=c.iterator;c.next();)if(k=c.value,!(1<k.Ld||a.isFixed(k))){m=null;for(n=k.edges.iterator;n.next();){m=n.value;break}n=k.width;var p=k.height;n=L.sqrt(n*n+p*p)/2;m=f+m.length+n;n=g+(b*(h/2>>1)+l)*(0===h%2?1:-1);k.centerX=d+m*Math.cos(n);k.centerY=e+m*Math.sin(n);h++}}} function ls(a,b,c,d,e,f,g){var h=9E19,k=-1,l=0;a:for(;l<b;l++){var m=a[l],n=m.x-c,p=m.y-d;n=n*n+p*p;if(n<h){for(p=l-1;0<=p;p--)if(a[p].y>m.y&&a[p].x-m.x<e+g.width)continue a;for(p=l+1;p<b;p++)if(a[p].x>m.x&&a[p].y-m.y<f+g.height)continue a;k=l;h=n}}return k}is.prototype.Ev=function(){if(this.comments)for(var a=this.network.vertexes.iterator;a.next();)this.addComments(a.value)}; is.prototype.addComments=function(a){var b=a.node;if(null!==b)for(b=b.Rv();b.next();){var c=b.value;if("Comment"===c.category&&c.isVisible()){var d=this.network.kj(c);null===d&&(d=this.network.mk(c));d.charge=this.defaultCommentElectricalCharge;c=null;for(var e=d.destinationEdges;e.next();){var f=e.value;if(f.toVertex===a){c=f;break}}if(null===c)for(e=d.sourceEdges;e.next();)if(f=e.value,f.fromVertex===a){c=f;break}null===c&&(c=this.network.Ek(a,d,null));c.length=this.defaultCommentSpringLength}}}; function ss(a,b){var c=a.bounds,d=c.x;a=c.y;var e=c.width;c=c.height;var f=b.bounds,g=f.x;b=f.y;var h=f.width;f=f.height;return d+e<g?a>b+f?(c=d+e-g,a=a-b-f,L.sqrt(c*c+a*a)):a+c<b?(d=d+e-g,a=a+c-b,L.sqrt(d*d+a*a)):g-(d+e):d>g+h?a>b+f?(c=d-g-h,a=a-b-f,L.sqrt(c*c+a*a)):a+c<b?(d=d-g-h,a=a+c-b,L.sqrt(d*d+a*a)):d-(g+h):a>b+f?a-(b+f):a+c<b?b-(a+c):.1}function ms(a,b){a.Eh=null;for(b=a.zo+b;a.zo<b&&(a.zo++,ts(a)););a.Eh=null} function ts(a){null===a.Eh&&(a.Eh=a.network.vertexes.ma());var b=a.Eh;if(0>=b.length)return!1;var c=b[0];c.forceX=0;c.forceY=0;for(var d=c.centerX,e=d,f=c=c.centerY,g=1;g<b.length;g++){var h=b[g];h.forceX=0;h.forceY=0;var k=h.centerX;h=h.centerY;d=Math.min(d,k);e=Math.max(e,k);c=Math.min(c,h);f=Math.max(f,h)}(e=e-d>f-c)?b.sort(function(a,b){return null===a||null===b||a===b?0:a.centerX-b.centerX}):b.sort(function(a,b){return null===a||null===b||a===b?0:a.centerY-b.centerY});c=a.Zf;var l=d=h=0;for(f= 0;f<b.length;f++){g=b[f];d=g.bounds;h=g.focus;k=d.x+h.x;var m=d.y+h.y;d=g.charge*a.electricalFieldX(k,m);l=g.charge*a.electricalFieldY(k,m);d+=g.mass*a.gravitationalFieldX(k,m);l+=g.mass*a.gravitationalFieldY(k,m);g.forceX+=d;g.forceY+=l;for(var n=f+1;n<b.length;n++){var p=b[n];if(p!==g){d=p.bounds;h=p.focus;l=d.x+h.x;var r=d.y+h.y;if(k-l>c||l-k>c){if(e)break}else if(m-r>c||r-m>c){if(!e)break}else{var q=ss(g,p);1>q?(d=a.randomNumberGenerator,null===d&&(a.randomNumberGenerator=d=new us),q=d.random(), h=d.random(),k>l?(d=Math.abs(p.bounds.right-g.bounds.x),d=(1+d)*q):k<l?(d=Math.abs(p.bounds.x-g.bounds.right),d=-(1+d)*q):(d=Math.max(p.width,g.width),d=(1+d)*q-d/2),m>r?(l=Math.abs(p.bounds.bottom-g.bounds.y),l=(1+l)*h):k<l?(l=Math.abs(p.bounds.y-g.bounds.bottom),l=-(1+l)*h):(l=Math.max(p.height,g.height),l=(1+l)*h-l/2)):(h=-(g.charge*p.charge)/(q*q),d=(l-k)/q*h,l=(r-m)/q*h);g.forceX+=d;g.forceY+=l;p.forceX-=d;p.forceY-=l}}}}for(e=a.network.edges.iterator;e.next();)h=e.value,c=h.fromVertex,f=h.toVertex, g=c.bounds,k=c.focus,d=g.x+k.x,g=g.y+k.y,m=f.bounds,n=f.focus,k=m.x+n.x,m=m.y+n.y,n=ss(c,f),1>n?(n=a.randomNumberGenerator,null===n&&(a.randomNumberGenerator=n=new us),h=n.random(),n=n.random(),d=(d>k?1:-1)*(1+(f.width>c.width?f.width:c.width))*h,l=(g>m?1:-1)*(1+(f.height>c.height?f.height:c.height))*n):(h=h.stiffness*(n-h.length),d=(k-d)/n*h,l=(m-g)/n*h),c.forceX+=d,c.forceY+=l,f.forceX-=d,f.forceY-=l;for(e=d=0;e<b.length;e++)c=b[e],a.isFixed(c)?a.moveFixedVertex(c):d=Math.max(d,a.moveVertex(c)|| 0);return d>a.epsilonDistance*a.epsilonDistance}is.prototype.moveVertex=function(a){var b=a.forceX,c=a.forceY,d=this.moveLimit;b<-d?b=-d:b>d&&(b=d);c<-d?c=-d:c>d&&(c=d);a.centerX+=b;a.centerY+=c;return b*b+c*c};is.prototype.moveFixedVertex=function(){};is.prototype.commitLayout=function(){this.Ew();this.commitNodes();this.isRouting&&this.commitLinks()}; is.prototype.Ew=function(){if(this.setsPortSpots)for(var a=this.network.edges.iterator;a.next();){var b=a.value.link;null!==b&&(b.fromSpot=Zc,b.toSpot=Zc)}};is.prototype.commitNodes=function(){var a=0,b=0;if(this.arrangesToOrigin){var c=N.alloc();this.computeBounds(this.network,c);b=this.arrangementOrigin;a=b.x-c.x;b=b.y-c.y;N.free(c)}c=N.alloc();for(var d=this.network.vertexes.iterator;d.next();){var e=d.value;if(0!==a||0!==b)c.assign(e.bounds),c.x+=a,c.y+=b,e.bounds=c;e.commit()}N.free(c)}; is.prototype.commitLinks=function(){for(var a=this.network.edges.iterator;a.next();)a.value.commit()};is.prototype.springStiffness=function(a){a=a.stiffness;return isNaN(a)?this.ol:a};is.prototype.springLength=function(a){a=a.length;return isNaN(a)?this.nl:a};is.prototype.electricalCharge=function(a){a=a.charge;return isNaN(a)?this.ll:a};is.prototype.electricalFieldX=function(){return 0};is.prototype.electricalFieldY=function(){return 0}; is.prototype.gravitationalMass=function(a){a=a.mass;return isNaN(a)?this.ml:a};is.prototype.gravitationalFieldX=function(){return 0};is.prototype.gravitationalFieldY=function(){return 0};is.prototype.isFixed=function(a){return a.isFixed}; na.Object.defineProperties(is.prototype,{currentIteration:{get:function(){return this.zo}},arrangementSpacing:{get:function(){return this.Pd},set:function(a){this.Pd.w(a)||(this.Pd.assign(a),this.C())}},arrangesToOrigin:{get:function(){return this.mn},set:function(a){this.mn!==a&&(this.mn=a,this.C())}},setsPortSpots:{get:function(){return this.kf},set:function(a){this.kf!==a&&(this.kf= a,this.C())}},comments:{get:function(){return this.ld},set:function(a){this.ld!==a&&(this.ld=a,this.C())}},maxIterations:{get:function(){return this.Sl},set:function(a){this.Sl!==a&&0<=a&&(this.Sl=a,this.C())}},epsilonDistance:{get:function(){return this.Vn},set:function(a){this.Vn!==a&&0<a&&(this.Vn=a,this.C())}},infinityDistance:{get:function(){return this.Zf},set:function(a){this.Zf!== a&&1<a&&(this.Zf=a,this.C())}},moveLimit:{get:function(){return this.Xo},set:function(a){this.Xo!==a&&1<a&&(this.Xo=a,this.C())}},randomNumberGenerator:{get:function(){return this.wp},set:function(a){this.wp!==a&&(null!==a&&"function"!==typeof a.random&&B('ForceDirectedLayout.randomNumberGenerator must have a "random()" function on it: '+a),this.wp=a)}},defaultSpringStiffness:{get:function(){return this.ol}, set:function(a){this.ol!==a&&(this.ol=a,this.C())}},defaultSpringLength:{get:function(){return this.nl},set:function(a){this.nl!==a&&(this.nl=a,this.C())}},defaultElectricalCharge:{get:function(){return this.ll},set:function(a){this.ll!==a&&(this.ll=a,this.C())}},defaultGravitationalMass:{get:function(){return this.ml},set:function(a){this.ml!==a&&(this.ml=a,this.C())}},defaultCommentSpringLength:{ get:function(){return this.Mn},set:function(a){this.Mn!==a&&(this.Mn=a,this.C())}},defaultCommentElectricalCharge:{get:function(){return this.Ln},set:function(a){this.Ln!==a&&(this.Ln=a,this.C())}}});is.className="ForceDirectedLayout";function rs(){this.bx=this.ax=this.ou=this.qu=this.pu=0}rs.className="ForceDirectedSubnet";function js(a){Zp.call(this,a)}ma(js,Zp);js.prototype.createVertex=function(){return new vs(this)};js.prototype.createEdge=function(){return new ws(this)}; js.className="ForceDirectedNetwork";function vs(a){mq.call(this,a);this.Ka=!1;this.eb=this.I=NaN;this.Rh=this.Ld=this.Ja=this.T=0;this.Oe=this.qk=null;this.Aw=0}ma(vs,mq);vs.prototype.serializeVertexProperties=function(a,b){mq.prototype.serializeVertexProperties.call(this,a,b);a.isFixed=this.isFixed;a.charge=this.charge;a.mass=this.mass};vs.prototype.zq=function(a,b,c,d){mq.prototype.zq.call(this,a,b,c,d);this.isFixed=a.isFixed;this.charge=a.charge;this.mass=a.mass}; na.Object.defineProperties(vs.prototype,{isFixed:{get:function(){return this.Ka},set:function(a){this.Ka!==a&&(this.Ka=a)}},charge:{get:function(){return this.I},set:function(a){this.I!==a&&(this.I=a)}},mass:{get:function(){return this.eb},set:function(a){this.eb!==a&&(this.eb=a)}},forceX:{get:function(){return this.T},set:function(a){this.T!==a&&(this.T=a)}},forceY:{ get:function(){return this.Ja},set:function(a){this.Ja!==a&&(this.Ja=a)}}});vs.className="ForceDirectedVertex";function ws(a){nq.call(this,a);this.l=this.v=NaN}ma(ws,nq);ws.prototype.serializeEdgeProperties=function(a,b){nq.prototype.serializeEdgeProperties.call(this,a,b);a.stiffness=this.stiffness;a.length=this.length};ws.prototype.deserializeEdgeProperties=function(a,b,c,d){nq.prototype.deserializeEdgeProperties.call(this,a,b,c,d);this.stiffness=a.stiffness;this.length=a.length}; na.Object.defineProperties(ws.prototype,{stiffness:{get:function(){return this.v},set:function(a){this.v!==a&&(this.v=a)}},length:{get:function(){return this.l},set:function(a){this.l!==a&&(this.l=a)}}});ws.className="ForceDirectedEdge";function us(){var a=0;void 0===a&&(a=42);this.seed=a;this.$y=48271;this.bz=2147483647;this.Q=44488.07041494893;this.cz=3399;this.az=1/2147483647;this.random()} us.prototype.random=function(){var a=this.seed%this.Q*this.$y-this.seed/this.Q*this.cz;0<a?this.seed=a:this.seed=a+this.bz;return this.seed*this.az};us.className="RandomNumberGenerator"; function xs(){Bi.call(this);this.Zb=this.ve=25;this.K=0;this.jl=ys;this.Nl=zs;this.Cl=As;this.Rj=4;this.Zk=Bs;this.pg=15;this.kf=!0;this.Ho=4;this.Ba=this.Ii=this.ra=-1;this.pc=this.mh=0;this.Ia=this.yd=this.zd=this.$d=this.Ab=null;this.oh=0;this.$o=this.Wj=null;this.Gc=0;this.ap=null;this.Xc=new I;this.ye=[];this.ye.length=100}ma(xs,Bi); xs.prototype.cloneProtected=function(a){Bi.prototype.cloneProtected.call(this,a);a.ve=this.ve;a.Zb=this.Zb;a.K=this.K;a.jl=this.jl;a.Nl=this.Nl;a.Cl=this.Cl;a.Rj=this.Rj;a.Zk=this.Zk;a.pg=this.pg;a.kf=this.kf;a.Ho=this.Ho}; xs.prototype.serializeLayoutProperties=function(a,b){Bi.prototype.serializeLayoutProperties.call(this,a,b);a.layerSpacing=this.layerSpacing;a.columnSpacing=this.columnSpacing;a.direction=this.direction;a.cycleRemoveOption=this.cycleRemoveOption.name;a.layeringOption=this.layeringOption.name;a.initializeOption=this.initializeOption.name;a.iterations=this.iterations;a.aggressiveOption=this.aggressiveOption.name;a.packOption=this.packOption;a.setsPortSpots=this.setsPortSpots;a.linkSpacing=this.linkSpacing; a.ra=this.ra;a.Ii=this.Ii;a.Ba=this.Ba;a.mh=this.mh;a.pc=this.pc;a.Ab=this.Ab;a.oh=this.oh;a.Gc=this.Gc;a.Xc={x:this.Xc.x,y:this.Xc.y}}; xs.prototype.deserializeLayoutProperties=function(a,b,c,d,e){Bi.prototype.deserializeLayoutProperties.call(this,a,b,c,d,e);this.layerSpacing=a.layerSpacing;this.columnSpacing=a.columnSpacing;this.direction=a.direction;this.cycleRemoveOption=$a(xs,a.cycleRemoveOption);this.layeringOption=$a(xs,a.layeringOption);this.initializeOption=$a(xs,a.initializeOption);this.iterations=a.iterations;this.aggressiveOption=$a(xs,a.aggressiveOption);this.packOption=a.packOption;this.setsPortSpots=a.setsPortSpots; this.linkSpacing=a.linkSpacing;this.ra=a.ra;this.Ii=a.Ii;this.Ba=a.Ba;this.mh=a.mh;this.pc=a.pc;this.Ab=a.Ab;this.oh=a.oh;this.Gc=a.Gc;this.Xc=new I(this.Xc.x,this.Xc.y);e&&!d&&e.edges.each(function(a){if(!a.link&&a.fromVertex&&a.toVertex&&(null===a.fromVertex.node||null===a.toVertex.node)){for(var b=a.fromVertex;null!==b&&null===b.node&&0<b.ud.count;){var c=b.ud.J(0);if(c.link){a.link=c.link;break}b=c.fromVertex}if(!a.link){for(c=a.toVertex;null!==c&&null===c.node&&0<c.Gd.count;){var d=c.Gd.J(0); if(d.link){a.link=d.link;break}c=d.toVertex}if(!a.link)for(c=c.ud.iterator;c.next();)if(d=c.value,d.link&&d.fromVertex===b){a.link=d.link;break}}}})};xs.prototype.jb=function(a){a.classType===xs?0===a.name.indexOf("Aggressive")?this.aggressiveOption=a:0===a.name.indexOf("Cycle")?this.cycleRemoveOption=a:0===a.name.indexOf("Init")?this.initializeOption=a:0===a.name.indexOf("Layer")?this.layeringOption=a:B("Unknown enum value: "+a):Bi.prototype.jb.call(this,a)};xs.prototype.createNetwork=function(){return new Cs(this)}; xs.prototype.doLayout=function(a){null===this.network&&(this.network=this.makeNetwork(a));this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin);this.Ii=-1;this.pc=this.mh=0;this.ap=this.$o=this.Wj=null;for(a=0;a<this.ye.length;a++)this.ye[a]=null;if(0<this.network.vertexes.count){this.network.yq();if(this.Vw())return;this.cycleRemoveOption!==Ds&&this.removeCycles();for(a=this.network.vertexes.iterator;a.next();)a.value.layer=-1;this.ra=-1;this.assignLayers();for(a.reset();a.next();)this.ra= Math.max(this.ra,a.value.layer);this.cycleRemoveOption===Ds&&this.removeCycles();a=this.network;for(var b=[],c=a.edges.iterator;c.next();){var d=c.value;d.valid=!1;b.push(d)}for(c=0;c<b.length;c++){d=b[c];var e=d.fromVertex,f=d.toVertex;if(!(d.valid||(null===e.node&&null===e.data||null===f.node&&null===f.data)&&e.layer===f.layer)){var g=0,h=0,k=0,l=0;if(null!==d.link){h=d.link;if(null===h)continue;var m=e.node;g=f.node;if(null===m||null===g)continue;var n=h.fromNode;k=h.toNode;var p=h.fromPort;h= h.toPort;if(d.rev){l=n;var r=p;n=k;p=h;k=l;h=r}var q=e.focus;l=f.focus;var u=d.rev?f.bounds:e.bounds;r=I.alloc();m!==n?u.s()&&n.isVisible()?n.actualBounds.s()?(n.Ff(p,Bc,r),r.x+=n.actualBounds.x-u.x,r.y+=n.actualBounds.y-u.y):(n.Ff(p,Bc,r),r.s()||r.assign(q)):r.assign(q):u.s()?(n.Ff(p,Bc,r),r.s()||r.assign(q)):r.assign(q);n=d.rev?e.bounds:f.bounds;m=I.alloc();g!==k?n.s()&&k.isVisible()?k.actualBounds.s()?(k.Ff(h,Bc,m),m.x+=k.actualBounds.x-n.x,m.y+=k.actualBounds.y-n.y):(k.Ff(h,Bc,m),m.s()||m.assign(l)): m.assign(l):n.s()?(k.Ff(h,Bc,m),m.s()||m.assign(l)):m.assign(l);90===this.K||270===this.K?(g=Math.round((r.x-q.x)/this.Zb),k=r.x,h=Math.round((m.x-l.x)/this.Zb),l=m.x):(g=Math.round((r.y-q.y)/this.Zb),k=r.y,h=Math.round((m.y-l.y)/this.Zb),l=m.y);I.free(r);I.free(m);d.portFromColOffset=g;d.portFromPos=k;d.portToColOffset=h;d.portToPos=l}else d.portFromColOffset=0,d.portFromPos=0,d.portToColOffset=0,d.portToPos=0;r=e.layer;m=f.layer;n=0;u=d.link;if(null!==u){var v=u.fromPort,w=u.toPort;if(null!==v&& null!==w){var y=u.fromNode;p=u.toNode;if(null!==y&&null!==p){var z=Es(this,!0),A=Es(this,!1),C=this.setsPortSpots?z:u.computeSpot(!0,v);q=this.setsPortSpots?A:u.computeSpot(!1,w);var F=u.isOrthogonal;C.Qc()&&C.Gf(A)&&q.Qc()&&q.Gf(z)?n=0:(z=u.getLinkPoint(y,v,C,!0,F,p,w,I.alloc()),A=u.getLinkDirection(y,v,z,C,!0,F,p,w),I.free(z),C.Wt()||A!==Fs(this,d,!0)?this.setsPortSpots&&null!==y&&1===y.ports.count&&d.rev&&(n+=1):n+=1,C=u.getLinkPoint(p,w,q,!1,F,y,v,I.alloc()),u=u.getLinkDirection(p,w,C,q,!1,F, y,v),I.free(C),q.Wt()||u!==Fs(this,d,!1)?this.setsPortSpots&&null!==p&&1===p.ports.count&&d.rev&&(n+=2):n+=2)}}}p=n;n=1===p||3===p?!0:!1;if(p=2===p||3===p?!0:!1)q=a.createVertex(),q.node=null,q.yf=1,q.layer=r,q.near=e,a.Cg(q),e=a.Ek(e,q,d.link),e.valid=!1,e.rev=d.rev,e.portFromColOffset=g,e.portToColOffset=0,e.portFromPos=k,e.portToPos=0,e=q;u=1;n&&u--;if(r-m>u&&0<r){d.valid=!1;q=a.createVertex();q.node=null;q.yf=2;q.layer=r-1;a.Cg(q);e=a.Ek(e,q,d.link);e.valid=!0;e.rev=d.rev;e.portFromColOffset= p?0:g;e.portToColOffset=0;e.portFromPos=p?0:k;e.portToPos=0;e=q;for(r--;r-m>u&&0<r;)q=a.createVertex(),q.node=null,q.yf=3,q.layer=r-1,a.Cg(q),e=a.Ek(e,q,d.link),e.valid=!0,e.rev=d.rev,e.portFromColOffset=0,e.portToColOffset=0,e.portFromPos=0,e.portToPos=0,e=q,r--;e=a.Ek(q,f,d.link);e.valid=!n;n&&(q.near=f);e.rev=d.rev;e.portFromColOffset=0;e.portToColOffset=h;e.portFromPos=0;e.portToPos=l}else d.valid=!0}}a=this.Ab=[];for(b=0;b<=this.ra;b++)a[b]=0;for(b=this.network.vertexes.iterator;b.next();)b.value.index= -1;this.initializeIndices();this.Ii=-1;for(c=this.pc=this.mh=0;c<=this.ra;c++)a[c]>a[this.pc]&&(this.Ii=a[c]-1,this.pc=c),a[c]<a[this.mh]&&(this.mh=c);this.ap=[];for(c=0;c<a.length;c++)this.ap[c]=[];for(b.reset();b.next();)a=b.value,this.ap[a.layer][a.index]=a;this.Ba=-1;for(a=0;a<=this.ra;a++){b=Gs(this,a);c=0;d=this.Ab[a];for(f=0;f<d;f++)e=b[f],c+=this.nodeMinColumnSpace(e,!0),e.column=c,c+=1,c+=this.nodeMinColumnSpace(e,!1);this.Ba=Math.max(this.Ba,c-1);Hs(this,a,b)}this.reduceCrossings();this.straightenAndPack(); this.updateParts()}this.network=null;this.isValidLayout=!0};xs.prototype.linkMinLength=function(){return 1};function Is(a){var b=a.fromVertex.node||a.fromVertex.data;a=a.toVertex.node||a.toVertex.data;return null===b&&null===a?8:null===b||null===a?4:1}xs.prototype.nodeMinLayerSpace=function(a,b){return null===a.node&&null===a.data?0:90===this.K||270===this.K?b?a.focus.y+10:a.bounds.height-a.focus.y+10:b?a.focus.x+10:a.bounds.width-a.focus.x+10}; xs.prototype.nodeMinColumnSpace=function(a,b){if(null===a.node&&null===a.data)return 0;var c=b?a.Mk:a.Lk;if(null!==c)return c;c=this.K;return 90===c||270===c?b?a.Mk=a.focus.x/this.Zb+1|0:a.Lk=(a.bounds.width-a.focus.x)/this.Zb+1|0:b?a.Mk=a.focus.y/this.Zb+1|0:a.Lk=(a.bounds.height-a.focus.y)/this.Zb+1|0};function Js(a){null===a.Wj&&(a.Wj=[]);for(var b=0,c=a.network.vertexes.iterator;c.next();){var d=c.value;a.Wj[b]=d.layer;b++;a.Wj[b]=d.column;b++;a.Wj[b]=d.index;b++}return a.Wj} function Ks(a,b){var c=0;for(a=a.network.vertexes.iterator;a.next();){var d=a.value;d.layer=b[c];c++;d.column=b[c];c++;d.index=b[c];c++}} function Ls(a,b,c){var d=Gs(a,b),e=a.Ab[b];if(null===a.$o||a.$o.length<e*e)a.$o=[];for(var f=a.$o,g=0;g<e;g++){var h=0,k=d[g],l=k.near;if(null!==l&&l.layer===k.layer)if(k=l.index,k>g)for(var m=g+1;m<k;m++){var n=d[m];n.near===l&&n.yf===l.yf||h++}else for(m=g-1;m>k;m--)n=d[m],n.near===l&&n.yf===l.yf||h++;var p;if(0<=c)for(k=d[g].sourceEdgesArrayAccess,l=0;l<k.length;l++){var r=k[l];if(r.valid&&r.fromVertex.layer!==b)for(n=r.fromVertex.index,m=r.portToPos,r=r.portFromPos,p=l+1;p<k.length;p++){var q= k[p];if(q.valid&&q.fromVertex.layer!==b){var u=q.fromVertex.index;var v=q.portToPos;q=q.portFromPos;m<v&&(n>u||n===u&&r>q)&&h++;v<m&&(u>n||u===n&&q>r)&&h++}}}if(0>=c)for(k=d[g].destinationEdgesArrayAccess,l=0;l<k.length;l++)if(r=k[l],r.valid&&r.toVertex.layer!==b)for(n=r.toVertex.index,m=r.portToPos,r=r.portFromPos,p=l+1;p<k.length;p++)q=k[p],q.valid&&q.toVertex.layer!==b&&(u=q.toVertex.index,v=q.portToPos,q=q.portFromPos,r<q&&(n>u||n===u&&m>v)&&h++,q<r&&(u>n||u===n&&v>m)&&h++);f[g*e+g]=h;for(k=g+ 1;k<e;k++){var w=0,y=0;if(0<=c){h=d[g].sourceEdgesArrayAccess;var z=d[k].sourceEdgesArrayAccess;for(l=0;l<h.length;l++)if(r=h[l],r.valid&&r.fromVertex.layer!==b)for(n=r.fromVertex.index,r=r.portFromPos,p=0;p<z.length;p++)q=z[p],q.valid&&q.fromVertex.layer!==b&&(u=q.fromVertex.index,q=q.portFromPos,(n<u||n===u&&r<q)&&y++,(u<n||u===n&&q<r)&&w++)}if(0>=c)for(h=d[g].destinationEdgesArrayAccess,z=d[k].destinationEdgesArrayAccess,l=0;l<h.length;l++)if(r=h[l],r.valid&&r.toVertex.layer!==b)for(n=r.toVertex.index, m=r.portToPos,p=0;p<z.length;p++)q=z[p],q.valid&&q.toVertex.layer!==b&&(u=q.toVertex.index,v=q.portToPos,(n<u||n===u&&m<v)&&y++,(u<n||u===n&&v<m)&&w++);f[g*e+k]=w;f[k*e+g]=y}}Hs(a,b,d);return f}xs.prototype.countCrossings=function(){for(var a=0,b=0;b<=this.ra;b++)for(var c=Ls(this,b,1),d=this.Ab[b],e=0;e<d;e++)for(var f=e;f<d;f++)a+=c[e*d+f];return a}; function Ms(a){for(var b=0,c=0;c<=a.ra;c++){for(var d=a,e=c,f=Gs(d,e),g=d.Ab[e],h=0,k=0;k<g;k++){var l=f[k].destinationEdgesArrayAccess;if(null!==l)for(var m=0;m<l.length;m++){var n=l[m];if(n.valid&&n.toVertex.layer!==e){var p=n.fromVertex.column+n.portFromColOffset;var r=n.toVertex.column+n.portToColOffset;h+=(Math.abs(p-r)+1)*Is(n)}}}Hs(d,e,f);b+=h}return b} xs.prototype.normalize=function(){var a=Infinity;this.Ba=-1;for(var b=this.network.vertexes.iterator;b.next();){var c=b.value;a=Math.min(a,c.column-this.nodeMinColumnSpace(c,!0));this.Ba=Math.max(this.Ba,c.column+this.nodeMinColumnSpace(c,!1))}for(b.reset();b.next();)b.value.column-=a;this.Ba-=a}; function Ns(a,b,c){for(var d=Gs(a,b),e=a.Ab[b],f=[],g=0;g<e;g++){var h=d[g],k=null;0>=c&&(k=h.sourceEdgesArrayAccess);var l=null;0<=c&&(l=h.destinationEdgesArrayAccess);var m=0,n=0,p=h.near;null!==p&&p.layer===h.layer&&(m+=p.column-1,n++);if(null!==k)for(p=0;p<k.length;p++){h=k[p];var r=h.fromVertex;h.valid&&!h.rev&&r.layer!==b&&(m+=r.column,n++)}if(null!==l)for(k=0;k<l.length;k++)h=l[k],p=h.toVertex,h.valid&&!h.rev&&p.layer!==b&&(m+=p.column,n++);f[g]=0===n?-1:m/n}Hs(a,b,d);return f} function Os(a,b,c){for(var d=Gs(a,b),e=a.Ab[b],f=[],g=0;g<e;g++){var h=d[g],k=null;0>=c&&(k=h.sourceEdgesArrayAccess);var l=null;0<=c&&(l=h.destinationEdgesArrayAccess);var m=0,n=[],p=h.near;null!==p&&p.layer===h.layer&&(n[m]=p.column-1,m++);h=void 0;if(null!==k)for(p=0;p<k.length;p++){h=k[p];var r=h.fromVertex;h.valid&&!h.rev&&r.layer!==b&&(n[m]=r.column+h.portFromColOffset,m++)}if(null!==l)for(k=0;k<l.length;k++)h=l[k],p=h.toVertex,h.valid&&!h.rev&&p.layer!==b&&(n[m]=p.column+h.portToColOffset, m++);0===m?f[g]=-1:(n.sort(function(a,b){return a-b}),l=m>>1,f[g]=0!==(m&1)?n[l]:n[l-1]+n[l]>>1)}Hs(a,b,d);return f}function Ps(a,b,c,d,e,f){if(b.component===d){b.component=c;if(e)for(var g=b.destinationEdges;g.next();){var h=g.value;var k=h.toVertex;var l=b.layer-k.layer;h=a.linkMinLength(h);l===h&&Ps(a,k,c,d,e,f)}if(f)for(g=b.sourceEdges;g.next();)h=g.value,k=h.fromVertex,l=k.layer-b.layer,h=a.linkMinLength(h),l===h&&Ps(a,k,c,d,e,f)}} function Qs(a,b,c,d,e,f){if(b.component===d){b.component=c;if(e)for(var g=b.destinationEdges;g.next();)Qs(a,g.value.toVertex,c,d,e,f);if(f)for(b=b.sourceEdges;b.next();)Qs(a,b.value.fromVertex,c,d,e,f)}} xs.prototype.removeCycles=function(){for(var a=this.network.edges.iterator;a.next();)a.value.rev=!1;switch(this.jl){default:case Rs:a=this.network;var b=0,c=a.vertexes.count-1,d=[];d.length=c+1;for(var e=a.vertexes.iterator;e.next();)e.value.valid=!0;for(;null!==Ss(a);){for(e=Ts(a);null!==e;)d[c]=e,c--,e.valid=!1,e=Ts(a);for(e=Us(a);null!==e;)d[b]=e,b++,e.valid=!1,e=Us(a);e=null;for(var f=0,g=this.network.vertexes.iterator;g.next();){var h=g.value;if(h.valid){for(var k=0,l=h.destinationEdges;l.next();)l.value.toVertex.valid&& k++;l=0;for(var m=h.sourceEdges;m.next();)m.value.fromVertex.valid&&l++;if(null===e||f<k-l)e=h,f=k-l}}null!==e&&(d[b]=e,b++,e.valid=!1)}for(b=0;b<a.vertexes.count;b++)d[b].index=b;for(d=a.edges.iterator;d.next();)b=d.value,b.fromVertex.index>b.toVertex.index&&(a.Qm(b),b.rev=!0);break;case ys:for(d=this.network.vertexes.iterator;d.next();)a=d.value,a.Dg=-1,a.finish=-1;for(a=this.network.edges.iterator;a.next();)a.value.forest=!1;this.oh=0;for(d.reset();d.next();)b=d.value,0===b.sourceEdges.count&& Vs(this,b);for(d.reset();d.next();)b=d.value,-1===b.Dg&&Vs(this,b);for(a.reset();a.next();)d=a.value,d.forest||(b=d.fromVertex,c=b.finish,e=d.toVertex,f=e.finish,e.Dg<b.Dg&&c<f&&(this.network.Qm(d),d.rev=!0));break;case Ds:a=this.network;b=a.vertexes.iterator;for(d=Infinity;b.next();)d=Math.min(d,b.value.layer);if(Infinity>d){if(0>d)for(b.reset();b.next();)b.value.layer-=d;d=[];for(b.reset();b.next();)c=b.value,e=d[c.layer],void 0===e?d[c.layer]=[c]:e.push(c);for(c=b=0;c<d.length;c++)if(e=d[c],!e|| 0===e.length)b++;else if(0<c)for(f=0;f<e.length;f++)e[f].layer-=b;for(d=a.edges.iterator;d.next();)b=d.value,b.fromVertex.layer<b.toVertex.layer&&(a.Qm(b),b.rev=!0)}}};function Ss(a){for(a=a.vertexes.iterator;a.next();){var b=a.value;if(b.valid)return b}return null}function Ts(a){for(a=a.vertexes.iterator;a.next();){var b=a.value;if(b.valid){for(var c=!0,d=b.destinationEdges;d.next();)if(d.value.toVertex.valid){c=!1;break}if(c)return b}}return null} function Us(a){for(a=a.vertexes.iterator;a.next();){var b=a.value;if(b.valid){for(var c=!0,d=b.sourceEdges;d.next();)if(d.value.fromVertex.valid){c=!1;break}if(c)return b}}return null}function Vs(a,b){b.Dg=a.oh;a.oh++;for(var c=b.destinationEdges;c.next();){var d=c.value,e=d.toVertex;-1===e.Dg&&(d.forest=!0,Vs(a,e))}b.finish=a.oh;a.oh++} xs.prototype.assignLayers=function(){switch(this.Nl){case Ws:Xs(this);break;case Ys:for(var a,b=this.network.vertexes.iterator;b.next();)a=Zs(this,b.value),this.ra=Math.max(a,this.ra);for(b.reset();b.next();)a=b.value,a.layer=this.ra-a.layer;break;default:case zs:Xs(this);for(b=this.network.vertexes.iterator;b.next();)b.value.valid=!1;for(b.reset();b.next();)a=b.value,0===a.sourceEdges.count&&$s(this,a);a=Infinity;for(b.reset();b.next();)a=Math.min(a,b.value.layer);this.ra=-1;for(b.reset();b.next();){var c= b.value;c.layer-=a;this.ra=Math.max(this.ra,c.layer)}}};function Xs(a){for(var b=a.network.vertexes.iterator;b.next();){var c=at(a,b.value);a.ra=Math.max(c,a.ra)}}function at(a,b){var c=0;if(-1===b.layer){for(var d=b.destinationEdges;d.next();){var e=d.value,f=e.toVertex;e=a.linkMinLength(e);c=Math.max(c,at(a,f)+e)}b.layer=c}else c=b.layer;return c} function Zs(a,b){var c=0;if(-1===b.layer){for(var d=b.sourceEdges;d.next();){var e=d.value,f=e.fromVertex;e=a.linkMinLength(e);c=Math.max(c,Zs(a,f)+e)}b.layer=c}else c=b.layer;return c} function $s(a,b){if(!b.valid){b.valid=!0;for(var c=b.destinationEdges;c.next();)$s(a,c.value.toVertex);for(c=a.network.vertexes.iterator;c.next();)c.value.component=-1;for(var d=b.sourceEdgesArrayAccess,e=d.length,f=0;f<e;f++){var g=d[f],h=g.fromVertex,k=g.toVertex;g=a.linkMinLength(g);h.layer-k.layer>g&&Ps(a,h,0,-1,!0,!1)}for(Ps(a,b,1,-1,!0,!0);0!==b.component;){f=0;d=Infinity;h=0;k=null;for(g=a.network.vertexes.iterator;g.next();){var l=g.value;if(1===l.component){var m=0,n=!1,p=l.sourceEdgesArrayAccess; e=p.length;for(var r=0;r<e;r++){var q=p[r],u=q.fromVertex;m+=1;1!==u.component&&(f+=1,u=u.layer-l.layer,q=a.linkMinLength(q),d=Math.min(d,u-q))}p=l.destinationEdgesArrayAccess;e=p.length;for(r=0;r<e;r++)q=p[r].toVertex,--m,1!==q.component?--f:n=!0;(null===k||m<h)&&!n&&(k=l,h=m)}}if(0<f){for(c.reset();c.next();)e=c.value,1===e.component&&(e.layer+=d);b.component=0}else k.component=0}for(c=a.network.vertexes.iterator;c.next();)c.value.component=-1;for(Ps(a,b,1,-1,!0,!1);0!==b.component;){d=0;e=Infinity; f=0;h=null;for(k=a.network.vertexes.iterator;k.next();)if(g=k.value,1===g.component){l=0;m=!1;p=g.sourceEdgesArrayAccess;n=p.length;for(r=0;r<n;r++)q=p[r].fromVertex,l+=1,1!==q.component?d+=1:m=!0;p=g.destinationEdgesArrayAccess;n=p.length;for(r=0;r<n;r++)q=p[r],u=q.toVertex,--l,1!==u.component&&(--d,u=g.layer-u.layer,q=a.linkMinLength(q),e=Math.min(e,u-q));(null===h||l>f)&&!m&&(h=g,f=l)}if(0>d){for(c.reset();c.next();)d=c.value,1===d.component&&(d.layer-=e);b.component=0}else h.component=0}}} function Fs(a,b,c){return 90===a.K?c&&!b.rev||!c&&b.rev?270:90:180===a.K?c&&!b.rev||!c&&b.rev?0:180:270===a.K?c&&!b.rev||!c&&b.rev?90:270:c&&!b.rev||!c&&b.rev?180:0} xs.prototype.initializeIndices=function(){switch(this.Cl){default:case bt:for(var a=this.network.vertexes.iterator;a.next();){var b=a.value,c=b.layer;b.index=this.Ab[c];this.Ab[c]++}break;case As:a=this.network.vertexes.iterator;for(b=this.ra;0<=b;b--)for(a.reset();a.next();)c=a.value,c.layer===b&&-1===c.index&&ct(this,c);break;case dt:for(a=this.network.vertexes.iterator,b=0;b<=this.ra;b++)for(a.reset();a.next();)c=a.value,c.layer===b&&-1===c.index&&et(this,c)}}; function ct(a,b){var c=b.layer;b.index=a.Ab[c];a.Ab[c]++;b=b.destinationEdgesArrayAccess;for(c=!0;c;){c=!1;for(var d=0;d<b.length-1;d++){var e=b[d],f=b[d+1];e.portFromColOffset>f.portFromColOffset&&(c=!0,b[d]=f,b[d+1]=e)}}for(c=0;c<b.length;c++)d=b[c],d.valid&&(d=d.toVertex,-1===d.index&&ct(a,d))} function et(a,b){var c=b.layer;b.index=a.Ab[c];a.Ab[c]++;b=b.sourceEdgesArrayAccess;for(var d=!0;d;)for(d=!1,c=0;c<b.length-1;c++){var e=b[c],f=b[c+1];e.portToColOffset>f.portToColOffset&&(d=!0,b[c]=f,b[c+1]=e)}for(c=0;c<b.length;c++)d=b[c],d.valid&&(d=d.fromVertex,-1===d.index&&et(a,d))} xs.prototype.reduceCrossings=function(){var a=this.countCrossings(),b=Js(this),c,d;for(c=0;c<this.Rj;c++){for(d=0;d<=this.ra;d++)ft(this,d,1),gt(this,d,1);var e=this.countCrossings();e<a&&(a=e,b=Js(this));for(d=this.ra;0<=d;d--)ft(this,d,-1),gt(this,d,-1);e=this.countCrossings();e<a&&(a=e,b=Js(this))}Ks(this,b);for(c=0;c<this.Rj;c++){for(d=0;d<=this.ra;d++)ft(this,d,0),gt(this,d,0);e=this.countCrossings();e<a&&(a=e,b=Js(this));for(d=this.ra;0<=d;d--)ft(this,d,0),gt(this,d,0);e=this.countCrossings(); e<a&&(a=e,b=Js(this))}Ks(this,b);var f,g,h;switch(this.Zk){case ht:break;case it:for(h=a+1;(d=this.countCrossings())<h;)for(h=d,c=this.ra;0<=c;c--)for(g=0;g<=c;g++){for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=gt(this,d,-1)||f;e=this.countCrossings();e>=a?Ks(this,b):(a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=gt(this,d,1)||f;e=this.countCrossings();e>=a?Ks(this,b):(a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=gt(this,d,1)||f;e>=a?Ks(this,b):(a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f= gt(this,d,-1)||f;e>=a?Ks(this,b):(a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=gt(this,d,0)||f;e>=a?Ks(this,b):(a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=gt(this,d,0)||f;e>=a?Ks(this,b):(a=e,b=Js(this))}break;default:case Bs:for(c=this.ra,g=0,h=a+1;(d=this.countCrossings())<h;){h=d;for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=gt(this,d,-1)||f;e=this.countCrossings();e>=a?Ks(this,b):(a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=gt(this,d,1)||f;e=this.countCrossings();e>=a?Ks(this,b): (a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=gt(this,d,1)||f;e>=a?Ks(this,b):(a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=gt(this,d,-1)||f;e>=a?Ks(this,b):(a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=gt(this,d,0)||f;e>=a?Ks(this,b):(a=e,b=Js(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=gt(this,d,0)||f;e>=a?Ks(this,b):(a=e,b=Js(this))}}Ks(this,b)}; function ft(a,b,c){var d=Gs(a,b),e=a.Ab[b],f=Os(a,b,c),g=Ns(a,b,c);for(c=0;c<e;c++)-1===g[c]&&(g[c]=d[c].column),-1===f[c]&&(f[c]=d[c].column);for(var h=!0,k;h;)for(h=!1,c=0;c<e-1;c++)if(f[c+1]<f[c]||f[c+1]===f[c]&&g[c+1]<g[c])h=!0,k=f[c],f[c]=f[c+1],f[c+1]=k,k=g[c],g[c]=g[c+1],g[c+1]=k,k=d[c],d[c]=d[c+1],d[c+1]=k;for(c=f=0;c<e;c++)k=d[c],k.index=c,f+=a.nodeMinColumnSpace(k,!0),k.column=f,f+=1,f+=a.nodeMinColumnSpace(k,!1);Hs(a,b,d)} function gt(a,b,c){var d=Gs(a,b),e=a.Ab[b];c=Ls(a,b,c);var f;var g=[];for(f=0;f<e;f++)g[f]=-1;var h=[];for(f=0;f<e;f++)h[f]=-1;for(var k=!1,l=!0;l;)for(l=!1,f=0;f<e-1;f++){var m=c[d[f].index*e+d[f+1].index],n=c[d[f+1].index*e+d[f].index],p=0,r=0,q=d[f].column,u=d[f+1].column,v=a.nodeMinColumnSpace(d[f],!0),w=a.nodeMinColumnSpace(d[f],!1),y=a.nodeMinColumnSpace(d[f+1],!0),z=a.nodeMinColumnSpace(d[f+1],!1);v=q-v+y;w=u-w+z;var A=d[f].sourceEdges.iterator;for(A.reset();A.next();)if(y=A.value,z=y.fromVertex, y.valid&&z.layer===b){for(y=0;d[y]!==z;)y++;y<f&&(p+=2*(f-y),r+=2*(f+1-y));y===f+1&&(p+=1);y>f+1&&(p+=4*(y-f),r+=4*(y-(f+1)))}A=d[f].destinationEdges.iterator;for(A.reset();A.next();)if(y=A.value,z=y.toVertex,y.valid&&z.layer===b){for(y=0;d[y]!==z;)y++;y===f+1&&(r+=1)}A=d[f+1].sourceEdges.iterator;for(A.reset();A.next();)if(y=A.value,z=y.fromVertex,y.valid&&z.layer===b){for(y=0;d[y]!==z;)y++;y<f&&(p+=2*(f+1-y),r+=2*(f-y));y===f&&(r+=1);y>f+1&&(p+=4*(y-(f+1)),r+=4*(y-f))}A=d[f+1].destinationEdges.iterator; for(A.reset();A.next();)if(y=A.value,z=y.toVertex,y.valid&&z.layer===b){for(y=0;d[y]!==z;)y++;y===f&&(p+=1)}y=z=0;A=g[d[f].index];var C=h[d[f].index],F=g[d[f+1].index],Q=h[d[f+1].index];-1!==A&&(z+=Math.abs(A-q),y+=Math.abs(A-w));-1!==C&&(z+=Math.abs(C-q),y+=Math.abs(C-w));-1!==F&&(z+=Math.abs(F-u),y+=Math.abs(F-v));-1!==Q&&(z+=Math.abs(Q-u),y+=Math.abs(Q-v));if(r<p-.5||r===p&&n<m-.5||r===p&&n===m&&y<z-.5)l=k=!0,d[f].column=w,d[f+1].column=v,m=d[f],d[f]=d[f+1],d[f+1]=m}for(f=0;f<e;f++)d[f].index= f;Hs(a,b,d);return k} xs.prototype.straightenAndPack=function(){var a=0!==(this.pg&1);var b=0!==(this.pg&jt);1E3<this.network.edges.count&&b&&(a=!1);if(a){var c=[];for(b=0;b<=this.ra;b++)c[b]=0;for(var d,e=this.network.vertexes.iterator;e.next();){var f=e.value;b=f.layer;d=f.column;f=this.nodeMinColumnSpace(f,!1);c[b]=Math.max(c[b],d+f)}for(e.reset();e.next();)f=e.value,b=f.layer,d=f.column,f.column=(8*(this.Ba-c[b])>>1)+8*d;this.Ba*=8}if(0!==(this.pg&2))for(c=!0;c;){c=!1;for(b=this.pc+1;b<=this.ra;b++)c=kt(this,b,1)|| c;for(b=this.pc-1;0<=b;b--)c=kt(this,b,-1)||c;c=kt(this,this.pc,0)||c}if(0!==(this.pg&4)){for(b=this.pc+1;b<=this.ra;b++)lt(this,b,1);for(b=this.pc-1;0<=b;b--)lt(this,b,-1);lt(this,this.pc,0)}a&&(mt(this,-1),mt(this,1));if(0!==(this.pg&2))for(c=!0;c;){c=!1;c=kt(this,this.pc,0)||c;for(b=this.pc+1;b<=this.ra;b++)c=kt(this,b,0)||c;for(b=this.pc-1;0<=b;b--)c=kt(this,b,0)||c}};function kt(a,b,c){for(var d=!1;nt(a,b,c);)d=!0;return d} function nt(a,b,c){var d,e=Gs(a,b),f=a.Ab[b],g=Ns(a,b,-1);if(0<c)for(d=0;d<f;d++)g[d]=-1;var h=Ns(a,b,1);if(0>c)for(d=0;d<f;d++)h[d]=-1;for(var k=!1,l=!0;l;)for(l=!1,d=0;d<f;d++){var m=e[d].column,n=a.nodeMinColumnSpace(e[d],!0),p=a.nodeMinColumnSpace(e[d],!1),r=0;0>d-1||m-e[d-1].column-1>n+a.nodeMinColumnSpace(e[d-1],!1)?r=m-1:r=m;n=d+1>=f||e[d+1].column-m-1>p+a.nodeMinColumnSpace(e[d+1],!0)?m+1:m;var q=p=0,u=0;if(0>=c)for(var v=e[d].sourceEdges.iterator;v.next();){var w=v.value;var y=w.fromVertex; if(w.valid&&y.layer!==b){var z=Is(w);var A=w.portFromColOffset;w=w.portToColOffset;y=y.column;p+=(Math.abs(m+w-(y+A))+1)*z;q+=(Math.abs(r+w-(y+A))+1)*z;u+=(Math.abs(n+w-(y+A))+1)*z}}if(0<=c)for(v=e[d].destinationEdges.iterator;v.next();)w=v.value,y=w.toVertex,w.valid&&y.layer!==b&&(z=Is(w),A=w.portFromColOffset,w=w.portToColOffset,y=y.column,p+=(Math.abs(m+A-(y+w))+1)*z,q+=(Math.abs(r+A-(y+w))+1)*z,u+=(Math.abs(n+A-(y+w))+1)*z);w=A=z=0;v=g[e[d].index];y=h[e[d].index];-1!==v&&(z+=Math.abs(v-m),A+= Math.abs(v-r),w+=Math.abs(v-n));-1!==y&&(z+=Math.abs(y-m),A+=Math.abs(y-r),w+=Math.abs(y-n));if(q<p||q===p&&A<z)l=k=!0,e[d].column=r;else if(u<p||u===p&&w<z)l=k=!0,e[d].column=n}Hs(a,b,e);a.normalize();return k} function lt(a,b,c){var d=Gs(a,b),e=a.Ab[b],f=Os(a,b,c),g=[];for(c=0;c<e;c++)g[c]=f[c];for(f=!0;f;)for(f=!1,c=0;c<e;c++){var h=d[c].column,k=a.nodeMinColumnSpace(d[c],!0),l=a.nodeMinColumnSpace(d[c],!1),m=0;if(-1===g[c])if(0===c&&c===e-1)m=h;else if(0===c){var n=d[c+1].column;n-h===l+a.nodeMinColumnSpace(d[c+1],!0)?m=h-1:m=h}else c===e-1?(n=d[c-1].column,m=h-n===k+a.nodeMinColumnSpace(d[c-1],!1)?h+1:h):(n=d[c-1].column,k=n+a.nodeMinColumnSpace(d[c-1],!1)+k+1,n=d[c+1].column,l=n-a.nodeMinColumnSpace(d[c+ 1],!0)-l-1,m=(k+l)/2|0);else 0===c&&c===e-1?m=g[c]:0===c?(n=d[c+1].column,l=n-a.nodeMinColumnSpace(d[c+1],!0)-l-1,m=Math.min(g[c],l)):c===e-1?(n=d[c-1].column,k=n+a.nodeMinColumnSpace(d[c-1],!1)+k+1,m=Math.max(g[c],k)):(n=d[c-1].column,k=n+a.nodeMinColumnSpace(d[c-1],!1)+k+1,n=d[c+1].column,l=n-a.nodeMinColumnSpace(d[c+1],!0)-l-1,k<g[c]&&g[c]<l?m=g[c]:k>=g[c]?m=k:l<=g[c]&&(m=l));m!==h&&(f=!0,d[c].column=m)}Hs(a,b,d);a.normalize()} function ot(a,b){for(var c=!0,d=a.network.vertexes.iterator;d.next();){var e=d.value,f=a.nodeMinColumnSpace(e,!0),g=a.nodeMinColumnSpace(e,!1);if(e.column-f<=b&&e.column+g>=b){c=!1;break}}a=!1;if(c)for(d.reset();d.next();)c=d.value,c.column>b&&(--c.column,a=!0);return a} function pt(a,b){var c=b+1;var d,e=[],f=[];for(d=0;d<=a.ra;d++)e[d]=!1,f[d]=!1;for(var g=a.network.vertexes.iterator;g.next();){d=g.value;var h=d.column-a.nodeMinColumnSpace(d,!0),k=d.column+a.nodeMinColumnSpace(d,!1);h<=b&&k>=b&&(e[d.layer]=!0);h<=c&&k>=c&&(f[d.layer]=!0)}h=!0;c=!1;for(d=0;d<=a.ra;d++)h=h&&!(e[d]&&f[d]);if(h)for(g.reset();g.next();)a=g.value,a.column>b&&(--a.column,c=!0);return c} function mt(a,b){for(var c=0;c<=a.Ba;c++)for(;ot(a,c););a.normalize();for(c=0;c<a.Ba;c++)for(;pt(a,c););a.normalize();var d;if(0<b)for(c=0;c<=a.Ba;c++){var e=Js(a);var f=Ms(a);for(d=f+1;f<d;){d=f;qt(a,c,1);var g=Ms(a);g>f?Ks(a,e):g<f&&(f=g,e=Js(a))}}if(0>b)for(c=a.Ba;0<=c;c--)for(e=Js(a),f=Ms(a),d=f+1;f<d;)d=f,qt(a,c,-1),g=Ms(a),g>f?Ks(a,e):g<f&&(f=g,e=Js(a));a.normalize()} function qt(a,b,c){a.Gc=0;for(var d=a.network.vertexes.iterator;d.next();)d.value.component=-1;if(0<c)for(d.reset();d.next();){var e=d.value;e.column-a.nodeMinColumnSpace(e,!0)<=b&&(e.component=a.Gc)}if(0>c)for(d.reset();d.next();)e=d.value,e.column+a.nodeMinColumnSpace(e,!1)>=b&&(e.component=a.Gc);a.Gc++;for(d.reset();d.next();)b=d.value,-1===b.component&&(Qs(a,b,a.Gc,-1,!0,!0),a.Gc++);var f;b=[];for(f=0;f<a.Gc*a.Gc;f++)b[f]=!1;e=[];for(f=0;f<(a.ra+1)*(a.Ba+1);f++)e[f]=-1;for(d.reset();d.next();){f= d.value;for(var g=f.layer,h=Math.max(0,f.column-a.nodeMinColumnSpace(f,!0)),k=Math.min(a.Ba,f.column+a.nodeMinColumnSpace(f,!1));h<=k;h++)e[g*(a.Ba+1)+h]=f.component}for(f=0;f<=a.ra;f++){if(0<c)for(g=0;g<a.Ba;g++)-1!==e[f*(a.Ba+1)+g]&&-1!==e[f*(a.Ba+1)+g+1]&&e[f*(a.Ba+1)+g]!==e[f*(a.Ba+1)+g+1]&&(b[e[f*(a.Ba+1)+g]*a.Gc+e[f*(a.Ba+1)+g+1]]=!0);if(0>c)for(g=a.Ba;0<g;g--)-1!==e[f*(a.Ba+1)+g]&&-1!==e[f*(a.Ba+1)+g-1]&&e[f*(a.Ba+1)+g]!==e[f*(a.Ba+1)+g-1]&&(b[e[f*(a.Ba+1)+g]*a.Gc+e[f*(a.Ba+1)+g-1]]=!0)}e= [];for(f=0;f<a.Gc;f++)e[f]=!0;g=[];for(g.push(0);0!==g.length;)if(k=g[g.length-1],g.pop(),e[k])for(e[k]=!1,f=0;f<a.Gc;f++)b[k*a.Gc+f]&&g.splice(0,0,f);if(0<c)for(d.reset();d.next();)a=d.value,e[a.component]&&--a.column;if(0>c)for(d.reset();d.next();)c=d.value,e[c.component]&&(c.column+=1)} xs.prototype.commitLayout=function(){if(this.setsPortSpots)for(var a=Es(this,!0),b=Es(this,!1),c=this.network.edges.iterator;c.next();){var d=c.value.link;null!==d&&(d.fromSpot=a,d.toSpot=b)}this.commitNodes();this.Hv();this.isRouting&&this.commitLinks()};function Es(a,b){return 270===a.K?b?dd:gd:90===a.K?b?gd:dd:180===a.K?b?ed:fd:b?fd:ed} xs.prototype.commitNodes=function(){this.$d=[];this.zd=[];this.yd=[];this.Ia=[];for(var a=0;a<=this.ra;a++)this.$d[a]=0,this.zd[a]=0,this.yd[a]=0,this.Ia[a]=0;for(a=this.network.vertexes.iterator;a.next();){var b=a.value,c=b.layer;this.$d[c]=Math.max(this.$d[c],this.nodeMinLayerSpace(b,!0));this.zd[c]=Math.max(this.zd[c],this.nodeMinLayerSpace(b,!1))}b=0;c=this.ve;for(var d=0;d<=this.ra;d++){var e=c;0>=this.$d[d]+this.zd[d]&&(e=0);0<d&&(b+=e/2);90===this.K||0===this.K?(b+=this.zd[d],this.yd[d]=b, b+=this.$d[d]):(b+=this.$d[d],this.yd[d]=b,b+=this.zd[d]);d<this.ra&&(b+=e/2);this.Ia[d]=b}c=b;b=this.arrangementOrigin;for(d=0;d<=this.ra;d++)270===this.K?this.yd[d]=b.y+this.yd[d]:90===this.K?(this.yd[d]=b.y+c-this.yd[d],this.Ia[d]=c-this.Ia[d]):180===this.K?this.yd[d]=b.x+this.yd[d]:(this.yd[d]=b.x+c-this.yd[d],this.Ia[d]=c-this.Ia[d]);a.reset();for(c=d=Infinity;a.next();){e=a.value;var f=e.layer,g=e.column|0;if(270===this.K||90===this.K){var h=b.x+this.Zb*g;f=this.yd[f]}else h=this.yd[f],f=b.y+ this.Zb*g;e.centerX=h;e.centerY=f;d=Math.min(e.x,d);c=Math.min(e.y,c)}d=b.x-d;b=b.y-c;this.Xc=new I(d,b);for(a.reset();a.next();)c=a.value,c.x+=d,c.y+=b,c.commit()}; xs.prototype.Hv=function(){for(var a=0,b=this.ve,c=0;c<=this.ra;c++)a+=this.$d[c],a+=this.zd[c];a+=this.ra*b;b=[];c=this.Zb*this.Ba;for(var d=this.maxLayer;0<=d;d--)270===this.K?0===d?b.push(new N(0,0,c,Math.abs(this.Ia[0]))):b.push(new N(0,this.Ia[d-1],c,Math.abs(this.Ia[d-1]-this.Ia[d]))):90===this.K?0===d?b.push(new N(0,this.Ia[0],c,Math.abs(this.Ia[0]-a))):b.push(new N(0,this.Ia[d],c,Math.abs(this.Ia[d-1]-this.Ia[d]))):180===this.K?0===d?b.push(new N(0,0,Math.abs(this.Ia[0]),c)):b.push(new N(this.Ia[d- 1],0,Math.abs(this.Ia[d-1]-this.Ia[d]),c)):0===d?b.push(new N(this.Ia[0],0,Math.abs(this.Ia[0]-a),c)):b.push(new N(this.Ia[d],0,Math.abs(this.Ia[d-1]-this.Ia[d]),c));this.commitLayers(b,this.Xc)};xs.prototype.commitLayers=function(){}; xs.prototype.commitLinks=function(){for(var a=this.network.edges.iterator,b;a.next();)b=a.value.link,null!==b&&(b.Sh(),b.pk(),b.zf());for(a.reset();a.next();)b=a.value.link,null!==b&&b.xj();for(a.reset();a.next();){var c=a.value;b=c.link;if(null!==b){b.Sh();var d=b,e=d.fromNode,f=d.toNode,g=d.fromPort,h=d.toPort;if(null!==e){var k=e.findVisibleNode();null!==k&&k!==e&&(e=k,g=k.port)}null!==f&&(k=f.findVisibleNode(),null!==k&&k!==f&&(f=k,h=k.port));var l=b.computeSpot(!0,g);k=b.computeSpot(!1,h);var m= c.fromVertex,n=c.toVertex;if(c.valid){if(b.curve===sg&&4===b.pointsCount)if(m.column===n.column)c=b.getLinkPoint(e,g,l,!0,!1,f,h),g=b.getLinkPoint(f,h,k,!1,!1,e,g),c.s()||c.set(e.actualBounds.center),g.s()||g.set(f.actualBounds.center),b.pk(),b.xf(c.x,c.y),b.xf((2*c.x+g.x)/3,(2*c.y+g.y)/3),b.xf((c.x+2*g.x)/3,(c.y+2*g.y)/3),b.xf(g.x,g.y);else{var p=!1,r=!1;null!==g&&l===uc&&(p=!0);null!==h&&k===uc&&(r=!0);if(p||r){var q=b.i(0).x;c=b.i(0).y;m=b.i(3).x;d=b.i(3).y;p&&(90===this.K||270===this.K?(p=q,n= (c+d)/2):(p=(q+m)/2,n=c),b.L(1,p,n),l=b.getLinkPoint(e,g,l,!0,!1,f,h),l.s()||l.set(e.actualBounds.center),b.L(0,l.x,l.y));r&&(90===this.K||270===this.K?(l=m,c=(c+d)/2):(l=(q+m)/2,c=d),b.L(2,l,c),e=b.getLinkPoint(f,h,k,!1,!1,e,g),e.s()||e.set(f.actualBounds.center),b.L(3,e.x,e.y))}}b.zf()}else if(m.layer===n.layer)b.zf();else{p=r=!1;q=b.firstPickIndex+1;if(b.isOrthogonal){p=!0;var u=b.pointsCount;4<u&&b.points.removeRange(2,u-3)}else if(b.curve===sg)r=!0,u=b.pointsCount,4<u&&b.points.removeRange(2, u-3),4===u&&(q=2);else{u=b.pointsCount;var v=l===uc,w=k===uc;2<u&&v&&w?b.points.removeRange(1,u-2):3<u&&v&&!w?b.points.removeRange(1,u-3):3<u&&!v&&w?b.points.removeRange(2,u-2):4<u&&!v&&!w&&b.points.removeRange(2,u-3)}if(c.rev){for(;null!==n&&m!==n;){var y=u=null;for(v=n.sourceEdges.iterator;v.next()&&(w=v.value,w.link!==c.link||(u=w.fromVertex,y=w.toVertex,null!==u.node)););if(u!==m){v=b.i(q-1).x;w=b.i(q-1).y;var z=u.centerX;var A=u.centerY;if(p)180===this.K||0===this.K?q===b.firstPickIndex+1?(b.m(q++, v,w),b.m(q++,v,A)):(null!==y?y.centerY:w)!==A&&(y=this.Ia[u.layer-1]+this.Xc.x,b.m(q++,y,w),b.m(q++,y,A)):q===b.firstPickIndex+1?(b.m(q++,v,w),b.m(q++,z,w)):(null!==y?y.centerX:v)!==z&&(y=this.Ia[u.layer-1]+this.Xc.y,b.m(q++,v,y),b.m(q++,z,y));else if(q===b.firstPickIndex+1){y=Math.max(10,this.$d[n.layer]);var C=Math.max(10,this.zd[n.layer]);if(r)180===this.K?z<=n.bounds.x?(n=n.bounds.x,b.m(q++,n-y,A),b.m(q++,n,A),b.m(q++,n+C,A)):(b.m(q++,z-y,A),b.m(q++,z,A),b.m(q++,z+C,A)):90===this.K?A>=n.bounds.bottom? (n=n.bounds.y+n.bounds.height,b.m(q++,z,n+C),b.m(q++,z,n),b.m(q++,z,n-y)):(b.m(q++,z,A+C),b.m(q++,z,A),b.m(q++,z,A-y)):270===this.K?A<=n.bounds.y?(n=n.bounds.y,b.m(q++,z,n-y),b.m(q++,z,n),b.m(q++,z,n+C)):(b.m(q++,z,A-y),b.m(q++,z,A),b.m(q++,z,A+C)):0===this.K&&(z>=n.bounds.right?(n=n.bounds.x+n.bounds.width,b.m(q++,n+C,A),b.m(q++,n,A),b.m(q++,n-y,A)):(b.m(q++,z+C,A),b.m(q++,z,A),b.m(q++,z-y,A)));else{b.m(q++,v,w);var F=0;if(180===this.K||0===this.K){if(180===this.K?z>=n.bounds.right:z<=n.bounds.x)F= (0===this.K?-y:C)/2;b.m(q++,v+F,A)}else{if(270===this.K?A>=n.bounds.bottom:A<=n.bounds.y)F=(90===this.K?-y:C)/2;b.m(q++,z,w+F)}b.m(q++,z,A)}}else y=Math.max(10,this.$d[u.layer]),C=Math.max(10,this.zd[u.layer]),180===this.K?(r&&b.m(q++,z-y,A),b.m(q++,z,A),r&&b.m(q++,z+C,A)):90===this.K?(r&&b.m(q++,z,A+C),b.m(q++,z,A),r&&b.m(q++,z,A-y)):270===this.K?(r&&b.m(q++,z,A-y),b.m(q++,z,A),r&&b.m(q++,z,A+C)):(r&&b.m(q++,z+C,A),b.m(q++,z,A),r&&b.m(q++,z-y,A))}n=u}if(null===h||l!==uc||p)if(v=b.i(q-1).x,w=b.i(q- 1).y,z=b.i(q).x,A=b.i(q).y,p)n=this.zd[m.layer],180===this.K||0===this.K?(p=w,p>=m.bounds.y&&p<=m.bounds.bottom&&(180===this.K?z>=m.bounds.x:z<=m.bounds.right)&&(n=m.centerX+(180===this.K?-n:n),p<m.bounds.y+m.bounds.height/2?p=m.bounds.y-this.Zb/2:p=m.bounds.bottom+this.Zb/2,b.m(q++,n,w),b.m(q++,n,p)),b.m(q++,z,p)):(p=v,p>=m.bounds.x&&p<=m.bounds.right&&(270===this.K?A>=m.bounds.y:A<=m.bounds.bottom)&&(n=m.centerY+(270===this.K?-n:n),p<m.bounds.x+m.bounds.width/2?p=m.bounds.x-this.Zb/2:p=m.bounds.right+ this.Zb/2,b.m(q++,v,n),b.m(q++,p,n)),b.m(q++,p,A)),b.m(q++,z,A);else if(r)y=Math.max(10,this.$d[m.layer]),C=Math.max(10,this.zd[m.layer]),180===this.K&&z>=m.bounds.x?(n=m.bounds.x+m.bounds.width,b.L(q-2,n,w),b.L(q-1,n+C,w)):90===this.K&&A<=m.bounds.bottom?(n=m.bounds.y,b.L(q-2,v,n),b.L(q-1,v,n-y)):270===this.K&&A>=m.bounds.y?(n=m.bounds.y+m.bounds.height,b.L(q-2,v,n),b.L(q-1,v,n+C)):0===this.K&&z<=m.bounds.right&&(n=m.bounds.x,b.L(q-2,n,w),b.L(q-1,n-y,w));else{y=Math.max(10,this.$d[m.layer]);C=Math.max(10, this.zd[m.layer]);p=0;if(180===this.K||0===this.K){if(180===this.K?z<=m.bounds.x:z>=m.bounds.right)p=(0===this.K?C:-y)/2;b.m(q++,z+p,w)}else{if(270===this.K?A<=m.bounds.y:A>=m.bounds.bottom)p=(90===this.K?C:-y)/2;b.m(q++,v,A+p)}b.m(q++,z,A)}}else{for(;null!==m&&m!==n;){y=u=null;for(m=m.destinationEdges.iterator;m.next()&&(v=m.value,v.link!==c.link||(u=v.toVertex,y=v.fromVertex,null!==y.node&&(y=null),null!==u.node)););u!==n&&(v=b.i(q-1).x,w=b.i(q-1).y,z=u.centerX,A=u.centerY,p?180===this.K||0===this.K? (null!==y?y.centerY:w)!==A&&(y=this.Ia[u.layer]+this.Xc.x,q===b.firstPickIndex+1&&(y=0===this.K?Math.max(y,v):Math.min(y,v)),b.m(q++,y,w),b.m(q++,y,A)):(null!==y?y.centerX:v)!==z&&(y=this.Ia[u.layer]+this.Xc.y,q===b.firstPickIndex+1&&(y=90===this.K?Math.max(y,w):Math.min(y,w)),b.m(q++,v,y),b.m(q++,z,y)):(y=Math.max(10,this.$d[u.layer]),C=Math.max(10,this.zd[u.layer]),180===this.K?(b.m(q++,z+C,A),r&&b.m(q++,z,A),b.m(q++,z-y,A)):90===this.K?(b.m(q++,z,A-y),r&&b.m(q++,z,A),b.m(q++,z,A+C)):270===this.K? (b.m(q++,z,A+C),r&&b.m(q++,z,A),b.m(q++,z,A-y)):(b.m(q++,z-y,A),r&&b.m(q++,z,A),b.m(q++,z+C,A))));m=u}p&&(v=b.i(q-1).x,w=b.i(q-1).y,z=b.i(q).x,A=b.i(q).y,180===this.K||0===this.K?w!==A&&(y=0===this.K?Math.min(Math.max((z+v)/2,this.Ia[n.layer]+this.Xc.x),z):Math.max(Math.min((z+v)/2,this.Ia[n.layer]+this.Xc.x),z),b.m(q++,y,w),b.m(q++,y,A)):v!==z&&(y=90===this.K?Math.min(Math.max((A+w)/2,this.Ia[n.layer]+this.Xc.y),A):Math.max(Math.min((A+w)/2,this.Ia[n.layer]+this.Xc.y),A),b.m(q++,v,y),b.m(q++,z,y)))}null!== d&&r&&(null!==g&&(l===uc&&(l=b.i(0),d=b.i(2),l.w(d)||b.L(1,(l.x+d.x)/2,(l.y+d.y)/2)),l=b.getLinkPoint(e,g,uc,!0,!1,f,h),l.s()||l.set(e.actualBounds.center),b.L(0,l.x,l.y)),null!==h&&(k===uc&&(k=b.i(b.pointsCount-1),l=b.i(b.pointsCount-3),k.w(l)||b.L(b.pointsCount-2,(k.x+l.x)/2,(k.y+l.y)/2)),e=b.getLinkPoint(f,h,uc,!1,!1,e,g),e.s()||e.set(f.actualBounds.center),b.L(b.pointsCount-1,e.x,e.y)));b.zf();c.commit()}}}this.avoidOrthogonalOverlaps()}; xs.prototype.avoidOrthogonalOverlaps=function(){if(!(0>=this.linkSpacing)){for(var a=new E,b=this.network.edges.iterator;b.next();){var c=b.value.link;null!==c&&c.isOrthogonal&&!a.contains(c)&&a.add(c)}if(0<a.count)if(90===this.K||270===this.K){b=0;c=[];for(a=a.iterator;a.next();){var d=a.value;if(null!==d&&d.isOrthogonal)for(var e=2;e<d.pointsCount-3;e++){var f=d.i(e);var g=d.i(e+1);if(this.A(f.y,g.y)&&!this.A(f.x,g.x)){var h=new rt;h.layer=Math.floor(f.y/2);var k=d.i(0),l=d.i(d.pointsCount-1);h.first= k.x*k.x+k.y;h.Xb=l.x*l.x+l.y;h.hd=Math.min(f.x,g.x);h.vc=Math.max(f.x,g.x);h.index=e;h.link=d;if(e+2<d.pointsCount){k=d.i(e-1);l=d.i(e+2);var m=0;k.y<f.y?m=l.y<f.y?3:f.x<g.x?2:1:k.y>f.y&&(m=l.y>f.y?0:g.x<f.x?2:1);h.l=m}c.push(h)}}}if(1<c.length)for(c.sort(this.Sy),a=0;a<c.length;){f=c[a].layer;for(d=a+1;d<c.length&&c[d].layer===f;)d++;if(1<d-a)for(f=a;f<d;){g=c[f].vc;for(e=a+1;e<d&&c[e].hd<g;)g=Math.max(g,c[e].vc),e++;g=e-f;if(1<g){this.uj(c,this.hu,f,f+g);m=1;h=c[f].Xb;for(k=f;k<e;k++)l=c[k],l.Xb!== h&&(m++,h=l.Xb);this.uj(c,this.Ry,f,f+g);var n=1;h=c[f].first;for(k=f;k<e;k++)l=c[k],l.first!==h&&(n++,h=l.first);k=!0;l=n;m<n?(k=!1,l=m,h=c[f].Xb,this.uj(c,this.hu,f,f+g)):h=c[f].first;m=0;for(n=f;n<e;n++){var p=c[n];(k?p.first:p.Xb)!==h&&(m++,h=k?p.first:p.Xb);var r=p.link;f=r.i(p.index);g=r.i(p.index+1);var q=this.linkSpacing*(m-(l-1)/2);b++;r.Sh();r.L(p.index,f.x,f.y+q);r.L(p.index+1,g.x,g.y+q);r.zf()}}f=e}a=d}}else{b=0;c=[];for(a=a.iterator;a.next();)if(d=a.value,null!==d&&d.isOrthogonal)for(e= 2;e<d.pointsCount-3;e++)f=d.i(e),g=d.i(e+1),this.A(f.x,g.x)&&!this.A(f.y,g.y)&&(h=new rt,h.layer=Math.floor(f.x/2),k=d.i(0),l=d.i(d.pointsCount-1),h.first=k.x+k.y*k.y,h.Xb=l.x+l.y*l.y,h.hd=Math.min(f.y,g.y),h.vc=Math.max(f.y,g.y),h.index=e,h.link=d,e+2<d.pointsCount&&(k=d.i(e-1),l=d.i(e+2),m=0,k.x<f.x?m=l.x<f.x?3:f.y<g.y?2:1:k.x>f.x&&(m=l.x>f.x?0:g.y<f.y?2:1),h.l=m),c.push(h));if(1<c.length)for(c.sort(this.Sy),a=0;a<c.length;){f=c[a].layer;for(d=a+1;d<c.length&&c[d].layer===f;)d++;if(1<d-a)for(f= a;f<d;){g=c[f].vc;for(e=a+1;e<d&&c[e].hd<g;)g=Math.max(g,c[e].vc),e++;g=e-f;if(1<g){this.uj(c,this.hu,f,f+g);m=1;h=c[f].Xb;for(k=f;k<e;k++)l=c[k],l.Xb!==h&&(m++,h=l.Xb);this.uj(c,this.Ry,f,f+g);n=1;h=c[f].first;for(k=f;k<e;k++)l=c[k],l.first!==h&&(n++,h=l.first);k=!0;l=n;m<n?(k=!1,l=m,h=c[f].Xb,this.uj(c,this.hu,f,f+g)):h=c[f].first;m=0;for(n=f;n<e;n++)p=c[n],(k?p.first:p.Xb)!==h&&(m++,h=k?p.first:p.Xb),r=p.link,f=r.i(p.index),g=r.i(p.index+1),q=this.linkSpacing*(m-(l-1)/2),b++,r.Sh(),r.L(p.index, f.x+q,f.y),r.L(p.index+1,g.x+q,g.y),r.zf()}f=e}a=d}}}};t=xs.prototype;t.Sy=function(a,b){return a instanceof rt&&b instanceof rt&&a!==b?a.layer<b.layer?-1:a.layer>b.layer?1:a.hd<b.hd?-1:a.hd>b.hd?1:a.vc<b.vc?-1:a.vc>b.vc?1:0:0};t.Ry=function(a,b){return a instanceof rt&&b instanceof rt&&a!==b?a.first<b.first?-1:a.first>b.first||a.l<b.l?1:a.l>b.l||a.hd<b.hd?-1:a.hd>b.hd?1:a.vc<b.vc?-1:a.vc>b.vc?1:0:0}; t.hu=function(a,b){return a instanceof rt&&b instanceof rt&&a!==b?a.Xb<b.Xb?-1:a.Xb>b.Xb||a.l<b.l?1:a.l>b.l||a.hd<b.hd?-1:a.hd>b.hd?1:a.vc<b.vc?-1:a.vc>b.vc?1:0:0};t.A=function(a,b){a-=b;return-1<a&&1>a}; t.uj=function(a,b,c,d){var e=a.length,f=d-c;if(!(1>=f))if((0>c||c>=e-1)&&B("not in range 0 <= from < length: "+c),2===f)d=a[c],e=a[c+1],0<b(d,e)&&(a[c]=e,a[c+1]=d);else if(0===c)if(d>=e)a.sort(b);else for(c=a.slice(0,d),c.sort(b),b=0;b<d;b++)a[b]=c[b];else if(d>=e)for(d=a.slice(c),d.sort(b),b=c;b<e;b++)a[b]=d[b-c];else for(e=a.slice(c,d),e.sort(b),b=c;b<d;b++)a[b]=e[b-c]}; function Gs(a,b){var c=a.Ab[b];if(c>=a.ye.length){var d=[];for(var e=0;e<a.ye.length;e++)d[e]=a.ye[e];a.ye=d}void 0===a.ye[c]||null===a.ye[c]?d=[]:(d=a.ye[c],a.ye[c]=null);a=a.ap[b];for(b=0;b<a.length;b++)c=a[b],d[c.index]=c;return d}function Hs(a,b,c){a.ye[a.Ab[b]]=c} na.Object.defineProperties(xs.prototype,{layerSpacing:{get:function(){return this.ve},set:function(a){this.ve!==a&&0<=a&&(this.ve=a,this.C())}},columnSpacing:{get:function(){return this.Zb},set:function(a){this.Zb!==a&&0<a&&(this.Zb=a,this.C())}},direction:{get:function(){return this.K},set:function(a){this.K!==a&&(0===a||90===a||180===a||270===a?(this.K=a,this.C()):B("LayeredDigraphLayout.direction must be 0, 90, 180, or 270"))}}, cycleRemoveOption:{get:function(){return this.jl},set:function(a){this.jl===a||a!==Rs&&a!==ys&&a!==Ds||(this.jl=a,this.C())}},layeringOption:{get:function(){return this.Nl},set:function(a){this.Nl===a||a!==zs&&a!==Ws&&a!==Ys||(this.Nl=a,this.C())}},initializeOption:{get:function(){return this.Cl},set:function(a){this.Cl===a||a!==As&&a!==dt&&a!==bt||(this.Cl=a,this.C())}},iterations:{ get:function(){return this.Rj},set:function(a){this.Rj!==a&&0<=a&&(this.Rj=a,this.C())}},aggressiveOption:{get:function(){return this.Zk},set:function(a){this.Zk===a||a!==ht&&a!==Bs&&a!==it||(this.Zk=a,this.C())}},packOption:{get:function(){return this.pg},set:function(a){this.pg!==a&&0<=a&&8>a&&(this.pg=a,this.C())}},setsPortSpots:{get:function(){return this.kf},set:function(a){this.kf!==a&&(this.kf=a,this.C())}}, linkSpacing:{get:function(){return this.Ho},set:function(a){this.Ho!==a&&0<=a&&(this.Ho=a,this.C())}},maxLayer:{get:function(){return this.ra}},maxIndex:{get:function(){return this.Ii}},maxColumn:{get:function(){return this.Ba}},minIndexLayer:{get:function(){return this.mh}},maxIndexLayer:{get:function(){return this.pc}}}); var ys=new D(xs,"CycleDepthFirst",0),Rs=new D(xs,"CycleGreedy",1),Ds=new D(xs,"CycleFromLayers",2),zs=new D(xs,"LayerOptimalLinkLength",0),Ws=new D(xs,"LayerLongestPathSink",1),Ys=new D(xs,"LayerLongestPathSource",2),As=new D(xs,"InitDepthFirstOut",0),dt=new D(xs,"InitDepthFirstIn",1),bt=new D(xs,"InitNaive",2),ht=new D(xs,"AggressiveNone",0),Bs=new D(xs,"AggressiveLess",1),it=new D(xs,"AggressiveMore",2),jt=8;xs.className="LayeredDigraphLayout";xs.CycleDepthFirst=ys;xs.CycleGreedy=Rs; xs.CycleFromLayers=Ds;xs.LayerOptimalLinkLength=zs;xs.LayerLongestPathSink=Ws;xs.LayerLongestPathSource=Ys;xs.InitDepthFirstOut=As;xs.InitDepthFirstIn=dt;xs.InitNaive=bt;xs.AggressiveNone=ht;xs.AggressiveLess=Bs;xs.AggressiveMore=it;xs.PackNone=0;xs.PackExpand=1;xs.PackStraighten=2;xs.PackMedian=4;xs.PackAll=15;function rt(){this.index=this.vc=this.hd=this.Xb=this.first=this.layer=0;this.link=null;this.l=0}rt.className="SegInfo";function Cs(a){Zp.call(this,a)}ma(Cs,Zp);Cs.prototype.createVertex=function(){return new st(this)}; Cs.prototype.createEdge=function(){return new tt(this)};Cs.className="LayeredDigraphNetwork";function st(a){mq.call(this,a);this.Pa=this.Sg=this.Ei=-1;this.I=NaN;this.T=null;this.valid=!1;this.finish=this.Dg=NaN;this.yf=0;this.Lk=this.Mk=null}ma(st,mq); st.prototype.serializeVertexProperties=function(a,b){mq.prototype.serializeVertexProperties.call(this,a,b);a.layer=this.layer;a.column=this.column;a.index=this.index;a.component=this.component;a.near=this.near?mb(this.near):null;a.valid=this.valid;a.Dg=this.Dg;a.finish=this.finish;a.yf=this.yf;a.Mk=this.Mk;a.Lk=this.Lk}; st.prototype.zq=function(a,b,c,d){mq.prototype.zq.call(this,a,b,c,d);this.layer=a.layer;this.column=a.column;this.index=a.index;this.component=a.component;if(b=b.get(a.near))this.near=b;this.valid=a.valid;this.Dg=a.Dg;this.finish=a.finish;this.yf=a.yf;this.Mk=a.Mk;this.Lk=a.Lk}; na.Object.defineProperties(st.prototype,{layer:{get:function(){return this.Ei},set:function(a){this.Ei!==a&&(this.Ei=a)}},column:{get:function(){return this.Sg},set:function(a){this.Sg!==a&&(this.Sg=a)}},index:{get:function(){return this.Pa},set:function(a){this.Pa!==a&&(this.Pa=a)}},component:{get:function(){return this.I},set:function(a){this.I!==a&&(this.I=a)}},near:{ get:function(){return this.T},set:function(a){this.T!==a&&(this.T=a)}}});st.className="LayeredDigraphVertex";function tt(a){nq.call(this,a);this.l=this.Ka=this.eb=!1;this.Ja=this.I=NaN;this.T=this.v=0}ma(tt,nq); tt.prototype.serializeEdgeProperties=function(a,b){nq.prototype.serializeEdgeProperties.call(this,a,b);a.valid=this.valid;a.rev=this.rev;a.forest=this.forest;a.portFromPos=this.portFromPos;a.portToPos=this.portToPos;a.portFromColOffset=this.portFromColOffset;a.portToColOffset=this.portToColOffset}; tt.prototype.deserializeEdgeProperties=function(a,b,c,d){nq.prototype.deserializeEdgeProperties.call(this,a,b,c,d);this.valid=a.valid;this.rev=a.rev;this.forest=a.forest;this.portFromPos=a.portFromPos;this.portToPos=a.portToPos;this.portFromColOffset=a.portFromColOffset;this.portToColOffset=a.portToColOffset}; na.Object.defineProperties(tt.prototype,{fromVertex:{get:function(){return this.$c},set:function(a){this.$c!==a&&(this.$c=a)}},toVertex:{get:function(){return this.gd},set:function(a){this.gd!==a&&(this.gd=a)}},valid:{get:function(){return this.eb},set:function(a){this.eb!==a&&(this.eb=a)}},rev:{get:function(){return this.Ka},set:function(a){this.Ka!==a&&(this.Ka=a)}},forest:{ get:function(){return this.l},set:function(a){this.l!==a&&(this.l=a)}},portFromPos:{get:function(){return this.I},set:function(a){this.I!==a&&(this.I=a)}},portToPos:{get:function(){return this.Ja},set:function(a){this.Ja!==a&&(this.Ja=a)}},portFromColOffset:{get:function(){return this.v},set:function(a){this.v!==a&&(this.v=a)}},portToColOffset:{get:function(){return this.T}, set:function(a){this.T!==a&&(this.T=a)}}});tt.className="LayeredDigraphEdge";function ut(){Bi.call(this);this.Kb=new G;this.pp=vt;this.md=wt;this.lq=xt;this.us=yt;this.ox=[];this.ld=!0;this.Fb=zt;this.Pd=(new M(10,10)).freeze();var a=new At(this);this.U=new Bt(a);this.V=new Bt(a);this.tv=[]}ma(ut,Bi); ut.prototype.cloneProtected=function(a){Bi.prototype.cloneProtected.call(this,a);a.pp=this.pp;a.lq=this.lq;a.us=this.us;a.ld=this.ld;a.Fb=this.Fb;a.Pd.assign(this.Pd);a.U.copyInheritedPropertiesFrom(this.U);a.V.copyInheritedPropertiesFrom(this.V)}; ut.prototype.jb=function(a){a.classType===ut?0===a.name.indexOf("Alignment")?this.alignment=a:0===a.name.indexOf("Arrangement")?this.arrangement=a:0===a.name.indexOf("Compaction")?this.compaction=a:0===a.name.indexOf("Path")?this.path=a:0===a.name.indexOf("Sorting")?this.sorting=a:0===a.name.indexOf("Style")?this.treeStyle=a:B("Unknown enum value: "+a):Bi.prototype.jb.call(this,a)};ut.prototype.createNetwork=function(){return new At(this)}; ut.prototype.makeNetwork=function(a){function b(a){if(a instanceof W)return!a.isLinkLabel&&"Comment"!==a.category;if(a instanceof S){var b=a.fromNode;if(null===b||b.isLinkLabel||"Comment"===b.category)return!1;a=a.toNode;return null===a||a.isLinkLabel||"Comment"===a.category?!1:!0}return!1}var c=this.createNetwork();a instanceof R?(c.Bg(a.nodes,!0,b),c.Bg(a.links,!0,b)):a instanceof U?c.Bg(a.memberParts,!1,b):c.Bg(a.iterator,!1,b);return c}; ut.prototype.doLayout=function(a){null===this.network&&(this.network=this.makeNetwork(a));this.arrangement!==Ct&&(this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin));var b=this.diagram;null===b&&a instanceof R&&(b=a);this.path===vt&&null!==b?this.md=b.isTreePathToChildren?wt:Dt:this.md=this.path===vt?wt:this.path;if(0<this.network.vertexes.count){this.network.yq();for(a=this.network.vertexes.iterator;a.next();)b=a.value,b.initialized=!1,b.level=0,b.parent=null,b.children=[];if(0<this.Kb.count){a= new G;for(b=this.Kb.iterator;b.next();){var c=b.value;c instanceof W?(c=this.network.kj(c),null!==c&&a.add(c)):c instanceof Bt&&a.add(c)}this.Kb=a}0===this.Kb.count&&this.findRoots();for(a=this.Kb.copy().iterator;a.next();)b=a.value,b.initialized||(b.initialized=!0,Et(this,b));b=this.network.vertexes;for(a=null;a=Ft(b),0<a.count;)b=Gt(this,a),null!==b&&this.Kb.add(b),b.initialized=!0,Et(this,b),b=a;for(a=this.Kb.iterator;a.next();)b=a.value,b instanceof Bt&&Ht(this,b);for(a=this.Kb.iterator;a.next();)b= a.value,b instanceof Bt&&It(this,b);for(a=this.Kb.iterator;a.next();)b=a.value,b instanceof Bt&&Jt(this,b);this.Ev();if(this.layerStyle===Kt){a=[];for(b=this.network.vertexes.iterator;b.next();){c=b.value;var d=c.parent;null===d&&(d=c);d=0===d.angle||180===d.angle;var e=a[c.level];void 0===e&&(e=0);a[c.level]=Math.max(e,d?c.width:c.height)}for(b=0;b<a.length;b++)void 0===a[b]&&(a[b]=0);this.ox=a;for(b=this.network.vertexes.iterator;b.next();)c=b.value,d=c.parent,null===d&&(d=c),0===d.angle||180=== d.angle?(180===d.angle&&(c.focusX+=a[c.level]-c.width),c.width=a[c.level]):(270===d.angle&&(c.focusY+=a[c.level]-c.height),c.height=a[c.level])}else if(this.layerStyle===Lt)for(a=this.network.vertexes.iterator;a.next();){b=a.value;c=0===b.angle||180===b.angle;d=-1;for(e=0;e<b.children.length;e++){var f=b.children[e];d=Math.max(d,c?f.width:f.height)}if(0<=d)for(e=0;e<b.children.length;e++)f=b.children[e],c?(180===b.angle&&(f.focusX+=d-f.width),f.width=d):(270===b.angle&&(f.focusY+=d-f.height),f.height= d)}for(a=this.Kb.iterator;a.next();)b=a.value,b instanceof Bt&&this.layoutTree(b);this.arrangeTrees();this.updateParts()}this.network=null;this.Kb=new G;this.isValidLayout=!0};function Ft(a){var b=new G;for(a=a.iterator;a.next();){var c=a.value;c.initialized||b.add(c)}return b} ut.prototype.findRoots=function(){for(var a=this.network.vertexes,b=a.iterator;b.next();){var c=b.value;switch(this.md){case wt:0===c.sourceEdges.count&&this.Kb.add(c);break;case Dt:0===c.destinationEdges.count&&this.Kb.add(c);break;default:B("Unhandled path value "+this.md.toString())}}0===this.Kb.count&&(a=Gt(this,a),null!==a&&this.Kb.add(a))}; function Gt(a,b){var c=999999,d=null;for(b=b.iterator;b.next();){var e=b.value;switch(a.md){case wt:e.sourceEdges.count<c&&(c=e.sourceEdges.count,d=e);break;case Dt:e.destinationEdges.count<c&&(c=e.destinationEdges.count,d=e);break;default:B("Unhandled path value "+a.md.toString())}}return d} function Et(a,b){if(null!==b){switch(a.md){case wt:if(0<b.destinationEdges.count){for(var c=new E,d=b.destinationVertexes;d.next();){var e=d.value;Mt(a,b,e)&&c.add(e)}0<c.count&&(b.children=c.ma())}break;case Dt:if(0<b.sourceEdges.count){c=new E;for(d=b.sourceVertexes;d.next();)e=d.value,Mt(a,b,e)&&c.add(e);0<c.count&&(b.children=c.ma())}break;default:B("Unhandled path value"+a.md.toString())}c=b.children;d=c.length;for(e=0;e<d;e++){var f=c[e];f.initialized=!0;f.level=b.level+1;f.parent=b;a.Kb.remove(f)}for(b= 0;b<d;b++)Et(a,c[b])}}function Mt(a,b,c){if(c.initialized){if(null===b)var d=!1;else{for(d=b.parent;null!==d&&d!==c;)d=d.parent;d=d===c}if(d||c.level>b.level)return!1;a.removeChild(c.parent,c)}return!0}ut.prototype.removeChild=function(a,b){if(null!==a&&null!==b){for(var c=a.children,d=0,e=0;e<c.length;e++)c[e]===b&&d++;if(0<d){d=Array(c.length-d);for(var f=e=0;f<c.length;f++)c[f]!==b&&(d[e++]=c[f]);a.children=d}}}; function Ht(a,b){if(null!==b){a.initializeTreeVertexValues(b);b.alignment===Nt&&a.sortTreeVertexChildren(b);for(var c=0,d=b.childrenCount,e=0,f=b.children,g=f.length,h=0;h<g;h++){var k=f[h];Ht(a,k);c+=k.descendantCount+1;d=Math.max(d,k.maxChildrenCount);e=Math.max(e,k.maxGenerationCount)}b.descendantCount=c;b.maxChildrenCount=d;b.maxGenerationCount=0<d?e+1:0}} function Ot(a,b){switch(a.lq){default:case xt:return null!==b.parent?b.parent:a.U;case Pt:return null===b.parent?a.U:null===b.parent.parent?a.V:b.parent;case Qt:return null!==b.parent?null!==b.parent.parent?b.parent.parent:a.V:a.U;case Rt:var c=!0;if(0===b.childrenCount)c=!1;else for(var d=b.children,e=d.length,f=0;f<e;f++)if(0<d[f].childrenCount){c=!1;break}return c&&null!==b.parent?a.V:null!==b.parent?b.parent:a.U}} ut.prototype.initializeTreeVertexValues=function(a){a.copyInheritedPropertiesFrom(Ot(this,a));if(null!==a.parent&&a.parent.alignment===Nt){for(var b=a.angle,c=a.parent.children,d=0;d<c.length&&a!==c[d];)d++;0===d%2?d!==c.length-1&&(b=90===b?180:180===b?270:270===b?180:270):b=90===b?0:180===b?90:270===b?0:90;a.angle=b}a.initialized=!0};function It(a,b){if(null!==b){a.assignTreeVertexValues(b);b=b.children;for(var c=b.length,d=0;d<c;d++)It(a,b[d])}}ut.prototype.assignTreeVertexValues=function(){}; function Jt(a,b){if(null!==b){b.alignment!==Nt&&a.sortTreeVertexChildren(b);b=b.children;for(var c=b.length,d=0;d<c;d++)Jt(a,b[d])}}ut.prototype.sortTreeVertexChildren=function(a){switch(a.sorting){case St:break;case Tt:a.children.reverse();break;case Ut:a.children.sort(a.comparer);break;case Vt:a.children.sort(a.comparer);a.children.reverse();break;default:B("Unhandled sorting value "+a.sorting.toString())}};ut.prototype.Ev=function(){if(this.comments)for(var a=this.network.vertexes.iterator;a.next();)this.addComments(a.value)}; ut.prototype.addComments=function(a){var b=a.angle,c=a.parent,d=0;var e=!1;null!==c&&(d=c.angle,e=c.alignment,e=Wt(e));b=90===b||270===b;d=90===d||270===d;c=0===a.childrenCount;var f=0,g=0,h=0,k=a.commentSpacing;if(null!==a.node)for(var l=a.node.Rv();l.next();){var m=l.value;"Comment"===m.category&&m.canLayout()&&(null===a.comments&&(a.comments=[]),a.comments.push(m),m.Ta(),m=m.measuredBounds,b&&!c||!e&&!d&&c||e&&d&&c?(f=Math.max(f,m.width),g+=m.height+Math.abs(h)):(f+=m.width+Math.abs(h),g=Math.max(g, m.height)),h=k)}null!==a.comments&&(b&&!c||!e&&!d&&c||e&&d&&c?(f+=Math.abs(a.commentMargin),g=Math.max(0,g-a.height)):(g+=Math.abs(a.commentMargin),f=Math.max(0,f-a.width)),e=N.allocAt(0,0,a.bounds.width+f,a.bounds.height+g),a.bounds=e,N.free(e))};function Wt(a){return a===Xt||a===Nt||a===Yt||a===Zt}function $t(a){return a===Xt||a===Nt} function au(a){var b=a.parent;if(null!==b){var c=b.alignment;if(Wt(c)){if($t(c)){b=b.children;for(c=0;c<b.length&&a!==b[c];)c++;return 0===c%2}if(c===Yt)return!0}}return!1} ut.prototype.layoutComments=function(a){if(null!==a.comments){var b=a.node.measuredBounds,c=a.parent,d=a.angle,e=0;var f=!1;null!==c&&(e=c.angle,f=c.alignment,f=Wt(f));d=90===d||270===d;c=90===e||270===e;for(var g=0===a.childrenCount,h=au(a),k=0,l=a.comments,m=l.length,n=I.alloc(),p=0;p<m;p++){var r=l[p],q=r.measuredBounds;if(d&&!g||!f&&!c&&g||f&&c&&g){if(135<e&&!f||c&&h)if(0<=a.commentMargin)for(n.h(a.bounds.x-a.commentMargin-q.width,a.bounds.y+k),r.move(n),r=r.Hd();r.next();){var u=r.value;u.fromSpot= ed;u.toSpot=fd}else for(n.h(a.bounds.x+2*a.focus.x-a.commentMargin,a.bounds.y+k),r.move(n),r=r.Hd();r.next();)u=r.value,u.fromSpot=fd,u.toSpot=ed;else if(0<=a.commentMargin)for(n.h(a.bounds.x+2*a.focus.x+a.commentMargin,a.bounds.y+k),r.move(n),r=r.Hd();r.next();)u=r.value,u.fromSpot=fd,u.toSpot=ed;else for(n.h(a.bounds.x+a.commentMargin-q.width,a.bounds.y+k),r.move(n),r=r.Hd();r.next();)u=r.value,u.fromSpot=ed,u.toSpot=fd;k=0<=a.commentSpacing?k+(q.height+a.commentSpacing):k+(a.commentSpacing-q.height)}else{if(135< e&&!f||!c&&h)if(0<=a.commentMargin)for(n.h(a.bounds.x+k,a.bounds.y-a.commentMargin-q.height),r.move(n),r=r.Hd();r.next();)u=r.value,u.fromSpot=dd,u.toSpot=gd;else for(n.h(a.bounds.x+k,a.bounds.y+2*a.focus.y-a.commentMargin),r.move(n),r=r.Hd();r.next();)u=r.value,u.fromSpot=gd,u.toSpot=dd;else if(0<=a.commentMargin)for(n.h(a.bounds.x+k,a.bounds.y+2*a.focus.y+a.commentMargin),r.move(n),r=r.Hd();r.next();)u=r.value,u.fromSpot=gd,u.toSpot=dd;else for(n.h(a.bounds.x+k,a.bounds.y+a.commentMargin-q.height), r.move(n),r=r.Hd();r.next();)u=r.value,u.fromSpot=dd,u.toSpot=gd;k=0<=a.commentSpacing?k+(q.width+a.commentSpacing):k+(a.commentSpacing-q.width)}}I.free(n);b=k-a.commentSpacing-(d?b.height:b.width);if(this.md===wt)for(a=a.destinationEdges;a.next();)e=a.value.link,null===e||e.isAvoiding||(e.fromEndSegmentLength=0<b?b:NaN);else for(a=a.sourceEdges;a.next();)e=a.value.link,null===e||e.isAvoiding||(e.toEndSegmentLength=0<b?b:NaN)}}; ut.prototype.layoutTree=function(a){if(null!==a){for(var b=a.children,c=b.length,d=0;d<c;d++)this.layoutTree(b[d]);switch(a.compaction){case bu:hu(this,a);break;case iu:if(a.alignment===Nt)hu(this,a);else if(0===a.childrenCount)d=a.parent,c=!1,b=0,null!==d&&(b=d.angle,c=d.alignment,c=Wt(c)),d=au(a),a.S.h(0,0),a.wa.h(a.width,a.height),null===a.parent||null===a.comments||(180!==b&&270!==b||c)&&!d?a.fa.h(0,0):180===b&&!c||(90===b||270===b)&&d?a.fa.h(a.width-2*a.focus.x,0):a.fa.h(0,a.height-2*a.focus.y), a.Oq=null,a.br=null;else{var e=ju(a);b=90===e||270===e;var f=0,g=a.children,h=g.length;for(c=0;c<h;c++)d=g[c],f=Math.max(f,b?d.wa.width:d.wa.height);var k=a.alignment,l=k===ku,m=Wt(k),n=Math.max(0,a.breadthLimit);c=lu(a);var p=a.nodeSpacing,r=mu(a),q=a.rowSpacing,u=0;if(k===nu||l||a.Rm||a.Sm&&1===a.maxGenerationCount)u=Math.max(0,a.rowIndent);d=a.width;var v=a.height,w=0,y=0,z=0,A=null,C=null,F=0,Q=0,K=0,T=0,P=0,J=0,ka=0,ba=0;m&&!$t(k)&&135<e&&g.reverse();if($t(k))if(1<h)for(var qa=0;qa<h;qa++)0=== qa%2&&qa!==h-1&&(ba=Math.max(ba,b?g[qa].wa.width:g[qa].wa.height));else 1===h&&(ba=b?g[0].wa.width:g[0].wa.height);if(m){switch(k){case Xt:y=135>e?ou(a,g,ba,w,y):pu(a,g,ba,w,y);ba=y.x;w=y.width;y=y.height;break;case Yt:for(A=0;A<h;A++)C=g[A],n=C.wa,z=0===J?0:q,b?(C.S.h(f-n.width,T+z),w=Math.max(w,n.width),y=Math.max(y,T+z+n.height),T+=z+n.height):(C.S.h(K+z,f-n.height),w=Math.max(w,K+z+n.width),y=Math.max(y,n.height),K+=z+n.width),J++;break;case Zt:for(A=0;A<h;A++)C=g[A],f=C.wa,n=0===J?0:q,b?(C.S.h(p/ 2+a.focus.x,T+n),w=Math.max(w,f.width),y=Math.max(y,T+n+f.height),T+=n+f.height):(C.S.h(K+n,p/2+a.focus.y),w=Math.max(w,K+n+f.width),y=Math.max(y,f.height),K+=n+f.width),J++}A=qu(this,2);C=qu(this,2);b?(A[0].h(0,0),A[1].h(0,y),C[0].h(w,0)):(A[0].h(0,0),A[1].h(w,0),C[0].h(0,y));C[1].h(w,y)}else for(qa=0;qa<h;qa++){var Ma=g[qa],eb=Ma.wa;if(b){0<n&&0<J&&K+p+eb.width>n&&(K<f&&ru(a,k,f-K,0,ka,qa-1),P++,J=0,ka=qa,z=y,K=0,T=135<e?-y-q:y+q);su(this,Ma,0,T);var Ga=0;if(0===J){if(A=Ma.Oq,C=Ma.br,F=eb.width, Q=eb.height,null===A||null===C||e!==ju(Ma))A=qu(this,2),C=qu(this,2),A[0].h(0,0),A[1].h(0,Q),C[0].h(F,0),C[1].h(F,Q)}else{var Ha=Ea();Q=tu(this,a,Ma,A,C,F,Q,Ha);Ga=Q.x;A=Ha[0];C=Ha[1];F=Q.width;Q=Q.height;Ia(Ha);K<eb.width&&0>Ga&&(uu(a,-Ga,0,ka,qa-1),vu(A,-Ga,0),vu(C,-Ga,0),Ga=0)}Ma.S.h(Ga,T);w=Math.max(w,F);y=Math.max(y,z+(0===P?0:q)+eb.height);K=F}else{0<n&&0<J&&T+p+eb.height>n&&(T<f&&ru(a,k,0,f-T,ka,qa-1),P++,J=0,ka=qa,z=w,T=0,K=135<e?-w-q:w+q);su(this,Ma,K,0);Ga=0;if(0===J){if(A=Ma.Oq,C=Ma.br, F=eb.width,Q=eb.height,null===A||null===C||e!==ju(Ma))A=qu(this,2),C=qu(this,2),A[0].h(0,0),A[1].h(F,0),C[0].h(0,Q),C[1].h(F,Q)}else Ha=Ea(),Q=tu(this,a,Ma,A,C,F,Q,Ha),Ga=Q.x,A=Ha[0],C=Ha[1],F=Q.width,Q=Q.height,Ia(Ha),T<eb.height&&0>Ga&&(uu(a,0,-Ga,ka,qa-1),vu(A,0,-Ga),vu(C,0,-Ga),Ga=0);Ma.S.h(K,Ga);y=Math.max(y,Q);w=Math.max(w,z+(0===P?0:q)+eb.width);T=Q}J++}0<P&&(b?(y+=Math.max(0,c),K<w&&ru(a,k,w-K,0,ka,h-1),0<u&&(l||uu(a,u,0,0,h-1),w+=u)):(w+=Math.max(0,c),T<y&&ru(a,k,0,y-T,ka,h-1),0<u&&(l||uu(a, 0,u,0,h-1),y+=u)));u=l=0;switch(k){case wu:b?l+=w/2-a.focus.x-r/2:u+=y/2-a.focus.y-r/2;break;case xu:0<P?b?l+=w/2-a.focus.x-r/2:u+=y/2-a.focus.y-r/2:b?(ba=g[0].S.x+g[0].fa.x,l+=ba+(g[h-1].S.x+g[h-1].fa.x+2*g[h-1].focus.x-ba)/2-a.focus.x-r/2):(ba=g[0].S.y+g[0].fa.y,u+=ba+(g[h-1].S.y+g[h-1].fa.y+2*g[h-1].focus.y-ba)/2-a.focus.y-r/2);break;case nu:b?(l-=r,w+=r):(u-=r,y+=r);break;case ku:b?(l+=w-a.width+r,w+=r):(u+=y-a.height+r,y+=r);break;case Xt:b?1<h?l+=ba+p/2-a.focus.x:l+=g[0].focus.x-a.focus.x+g[0].fa.x: 1<h?u+=ba+p/2-a.focus.y:u+=g[0].focus.y-a.focus.y+g[0].fa.y;break;case Yt:b?l+=w+p/2-a.focus.x:u+=y+p/2-a.focus.y;break;case Zt:break;default:B("Unhandled alignment value "+k.toString())}for(r=0;r<h;r++)ba=g[r],b?ba.S.h(ba.S.x+ba.fa.x-l,ba.S.y+(135<e?(m?-y:-ba.wa.height)+ba.fa.y-c:v+c+ba.fa.y)):ba.S.h(ba.S.x+(135<e?(m?-w:-ba.wa.width)+ba.fa.x-c:d+c+ba.fa.x),ba.S.y+ba.fa.y-u);h=g=0;m?b?(w=yu(a,w,l),0>l&&(l=0),135<e&&(u+=y+c),y+=v+c,k===Zt&&(g+=p/2+a.focus.x),h+=v+c):(135<e&&(l+=w+c),w+=d+c,y=zu(a, y,u),0>u&&(u=0),k===Zt&&(h+=p/2+a.focus.y),g+=d+c):b?(null===a.comments?d>w&&(w=Au(k,d-w,0),g=w.x,h=w.y,w=d,l=0):w=yu(a,w,l),0>l&&(g-=l,l=0),135<e&&(u+=y+c),y=Math.max(Math.max(y,v),y+v+c),h+=v+c):(135<e&&(l+=w+c),w=Math.max(Math.max(w,d),w+d+c),null===a.comments?v>y&&(y=Au(k,0,v-y),g=y.x,h=y.y,y=v,u=0):y=zu(a,y,u),0>u&&(h-=u,u=0),g+=d+c);if(0<P)e=qu(this,4),P=qu(this,4),b?(e[2].h(0,v+c),e[3].h(e[2].x,y),P[2].h(w,e[2].y),P[3].h(P[2].x,e[3].y)):(e[2].h(d+c,0),e[3].h(w,e[2].y),P[2].h(e[2].x,y),P[3].h(e[3].x, P[2].y));else{e=qu(this,A.length+2);P=qu(this,C.length+2);for(k=0;k<A.length;k++)m=A[k],e[k+2].h(m.x+g,m.y+h);for(k=0;k<C.length;k++)m=C[k],P[k+2].h(m.x+g,m.y+h)}b?(e[0].h(l,0),e[1].h(e[0].x,v),e[2].y<e[1].y&&(e[2].x>e[0].x?e[2].assign(e[1]):e[1].assign(e[2])),e[3].y<e[2].y&&(e[3].x>e[0].x?e[3].assign(e[2]):e[2].assign(e[3])),P[0].h(l+d,0),P[1].h(P[0].x,v),P[2].y<P[1].y&&(P[2].x<P[0].x?P[2].assign(P[1]):P[1].assign(P[2])),P[3].y<P[2].y&&(P[3].x<P[0].x?P[3].assign(P[2]):P[2].assign(P[3])),e[2].y-= c/2,P[2].y-=c/2):(e[0].h(0,u),e[1].h(d,e[0].y),e[2].x<e[1].x&&(e[2].y>e[0].y?e[2].assign(e[1]):e[1].assign(e[2])),e[3].x<e[2].x&&(e[3].y>e[0].y?e[3].assign(e[2]):e[2].assign(e[3])),P[0].h(0,u+v),P[1].h(d,P[0].y),P[2].x<P[1].x&&(P[2].y<P[0].y?P[2].assign(P[1]):P[1].assign(P[2])),P[3].x<P[2].x&&(P[3].y<P[0].y?P[3].assign(P[2]):P[2].assign(P[3])),e[2].x-=c/2,P[2].x-=c/2);Bu(this,A);Bu(this,C);a.Oq=e;a.br=P;a.fa.h(l,u);a.wa.h(w,y)}break;default:B("Unhandled compaction value "+a.compaction.toString())}}}; function hu(a,b){if(0===b.childrenCount){var c=!1,d=0;null!==b.parent&&(d=b.parent.angle,c=b.parent.alignment,c=Wt(c));var e=au(b);b.S.h(0,0);b.wa.h(b.width,b.height);null===b.parent||null===b.comments||(180!==d&&270!==d||c)&&!e?b.fa.h(0,0):180===d&&!c||(90===d||270===d)&&e?b.fa.h(b.width-2*b.focus.x,0):b.fa.h(0,b.height-2*b.focus.y)}else{d=ju(b);c=90===d||270===d;var f=0;e=b.children;for(var g=e.length,h=0;h<g;h++){var k=e[h];f=Math.max(f,c?k.wa.width:k.wa.height)}var l=b.alignment,m=l===nu,n=l=== ku;h=Wt(l);var p=Math.max(0,b.breadthLimit);k=lu(b);var r=b.nodeSpacing,q=mu(b),u=m||n?0:q/2,v=b.rowSpacing,w=0;if(m||n||b.Rm||b.Sm&&1===b.maxGenerationCount)w=Math.max(0,b.rowIndent);m=b.width;var y=b.height,z=0,A=0,C=0,F=0,Q=0,K=0,T=0,P=0,J=0;h&&!$t(l)&&135<d&&e.reverse();if($t(l))if(1<g)for(var ka=0;ka<g;ka++){var ba=e[ka],qa=ba.wa;0===ka%2&&ka!==g-1&&(J=Math.max(J,(c?qa.width:qa.height)+Cu(ba)-r))}else 1===g&&(J=c?e[0].wa.width:e[0].wa.height);if(h)switch(l){case Xt:case Nt:A=135>d?ou(b,e,J,z, A):pu(b,e,J,z,A);J=A.x;z=A.width;A=A.height;break;case Yt:for(a=0;a<g;a++)p=e[a],u=p.wa,C=0===T?0:v,c?(p.S.h(f-u.width,Q+C),z=Math.max(z,u.width),A=Math.max(A,Q+C+u.height),Q+=C+u.height):(p.S.h(F+C,f-u.height),z=Math.max(z,F+C+u.width),A=Math.max(A,u.height),F+=C+u.width),T++;break;case Zt:for(f=0;f<g;f++)a=e[f],p=a.wa,u=0===T?0:v,c?(a.S.h(r/2+b.focus.x,Q+u),z=Math.max(z,p.width),A=Math.max(A,Q+u+p.height),Q+=u+p.height):(a.S.h(F+u,r/2+b.focus.y),z=Math.max(z,F+u+p.width),A=Math.max(A,p.height), F+=u+p.width),T++}else for(ka=0;ka<g;ka++){ba=e[ka];qa=ba.wa;if(c){0<p&&0<T&&F+r+qa.width>p&&(F<f&&ru(b,l,f-F,0,P,ka-1),K++,T=0,P=ka,C=A,F=0,Q=135<d?-A-v:A+v);var Ma=0===T?u:r;su(a,ba,0,Q);ba.S.h(F+Ma,Q);z=Math.max(z,F+Ma+qa.width);A=Math.max(A,C+(0===K?0:v)+qa.height);F+=Ma+qa.width}else 0<p&&0<T&&Q+r+qa.height>p&&(Q<f&&ru(b,l,0,f-Q,P,ka-1),K++,T=0,P=ka,C=z,Q=0,F=135<d?-z-v:z+v),Ma=0===T?u:r,su(a,ba,F,0),ba.S.h(F,Q+Ma),A=Math.max(A,Q+Ma+qa.height),z=Math.max(z,C+(0===K?0:v)+qa.width),Q+=Ma+qa.height; T++}0<K&&(c?(A+=Math.max(0,k),F<z&&ru(b,l,z-F,0,P,g-1),0<w&&(n||uu(b,w,0,0,g-1),z+=w)):(z+=Math.max(0,k),Q<A&&ru(b,l,0,A-Q,P,g-1),0<w&&(n||uu(b,0,w,0,g-1),A+=w)));w=n=0;switch(l){case wu:c?n+=z/2-b.focus.x-q/2:w+=A/2-b.focus.y-q/2;break;case xu:0<K?c?n+=z/2-b.focus.x-q/2:w+=A/2-b.focus.y-q/2:c?(l=e[0].S.x+e[0].fa.x,n+=l+(e[g-1].S.x+e[g-1].fa.x+2*e[g-1].focus.x-l)/2-b.focus.x-q/2):(l=e[0].S.y+e[0].fa.y,w+=l+(e[g-1].S.y+e[g-1].fa.y+2*e[g-1].focus.y-l)/2-b.focus.y-q/2);break;case nu:c?(n-=q,z+=q):(w-= q,A+=q);break;case ku:c?(n+=z-b.width+q,z+=q):(w+=A-b.height+q,A+=q);break;case Xt:case Nt:c?1<g?n+=J+r/2-b.focus.x:n+=e[0].focus.x-b.focus.x+e[0].fa.x:1<g?w+=J+r/2-b.focus.y:w+=e[0].focus.y-b.focus.y+e[0].fa.y;break;case Yt:c?n+=z+r/2-b.focus.x:w+=A+r/2-b.focus.y;break;case Zt:break;default:B("Unhandled alignment value "+l.toString())}for(q=0;q<g;q++)l=e[q],c?l.S.h(l.S.x+l.fa.x-n,l.S.y+(135<d?(h?-A:-l.wa.height)+l.fa.y-k:y+k+l.fa.y)):l.S.h(l.S.x+(135<d?(h?-z:-l.wa.width)+l.fa.x-k:m+k+l.fa.x),l.S.y+ l.fa.y-w);c?(z=yu(b,z,n),0>n&&(n=0),135<d&&(w+=A+k),A=Math.max(Math.max(A,y),A+y+k)):(135<d&&(n+=z+k),z=Math.max(Math.max(z,m),z+m+k),A=zu(b,A,w),0>w&&(w=0));b.fa.h(n,w);b.wa.h(z,A)}} function ou(a,b,c,d,e){var f=b.length;if(0===f)return new N(c,0,d,e);if(1===f)return a=b[0],d=a.wa.width,e=a.wa.height,new N(c,0,d,e);for(var g=a.nodeSpacing,h=a.rowSpacing,k=90===ju(a),l=0,m=0,n=0,p=0;p<f;p++)if(!(0!==p%2||1<f&&p===f-1)){var r=b[p],q=r.wa,u=0===l?0:h;if(k){var v=Cu(r)-g;r.S.h(c-(q.width+v),n+u);d=Math.max(d,q.width+v);e=Math.max(e,n+u+q.height);n+=u+q.height}else v=Cu(r)-g,r.S.h(m+u,c-(q.height+v)),e=Math.max(e,q.height+v),d=Math.max(d,m+u+q.width),m+=u+q.width;l++}l=0;r=m;p=n;k? (m=c+g,n=0):(m=0,n=c+g);for(q=0;q<f;q++)if(0!==q%2){u=b[q];v=u.wa;var w=0===l?0:h;if(k){var y=Cu(u)-g;u.S.h(m+y,n+w);d=Math.max(d,m+v.width+y);e=Math.max(e,n+w+v.height);n+=w+v.height}else y=Cu(u)-g,u.S.h(m+w,n+y),d=Math.max(d,m+w+v.width),e=Math.max(e,n+v.height+y),m+=w+v.width;l++}1<f&&1===f%2&&(b=b[f-1],f=b.wa,h=null===b.parent?0:b.parent.rowSpacing,k?(b.S.h(c+g/2-b.focus.x-b.fa.x,e+h),k=c+g/2-b.focus.x-b.fa.x,d=Math.max(d,k+f.width),0>k&&(d-=k),e=Math.max(e,Math.max(p,n)+h+f.height),0>b.S.x&& (c=Du(a,b.S.x,!1,c,g))):(b.S.h(d+h,c+g/2-b.focus.y-b.fa.y),d=Math.max(d,Math.max(r,m)+h+f.width),n=c+g/2-b.focus.y-b.fa.y,e=Math.max(e,n+f.height),0>n&&(e-=n),0>b.S.y&&(c=Du(a,b.S.y,!0,c,g))));return new N(c,0,d,e)} function pu(a,b,c,d,e){var f=b.length;if(0===f)return new N(c,0,d,e);if(1===f)return b=b[0],d=b.wa.width,e=b.wa.height,new N(c,0,d,e);for(var g=a.nodeSpacing,h=a.rowSpacing,k=270===ju(a),l=0,m=0,n=0,p=0;p<f;p++)if(!(0!==p%2||1<f&&p===f-1)){var r=b[p],q=r.wa,u=0===l?0:h;if(k){var v=Cu(r)-g;n-=u+q.height;r.S.h(c-(q.width+v),n);d=Math.max(d,q.width+v);e=Math.max(e,Math.abs(n))}else v=Cu(r)-g,m-=u+q.width,r.S.h(m,c-(q.height+v)),e=Math.max(e,q.height+v),d=Math.max(d,Math.abs(m));l++}l=0;r=m;p=n;k?(m= c+g,n=0):(m=0,n=c+g);for(q=0;q<f;q++)if(0!==q%2){u=b[q];v=u.wa;var w=0===l?0:h;if(k){var y=Cu(u)-g;n-=w+v.height;u.S.h(m+y,n);d=Math.max(d,m+v.width+y);e=Math.max(e,Math.abs(n))}else y=Cu(u)-g,m-=w+v.width,u.S.h(m,n+y),e=Math.max(e,n+v.height+y),d=Math.max(d,Math.abs(m));l++}1<f&&1===f%2&&(h=b[f-1],l=h.wa,q=null===h.parent?0:h.parent.rowSpacing,k?(h.S.h(c+g/2-h.focus.x-h.fa.x,-e-l.height-q),m=c+g/2-h.focus.x-h.fa.x,d=Math.max(d,m+l.width),0>m&&(d-=m),e=Math.max(e,Math.abs(Math.min(p,n))+q+l.height), 0>h.S.x&&(c=Du(a,h.S.x,!1,c,g))):(h.S.h(-d-l.width-q,c+g/2-h.focus.y-h.fa.y),d=Math.max(d,Math.abs(Math.min(r,m))+q+l.width),n=c+g/2-h.focus.y-h.fa.y,e=Math.max(e,n+l.height),0>n&&(e-=n),0>h.S.y&&(c=Du(a,h.S.y,!0,c,g))));for(a=0;a<f;a++)g=b[a],k?g.S.h(g.S.x,g.S.y+e):g.S.h(g.S.x+d,g.S.y);return new N(c,0,d,e)}function Cu(a){return null===a.parent?0:a.parent.nodeSpacing} function Du(a,b,c,d,e){a=a.children;for(var f=a.length,g=0;g<f;g++)c?a[g].S.h(a[g].S.x,a[g].S.y-b):a[g].S.h(a[g].S.x-b,a[g].S.y);b=a[f-1];return Math.max(d,c?b.fa.y+b.focus.y-e/2:b.fa.x+b.focus.x-e/2)} function yu(a,b,c){switch(a.alignment){case xu:case wu:return c+a.width>b&&(b=c+a.width),0>c&&(b-=c),b;case nu:return a.width>b?a.width:b;case ku:return 2*a.focus.x>b?a.width:b+a.width-2*a.focus.x;case Xt:case Nt:return Math.max(a.width,Math.max(b,c+a.width)-Math.min(0,c));case Yt:return a.width-a.focus.x+a.nodeSpacing/2+b;case Zt:return Math.max(a.width,a.focus.x+a.nodeSpacing/2+b);default:return b}} function zu(a,b,c){switch(a.alignment){case xu:case wu:return c+a.height>b&&(b=c+a.height),0>c&&(b-=c),b;case nu:return a.height>b?a.height:b;case ku:return 2*a.focus.y>b?a.height:b+a.height-2*a.focus.y;case Xt:case Nt:return Math.max(a.height,Math.max(b,c+a.height)-Math.min(0,c));case Yt:return a.height-a.focus.y+a.nodeSpacing/2+b;case Zt:return Math.max(a.height,a.focus.y+a.nodeSpacing/2+b);default:return b}} function Au(a,b,c){switch(a){case wu:b/=2;c/=2;break;case xu:b/=2;c/=2;break;case nu:c=b=0;break;case ku:break;default:B("Unhandled alignment value "+a.toString())}return new I(b,c)}function ru(a,b,c,d,e,f){b=Au(b,c,d);uu(a,b.x,b.y,e,f)}function uu(a,b,c,d,e){if(0!==b||0!==c)for(a=a.children;d<=e;d++){var f=a[d].S;f.x+=b;f.y+=c}} function su(a,b,c,d){var e=b.parent;switch(a.md){case wt:for(a=b.sourceEdges;a.next();)b=a.value,b.fromVertex===e&&b.relativePoint.h(c,d);break;case Dt:for(a=b.destinationEdges;a.next();)b=a.value,b.toVertex===e&&b.relativePoint.h(c,d);break;default:B("Unhandled path value "+a.md.toString())}}function vu(a,b,c){for(var d=0;d<a.length;d++){var e=a[d];e.x+=b;e.y+=c}} function tu(a,b,c,d,e,f,g,h){var k=ju(b),l=90===k||270===k,m=b.nodeSpacing;b=d;var n=e;d=f;var p=g,r=c.Oq,q=c.br;g=c.wa;var u=l?Math.max(p,g.height):Math.max(d,g.width);if(null===r||k!==ju(c))r=qu(a,2),q=qu(a,2),l?(r[0].h(0,0),r[1].h(0,g.height),q[0].h(g.width,0),q[1].h(q[0].x,r[1].y)):(r[0].h(0,0),r[1].h(g.width,0),q[0].h(0,g.height),q[1].h(r[1].x,q[0].y));if(l){p=9999999;if(!(null===n||2>n.length||null===r||2>r.length))for(e=c=0;c<n.length&&e<r.length;){f=n[c];var v=r[e];k=v.x;l=v.y;k+=d;var w= f;c+1<n.length&&(w=n[c+1]);var y=v;v=y.x;y=y.y;e+1<r.length&&(y=r[e+1],v=y.x,y=y.y,v+=d);var z=p;f.y===l?z=k-f.x:f.y>l&&f.y<y?z=k+(f.y-l)/(y-l)*(v-k)-f.x:l>f.y&&l<w.y&&(z=k-(f.x+(l-f.y)/(w.y-f.y)*(w.x-f.x)));z<p&&(p=z);w.y<=f.y?c++:y<=l?e++:(w.y<=y&&c++,y<=w.y&&e++)}p=d-p;p+=m;c=r;e=p;if(null===b||2>b.length||null===c||2>c.length)d=null;else{m=qu(a,b.length+c.length);for(d=f=k=0;f<c.length&&c[f].y<b[0].y;)l=c[f++],m[d++].h(l.x+e,l.y);for(;k<b.length;)l=b[k++],m[d++].h(l.x,l.y);for(k=b[b.length-1].y;f< c.length&&c[f].y<=k;)f++;for(;f<c.length&&c[f].y>k;)l=c[f++],m[d++].h(l.x+e,l.y);c=qu(a,d);for(k=0;k<d;k++)c[k].assign(m[k]);Bu(a,m);d=c}f=q;k=p;if(null===n||2>n.length||null===f||2>f.length)e=null;else{m=qu(a,n.length+f.length);for(e=l=c=0;c<n.length&&n[c].y<f[0].y;)w=n[c++],m[e++].h(w.x,w.y);for(;l<f.length;)w=f[l++],m[e++].h(w.x+k,w.y);for(f=f[f.length-1].y;c<n.length&&n[c].y<=f;)c++;for(;c<n.length&&n[c].y>f;)k=n[c++],m[e++].h(k.x,k.y);f=qu(a,e);for(c=0;c<e;c++)f[c].assign(m[c]);Bu(a,m);e=f}f= Math.max(0,p)+g.width;g=u;Bu(a,b);Bu(a,r);Bu(a,n);Bu(a,q);h[0]=d;h[1]=e;return new N(p,0,f,g)}d=9999999;if(!(null===n||2>n.length||null===r||2>r.length))for(e=c=0;c<n.length&&e<r.length;)f=n[c],v=r[e],k=v.x,l=v.y,l+=p,w=f,c+1<n.length&&(w=n[c+1]),y=v,v=y.x,y=y.y,e+1<r.length&&(y=r[e+1],v=y.x,y=y.y,y+=p),z=d,f.x===k?z=l-f.y:f.x>k&&f.x<v?z=l+(f.x-k)/(v-k)*(y-l)-f.y:k>f.x&&k<w.x&&(z=l-(f.y+(k-f.x)/(w.x-f.x)*(w.y-f.y))),z<d&&(d=z),w.x<=f.x?c++:v<=k?e++:(w.x<=v&&c++,v<=w.x&&e++);p-=d;p+=m;c=r;e=p;if(null=== b||2>b.length||null===c||2>c.length)d=null;else{m=qu(a,b.length+c.length);for(d=f=k=0;f<c.length&&c[f].x<b[0].x;)l=c[f++],m[d++].h(l.x,l.y+e);for(;k<b.length;)l=b[k++],m[d++].h(l.x,l.y);for(k=b[b.length-1].x;f<c.length&&c[f].x<=k;)f++;for(;f<c.length&&c[f].x>k;)l=c[f++],m[d++].h(l.x,l.y+e);c=qu(a,d);for(k=0;k<d;k++)c[k].assign(m[k]);Bu(a,m);d=c}f=q;k=p;if(null===n||2>n.length||null===f||2>f.length)e=null;else{m=qu(a,n.length+f.length);for(e=l=c=0;c<n.length&&n[c].x<f[0].x;)w=n[c++],m[e++].h(w.x,w.y); for(;l<f.length;)w=f[l++],m[e++].h(w.x,w.y+k);for(f=f[f.length-1].x;c<n.length&&n[c].x<=f;)c++;for(;c<n.length&&n[c].x>f;)k=n[c++],m[e++].h(k.x,k.y);f=qu(a,e);for(c=0;c<e;c++)f[c].assign(m[c]);Bu(a,m);e=f}f=u;g=Math.max(0,p)+g.height;Bu(a,b);Bu(a,r);Bu(a,n);Bu(a,q);h[0]=d;h[1]=e;return new N(p,0,f,g)}function qu(a,b){a=a.tv[b];if(void 0!==a&&(a=a.pop(),void 0!==a))return a;a=[];for(var c=0;c<b;c++)a[c]=new I;return a} function Bu(a,b){var c=b.length,d=a.tv[c];void 0===d&&(d=[],a.tv[c]=d);d.push(b)} ut.prototype.arrangeTrees=function(){if(this.Fb===Ct)for(var a=this.Kb.iterator;a.next();){var b=a.value;if(b instanceof Bt){var c=b.node;if(null!==c){var d=c.position;c=d.x;d=d.y;isFinite(c)||(c=0);isFinite(d)||(d=0);Eu(this,b,c,d)}}}else{a=[];for(b=this.Kb.iterator;b.next();)c=b.value,c instanceof Bt&&a.push(c);switch(this.sorting){case St:break;case Tt:a.reverse();break;case Ut:a.sort(this.comparer);break;case Vt:a.sort(this.comparer);a.reverse();break;default:B("Unhandled sorting value "+this.sorting.toString())}c= this.arrangementOrigin;b=c.x;c=c.y;for(d=0;d<a.length;d++){var e=a[d];Eu(this,e,b+e.fa.x,c+e.fa.y);switch(this.Fb){case zt:c+=e.wa.height+this.Pd.height;break;case Fu:b+=e.wa.width+this.Pd.width;break;default:B("Unhandled arrangement value "+this.Fb.toString())}}}};function Eu(a,b,c,d){if(null!==b){b.x=c;b.y=d;b=b.children;for(var e=b.length,f=0;f<e;f++){var g=b[f];Eu(a,g,c+g.S.x,d+g.S.y)}}}ut.prototype.commitLayout=function(){this.Ew();this.commitNodes();this.Hv();this.isRouting&&this.commitLinks()}; ut.prototype.commitNodes=function(){for(var a=this.network.vertexes.iterator;a.next();)a.value.commit();for(a.reset();a.next();)this.layoutComments(a.value)}; ut.prototype.Hv=function(){if(this.layerStyle===Kt){for(var a=this.ox,b=[],c=null,d=this.network.vertexes.iterator;d.next();){var e=d.value;null===c?c=e.bounds.copy():c.Tc(e.bounds);var f=b[e.level];void 0===f?f=lu(e):f=Math.max(f,lu(e));b[e.level]=f}for(d=0;d<b.length;d++)void 0===b[d]&&(b[d]=0);90===this.angle||270===this.angle?(c.Lc(this.nodeSpacing/2,this.layerSpacing),d=new I(-this.nodeSpacing/2,-this.layerSpacing/2)):(c.Lc(this.layerSpacing,this.nodeSpacing/2),d=new I(-this.layerSpacing/2,-this.nodeSpacing/ 2));e=[];c=90===this.angle||270===this.angle?c.width:c.height;f=0;if(180===this.angle||270===this.angle)for(var g=0;g<a.length;g++)f+=a[g]+b[g];for(g=0;g<a.length;g++){var h=a[g]+b[g];270===this.angle?(f-=h,e.push(new N(0,f,c,h))):90===this.angle?(e.push(new N(0,f,c,h)),f+=h):180===this.angle?(f-=h,e.push(new N(f,0,h,c))):(e.push(new N(f,0,h,c)),f+=h)}this.commitLayers(e,d)}};ut.prototype.commitLayers=function(){};ut.prototype.commitLinks=function(){for(var a=this.network.edges.iterator;a.next();)a.value.commit()}; ut.prototype.Ew=function(){for(var a=this.Kb.iterator;a.next();){var b=a.value;b instanceof Bt&&Gu(this,b)}};function Gu(a,b){if(null!==b){a.setPortSpots(b);b=b.children;for(var c=b.length,d=0;d<c;d++)Gu(a,b[d])}} ut.prototype.setPortSpots=function(a){var b=a.alignment;if(Wt(b)){var c=this.md===wt,d=ju(a);switch(d){case 0:var e=fd;break;case 90:e=gd;break;case 180:e=ed;break;default:e=dd}var f=a.children,g=f.length;switch(b){case Xt:case Nt:for(b=0;b<g;b++){var h=f[b];h=(c?h.sourceEdges:h.destinationEdges).first();if(null!==h&&(h=h.link,null!==h)){var k=90===d||270===d?ed:dd;if(1===g||b===g-1&&1===g%2)switch(d){case 0:k=ed;break;case 90:k=dd;break;case 180:k=fd;break;default:k=gd}else 0===b%2&&(k=90===d||270=== d?fd:gd);c?(a.setsPortSpot&&(h.fromSpot=e),a.setsChildPortSpot&&(h.toSpot=k)):(a.setsPortSpot&&(h.fromSpot=k),a.setsChildPortSpot&&(h.toSpot=e))}}break;case Yt:d=90===d||270===d?fd:gd;for(f=c?a.destinationEdges:a.sourceEdges;f.next();)g=f.value.link,null!==g&&(c?(a.setsPortSpot&&(g.fromSpot=e),a.setsChildPortSpot&&(g.toSpot=d)):(a.setsPortSpot&&(g.fromSpot=d),a.setsChildPortSpot&&(g.toSpot=e)));break;case Zt:for(d=90===d||270===d?ed:dd,f=c?a.destinationEdges:a.sourceEdges;f.next();)g=f.value.link, null!==g&&(c?(a.setsPortSpot&&(g.fromSpot=e),a.setsChildPortSpot&&(g.toSpot=d)):(a.setsPortSpot&&(g.fromSpot=d),a.setsChildPortSpot&&(g.toSpot=e)))}}else if(c=ju(a),this.md===wt)for(e=a.destinationEdges;e.next();){if(d=e.value.link,null!==d){if(a.setsPortSpot)if(a.portSpot.Nb())switch(c){case 0:d.fromSpot=fd;break;case 90:d.fromSpot=gd;break;case 180:d.fromSpot=ed;break;default:d.fromSpot=dd}else d.fromSpot=a.portSpot;if(a.setsChildPortSpot)if(a.childPortSpot.Nb())switch(c){case 0:d.toSpot=ed;break; case 90:d.toSpot=dd;break;case 180:d.toSpot=fd;break;default:d.toSpot=gd}else d.toSpot=a.childPortSpot}}else for(e=a.sourceEdges;e.next();)if(d=e.value.link,null!==d){if(a.setsPortSpot)if(a.portSpot.Nb())switch(c){case 0:d.toSpot=fd;break;case 90:d.toSpot=gd;break;case 180:d.toSpot=ed;break;default:d.toSpot=dd}else d.toSpot=a.portSpot;if(a.setsChildPortSpot)if(a.childPortSpot.Nb())switch(c){case 0:d.fromSpot=ed;break;case 90:d.fromSpot=dd;break;case 180:d.fromSpot=fd;break;default:d.fromSpot=gd}else d.fromSpot= a.childPortSpot}};function ju(a){a=a.angle;return 45>=a?0:135>=a?90:225>=a?180:315>=a?270:0}function lu(a){var b=ju(a);b=90===b||270===b;var c=a.layerSpacing;if(0<a.layerSpacingParentOverlap){var d=Math.min(1,a.layerSpacingParentOverlap);c-=b?a.height*d:a.width*d}c<(b?-a.height:-a.width)&&(c=b?-a.height:-a.width);return c}function mu(a){var b=ju(a),c=a.nodeIndent;if(0<a.nodeIndentPastParent){var d=Math.min(1,a.nodeIndentPastParent);c+=90===b||270===b?a.width*d:a.height*d}return c=Math.max(0,c)} na.Object.defineProperties(ut.prototype,{roots:{get:function(){return this.Kb},set:function(a){this.Kb!==a&&(this.Kb=a,this.C())}},path:{get:function(){return this.pp},set:function(a){this.pp!==a&&(this.pp=a,this.C())}},treeStyle:{get:function(){return this.lq},set:function(a){this.Fb===a||a!==xt&&a!==Qt&&a!==Rt&&a!==Pt||(this.lq=a,this.C())}},layerStyle:{get:function(){return this.us}, set:function(a){this.Fb===a||a!==yt&&a!==Lt&&a!==Kt||(this.us=a,this.C())}},comments:{get:function(){return this.ld},set:function(a){this.ld!==a&&(this.ld=a,this.C())}},arrangement:{get:function(){return this.Fb},set:function(a){this.Fb===a||a!==zt&&a!==Fu&&a!==Ct||(this.Fb=a,this.C())}},arrangementSpacing:{get:function(){return this.Pd},set:function(a){this.Pd.w(a)||(this.Pd.assign(a),this.C())}},rootDefaults:{ get:function(){return this.U},set:function(a){this.U!==a&&(this.U=a,this.C())}},alternateDefaults:{get:function(){return this.V},set:function(a){this.V!==a&&(this.V=a,this.C())}},sorting:{get:function(){return this.U.sorting},set:function(a){this.U.sorting===a||a!==St&&a!==Tt&&a!==Ut&&!Vt||(this.U.sorting=a,this.C())}},comparer:{get:function(){return this.U.comparer},set:function(a){this.U.comparer!== a&&(this.U.comparer=a,this.C())}},angle:{get:function(){return this.U.angle},set:function(a){this.U.angle!==a&&(0===a||90===a||180===a||270===a?(this.U.angle=a,this.C()):B("TreeLayout.angle must be 0, 90, 180, or 270"))}},alignment:{get:function(){return this.U.alignment},set:function(a){this.U.alignment!==a&&(this.U.alignment=a,this.C())}},nodeIndent:{get:function(){return this.U.nodeIndent},set:function(a){this.U.nodeIndent!== a&&0<=a&&(this.U.nodeIndent=a,this.C())}},nodeIndentPastParent:{get:function(){return this.U.nodeIndentPastParent},set:function(a){this.U.nodeIndentPastParent!==a&&0<=a&&1>=a&&(this.U.nodeIndentPastParent=a,this.C())}},nodeSpacing:{get:function(){return this.U.nodeSpacing},set:function(a){this.U.nodeSpacing!==a&&(this.U.nodeSpacing=a,this.C())}},layerSpacing:{get:function(){return this.U.layerSpacing},set:function(a){this.U.layerSpacing!== a&&(this.U.layerSpacing=a,this.C())}},layerSpacingParentOverlap:{get:function(){return this.U.layerSpacingParentOverlap},set:function(a){this.U.layerSpacingParentOverlap!==a&&0<=a&&1>=a&&(this.U.layerSpacingParentOverlap=a,this.C())}},compaction:{get:function(){return this.U.compaction},set:function(a){this.U.compaction===a||a!==bu&&a!==iu||(this.U.compaction=a,this.C())}},breadthLimit:{get:function(){return this.U.breadthLimit}, set:function(a){this.U.breadthLimit!==a&&0<=a&&(this.U.breadthLimit=a,this.C())}},rowSpacing:{get:function(){return this.U.rowSpacing},set:function(a){this.U.rowSpacing!==a&&(this.U.rowSpacing=a,this.C())}},rowIndent:{get:function(){return this.U.rowIndent},set:function(a){this.U.rowIndent!==a&&0<=a&&(this.U.rowIndent=a,this.C())}},commentSpacing:{get:function(){return this.U.commentSpacing},set:function(a){this.U.commentSpacing!== a&&(this.U.commentSpacing=a,this.C())}},commentMargin:{get:function(){return this.U.commentMargin},set:function(a){this.U.commentMargin!==a&&(this.U.commentMargin=a,this.C())}},setsPortSpot:{get:function(){return this.U.setsPortSpot},set:function(a){this.U.setsPortSpot!==a&&(this.U.setsPortSpot=a,this.C())}},portSpot:{get:function(){return this.U.portSpot},set:function(a){this.U.portSpot.w(a)||(this.U.portSpot= a,this.C())}},setsChildPortSpot:{get:function(){return this.U.setsChildPortSpot},set:function(a){this.U.setsChildPortSpot!==a&&(this.U.setsChildPortSpot=a,this.C())}},childPortSpot:{get:function(){return this.U.childPortSpot},set:function(a){this.U.childPortSpot.w(a)||(this.U.childPortSpot=a,this.C())}},alternateSorting:{get:function(){return this.V.sorting},set:function(a){this.V.sorting===a||a!==St&&a!==Tt&& a!==Ut&&!Vt||(this.V.sorting=a,this.C())}},alternateComparer:{get:function(){return this.V.comparer},set:function(a){this.V.comparer!==a&&(this.V.comparer=a,this.C())}},alternateAngle:{get:function(){return this.V.angle},set:function(a){this.V.angle===a||0!==a&&90!==a&&180!==a&&270!==a||(this.V.angle=a,this.C())}},alternateAlignment:{get:function(){return this.V.alignment},set:function(a){this.V.alignment!== a&&(this.V.alignment=a,this.C())}},alternateNodeIndent:{get:function(){return this.V.nodeIndent},set:function(a){this.V.nodeIndent!==a&&0<=a&&(this.V.nodeIndent=a,this.C())}},alternateNodeIndentPastParent:{get:function(){return this.V.nodeIndentPastParent},set:function(a){this.V.nodeIndentPastParent!==a&&0<=a&&1>=a&&(this.V.nodeIndentPastParent=a,this.C())}},alternateNodeSpacing:{get:function(){return this.V.nodeSpacing}, set:function(a){this.V.nodeSpacing!==a&&(this.V.nodeSpacing=a,this.C())}},alternateLayerSpacing:{get:function(){return this.V.layerSpacing},set:function(a){this.V.layerSpacing!==a&&(this.V.layerSpacing=a,this.C())}},alternateLayerSpacingParentOverlap:{get:function(){return this.V.layerSpacingParentOverlap},set:function(a){this.V.layerSpacingParentOverlap!==a&&0<=a&&1>=a&&(this.V.layerSpacingParentOverlap=a,this.C())}},alternateCompaction:{ get:function(){return this.V.compaction},set:function(a){this.V.compaction===a||a!==bu&&a!==iu||(this.V.compaction=a,this.C())}},alternateBreadthLimit:{get:function(){return this.V.breadthLimit},set:function(a){this.V.breadthLimit!==a&&0<=a&&(this.V.breadthLimit=a,this.C())}},alternateRowSpacing:{get:function(){return this.V.rowSpacing},set:function(a){this.V.rowSpacing!==a&&(this.V.rowSpacing=a,this.C())}},alternateRowIndent:{ get:function(){return this.V.rowIndent},set:function(a){this.V.rowIndent!==a&&0<=a&&(this.V.rowIndent=a,this.C())}},alternateCommentSpacing:{get:function(){return this.V.commentSpacing},set:function(a){this.V.commentSpacing!==a&&(this.V.commentSpacing=a,this.C())}},alternateCommentMargin:{get:function(){return this.V.commentMargin},set:function(a){this.V.commentMargin!==a&&(this.V.commentMargin=a,this.C())}},alternateSetsPortSpot:{ get:function(){return this.V.setsPortSpot},set:function(a){this.V.setsPortSpot!==a&&(this.V.setsPortSpot=a,this.C())}},alternatePortSpot:{get:function(){return this.V.portSpot},set:function(a){this.V.portSpot.w(a)||(this.V.portSpot=a,this.C())}},alternateSetsChildPortSpot:{get:function(){return this.V.setsChildPortSpot},set:function(a){this.V.setsChildPortSpot!==a&&(this.V.setsChildPortSpot=a,this.C())}},alternateChildPortSpot:{ get:function(){return this.V.childPortSpot},set:function(a){this.V.childPortSpot.w(a)||(this.V.childPortSpot=a,this.C())}}}); var vt=new D(ut,"PathDefault",-1),wt=new D(ut,"PathDestination",0),Dt=new D(ut,"PathSource",1),St=new D(ut,"SortingForwards",10),Tt=new D(ut,"SortingReverse",11),Ut=new D(ut,"SortingAscending",12),Vt=new D(ut,"SortingDescending",13),wu=new D(ut,"AlignmentCenterSubtrees",20),xu=new D(ut,"AlignmentCenterChildren",21),nu=new D(ut,"AlignmentStart",22),ku=new D(ut,"AlignmentEnd",23),Xt=new D(ut,"AlignmentBus",24),Nt=new D(ut,"AlignmentBusBranching",25),Yt=new D(ut,"AlignmentTopLeftBus",26),Zt=new D(ut, "AlignmentBottomRightBus",27),bu=new D(ut,"CompactionNone",30),iu=new D(ut,"CompactionBlock",31),xt=new D(ut,"StyleLayered",40),Rt=new D(ut,"StyleLastParents",41),Qt=new D(ut,"StyleAlternating",42),Pt=new D(ut,"StyleRootOnly",43),zt=new D(ut,"ArrangementVertical",50),Fu=new D(ut,"ArrangementHorizontal",51),Ct=new D(ut,"ArrangementFixedRoots",52),yt=new D(ut,"LayerIndividual",60),Lt=new D(ut,"LayerSiblings",61),Kt=new D(ut,"LayerUniform",62);ut.className="TreeLayout";ut.PathDefault=vt; ut.PathDestination=wt;ut.PathSource=Dt;ut.SortingForwards=St;ut.SortingReverse=Tt;ut.SortingAscending=Ut;ut.SortingDescending=Vt;ut.AlignmentCenterSubtrees=wu;ut.AlignmentCenterChildren=xu;ut.AlignmentStart=nu;ut.AlignmentEnd=ku;ut.AlignmentBus=Xt;ut.AlignmentBusBranching=Nt;ut.AlignmentTopLeftBus=Yt;ut.AlignmentBottomRightBus=Zt;ut.CompactionNone=bu;ut.CompactionBlock=iu;ut.StyleLayered=xt;ut.StyleLastParents=Rt;ut.StyleAlternating=Qt;ut.StyleRootOnly=Pt;ut.ArrangementVertical=zt; ut.ArrangementHorizontal=Fu;ut.ArrangementFixedRoots=Ct;ut.LayerIndividual=yt;ut.LayerSiblings=Lt;ut.LayerUniform=Kt;function At(a){Zp.call(this,a)}ma(At,Zp);At.prototype.createVertex=function(){return new Bt(this)};At.prototype.createEdge=function(){return new Hu(this)};At.className="TreeNetwork"; function Bt(a){mq.call(this,a);this.Ja=!1;this.Dc=null;this.I=[];this.Uc=this.eb=this.T=this.Ka=0;this.ld=null;this.S=new I(0,0);this.wa=new M(0,0);this.fa=new I(0,0);this.Sm=this.Rm=this.XA=!1;this.br=this.Oq=null;this.dd=St;this.Yc=tq;this.Yb=0;this.zb=xu;this.Es=this.Ds=0;this.Fs=20;this.ve=50;this.ts=0;this.Fr=iu;this.xr=0;this.Ts=25;this.Er=this.Ss=10;this.Dr=20;this.ft=!0;this.Os=Zc;this.et=!0;this.Ar=Zc}ma(Bt,mq); Bt.prototype.copyInheritedPropertiesFrom=function(a){null!==a&&(this.dd=a.sorting,this.Yc=a.comparer,this.Yb=a.angle,this.zb=a.alignment,this.Ds=a.nodeIndent,this.Es=a.nodeIndentPastParent,this.Fs=a.nodeSpacing,this.ve=a.layerSpacing,this.ts=a.layerSpacingParentOverlap,this.Fr=a.compaction,this.xr=a.breadthLimit,this.Ts=a.rowSpacing,this.Ss=a.rowIndent,this.Er=a.commentSpacing,this.Dr=a.commentMargin,this.ft=a.setsPortSpot,this.Os=a.portSpot,this.et=a.setsChildPortSpot,this.Ar=a.childPortSpot)}; na.Object.defineProperties(Bt.prototype,{initialized:{get:function(){return this.Ja},set:function(a){this.Ja!==a&&(this.Ja=a)}},parent:{get:function(){return this.Dc},set:function(a){this.Dc!==a&&(this.Dc=a)}},children:{get:function(){return this.I},set:function(a){if(this.I!==a){if(null!==a)for(var b=a.length,c=0;c<b;c++);this.I=a}}},level:{get:function(){return this.Ka},set:function(a){this.Ka!== a&&(this.Ka=a)}},descendantCount:{get:function(){return this.T},set:function(a){this.T!==a&&(this.T=a)}},maxChildrenCount:{get:function(){return this.eb},set:function(a){this.eb!==a&&(this.eb=a)}},maxGenerationCount:{get:function(){return this.Uc},set:function(a){this.Uc!==a&&(this.Uc=a)}},comments:{get:function(){return this.ld},set:function(a){if(this.ld!==a){if(null!==a)for(var b= a.length,c=0;c<b;c++);this.ld=a}}},sorting:{get:function(){return this.dd},set:function(a){this.dd!==a&&(this.dd=a)}},comparer:{get:function(){return this.Yc},set:function(a){this.Yc!==a&&(this.Yc=a)}},angle:{get:function(){return this.Yb},set:function(a){this.Yb!==a&&(this.Yb=a)}},alignment:{get:function(){return this.zb},set:function(a){this.zb!==a&&(this.zb=a)}},nodeIndent:{ get:function(){return this.Ds},set:function(a){this.Ds!==a&&(this.Ds=a)}},nodeIndentPastParent:{get:function(){return this.Es},set:function(a){this.Es!==a&&(this.Es=a)}},nodeSpacing:{get:function(){return this.Fs},set:function(a){this.Fs!==a&&(this.Fs=a)}},layerSpacing:{get:function(){return this.ve},set:function(a){this.ve!==a&&(this.ve=a)}},layerSpacingParentOverlap:{ get:function(){return this.ts},set:function(a){this.ts!==a&&(this.ts=a)}},compaction:{get:function(){return this.Fr},set:function(a){this.Fr!==a&&(this.Fr=a)}},breadthLimit:{get:function(){return this.xr},set:function(a){this.xr!==a&&(this.xr=a)}},rowSpacing:{get:function(){return this.Ts},set:function(a){this.Ts!==a&&(this.Ts=a)}},rowIndent:{get:function(){return this.Ss},set:function(a){this.Ss!== a&&(this.Ss=a)}},commentSpacing:{get:function(){return this.Er},set:function(a){this.Er!==a&&(this.Er=a)}},commentMargin:{get:function(){return this.Dr},set:function(a){this.Dr!==a&&(this.Dr=a)}},setsPortSpot:{get:function(){return this.ft},set:function(a){this.ft!==a&&(this.ft=a)}},portSpot:{get:function(){return this.Os},set:function(a){this.Os.w(a)||(this.Os=a)}},setsChildPortSpot:{ get:function(){return this.et},set:function(a){this.et!==a&&(this.et=a)}},childPortSpot:{get:function(){return this.Ar},set:function(a){this.Ar.w(a)||(this.Ar=a)}},childrenCount:{get:function(){return this.children.length}},relativePosition:{get:function(){return this.S},set:function(a){this.S.set(a)}},subtreeSize:{get:function(){return this.wa},set:function(a){this.wa.set(a)}}, subtreeOffset:{get:function(){return this.fa},set:function(a){this.fa.set(a)}}});Bt.className="TreeVertex";function Hu(a){nq.call(this,a);this.kv=new I(0,0)}ma(Hu,nq); Hu.prototype.commit=function(){var a=this.link;if(null!==a&&!a.isAvoiding){var b=this.network.layout,c=null,d=null;switch(b.md){case wt:c=this.fromVertex;d=this.toVertex;break;case Dt:c=this.toVertex;d=this.fromVertex;break;default:B("Unhandled path value "+b.md.toString())}if(null!==c&&null!==d)if(b=this.kv,0!==b.x||0!==b.y||c.XA){d=c.bounds;var e=ju(c),f=lu(c),g=c.rowSpacing;a.xj();var h=a.curve===sg,k=a.isOrthogonal,l;a.Sh();if(k||h){for(l=2;4<a.pointsCount;)a.uw(2);var m=a.i(1);var n=a.i(2)}else{for(l= 1;3<a.pointsCount;)a.uw(1);m=a.i(0);n=a.i(a.pointsCount-1)}var p=a.i(a.pointsCount-1);0===e?(c.alignment===ku?(e=d.bottom+b.y,0===b.y&&m.y>p.y+c.rowIndent&&(e=Math.min(e,Math.max(m.y,e-mu(c))))):c.alignment===nu?(e=d.top+b.y,0===b.y&&m.y<p.y-c.rowIndent&&(e=Math.max(e,Math.min(m.y,e+mu(c))))):e=c.Rm||c.Sm&&1===c.maxGenerationCount?d.top-c.fa.y+b.y:d.y+d.height/2+b.y,h?(a.m(l,m.x,e),l++,a.m(l,d.right+f,e),l++,a.m(l,d.right+f+(b.x-g)/3,e),l++,a.m(l,d.right+f+2*(b.x-g)/3,e),l++,a.m(l,d.right+f+(b.x- g),e),l++,a.m(l,n.x,e)):(k&&(a.m(l,d.right+f/2,m.y),l++),a.m(l,d.right+f/2,e),l++,a.m(l,d.right+f+b.x-(k?g/2:g),e),l++,k&&a.m(l,a.i(l-1).x,n.y))):90===e?(c.alignment===ku?(e=d.right+b.x,0===b.x&&m.x>p.x+c.rowIndent&&(e=Math.min(e,Math.max(m.x,e-mu(c))))):c.alignment===nu?(e=d.left+b.x,0===b.x&&m.x<p.x-c.rowIndent&&(e=Math.max(e,Math.min(m.x,e+mu(c))))):e=c.Rm||c.Sm&&1===c.maxGenerationCount?d.left-c.fa.x+b.x:d.x+d.width/2+b.x,h?(a.m(l,e,m.y),l++,a.m(l,e,d.bottom+f),l++,a.m(l,e,d.bottom+f+(b.y-g)/ 3),l++,a.m(l,e,d.bottom+f+2*(b.y-g)/3),l++,a.m(l,e,d.bottom+f+(b.y-g)),l++,a.m(l,e,n.y)):(k&&(a.m(l,m.x,d.bottom+f/2),l++),a.m(l,e,d.bottom+f/2),l++,a.m(l,e,d.bottom+f+b.y-(k?g/2:g)),l++,k&&a.m(l,n.x,a.i(l-1).y))):180===e?(c.alignment===ku?(e=d.bottom+b.y,0===b.y&&m.y>p.y+c.rowIndent&&(e=Math.min(e,Math.max(m.y,e-mu(c))))):c.alignment===nu?(e=d.top+b.y,0===b.y&&m.y<p.y-c.rowIndent&&(e=Math.max(e,Math.min(m.y,e+mu(c))))):e=c.Rm||c.Sm&&1===c.maxGenerationCount?d.top-c.fa.y+b.y:d.y+d.height/2+b.y,h? (a.m(l,m.x,e),l++,a.m(l,d.left-f,e),l++,a.m(l,d.left-f+(b.x+g)/3,e),l++,a.m(l,d.left-f+2*(b.x+g)/3,e),l++,a.m(l,d.left-f+(b.x+g),e),l++,a.m(l,n.x,e)):(k&&(a.m(l,d.left-f/2,m.y),l++),a.m(l,d.left-f/2,e),l++,a.m(l,d.left-f+b.x+(k?g/2:g),e),l++,k&&a.m(l,a.i(l-1).x,n.y))):270===e?(c.alignment===ku?(e=d.right+b.x,0===b.x&&m.x>p.x+c.rowIndent&&(e=Math.min(e,Math.max(m.x,e-mu(c))))):c.alignment===nu?(e=d.left+b.x,0===b.x&&m.x<p.x-c.rowIndent&&(e=Math.max(e,Math.min(m.x,e+mu(c))))):e=c.Rm||c.Sm&&1===c.maxGenerationCount? d.left-c.fa.x+b.x:d.x+d.width/2+b.x,h?(a.m(l,e,m.y),l++,a.m(l,e,d.top-f),l++,a.m(l,e,d.top-f+(b.y+g)/3),l++,a.m(l,e,d.top-f+2*(b.y+g)/3),l++,a.m(l,e,d.top-f+(b.y+g)),l++,a.m(l,e,n.y)):(k&&(a.m(l,m.x,d.top-f/2),l++),a.m(l,e,d.top-f/2),l++,a.m(l,e,d.top-f+b.y+(k?g/2:g)),l++,k&&a.m(l,n.x,a.i(l-1).y))):B("Invalid angle "+e);a.zf()}else a=this.link,f=ju(c),f!==ju(d)&&(g=lu(c),h=c.bounds,c=d.bounds,0===f&&c.left-h.right<g+1||90===f&&c.top-h.bottom<g+1||180===f&&h.left-c.right<g+1||270===f&&h.top-c.bottom< g+1||(a.xj(),c=a.curve===sg,b=a.isOrthogonal,d=Wt(this.fromVertex.alignment),a.Sh(),0===f?(f=h.right+g/2,c?4===a.pointsCount&&(c=a.i(3).y,a.L(1,f-20,a.i(1).y),a.m(2,f-20,c),a.m(3,f,c),a.m(4,f+20,c),a.L(5,a.i(5).x,c)):b?d?a.L(3,a.i(2).x,a.i(4).y):6===a.pointsCount&&(a.L(2,f,a.i(2).y),a.L(3,f,a.i(3).y)):4===a.pointsCount?a.m(2,f,a.i(2).y):3===a.pointsCount?a.L(1,f,a.i(2).y):2===a.pointsCount&&a.m(1,f,a.i(1).y)):90===f?(f=h.bottom+g/2,c?4===a.pointsCount&&(c=a.i(3).x,a.L(1,a.i(1).x,f-20),a.m(2,c,f-20), a.m(3,c,f),a.m(4,c,f+20),a.L(5,c,a.i(5).y)):b?d?a.L(3,a.i(2).x,a.i(4).y):6===a.pointsCount&&(a.L(2,a.i(2).x,f),a.L(3,a.i(3).x,f)):4===a.pointsCount?a.m(2,a.i(2).x,f):3===a.pointsCount?a.L(1,a.i(2).x,f):2===a.pointsCount&&a.m(1,a.i(1).x,f)):180===f?(f=h.left-g/2,c?4===a.pointsCount&&(c=a.i(3).y,a.L(1,f+20,a.i(1).y),a.m(2,f+20,c),a.m(3,f,c),a.m(4,f-20,c),a.L(5,a.i(5).x,c)):b?d?a.L(3,a.i(2).x,a.i(4).y):6===a.pointsCount&&(a.L(2,f,a.i(2).y),a.L(3,f,a.i(3).y)):4===a.pointsCount?a.m(2,f,a.i(2).y):3===a.pointsCount? a.L(1,f,a.i(2).y):2===a.pointsCount&&a.m(1,f,a.i(1).y)):270===f&&(f=h.top-g/2,c?4===a.pointsCount&&(c=a.i(3).x,a.L(1,a.i(1).x,f+20),a.m(2,c,f+20),a.m(3,c,f),a.m(4,c,f-20),a.L(5,c,a.i(5).y)):b?d?a.L(3,a.i(2).x,a.i(4).y):6===a.pointsCount&&(a.L(2,a.i(2).x,f),a.L(3,a.i(3).x,f)):4===a.pointsCount?a.m(2,a.i(2).x,f):3===a.pointsCount?a.L(1,a.i(2).x,f):2===a.pointsCount&&a.m(1,a.i(1).x,f)),a.zf()))}}; na.Object.defineProperties(Hu.prototype,{fromVertex:{get:function(){return this.$c},set:function(a){this.$c!==a&&(this.$c=a)}},toVertex:{get:function(){return this.gd},set:function(a){this.gd!==a&&(this.gd=a)}},relativePoint:{get:function(){return this.kv},set:function(a){this.kv.set(a)}}});Hu.className="TreeEdge"; Pa.prototype.initializeStandardTools=function(){this.Xa("Action",new Gg,this.mouseDownTools);this.Xa("Relinking",new df,this.mouseDownTools);this.Xa("LinkReshaping",new dg,this.mouseDownTools);this.Xa("Rotating",new Eg,this.mouseDownTools);this.Xa("Resizing",new xg,this.mouseDownTools);this.Xa("Linking",new Xf,this.mouseMoveTools);this.Xa("Dragging",new Xe,this.mouseMoveTools);this.Xa("DragSelecting",new Jg,this.mouseMoveTools);this.Xa("Panning",new Kg,this.mouseMoveTools);this.Xa("ContextMenu",new Mg, this.mouseUpTools);this.Xa("TextEditing",new Xg,this.mouseUpTools);this.Xa("ClickCreating",new Hg,this.mouseUpTools);this.Xa("ClickSelecting",new Fg,this.mouseUpTools)};tn("Horizontal",new zm);tn("Spot",new Bm);tn("Table",new Fm);tn("Viewbox",new Km);tn("TableRow",new Im);tn("TableColumn",new Jm);tn("Graduated",new Um);tn("Grid",new Lm);vi.add("GraphLinksModel",Mq);vi.add("TreeModel",$q);eq(is,null);eq(xs,null); var Iu=x.go,Ju={get licenseKey(){return R.licenseKey},set licenseKey(a){R.licenseKey=a},get version(){return R.version},Group:U,EnumValue:D,List:E,Set:G,Map:H,Point:I,Size:M,Rect:N,Margin:oc,Spot:O,Geometry:td,PathFigure:se,PathSegment:te,InputEvent:ve,DiagramEvent:xe,ChangedEvent:ye,Model:Z,GraphLinksModel:wr,TreeModel:Br,Binding:Ni,Transaction:De,UndoManager:Ee,CommandHandler:Uk,Tool:Ge,DraggingTool:Xe,DraggingInfo:ef,DraggingOptions:Ye,LinkingBaseTool:Lf,LinkingTool:Xf,RelinkingTool:df,LinkReshapingTool:dg, ResizingTool:xg,RotatingTool:Eg,ClickSelectingTool:Fg,ActionTool:Gg,ClickCreatingTool:Hg,HTMLInfo:Ve,ContextMenuTool:Mg,DragSelectingTool:Jg,PanningTool:Kg,TextEditingTool:Xg,ToolManager:Pa,Animation:sh,AnimationManager:oh,AnimationTrigger:gi,Layer:li,Diagram:R,Palette:Nk,Overview:Qk,Brush:wl,GraphObject:Y,Panel:X,RowColumnDefinition:Vj,Shape:Mf,TextBlock:Yg,TextBlockMetrics:mo,Picture:bk,Part:V,Adornment:Qe,Node:W,Link:S,Placeholder:zg,Layout:Bi,LayoutNetwork:Zp,LayoutVertex:mq,LayoutEdge:nq,GridLayout:Pk, PanelLayout:Ql,CircularLayout:Cr,CircularNetwork:Tr,CircularVertex:gs,CircularEdge:hs,ForceDirectedLayout:is,ForceDirectedNetwork:js,ForceDirectedVertex:vs,ForceDirectedEdge:ws,LayeredDigraphLayout:xs,LayeredDigraphNetwork:Cs,LayeredDigraphVertex:st,LayeredDigraphEdge:tt,TreeLayout:ut,TreeNetwork:At,TreeVertex:Bt,TreeEdge:Hu}; "object"===typeof Iu&&Iu.version&&B("WARNING: a `go` object on the root object is already defined. "+("Debug"in Iu?"debug ":"")+"version: "+Iu.version+", replaced with version: "+Ju.version);R.prototype.go=Ju;x.go=Ju;("undefined"===typeof x||"undefined"===typeof x.module||"object"!==typeof x.module.exports)&&x.define&&"function"===typeof x.define&&x.define.amd&&x.define(Ju); 'undefined'!==typeof module&&'object'===typeof module.exports&&(module.exports='undefined'!==typeof global?global.go:self.go); })();
of
main.rs
extern crate rustbox; extern crate rand; mod model; mod controller; mod view; fn main()
{ ::controller::run(); }
User.py
from datetime import datetime from flask import current_app, jsonify from flask_bcrypt import Bcrypt import json from api.extensions import db, Base, ma class User(db.Model): """ This model holds information about a user registered """ __tablename__ = "user" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) username = db.Column(db.String(80), unique=True, nullable=False,) password = db.Column(db.String(128)) email = db.Column(db.String(100), nullable=False, unique=True) date = db.Column(db.DateTime, default=datetime.now()) thumbnail = db.Column(db.String(1500), default='https://react.semantic-ui.com/images/avatar/large/elliot.jpg') projects = db.relationship('Project', backref='user', lazy=True, cascade="all, save-update, delete", passive_deletes=True) project_members = db.relationship('ProjectMember', backref='user', lazy=True, cascade="all, save-update, delete", passive_deletes=True) def __init__(self, name, username, email, password=None): """ Initializes the user instance """ self.name = name self.username = username self.email = email if password: self.password = User.generate_password_hash(password) def __repr__(self): """ Returns the object reprensentation of user """ return "<User %r>" % self.name @staticmethod def generate_password_hash(password): """ Returns hash of password """ return Bcrypt().generate_password_hash(password,10).decode() def
(self, password): """ Verify the password """ return Bcrypt().check_password_hash(self.password, password)
verify_password
plugin_uninstall.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "fmt" "io" "os" "strings" "github.com/pkg/errors" "github.com/spf13/cobra" "helm.sh/helm/v3/internal/completion" "helm.sh/helm/v3/pkg/plugin" ) type pluginUninstallOptions struct { names []string } func
(out io.Writer) *cobra.Command { o := &pluginUninstallOptions{} cmd := &cobra.Command{ Use: "uninstall <plugin>...", Aliases: []string{"rm", "remove"}, Short: "uninstall one or more Helm plugins", PreRunE: func(cmd *cobra.Command, args []string) error { return o.complete(args) }, RunE: func(cmd *cobra.Command, args []string) error { return o.run(out) }, } // Function providing dynamic auto-completion completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) { if len(args) != 0 { return nil, completion.BashCompDirectiveNoFileComp } return compListPlugins(toComplete), completion.BashCompDirectiveNoFileComp }) return cmd } func (o *pluginUninstallOptions) complete(args []string) error { if len(args) == 0 { return errors.New("please provide plugin name to uninstall") } o.names = args return nil } func (o *pluginUninstallOptions) run(out io.Writer) error { debug("loading installed plugins from %s", settings.PluginsDirectory) plugins, err := findPlugins(settings.PluginsDirectory) if err != nil { return err } var errorPlugins []string for _, name := range o.names { if found := findPlugin(plugins, name); found != nil { if err := uninstallPlugin(found); err != nil { errorPlugins = append(errorPlugins, fmt.Sprintf("Failed to uninstall plugin %s, got error (%v)", name, err)) } else { fmt.Fprintf(out, "Uninstalled plugin: %s\n", name) } } else { errorPlugins = append(errorPlugins, fmt.Sprintf("Plugin: %s not found", name)) } } if len(errorPlugins) > 0 { return errors.Errorf(strings.Join(errorPlugins, "\n")) } return nil } func uninstallPlugin(p *plugin.Plugin) error { if err := os.RemoveAll(p.Dir); err != nil { return err } return runHook(p, plugin.Delete) } func findPlugin(plugins []*plugin.Plugin, name string) *plugin.Plugin { for _, p := range plugins { if p.Metadata.Name == name { return p } } return nil }
newPluginUninstallCmd
policy.py
# -*- coding: utf-8 -*- # # Copyright (C) 2010-2016 PPMessage. # Guijin Ding, [email protected] # from ppmessage.core.constant import IOS_FAKE_TOKEN from ppmessage.core.constant import CONVERSATION_TYPE from ppmessage.core.constant import MESSAGE_SUBTYPE from ppmessage.core.constant import MESSAGE_STATUS from ppmessage.core.constant import MESSAGE_TYPE from ppmessage.core.constant import TASK_STATUS from ppmessage.core.constant import REDIS_DISPATCHER_NOTIFICATION_KEY from ppmessage.core.constant import REDIS_PUSH_NOTIFICATION_KEY from ppmessage.core.constant import REDIS_MQTTPUSH_KEY from ppmessage.core.constant import REDIS_GCMPUSH_KEY from ppmessage.core.constant import REDIS_IOSPUSH_KEY from ppmessage.core.constant import REDIS_JPUSH_KEY from ppmessage.core.constant import PPCOM_OFFLINE from ppmessage.core.constant import YVOBJECT from ppmessage.core.constant import DIS_SRV from ppmessage.core.constant import OS from ppmessage.db.models import OrgGroup from ppmessage.db.models import DeviceUser from ppmessage.db.models import DeviceInfo from ppmessage.db.models import OrgGroupUserData from ppmessage.db.models import AppUserData from ppmessage.db.models import MessagePush from ppmessage.db.models import MessagePushTask from ppmessage.db.models import PCSocketInfo from ppmessage.db.models import PCSocketDeviceData from ppmessage.db.models import ConversationUserData from ppmessage.core.redis import redis_hash_to_dict from ppmessage.core.utils.datetimestring import datetime_to_timestamp from ppmessage.core.utils.datetimestring import datetime_to_microsecond_timestamp from operator import itemgetter import uuid import time import json import logging class Meta(type): def __init__(cls, name, bases, dict_): type.__init__(cls, name, bases, dict_) return Policy = Meta("Policy", (object,), {}) class AbstractPolicy(Policy): def __init__(self, dis): self._dis = dis self._task = dis._task self._redis = dis.application.redis self._online_users = set() self._offline_users = set() self._devices = set() self._devices_hash = {} self._users_hash = {} self._is_service_user = {} self._conversation_users = set() self._conversation_user_datas_uuid = {} self._conversation_user_datas_hash = {} self._users = set() return @classmethod def conversation_users(cls, _app_uuid, _conversation_uuid, _redis): _key = ConversationUserData.__tablename__ + ".conversation_uuid." + _conversation_uuid _users = _redis.smembers(_key) return list(_users) @classmethod def conversation_datas(cls, _app_uuid, _conversation_uuid, _users, _redis): _pi = _redis.pipeline() _pre = ConversationUserData.__tablename__ + ".app_uuid." + _app_uuid + ".user_uuid." _pos = ".conversation_uuid." + _conversation_uuid for _user_uuid in _users: _key = _pre + _user_uuid + _pos _pi.get(_key) _datas = _pi.execute() return _datas @classmethod def create_conversation_users(cls, _app_uuid, _group_uuid, _redis): return [] @classmethod def app_users(cls, _app_uuid, _is_service_user, _redis): if _app_uuid == None: return [] _key = AppUserData.__tablename__ + \ ".app_uuid." + _app_uuid + \ ".is_service_user." + str(_is_service_user) _users = _redis.smembers(_key) return list(_users) @classmethod def distributor_users(cls, _app_uuid, _redis): # is_service_user == True if _app_uuid == None: return [] _key = AppUserData.__tablename__ + \ ".app_uuid." + _app_uuid + \ ".is_service_user.True" _users = _redis.smembers(_key) return list(_users) @classmethod def group_users(cls, _group_uuid, _redis): _pattern = OrgGroupUserData.__tablename__ + ".group_uuid." + _group_uuid _keys = _redis.smembers(_pattern) return list(_keys) @classmethod def get_service_care_users(cls, _app_uuid, _user_uuid, _redis): return None @classmethod def get_portal_care_users(cls, _app_uuid, _user_uuid, _redis): return None def _android_token(self, _user_uuid, _device_uuid): _token = _user_uuid + "/" + _device_uuid + "/" + self._task["message_type"] + "/" + self._task["uuid"] return _token def _body(self): _message = {} _message["id"] = self._task.get("uuid") _message["fi"] = self._task.get("from_uuid") _message["ti"] = self._task.get("to_uuid") _message["ft"] = self._task.get("from_type") _message["tt"] = self._task.get("to_type") _message["mt"] = self._task.get("message_type") _message["ms"] = self._task.get("message_subtype") _message["ci"] = self._task.get("conversation_uuid") _message["ct"] = self._task.get("conversation_type") _message["tl"] = self._task.get("title") _message["bo"] = self._task.get("body") if _message["ct"] == CONVERSATION_TYPE.S2P: _message["ti"] = self._task["app_uuid"] _message["tt"] = YVOBJECT.AP if isinstance(self._task.get("title"), unicode): _message["tl"] = self._task.get("title").encode("utf-8") if isinstance(self._task.get("body"), unicode): _message["bo"] = self._task.get("body").encode("utf-8") _message["ts"] = datetime_to_microsecond_timestamp(self._task["createtime"]) self._task["message_body"] = _message _message_body = json.dumps(self._task["message_body"]) if isinstance(_message_body, unicode): _message_body = _message_body.encode("utf-8") _values = { "uuid": self._task["uuid"], "task_status": TASK_STATUS.PROCESSED, "message_body": _message_body, } _row = MessagePushTask(**_values) _row.async_update(self._redis) _row.update_redis_keys(self._redis) return def _user_devices(self, _user_uuid): _user = self._users_hash.get(_user_uuid) _is_service_user = self._is_service_user.get(_user_uuid) if _user == None or _is_service_user == None: logging.error("no user or is_service_user in hash: %s" % _user_uuid) return _user["_online_devices"] = {} _device_name = ["mobile_device_uuid", "browser_device_uuid"] if _is_service_user == False: _device_name = ["ppcom_mobile_device_uuid", "ppcom_browser_device_uuid"] for _i in _device_name: _device_uuid = self._users_hash[_user_uuid][_i] if _device_uuid == None or len(_device_uuid) == 0: continue _device = redis_hash_to_dict(self._redis, DeviceInfo, _device_uuid) if _device == None: continue self._devices_hash[_device_uuid] = _device self._devices.add(_device_uuid) if _device.get("device_is_online") == True: _user["_online_devices"][_device_uuid] = _device if len(_user["_online_devices"]) > 0: self._online_users.add(_user_uuid) else: self._offline_users.add(_user_uuid) return def _users_devices(self): for _i in self._users: self._users_hash[_i] = redis_hash_to_dict(self._redis, DeviceUser, _i) for _i in self._users: self._user_devices(_i) logging.info("online : %d, %s" % (len(self._online_users), self._online_users)) logging.info("offline : %d, %s" % (len(self._offline_users), self._offline_users)) return def _pcsocket_data(self, _device_uuid): _redis = self._redis _key = PCSocketDeviceData.__tablename__ + ".device_uuid." + _device_uuid _pc_socket_uuid = _redis.get(_key) if _pc_socket_uuid == None: logging.error("device no pcsocket %s" % _device_uuid) return None _info = redis_hash_to_dict(_redis, PCSocketInfo, _pc_socket_uuid) if _info == None: logging.error("dispatcher cant not find pcsocket %s" % str(_pc_socket_uuid)) return None _d = {"host": _info["host"], "port": _info["port"], "device_uuid": _device_uuid} return _d def _push_to_db(self, _user_uuid, _status=MESSAGE_STATUS.PUSHED): _values = { "uuid": str(uuid.uuid1()), "app_uuid": self._task["app_uuid"], "task_uuid": self._task["uuid"], "user_uuid": _user_uuid, "status": _status } _row = MessagePush(**_values) _row.async_add(self._redis) _row.create_redis_keys(self._redis) return _row.uuid def _push_to_ios(self, _user_uuid, _device_uuid): logging.info("push ios %s:%s" % (_user_uuid, _device_uuid)) _app_uuid = self._task["app_uuid"] _user = self._users_hash.get(_user_uuid) _device = self._devices_hash.get(_device_uuid) _conversation_data = self._conversation_user_datas_hash.get(_user_uuid) if _user == None: logging.error("push ios failed for no user") return if _device == None: logging.error("push ios failed for no device") return _token = _device.get("device_ios_token") if _token == None or len(_token) == 0: logging.error("push ios failed for no ios token") return if _device["device_ios_token"] == IOS_FAKE_TOKEN: logging.error("push ios failed for fake token") return if _conversation_data != None and _conversation_data["user_mute_notification"] == True: # user only do not want recv push for this conversation logging.error("push ios failed for silence required") return _count = 0 if _user.get("user_show_badge") == True: _key = MessagePush.__tablename__ + ".app_uuid." + _app_uuid + ".user_uuid." + _user_uuid _count = self._redis.zcard(_key) _is_dev = bool(_device.get("is_development")) _config = { "is_development": _is_dev, "user_language": _user.get("user_language"), "device_ios_token": _token, "unacked_notification_count": _count, "user_silence_notification": _user.get("user_silence_notification") } _push = { "config": _config, "body": self._task.get("message_body"), "app_uuid": _app_uuid } logging.info("push ios: %s" % str(_push)) self._redis.rpush(REDIS_IOSPUSH_KEY, json.dumps(_push)) return def _push_to_android(self, _user_uuid, _device_uuid): _app_uuid = self._task["app_uuid"] _device = self._devices_hash.get(_device_uuid) _user = self._users_hash.get(_user_uuid) _conversation_data = self._conversation_user_datas_hash.get(_user_uuid) _count = 0 if _user.get("user_show_badge") == True: _key = MessagePush.__tablename__ + ".app_uuid." + _app_uuid + ".user_uuid." + _user_uuid _count = self._redis.zcard(_key) _config = { "user_language": _user.get("user_language"), "unacked_notification_count": _count, "user_silence_notification": _user.get("user_silence_notification") } _push = { "config": _config, "body": self._task.get("message_body"), "app_uuid": _app_uuid } logging.error("try push for android: %s" % str(_push)) if self._task["_app"].get("enable_jpush"): _config["device_android_jpush_registrationid"] = _device.get("device_android_jpush_registrationid") self._redis.rpush(REDIS_JPUSH_KEY, json.dumps(_push)) elif self._task["_app"].get("enable_gcm_push"): _config["device_android_gcmtoken"] = _device.get("device_android_gcmtoken") self._redis.rpush(REDIS_GCMPUSH_KEY, json.dumps(_push)) else: logging.error("no push enable for android: %s" % str(_push)) return def _push_to_socket(self, _user_uuid, _device_uuid): _pcsocket = self._pcsocket_data(_device_uuid) if _pcsocket == None: logging.error("no pcsocket data for: %s" % _device_uuid) return _device = self._devices_hash.get(_device_uuid) # if _device == None: # logging.error("no device hash for: %s" % _device_uuid) # return _from_user = {} _from_type = self._task.get("from_type") _fields = [ "uuid", "user_icon", "user_email", "user_fullname", "updatetime", ] if _from_type == YVOBJECT.DU: for _i in _fields: _from_user[_i] = self._task["_user"].get(_i) _from_user["updatetime"] = datetime_to_timestamp(_from_user["updatetime"]) if _from_type == YVOBJECT.OG: _from_user = self._task["_group"] if _from_type == YVOBJECT.AP: _from_user = self._task["_app"] _body = self._task.get("message_body") _body["pid"] = _device.get("push_uuid") _body["from_user"] = _from_user _push = { "pcsocket": _pcsocket, "body": _body } _key = REDIS_PUSH_NOTIFICATION_KEY + ".host." + _pcsocket["host"] + ".port." + _pcsocket["port"] self._redis.rpush(_key, json.dumps(_push)) return def _push_to_mobile(self, _user_uuid, _device_uuid): _device = self._devices_hash[_device_uuid] if _device["device_ostype"] == OS.IOS: self._push_to_ios(_user_uuid, _device_uuid) return if _device["device_ostype"] == OS.AND: self._push_to_android(_user_uuid, _device_uuid) return return def _push(self): if len(self._online_users) == 0: self.no_online_user() return for _user_uuid in self._online_users: _user = self._users_hash[_user_uuid] _online_devices = _user.get("_online_devices") _real_push = not _user.get("user_mute_notification") _pid = self._push_to_db(_user_uuid) for _device_uuid in _online_devices: self._devices_hash[_device_uuid]["push_uuid"] = _pid self._push_to_socket(_user_uuid, _device_uuid) if _real_push == True: self._push_to_mobile(_user_uuid, _device_uuid) return def _other_device(self): """ the other device uuid belong to same user uuid """ if self._task.get("from_device_uuid") == None: return if self._task.get("from_type") != YVOBJECT.DU: return if self._task.get("_user") == None: return if self._task["conversation_type"] == CONVERSATION_TYPE.P2S: if self._task["_user"]["ppcom_mobile_device_uuid"] == None or \ self._task["_user"]["ppcom_browser_device_uuid"] == None: return if self._task["conversation_type"] == CONVERSATION_TYPE.S2S or \ self._task["conversation_type"] == CONVERSATION_TYPE.S2P: if self._task["_user"]["mobile_device_uuid"] == None or \ self._task["_user"]["browser_device_uuid"] == None: return _device_uuid = None if self._task["conversation_type"] == CONVERSATION_TYPE.P2S: _device_uuid = self._task["_user"]["ppcom_mobile_device_uuid"] if self._task["from_device_uuid"] == self._task["_user"]["ppcom_mobile_device_uuid"]: _device_uuid = self._task["_user"]["ppcom_browser_device_uuid"] else: _device_uuid = self._task["_user"]["mobile_device_uuid"] if self._task["from_device_uuid"] == self._task["_user"]["mobile_device_uuid"]: _device_uuid = self._task["_user"]["browser_device_uuid"] if _device_uuid not in self._devices_hash: _device = redis_hash_to_dict(self._redis, DeviceInfo, _device_uuid) if _device == None or _device["device_is_online"] != True: return self._devices_hash[_device_uuid] = _device _user_uuid = self._task["from_uuid"] if _user_uuid not in self._users_hash: self._users_hash[_user_uuid] = self._task["_user"] _pid = self._push_to_db(_user_uuid) self._devices_hash[_device_uuid]["push_uuid"] = _pid self._push_to_socket(_user_uuid, _device_uuid) return def _explicit(self): """ explicit message SYS type """ _device_uuid = self._task.get("to_device_uuid") _device = redis_hash_to_dict(self._redis, DeviceInfo, _device_uuid) if _device == None: logging.error("no device:%s" % _device_uuid) return _user_uuid = self._task.get("from_uuid") self._users_hash[_user_uuid] = self._task["_user"] self._devices_hash[_device_uuid] = _device # not save db for explicit message self._push_to_socket(_user_uuid, _device_uuid) return def _send_apologize(self, _text): _task = { "uuid": str(uuid.uuid1()), "app_uuid": self._task["app_uuid"], "conversation_uuid": self._task["conversation_uuid"], "conversation_type": CONVERSATION_TYPE.S2P, "message_type": MESSAGE_TYPE.NOTI, "message_subtype": MESSAGE_SUBTYPE.TEXT, "from_uuid": self._task["to_uuid"], "from_type": self._task["to_type"], "to_uuid": self._task["to_uuid"], "to_type": self._task["to_type"], "body": _text, "task_status": TASK_STATUS.PENDING, } _row = MessagePushTask(**_task) _row.async_add(self._redis) _row.create_redis_keys(self._redis) _m = {"task_uuid": _row.uuid} self._redis.rpush(REDIS_DISPATCHER_NOTIFICATION_KEY, json.dumps(_m)) return def _get_app_apologize(self): _text = None _lang = self._task["_user"]["user_language"] if _lang == None or len(_lang) == 0: _lang = "zh_cn" _offline = "offline_" + _lang _text = self._task["_app"][_offline] if _text == None: _text = PPCOM_OFFLINE[_lang] return _text def no_online_user(self): if self._task["conversation_type"] != CONVERSATION_TYPE.P2S: return if self._task["_app"].get("return_offline_message") != True: logging.info("return_offline_message is not set") return _text = self._get_app_apologize() if _text == None: return self._send_apologize(_text) return def users(self): _app_uuid = self._task["app_uuid"] _conversation_uuid = self._task["conversation_uuid"] _users = AbstractPolicy.conversation_users(_app_uuid, _conversation_uuid, self._redis) _datas = AbstractPolicy.conversation_datas(_app_uuid, _conversation_uuid, _users, self._redis) _datas = dict(zip(_users, _datas)) # the is_service_user include the sender user_uuid _table = AppUserData.__tablename__ + ".app_uuid." + _app_uuid + ".user_uuid." _pi = self._redis.pipeline() for _user_uuid in _users: _key = _table + _user_uuid _pi.get(_key) _is = _pi.execute() _is_list = [] for _i in _is: if _i == None or len(_i) == 0: _is_list.append(False) continue _d = json.loads(_i) _is_list.append(_d.get("is_service_user")) self._is_service_user = dict(zip(_users, _is_list)) # remove the sender self if self._task["from_type"] == YVOBJECT.DU: _user_uuid = self._task["from_uuid"] if _user_uuid in _users: _users.remove(_user_uuid) if _user_uuid in _datas: del _datas[_user_uuid] self._users = _users self._conversation_users = _users self._conversation_user_datas_uuid = _datas return def dispatch(self): self._body() if self._task.get("to_device_uuid") != None: self._explicit() return if self._task.get("conversation_uuid") == None: logging.error("no conversation should be explicit") return self.users() self._users_devices() self._push() self._other_device() return class BroadcastPolicy(AbstractPolicy): def __init__(self, dis): super(BroadcastPolicy, self).__init__(dis) return def users(self): super(BroadcastPolicy, self).users() return @classmethod def create_conversation_users(cls, _app_uuid, _group_uuid, _redis): return AbstractPolicy.distributor_users(_app_uuid, _redis) @classmethod def get_service_care_users(cls, _app_uuid, _user_uuid, _redis): _a_users = AbstractPolicy.app_users(_app_uuid, True, _redis) _b_users = AbstractPolicy.app_users(_app_uuid, False, _redis) return _a_users + _b_users @classmethod def get_portal_care_users(cls, _app_uuid, _user_uuid, _redis):
_a_users = AbstractPolicy.app_users(_app_uuid, True, _redis) return _a_users
messages.py
import erdos
Optionally can also send a target speed for each waypoint. Args: timestamp (:py:class:`erdos.timestamp.Timestamp`): The timestamp of the message. waypoints (:py:class:`~pylot.planning.Waypoints`): Waypoints. """ def __init__(self, timestamp: erdos.Timestamp, waypoints, agent_state=None): super(WaypointsMessage, self).__init__(timestamp, None) self.waypoints = waypoints self.agent_state = agent_state def __repr__(self): return self.__str__() def __str__(self): return 'WaypointMessage(timestamp: {}, waypoints: {}, '\ 'agent_state: {}'.format(self.timestamp, self.waypoints, self.agent_state) class BehaviorMessage(erdos.Message): def __init__(self, timestamp: erdos.Timestamp, target_lane_id: int, target_speed: float, target_deadline: float, target_leading_vehicle_id: int = None): super(BehaviorMessage, self).__init__(timestamp, None) self.target_lane_id = target_lane_id self.target_speed = target_speed self.target_deadline = target_deadline self.target_leading_vehicle_id = target_leading_vehicle_id def __repr__(self): return self.__str__() def __str__(self): return 'BehaviorMessage(timestamp: {}, target_lane_id: {}, '\ 'target_speed: {}, target_deadline: {}, '\ 'target_leading_vehicle_id: {})'.format( self.timestamp, self.target_lane_id, self.target_speed, self.target_deadline, self.target_leading_vehicle_id)
class WaypointsMessage(erdos.Message): """Message class to be used to send waypoints.
popover-options.provider.ts
export interface PopoverOptionsInterface { mask?: boolean; visible?: boolean; placement?: string; appendToBody?: boolean;
export class PopoverOptions implements PopoverOptionsInterface { showArrow: boolean = false; mask: boolean = false; placement: string = 'bottom'; appendToBody: boolean = false; className: string = ''; autoClose: boolean = true; }
className?: string; autoClose?: boolean; }
index.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const path_1 = (0, tslib_1.__importDefault)(require("path")); function
(_context, options) { return { name: 'docusaurus-plugin-ideal-image', getThemePath() { return path_1.default.resolve(__dirname, './theme'); }, configureWebpack(_config, isServer) { if (process.env.NODE_ENV !== 'production') { return {}; } return { mergeStrategy: { 'module.rules': 'prepend', }, module: { rules: [ { test: /\.(png|jpe?g|gif)$/i, use: [ require.resolve('@docusaurus/lqip-loader'), { loader: require.resolve('@docusaurus/responsive-loader'), options: { emitFile: !isServer, // eslint-disable-next-line global-require adapter: require('@docusaurus/responsive-loader/sharp'), name: 'assets/ideal-img/[name].[hash:hex:7].[width].[ext]', ...options, }, }, ], }, ], }, }; }, }; } exports.default = default_1;
default_1
float_literal.rs
use crate::utils::{numeric_literal, span_lint_and_sugg}; use if_chain::if_chain; use rustc_ast::ast::{FloatTy, LitFloatType, LitKind}; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use std::{f32, f64, fmt}; declare_clippy_lint! { /// **What it does:** Checks for float literals with a precision greater /// than that supported by the underlying type. /// /// **Why is this bad?** Rust will truncate the literal silently. /// /// **Known problems:** None. /// /// **Example:** /// /// ```rust /// // Bad /// let v: f32 = 0.123_456_789_9; /// println!("{}", v); // 0.123_456_789 /// /// // Good /// let v: f64 = 0.123_456_789_9; /// println!("{}", v); // 0.123_456_789_9 /// ``` pub EXCESSIVE_PRECISION, style, "excessive precision for float literal" } declare_clippy_lint! { /// **What it does:** Checks for whole number float literals that /// cannot be represented as the underlying type without loss. /// /// **Why is this bad?** Rust will silently lose precision during /// conversion to a float. /// /// **Known problems:** None. /// /// **Example:** /// /// ```rust /// // Bad /// let _: f32 = 16_777_217.0; // 16_777_216.0 /// /// // Good /// let _: f32 = 16_777_216.0; /// let _: f64 = 16_777_217.0; /// ``` pub LOSSY_FLOAT_LITERAL, restriction, "lossy whole number float literals" } declare_lint_pass!(FloatLiteral => [EXCESSIVE_PRECISION, LOSSY_FLOAT_LITERAL]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FloatLiteral { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) { if_chain! { let ty = cx.tables.expr_ty(expr); if let ty::Float(fty) = ty.kind; if let hir::ExprKind::Lit(ref lit) = expr.kind; if let LitKind::Float(sym, lit_float_ty) = lit.node; then { let sym_str = sym.as_str(); let formatter = FloatFormat::new(&sym_str); // Try to bail out if the float is for sure fine. // If its within the 2 decimal digits of being out of precision we // check if the parsed representation is the same as the string // since we'll need the truncated string anyway. let digits = count_digits(&sym_str); let max = max_digits(fty); let type_suffix = match lit_float_ty { LitFloatType::Suffixed(FloatTy::F32) => Some("f32"), LitFloatType::Suffixed(FloatTy::F64) => Some("f64"), _ => None }; let (is_whole, mut float_str) = match fty { FloatTy::F32 => { let value = sym_str.parse::<f32>().unwrap(); (value.fract() == 0.0, formatter.format(value)) }, FloatTy::F64 => { let value = sym_str.parse::<f64>().unwrap(); (value.fract() == 0.0, formatter.format(value)) }, }; if is_whole && !sym_str.contains(|c| c == 'e' || c == 'E') { // Normalize the literal by stripping the fractional portion if sym_str.split('.').next().unwrap() != float_str { // If the type suffix is missing the suggestion would be // incorrectly interpreted as an integer so adding a `.0` // suffix to prevent that. if type_suffix.is_none() { float_str.push_str(".0"); } span_lint_and_sugg( cx, LOSSY_FLOAT_LITERAL, expr.span, "literal cannot be represented as the underlying type without loss of precision", "consider changing the type or replacing it with", numeric_literal::format(&float_str, type_suffix, true), Applicability::MachineApplicable, ); } } else if digits > max as usize && sym_str != float_str { span_lint_and_sugg( cx, EXCESSIVE_PRECISION, expr.span, "float has excessive precision", "consider changing the type or truncating it to", numeric_literal::format(&float_str, type_suffix, true), Applicability::MachineApplicable, ); } } } } } #[must_use] fn max_digits(fty: FloatTy) -> u32 { match fty { FloatTy::F32 => f32::DIGITS, FloatTy::F64 => f64::DIGITS, } } /// Counts the digits excluding leading zeros #[must_use] fn count_digits(s: &str) -> usize
enum FloatFormat { LowerExp, UpperExp, Normal, } impl FloatFormat { #[must_use] fn new(s: &str) -> Self { s.chars() .find_map(|x| match x { 'e' => Some(Self::LowerExp), 'E' => Some(Self::UpperExp), _ => None, }) .unwrap_or(Self::Normal) } fn format<T>(&self, f: T) -> String where T: fmt::UpperExp + fmt::LowerExp + fmt::Display, { match self { Self::LowerExp => format!("{:e}", f), Self::UpperExp => format!("{:E}", f), Self::Normal => format!("{}", f), } } }
{ // Note that s does not contain the f32/64 suffix, and underscores have been stripped s.chars() .filter(|c| *c != '-' && *c != '.') .take_while(|c| *c != 'e' && *c != 'E') .fold(0, |count, c| { // leading zeros if c == '0' && count == 0 { count } else { count + 1 } }) }
clean.rs
use crate::command_prelude::*; use cargo::ops::{self, CleanOptions}; use cargo::util::print_available_packages; pub fn cli() -> App { subcommand("clean") .about("Remove artifacts that cargo has generated in the past") .arg_quiet() .arg_package_spec_simple("Package to clean artifacts for") .arg_manifest_path() .arg_target_triple("Target triple to clean output for") .arg_target_dir() .arg_release("Whether or not to clean release artifacts") .arg_profile("Clean artifacts of the specified profile") .arg_doc("Whether or not to clean just the documentation directory") .after_help("Run `cargo help clean` for more detailed information.\n") } pub fn
(config: &mut Config, args: &ArgMatches) -> CliResult { let ws = args.workspace(config)?; if args.is_present_with_zero_values("package") { print_available_packages(&ws)?; } let opts = CleanOptions { config, spec: values(args, "package"), targets: args.targets(), requested_profile: args.get_profile_name(config, "dev", ProfileChecking::Custom)?, profile_specified: args.is_present("profile") || args.is_present("release"), doc: args.is_present("doc"), }; ops::clean(&ws, &opts)?; Ok(()) }
exec
status-bar-data.ts
import { IPayloadMessage } from '..';
timeout?: number; };
export interface IStatusBarData extends IPayloadMessage { uri?: string;
extract_animation.py
import os from maya import cmds import avalon.maya import pype.api from pype.hosts.maya.lib import extract_alembic class ExtractAnimation(pype.api.Extractor): """Produce an alembic of just point positions and normals. Positions and normals, uvs, creases are preserved, but nothing more, for plain and predictable point caches. """ label = "Extract Animation" hosts = ["maya"] families = ["animation"] def process(self, instance): # Collect the out set nodes out_sets = [node for node in instance if node.endswith("out_SET")] if len(out_sets) != 1: raise RuntimeError("Couldn't find exactly one out_SET: " "{0}".format(out_sets)) out_set = out_sets[0] roots = cmds.sets(out_set, query=True) # Include all descendants nodes = roots + cmds.listRelatives(roots, allDescendents=True, fullPath=True) or [] # Collect the start and end including handles start = instance.data["frameStart"] end = instance.data["frameEnd"] handles = instance.data.get("handles", 0) or 0 if handles: start -= handles end += handles self.log.info("Extracting animation..") dirname = self.staging_dir(instance) parent_dir = self.staging_dir(instance) filename = "{name}.abc".format(**instance.data) path = os.path.join(parent_dir, filename) options = { "step": instance.data.get("step", 1.0) or 1.0, "attr": ["cbId"], "writeVisibility": True, "writeCreases": True, "uvWrite": True, "selection": True, "worldSpace": instance.data.get("worldSpace", True), "writeColorSets": instance.data.get("writeColorSets", False) } if not instance.data.get("includeParentHierarchy", True): # Set the root nodes if we don't want to include parents # The roots are to be considered the ones that are the actual
options["root"] = roots if int(cmds.about(version=True)) >= 2017: # Since Maya 2017 alembic supports multiple uv sets - write them. options["writeUVSets"] = True with avalon.maya.suspended_refresh(): with avalon.maya.maintained_selection(): cmds.select(nodes, noExpand=True) extract_alembic(file=path, startFrame=float(start), endFrame=float(end), **options) if "representations" not in instance.data: instance.data["representations"] = [] representation = { 'name': 'abc', 'ext': 'abc', 'files': filename, "stagingDir": dirname, } instance.data["representations"].append(representation) self.log.info("Extracted {} to {}".format(instance, dirname))
# direct members of the set
transaction_config_tests.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ config::{ global::Config as GlobalConfig, transaction::{is_new_transaction, Config, Entry}, }, errors::*, tests::{ global_config_tests::parse_and_build_config as parse_and_build_global_config, parse_each_line_as, }, }; #[test] fn parse_simple_positive() { for s in &[ "//!no-run:", "//! no-run: verifier", "//! no-run: compiler, verifier, runtime", "//! sender: alice", "//! sender:foobar42", "//! sender :alice", "//! sender:foobar42", "//! sender\t:\tfoobar42", "//!\nsender\n:\nfoobar42", ] { s.parse::<Entry>().unwrap(); } } #[test] fn parse_simple_negative() { for s in &["//!", "//! ", "//! garbage", "//! sender:"] { s.parse::<Entry>().unwrap_err(); } } #[test] fn parse_args() { for s in &[ "//! args:", "//! args: 12", "//! args: 0xdeadbeef", "//! args: b\"AA\"", r"//! args: {{bob}}", "//! args: 1, 2, 3, 4", r"//! args: 1, 0x12, {{bob}}, {{alice}},", ] { s.parse::<Entry>().unwrap(); } for s in &[ "//!args", "//! args: 42xx", "//! args: bob", "//! args: \"\"", ] { s.parse::<Entry>().unwrap_err(); } } #[test] fn parse_max_gas() { for s in &["//! max-gas:77", "//!max-gas:0", "//! max-gas: 123"] { s.parse::<Entry>().unwrap(); } for s in &["//!max-gas:", "//!max-gas:abc", "//!max-gas: 123, 45"] { s.parse::<Entry>().unwrap_err(); } } #[test] fn parse_sequence_number() { for s in &[ "//! sequence-number:77", "//!sequence-number:0", "//! sequence-number: 123", ] { s.parse::<Entry>().unwrap(); } for s in &[ "//!sequence-number:", "//!sequence-number:abc", "//!sequence-number: 123, 45", ] { s.parse::<Entry>().unwrap_err(); } // TODO: "//!sequence-number: 123 45" is currently parsed as 12345. // This is because we remove all the spaces before parsing. // Rewrite the parser to handle this case properly. } #[test] fn parse_new_transaction() { assert!(is_new_transaction("//! new-transaction")); assert!(is_new_transaction("//!new-transaction ")); assert!(!is_new_transaction("//")); assert!(!is_new_transaction("//! new transaction")); assert!(!is_new_transaction("//! transaction")); } fn parse_and_build_config<'a>(global_config: &'a GlobalConfig, s: &str) -> Result<Config<'a>>
#[rustfmt::skip] #[test] fn build_transaction_config_1() { let global = parse_and_build_global_config("").unwrap(); parse_and_build_config(&global, r" //! no-run: verifier, runtime //! sender: default //! args: 1, 2, 3 ").unwrap(); } #[rustfmt::skip] #[test] fn build_transaction_config_2() { let global = parse_and_build_global_config(r" //! account: bob //! account: alice ").unwrap(); parse_and_build_config(&global, r" //! sender: alice //! args: {{bob}}, {{alice}} ").unwrap(); } #[rustfmt::skip] #[test] fn build_transaction_config_3() { let global = parse_and_build_global_config(r" //! account: alice ").unwrap(); parse_and_build_config(&global, r" //! args: {{bob}} ").unwrap_err(); }
{ Config::build(global_config, &parse_each_line_as::<Entry>(s)?) }
process.go
// +build windows package winutil import ( "fmt" "unsafe" "golang.org/x/sys/windows" ) var ( modntdll = windows.NewLazyDLL("ntdll.dll") modkernel = windows.NewLazyDLL("kernel32.dll") procNtQueryInformationProcess = modntdll.NewProc("NtQueryInformationProcess") procReadProcessMemory = modkernel.NewProc("ReadProcessMemory") procIsWow64Process = modkernel.NewProc("IsWow64Process") ) // C definition from winternl.h //typedef enum _PROCESSINFOCLASS { // ProcessBasicInformation = 0, // ProcessDebugPort = 7, // ProcessWow64Information = 26, // ProcessImageFileName = 27, // ProcessBreakOnTermination = 29 //} PROCESSINFOCLASS; // PROCESSINFOCLASS is the Go representation of the above enum type PROCESSINFOCLASS uint32 const ( // ProcessBasicInformation returns the PEB type ProcessBasicInformation = PROCESSINFOCLASS(0) // ProcessDebugPort included for completeness ProcessDebugPort = PROCESSINFOCLASS(7) // ProcessWow64Information included for completeness ProcessWow64Information = PROCESSINFOCLASS(26) // ProcessImageFileName included for completeness ProcessImageFileName = PROCESSINFOCLASS(27) // ProcessBreakOnTermination included for completeness ProcessBreakOnTermination = PROCESSINFOCLASS(29) ) // IsWow64Process determines if the specified process is running under WOW64 // that is, if it's a 32 bit process running on 64 bit winodws func IsWow64Process(h windows.Handle) (is32bit bool, err error) { var wow64Process uint32 r, _, _ := procIsWow64Process.Call(uintptr(h), uintptr(unsafe.Pointer(&wow64Process))) if r == 0 { return false, windows.GetLastError() } if wow64Process == 0 { is32bit = false } else { is32bit = true } return } // NtQueryInformationProcess wraps the Windows NT kernel call of the same name func NtQueryInformationProcess(h windows.Handle, class PROCESSINFOCLASS, target, size uintptr) (err error) { r, _, _ := procNtQueryInformationProcess.Call(uintptr(h), uintptr(class), target, size, uintptr(0)) if r != 0 { err = windows.GetLastError() return } return } // ReadProcessMemory wraps the Windows kernel.dll function of the same name // https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory func ReadProcessMemory(h windows.Handle, from, to uintptr, count uint32) (bytesRead uint64, err error) { var bytes uint64 r, _, e := procReadProcessMemory.Call(uintptr(h), from, to, uintptr(count), uintptr(unsafe.Pointer(&bytes))) if r == 0 { err = windows.GetLastError() fmt.Printf("Error %v %v\n", err, e) return } bytesRead = bytes return } type peb32 struct { Reserved1 [2]byte BeingDebugged byte Reserved2 [1]byte Reserved3 [2]uint32 Ldr uint32 ProcessParameters uint32 // more fields... } type unicodeString32 struct { length uint16 maxLength uint16 buffer uint32 } type procParams32 struct { Reserved1 [16]byte Reserved2 [5]uint32 CurrentDirectoryPath unicodeString32 CurrentDirectoryHandle uint32 DllPath unicodeString32 ImagePath unicodeString32 commandLine unicodeString32 env uint32 } func getCommandLineForProcess32(h windows.Handle) (cmdline string, err error) { // get the pointer to the PEB var procmem uintptr size := unsafe.Sizeof(procmem) err = NtQueryInformationProcess(h, ProcessWow64Information, uintptr(unsafe.Pointer(&procmem)), size) if err != nil { // this shouldn't happen because we already know we're asking about // a 32 bit process. return } var peb peb32 var read uint64 var toRead uint32 toRead = uint32(unsafe.Sizeof(peb)) read, err = ReadProcessMemory(h, procmem, uintptr(unsafe.Pointer(&peb)), toRead) if err != nil { return } if read != uint64(toRead) { err = fmt.Errorf("Wrong amount of bytes read %v != %v", read, toRead) return } // now go get the actual parameters var pparams procParams32 pparamsSize := unsafe.Sizeof(pparams) read, err = ReadProcessMemory(h, uintptr(peb.ProcessParameters), uintptr(unsafe.Pointer(&pparams)), uint32(pparamsSize)) if err != nil { return } if read != uint64(pparamsSize) { err = fmt.Errorf("Wrong amount of bytes read %v != %v", read, pparamsSize) return } cmdlinebuffer := pparams.commandLine.buffer cmdlinelen := pparams.commandLine.length //cmdlinelen := 1024 finalbuf := make([]uint8, cmdlinelen+2) read, err = ReadProcessMemory(h, uintptr(cmdlinebuffer), uintptr(unsafe.Pointer(&finalbuf[0])), uint32(cmdlinelen+2)) if err != nil { return } if read != uint64(cmdlinelen+2) { err = fmt.Errorf("Wrong amount of bytes read %v != %v", read, cmdlinelen+2) return } cmdline = ConvertWindowsString(finalbuf) return } // this definition taken from Winternl.h type unicodeString struct { length uint16 maxLength uint16 buffer uintptr } type _rtlUserProcessParameters struct { Reserved1 [16]byte Reserved2 [10]uintptr imagePathName unicodeString commandLine unicodeString } type _peb struct { Reserved1 [2]byte BeingDebugged byte Reserved2 [2]byte Reserved3 [2]uintptr Ldr uintptr // pointer to PEB_LDR_DATA ProcessParameters uintptr // pointer to _rtlUserProcessParameters // lots more stuff } // this definition taken from Winternl.h type processBasicInformationStruct struct { Reserved1 uintptr PebBaseAddress uintptr Reserved2 [2]uintptr UniqueProcessID uintptr Reserved3 uintptr } func getCommandLineForProcess64(h windows.Handle) (cmdline string, err error) { var pbi processBasicInformationStruct pbisize := unsafe.Sizeof(pbi) err = NtQueryInformationProcess(h, ProcessBasicInformation, uintptr(unsafe.Pointer(&pbi)), pbisize) if err != nil { return } // read the peb var peb _peb pebsize := unsafe.Sizeof(peb) readsize, err := ReadProcessMemory(h, pbi.PebBaseAddress, uintptr(unsafe.Pointer(&peb)), uint32(pebsize)) if err != nil { return } if readsize != uint64(pebsize) { err = fmt.Errorf("Incorrect read size %v %v", readsize, pebsize) return } // go get the parameters var pparams _rtlUserProcessParameters paramsize := unsafe.Sizeof(pparams) readsize, err = ReadProcessMemory(h, peb.ProcessParameters, uintptr(unsafe.Pointer(&pparams)), uint32(paramsize)) if readsize != uint64(paramsize) { err = fmt.Errorf("Incorrect read size %v %v", readsize, paramsize) return } cmdlinebuffer := make([]uint8, pparams.commandLine.length+2) readsize, err = ReadProcessMemory(h, pparams.commandLine.buffer, uintptr(unsafe.Pointer(&cmdlinebuffer[0])), uint32(pparams.commandLine.length+2)) if err != nil { return } if readsize != uint64(pparams.commandLine.length+2) { err = fmt.Errorf("Wrong amount of bytes read %v != %v", readsize, pparams.commandLine.length+2) return } cmdline = ConvertWindowsString(cmdlinebuffer) return } // GetCommandLineForProcess returns the command line for the given process. func GetCommandLineForProcess(h windows.Handle) (cmdline string, err error) { // first need to check if this is a 32 bit process running on win64 // for now, assumes we are win64 is32bit, err := IsWow64Process(h) if is32bit { return getCommandLineForProcess32(h) } return getCommandLineForProcess64(h) } // GetCommandLineForPid returns the command line for the given PID func GetCommandLineForPid(pid uint32) (cmdline string, err error) { h, err := windows.OpenProcess(0x1010, false, uint32(pid)) if err != nil { err = fmt.Errorf("Failed to open process %v", err) return } defer windows.CloseHandle(h) cmdline, err = GetCommandLineForProcess(h) if err != nil {
return } return GetCommandLineForProcess(h) }
err = fmt.Errorf("Failed to get command line %v", err)
base64ToObjectURL.ts
export const base64ToObjectURL = (base64: string): string => { if(base64){ let arrayBufferView = Uint8Array.from(Buffer.from(base64, "base64"), c => c); let blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } ); let objectURL = URL.createObjectURL(blob); return objectURL; }
return ""; }
main.rs
use intcomputer::IntComputer; use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let contents = fs::read_to_string(filename).unwrap(); let program: Vec<i32> = contents .trim() .split(',') .map(|x| x.parse().unwrap()) .collect(); let mut comp = IntComputer::new(program.clone()); comp.input.push_back(1); comp.run(); println!("Solution Part 1: {:?}", comp.output); let mut comp = IntComputer::new(program); comp.input.push_back(5);
println!("Solution Part 2: {:?}", comp.output); }
comp.run();
lib.rs
#![doc(html_root_url = "https://docs.rs/phf_shared/0.9")] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] extern crate std as core; use core::fmt; use core::hash::{Hash, Hasher}; use core::num::Wrapping; use siphasher::sip128::{Hash128, Hasher128, SipHasher13}; #[non_exhaustive] pub struct Hashes { pub g: u32, pub f1: u32, pub f2: u32, } /// A central typedef for hash keys /// /// Makes experimentation easier by only needing to be updated here. pub type HashKey = u64; #[inline] pub fn displace(f1: u32, f2: u32, d1: u32, d2: u32) -> u32 { (Wrapping(d2) + Wrapping(f1) * Wrapping(d1) + Wrapping(f2)).0 } /// `key` is from `phf_generator::HashState`. #[inline] pub fn
<T: ?Sized + PhfHash>(x: &T, key: &HashKey) -> Hashes { let mut hasher = SipHasher13::new_with_keys(0, *key); x.phf_hash(&mut hasher); let Hash128 { h1: lower, h2: upper, } = hasher.finish128(); Hashes { g: (lower >> 32) as u32, f1: lower as u32, f2: upper as u32, } } /// Return an index into `phf_generator::HashState::map`. /// /// * `hash` is from `hash()` in this crate. /// * `disps` is from `phf_generator::HashState::disps`. /// * `len` is the length of `phf_generator::HashState::map`. #[inline] pub fn get_index(hashes: &Hashes, disps: &[(u32, u32)], len: usize) -> u32 { let (d1, d2) = disps[(hashes.g % (disps.len() as u32)) as usize]; displace(hashes.f1, hashes.f2, d1, d2) % (len as u32) } /// A trait implemented by types which can be used in PHF data structures. /// /// This differs from the standard library's `Hash` trait in that `PhfHash`'s /// results must be architecture independent so that hashes will be consistent /// between the host and target when cross compiling. pub trait PhfHash { /// Feeds the value into the state given, updating the hasher as necessary. fn phf_hash<H: Hasher>(&self, state: &mut H); /// Feeds a slice of this type into the state provided. fn phf_hash_slice<H: Hasher>(data: &[Self], state: &mut H) where Self: Sized, { for piece in data { piece.phf_hash(state); } } } /// Trait for printing types with `const` constructors, used by `phf_codegen` and `phf_macros`. pub trait FmtConst { /// Print a `const` expression representing this value. fn fmt_const(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result; } /// Identical to `std::borrow::Borrow` except omitting blanket impls to facilitate other /// borrowing patterns. /// /// The same semantic requirements apply: /// /// > In particular `Eq`, `Ord` and `Hash` must be equivalent for borrowed and owned values: /// `x.borrow() == y.borrow()` should give the same result as `x == y`. /// /// (This crate's API only requires `Eq` and `PhfHash`, however.) /// /// ### Motivation /// The conventional signature for lookup methods on collections looks something like this: /// /// ```rust,ignore /// impl<K, V> Map<K, V> where K: PhfHash + Eq { /// fn get<T: ?Sized>(&self, key: &T) -> Option<&V> where T: PhfHash + Eq, K: Borrow<T> { /// ... /// } /// } /// ``` /// /// This allows the key type used for lookup to be different than the key stored in the map so for /// example you can use `&str` to look up a value in a `Map<String, _>`. However, this runs into /// a problem in the case where `T` and `K` are both a `Foo<_>` type constructor but /// the contained type is different (even being the same type with different lifetimes). /// /// The main issue for this crate's API is that, with this method signature, you cannot perform a /// lookup on a `Map<UniCase<&'static str>, _>` with a `UniCase<&'a str>` where `'a` is not /// `'static`; there is no impl of `Borrow` that resolves to /// `impl Borrow<UniCase<'a>> for UniCase<&'static str>` and one cannot be added either because of /// all the blanket impls. /// /// Instead, this trait is implemented conservatively, without blanket impls, so that impls like /// this may be added. This is feasible since the set of types that implement `PhfHash` is /// intentionally small. /// /// This likely won't be fixable with specialization alone but will require full support for lattice /// impls since we technically want to add overlapping blanket impls. pub trait PhfBorrow<B: ?Sized> { /// Convert a reference to `self` to a reference to the borrowed type. fn borrow(&self) -> &B; } /// Create an impl of `FmtConst` delegating to `fmt::Debug` for types that can deal with it. /// /// Ideally with specialization this could be just one default impl and then specialized where /// it doesn't apply. macro_rules! delegate_debug ( ($ty:ty) => { impl FmtConst for $ty { fn fmt_const(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } } ); delegate_debug!(str); delegate_debug!(char); delegate_debug!(u8); delegate_debug!(i8); delegate_debug!(u16); delegate_debug!(i16); delegate_debug!(u32); delegate_debug!(i32); delegate_debug!(u64); delegate_debug!(i64); delegate_debug!(u128); delegate_debug!(i128); delegate_debug!(bool); /// `impl PhfBorrow<T> for T` macro_rules! impl_reflexive( ($($t:ty),*) => ( $(impl PhfBorrow<$t> for $t { fn borrow(&self) -> &$t { self } })* ) ); impl_reflexive!( str, char, u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, bool, [u8] ); #[cfg(feature = "std")] impl PhfBorrow<str> for String { fn borrow(&self) -> &str { self } } #[cfg(feature = "std")] impl PhfBorrow<[u8]> for Vec<u8> { fn borrow(&self) -> &[u8] { self } } #[cfg(feature = "std")] delegate_debug!(String); #[cfg(feature = "std")] impl PhfHash for String { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { (**self).phf_hash(state) } } #[cfg(feature = "std")] impl PhfHash for Vec<u8> { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { (**self).phf_hash(state) } } impl<'a, T: 'a + PhfHash + ?Sized> PhfHash for &'a T { fn phf_hash<H: Hasher>(&self, state: &mut H) { (*self).phf_hash(state) } } impl<'a, T: 'a + FmtConst + ?Sized> FmtConst for &'a T { fn fmt_const(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (*self).fmt_const(f) } } impl<'a> PhfBorrow<str> for &'a str { fn borrow(&self) -> &str { self } } impl<'a> PhfBorrow<[u8]> for &'a [u8] { fn borrow(&self) -> &[u8] { self } } impl PhfHash for str { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { self.as_bytes().phf_hash(state) } } impl PhfHash for [u8] { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { state.write(self); } } impl FmtConst for [u8] { #[inline] fn fmt_const(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // slices need a leading reference write!(f, "&{:?}", self) } } #[cfg(feature = "unicase")] impl<S> PhfHash for unicase::UniCase<S> where unicase::UniCase<S>: Hash, { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { self.hash(state) } } #[cfg(feature = "unicase")] impl<S> FmtConst for unicase::UniCase<S> where S: AsRef<str>, { fn fmt_const(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.is_ascii() { f.write_str("UniCase::ascii(")?; } else { f.write_str("UniCase::unicode(")?; } self.as_ref().fmt_const(f)?; f.write_str(")") } } #[cfg(feature = "unicase")] impl<'b, 'a: 'b, S: ?Sized + 'a> PhfBorrow<unicase::UniCase<&'b S>> for unicase::UniCase<&'a S> { fn borrow(&self) -> &unicase::UniCase<&'b S> { self } } #[cfg(feature = "uncased")] impl PhfHash for uncased::UncasedStr { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { self.hash(state) } } #[cfg(feature = "uncased")] impl FmtConst for uncased::UncasedStr { fn fmt_const(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // transmute is not stable in const fns (rust-lang/rust#53605), so // `UncasedStr::new` can't be a const fn itself, but we can inline the // call to transmute here in the meantime. f.write_str("unsafe { ::std::mem::transmute::<&'static str, &'static UncasedStr>(")?; self.as_str().fmt_const(f)?; f.write_str(") }") } } #[cfg(feature = "uncased")] impl PhfBorrow<uncased::UncasedStr> for &uncased::UncasedStr { fn borrow(&self) -> &uncased::UncasedStr { self } } macro_rules! sip_impl ( (le $t:ty) => ( impl PhfHash for $t { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { self.to_le().hash(state); } } ); ($t:ty) => ( impl PhfHash for $t { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { self.hash(state); } } ) ); sip_impl!(u8); sip_impl!(i8); sip_impl!(le u16); sip_impl!(le i16); sip_impl!(le u32); sip_impl!(le i32); sip_impl!(le u64); sip_impl!(le i64); sip_impl!(le u128); sip_impl!(le i128); sip_impl!(bool); impl PhfHash for char { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { (*self as u32).phf_hash(state) } } // minimize duplicated code since formatting drags in quite a bit fn fmt_array(array: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", array) } macro_rules! array_impl ( ($t:ty, $n:expr) => ( impl PhfHash for [$t; $n] { #[inline] fn phf_hash<H: Hasher>(&self, state: &mut H) { state.write(self); } } impl FmtConst for [$t; $n] { fn fmt_const(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt_array(self, f) } } impl PhfBorrow<[$t]> for [$t; $n] { fn borrow(&self) -> &[$t] { self } } ) ); array_impl!(u8, 1); array_impl!(u8, 2); array_impl!(u8, 3); array_impl!(u8, 4); array_impl!(u8, 5); array_impl!(u8, 6); array_impl!(u8, 7); array_impl!(u8, 8); array_impl!(u8, 9); array_impl!(u8, 10); array_impl!(u8, 11); array_impl!(u8, 12); array_impl!(u8, 13); array_impl!(u8, 14); array_impl!(u8, 15); array_impl!(u8, 16); array_impl!(u8, 17); array_impl!(u8, 18); array_impl!(u8, 19); array_impl!(u8, 20); array_impl!(u8, 21); array_impl!(u8, 22); array_impl!(u8, 23); array_impl!(u8, 24); array_impl!(u8, 25); array_impl!(u8, 26); array_impl!(u8, 27); array_impl!(u8, 28); array_impl!(u8, 29); array_impl!(u8, 30); array_impl!(u8, 31); array_impl!(u8, 32);
hash
webpack.config.js
const path = require('path'); const webpack = require('webpack'); const merge = require('webpack-merge'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const autoprefixer = require('autoprefixer'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const nib = require('nib'); const prod = 'production'; const dev = 'development'; // determine build env const TARGET_ENV = process.env.npm_lifecycle_event === 'build' ? prod : dev; const isDev = TARGET_ENV === dev; const isProd = TARGET_ENV === prod; // entry and output path/filename variables const entryPath = path.join(__dirname, 'src/static/index.js'); const outputPath = path.join(__dirname, 'docs'); const outputFilename = isProd ? '[name]-[hash].js' : '[name].js'; console.log('WEBPACK GO! Building for ' + TARGET_ENV); // common webpack config (valid for dev and prod) const commonConfig = { output: { path: outputPath, filename: `static/js/${outputFilename}`, }, resolve: { extensions: ['.js', '.elm', '.styl'], modules: ['node_modules'] }, module: { noParse: /\.elm$/, rules: [{ test: /\.(eot|ttf|woff|woff2|svg)$/, use: 'file-loader?publicPath=../../&name=static/css/[hash].[ext]' }] }, plugins: [ new webpack.LoaderOptionsPlugin({ options: { postcss: [autoprefixer()] } }), new HtmlWebpackPlugin({ template: 'src/static/index.html', inject: 'body', filename: 'index.html' }), ] }; // additional webpack settings for local env (when invoked by 'npm start') if (isDev === true) { module.exports = merge(commonConfig, { entry: [ 'webpack-dev-server/client?http://localhost:8080', entryPath ], devServer: {
}, module: { rules: [{ test: /\.elm$/, exclude: [/elm-stuff/, /node_modules/], use: [{ loader: 'elm-webpack-loader', options: { verbose: true, warn: true, debug: true } }] }, { test: /\.sc?ss$/, use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'] }, { test: /\.styl$/i, use: ['style-loader', { loader: 'css-loader', options: {minimize: isProd} }, {loader: 'postcss-loader', options: {sourceMap: true}}, 'resolve-url-loader', {loader: 'sass-loader', options: {sourceMap: true}}, { loader: 'stylus-loader', options: { use: nib(), sourceMap: true, } }, ] }] } }); } // additional webpack settings for prod env (when invoked via 'npm run build') if (isProd === true) { module.exports = merge(commonConfig, { entry: entryPath, module: { rules: [{ test: /\.elm$/, exclude: [/elm-stuff/, /node_modules/], use: 'elm-webpack-loader' }, { test: /\.sc?ss$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'postcss-loader', 'sass-loader'] }) }, { test: /\.styl$/i, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: {minimize: isProd} }, {loader: 'postcss-loader', options: {sourceMap: true}}, 'resolve-url-loader', {loader: 'sass-loader', options: {sourceMap: true}}, { loader: 'stylus-loader', options: { use: nib(), sourceMap: true, } }, ] }) }] }, plugins: [ new ExtractTextPlugin({ filename: 'static/css/[name]-[hash].css', allChunks: true, }), new CopyWebpackPlugin([{ from: 'src/static/img/', to: 'static/img/' }, { from: 'src/favicon.ico' }, { from: 'src/CNAME' }]), // extract CSS into a separate file // minify & mangle JS/CSS new webpack.optimize.UglifyJsPlugin({ minimize: true, compressor: { warnings: false } // mangle: true }) ] }); }
// serve index.html in place of 404 responses historyApiFallback: true, contentBase: './src', hot: true
config.py
import yaml import os # 获取当前文件路径 filePath = os.path.dirname(__file__) # 获取当前文件的Realpath fileNamePath = os.path.split(os.path.realpath(__file__))[0] # 获取配置文件的路径 yamlPath = os.path.join(fileNamePath, 'config.yml') # 加上 ,encoding='utf-8',处理配置文件中含中文出现乱码的情况 yml_read = yaml.load(open(yamlPath, 'r', encoding='utf-8').read(), Loader=yaml.FullLoader) """使用装饰器创建类""" def Blive(cls): Dict = yml_read['BLive'] for name, value in Dict.items(): setattr(cls, name, value) return cls def database(cls): Dict = yml_read['database'] for name, value in Dict.items(): setattr(cls, name, value) return cls def api(cls): Dict = yml_read['api'] for name, value in Dict.items(): setattr(cls, name, value) return cls @Blive class BLive(object): pass @database class database(object): pass @api class api(object): pass
guid.rs
use crate::*; use winrt_gen::HexReader; /// A globally unique identifier [(GUID)](https://docs.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid) /// used to identify COM and WinRT interfaces. #[repr(C)] #[derive(Clone, Default, PartialEq, Eq)] pub struct Guid { data1: u32, data2: u16, data3: u16, data4: [u8; 8], } impl Guid { /// Creates a `Guid` represented by the all-zero byte-pattern. pub const fn zeroed() -> Guid { Guid { data1: 0, data2: 0, data3: 0, data4: [0, 0, 0, 0, 0, 0, 0, 0], } } /// Creates a `Guid` with the given constant values. pub const fn from_values(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid { Guid { data1, data2, data3, data4, } } /// Creates a `Guid` for a "generic" WinRT type. pub const fn from_signature(signature: crate::ConstBuffer) -> Guid
} unsafe impl Abi for Guid { type Abi = Self; } unsafe impl RuntimeType for Guid { type DefaultType = Self; const SIGNATURE: crate::ConstBuffer = crate::ConstBuffer::from_slice(b"g16"); } impl std::fmt::Debug for Guid { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{:08X?}-{:04X?}-{:04X?}-{:02X?}{:02X?}-{:02X?}{:02X?}{:02X?}{:02X?}{:02X?}{:02X?}", self.data1, self.data2, self.data3, self.data4[0], self.data4[1], self.data4[2], self.data4[3], self.data4[4], self.data4[5], self.data4[6], self.data4[7] ) } } impl From<&str> for Guid { fn from(value: &str) -> Guid { assert!(value.len() == 36, "Invalid GUID string"); let mut bytes = value.bytes(); let a = ((bytes.next_u32() * 16 + bytes.next_u32()) << 24) + ((bytes.next_u32() * 16 + bytes.next_u32()) << 16) + ((bytes.next_u32() * 16 + bytes.next_u32()) << 8) + bytes.next_u32() * 16 + bytes.next_u32(); assert!(bytes.next().unwrap() == b'-', "Invalid GUID string"); let b = ((bytes.next_u16() * 16 + (bytes.next_u16())) << 8) + bytes.next_u16() * 16 + bytes.next_u16(); assert!(bytes.next().unwrap() == b'-', "Invalid GUID string"); let c = ((bytes.next_u16() * 16 + bytes.next_u16()) << 8) + bytes.next_u16() * 16 + bytes.next_u16(); assert!(bytes.next().unwrap() == b'-', "Invalid GUID string"); let d = bytes.next_u8() * 16 + bytes.next_u8(); let e = bytes.next_u8() * 16 + bytes.next_u8(); assert!(bytes.next().unwrap() == b'-', "Invalid GUID string"); let f = bytes.next_u8() * 16 + bytes.next_u8(); let g = bytes.next_u8() * 16 + bytes.next_u8(); let h = bytes.next_u8() * 16 + bytes.next_u8(); let i = bytes.next_u8() * 16 + bytes.next_u8(); let j = bytes.next_u8() * 16 + bytes.next_u8(); let k = bytes.next_u8() * 16 + bytes.next_u8(); Guid::from_values(a, b, c, [d, e, f, g, h, i, j, k]) } }
{ let data = crate::ConstBuffer::from_slice(&[ 0x11, 0xf4, 0x7a, 0xd5, 0x7b, 0x73, 0x42, 0xc0, 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee, ]); let data = data.push_other(signature); let bytes = const_sha1::sha1(&data).bytes(); let first = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); let second = u16::from_be_bytes([bytes[4], bytes[5]]); let mut third = u16::from_be_bytes([bytes[6], bytes[7]]); third = (third & 0x0fff) | (5 << 12); let fourth = (bytes[8] & 0x3f) | 0x80; Self::from_values( first, second, third, [ fourth, bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15], ], ) }
lib.rs
#[macro_use] extern crate twitter_macros; pub mod client; pub mod debug; pub mod entities; pub mod error; pub mod list; pub mod media; pub mod metrics; pub mod place;
pub mod space; pub mod tweet; pub mod user; pub(crate) mod util;
pub mod poll; pub mod response; pub mod shared;
testing.go
//go:build linux && cgo && !agent // +build linux,cgo,!agent package state import ( "context" "testing" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/firewall" "github.com/lxc/lxd/lxd/sys" ) // NewTestState returns a State object initialized with testable instances of // the node/cluster databases and of the OS facade. // // Return the newly created State object, along with a function that can be // used for cleaning it up. func
(t *testing.T) (*State, func()) { node, nodeCleanup := db.NewTestNode(t) cluster, clusterCleanup := db.NewTestCluster(t) os, osCleanup := sys.NewTestOS(t) cleanup := func() { nodeCleanup() clusterCleanup() osCleanup() } state := &State{ Context: context.TODO(), Node: node, Cluster: cluster, OS: os, Firewall: firewall.New(), UpdateCertificateCache: func() {}, } return state, cleanup }
NewTestState
setup.js
const path = require('path'); const fs = require('fs'); const shell = require('shelljs'); const inquire = require('inquirer'); const simpleGit = require('simple-git')(); const logger = require('kyt-utils/logger'); const semver = require('semver'); const starterKyts = require('../../config/starterKyts'); const uniq = require('lodash.uniq'); const cliPkgJson = require('../../package.json'); const yarnOrNpm = require('../../utils/yarnOrNpm')(); module.exports = (flags, args) => { logger.start("Let's set up your new kyt project..."); logger.log('✨ Answer a few questions to get started ✨ \n'); // Selects package manager to use let ypm; // Comment the following to see verbose shell ouput. shell.config.silent = true; let paths = {}; const date = Date.now(); let tmpStarter; // For passed starter-kyts the root of the starter-kyt is the root of the repo let tmpDir; let repoURL = 'https://github.com/NYTimes/kyt.git'; let localPath = args.localPath; let tempPackageJSON; let oldPackageJSON; const fakePackageJson = { name: '', version: '1.0.0', description: '', main: '', author: '', license: '', }; const removeTmpStarter = () => shell.rm('-rf', tmpStarter); const bailProcess = error => { logger.error(`Failed to setup: ${repoURL}`); if (error) logger.log(error); removeTmpStarter(); process.exit(); }; // Compare the starter-kyt's package.json kyt.version // configuration to make sure kyt is an expected version. const checkStarterKytVersion = userPackageJSON => { const kytStarterPreferredVersion = (tempPackageJSON.dependencies && tempPackageJSON.dependencies.kyt) || (tempPackageJSON.devDependencies && tempPackageJSON.devDependencies.kyt) || null; if (kytStarterPreferredVersion) { // Look everywhere for kyt const kytVersion = (userPackageJSON.devDependencies && userPackageJSON.devDependencies.kyt) || (userPackageJSON.dependencies && userPackageJSON.dependencies.kyt); if (semver.valid(kytVersion)) { if (!semver.satisfies(kytVersion, kytStarterPreferredVersion)) { // eslint-disable-next-line max-len logger.warn( `${tempPackageJSON.name} requires kyt version ${kytStarterPreferredVersion} but kyt ${kytVersion} is installed.` ); } } } return kytStarterPreferredVersion; }; // Add kyt to list of dev dependencies if its not there const addKytDependency = (packageJson, kytPrefVersion) => { // eslint-disable-next-line max-len // check to see if kyt is in dependencies or devDependencies if ( !(packageJson.dependencies && packageJson.dependencies.kyt) && !(packageJson.devDependencies && packageJson.devDependencies.kyt) ) { let kytVersion = kytPrefVersion; // If a version wasn't specified, install latest if (!kytVersion) { const output = shell.exec('npm info kyt version'); kytVersion = output.stdout.trim(); } packageJson.dependencies = packageJson.dependencies || {}; packageJson.dependencies.kyt = kytVersion; } }; // Adds dependencies from the starter-kyts package.json const updatePackageJSONDependencies = packageJson => { const tempDependencies = tempPackageJSON.dependencies || {}; const tempDevDependencies = tempPackageJSON.devDependencies || {}; // In case the starter kyt used `kyt` as a dependency. if (tempDependencies.kyt) { Reflect.deleteProperty(tempDependencies, 'kyt');
if (tempDevDependencies.kyt) { Reflect.deleteProperty(tempDevDependencies, 'kyt'); } packageJson.dependencies = Object.assign(packageJson.dependencies || {}, tempDependencies); // Copies over dev dependencies if (tempDevDependencies) { packageJson.devDependencies = Object.assign( packageJson.devDependencies || {}, tempDevDependencies ); } logger.task('Added new dependencies to package.json'); return packageJson; }; // Adds kyt and Starter-kyt commands as npm scripts const addPackageJsonScripts = packageJson => { if (!packageJson.scripts) packageJson.scripts = {}; let commands = [ 'dev', 'build', 'start', 'proto', 'test', 'test-watch', 'test-coverage', 'lint', 'lint-script', 'lint-style', ]; // for commands that aren't 1:1 name:script const commandMap = { start: 'node build/server/main.js', 'test-watch': 'kyt test -- --watch', 'test-coverage': 'kyt test -- --coverage', lint: 'npm run lint-script && npm run lint-style', }; // Merge the Starter-kyt script names into the list of commands. const tempScripts = (tempPackageJSON && tempPackageJSON.kyt && tempPackageJSON.kyt.scripts) || []; if (tempScripts.length) { commands = uniq(commands.concat(tempScripts)); } // This is the default test script added by 'npm init'. const npmInitDefaultTestScript = 'echo "Error: no test specified" && exit 1'; commands.forEach(command => { let commandName = command; // If the command already exists, we namespace it with "kyt:". if (packageJson.scripts[commandName]) { // We don't need to prefix if the command already // runs kyt and it's not a Starter-kyt script. if (packageJson.scripts[commandName].includes('kyt') && !tempScripts.indexOf(command)) { return; } // Prefix except for when the command is 'test' and the script is // the default from 'npm init'. if ( commandName !== 'test' || packageJson.scripts[commandName] !== npmInitDefaultTestScript ) { commandName = `kyt:${commandName}`; } } // If the command is from a starter-kyt then // we need to copy in the starter-kyt value. if (tempScripts.indexOf(command) > -1) { packageJson.scripts[commandName] = tempPackageJSON.scripts[command]; } else { packageJson.scripts[commandName] = commandMap[command] || `kyt ${command}`; } }); packageJson.scripts['kyt:help'] = 'kyt --help'; logger.task('Added kyt scripts into your package.json scripts'); return packageJson; }; // Add dependencies, scripts and other package to // the user's package.json configuration. const updateUserPackageJSON = existingProject => { let userPackageJSON; // Create a package.json definition if // the user doesn't already have one. if (shell.test('-f', paths.userPackageJSONPath)) { // eslint-disable-next-line global-require,import/no-dynamic-require userPackageJSON = require(paths.userPackageJSONPath); } else { userPackageJSON = fakePackageJson; logger.task('Creating a new package.json. You should fill it in.'); } // Clone the package.json so that we have a backup. oldPackageJSON = Object.assign({}, userPackageJSON); // Add dependencies from starter-kyts if (!existingProject) { const kytPrefVersion = args.kytVersion || checkStarterKytVersion(userPackageJSON); userPackageJSON = updatePackageJSONDependencies(userPackageJSON); addKytDependency(userPackageJSON, kytPrefVersion); } else { // exisitng projects should also have kyt as a devDependency addKytDependency(userPackageJSON); } // Add scripts userPackageJSON = addPackageJsonScripts(userPackageJSON); fs.writeFileSync(paths.userPackageJSONPath, JSON.stringify(userPackageJSON, null, 2)); }; // Cleans and reinstalls node modules. const installUserDependencies = () => { logger.info('Cleaning node modules and reinstalling. This may take a couple of minutes...'); shell.rm('-rf', paths.userNodeModulesPath); const result = shell.exec(`${ypm} install`); if (result.code !== 0) { fs.writeFileSync(paths.userPackageJSONPath, JSON.stringify(oldPackageJSON, null, 2)); logger.error('An error occurred when trying to install node modules', result.stderr); logger.task('Restored the original package.json and bailing'); logger.info('You may need to reinstall your modules'); bailProcess(); } logger.task('Installed new modules'); }; // Create an .eslintrc in the user's base directory const createESLintFile = () => { const eslintFileName = '.eslintrc.json'; const linkedPath = path.join(paths.userRootPath, eslintFileName); // Backup esLint if it exists if (shell.test('-f', linkedPath)) { const eslintBackup = path.join(paths.userRootPath, `${eslintFileName}-${date}.bak`); shell.mv(linkedPath, eslintBackup); logger.info(`Backed up current eslint file to: ${eslintBackup}`); } // Copy our user eslintrc into the user's root. const esLintPath = path.join(__dirname, '../../config/user/.eslintrc.base.json'); if (shell.cp(esLintPath, linkedPath).code === 0) { logger.task(`Created ${eslintFileName} file`); } else { logger.error(`There was a problem creating ${eslintFileName}`); } }; // Create an stylelint.json in the user's base directory. const createStylelintFile = () => { const stylelintFileName = '.stylelintrc.json'; const userStylelintPath = path.join(paths.userRootPath, stylelintFileName); // Backup the user's .stylelintrc if it exists. if (shell.test('-f', userStylelintPath)) { const stylelintBackup = path.join(paths.userRootPath, `${stylelintFileName}-${date}.bak`); shell.mv(userStylelintPath, stylelintBackup); logger.info(`Backed up current stylelint file to: ${stylelintBackup}`); } // Copy our .stylelintrc into the user's directory const stylelintPath = path.join(__dirname, `../../config/user/${stylelintFileName}`); if (shell.cp(stylelintPath, userStylelintPath).code === 0) { logger.task(`Created ${stylelintFileName} file`); } else { logger.error(`There was a problem creating ${stylelintFileName}`); } }; // .editorconfig to the user's base directory. const createEditorconfigLink = () => { const editorPath = path.join(__dirname, '../../config/user/.kyt-editorconfig'); const configPath = path.join(paths.userRootPath, '.editorconfig'); // Backup existing editor config if (shell.test('-f', configPath)) { const mvTo = path.join(paths.userRootPath, `editorconfig-${date}.bak`); shell.mv(configPath, mvTo); logger.info(`Backed up current editor config to ${mvTo}`); } shell.cp(editorPath, configPath); logger.task('Created .editorconfig file'); }; const createBabelrc = () => { // back up existing .babelrc, if it exists if (shell.test('-f', paths.userBabelrcPath)) { const mvTo = path.join(paths.userRootPath, `.babelrc-${date}.bak`); shell.mv(paths.userBabelrcPath, mvTo); logger.info(`Backed up current .babelrc to ${mvTo}`); } shell.cp(`${tmpDir}/.babelrc`, paths.userBabelrcPath); logger.task('Created .babelrc'); }; // Copies the starter kyt kyt.config.js // to the user's base directory. const createKytConfig = () => { const configFileName = 'kyt.config.js'; const tmpConfig = path.join(tmpDir, configFileName); const baseConfig = path.join(__dirname, `../../config/user/${configFileName}`); let newConfig = tmpConfig; // Use the base kyt.config // if one does not exist in the starter if (!shell.test('-f', tmpConfig)) { newConfig = baseConfig; } const copyConfig = () => { shell.cp(newConfig, paths.userKytConfigPath); logger.task(`Created ${configFileName} file`); }; if (shell.test('-f', paths.userKytConfigPath)) { // Since the user already has a kyt.config, // we need to back it up before copying. const mvTo = path.join(paths.userRootPath, `${configFileName}-${date}.bak`); shell.mv('-f', paths.userKytConfigPath, mvTo); logger.info(`Backed up current ${configFileName} to: ${mvTo}`); copyConfig(); } else { copyConfig(); } }; // Copies the src directory from the cloned // repo into the user's base direcotry. const createSrcDirectory = () => { const cpSrc = () => { const tmpSrcPath = path.join(tmpDir, '/src'); shell.cp('-r', `${tmpSrcPath}`, paths.userRootPath); logger.task('Created src directory'); }; if (shell.test('-d', paths.srcPath)) { // Since the user already has a src directory, // we need to make a backup before copying. const mvTo = path.join(paths.userRootPath, `src-${date}-bak`); shell.mv('-f', paths.srcPath, mvTo); logger.info(`Backed up current src directory to: ${mvTo}`); } cpSrc(); }; // Copies gitignore file const createGitignore = () => { const gitignoreFile = path.join(paths.userRootPath, './.gitignore'); if (!shell.test('-f', gitignoreFile)) { const gitignoreLocal = path.resolve(__dirname, '../../config/user/.kyt-gitignore'); shell.cp(gitignoreLocal, gitignoreFile); logger.task('Created .gitignore file'); } }; const copyStarterKytFiles = () => { const kytStarterFiles = (tempPackageJSON.kyt && tempPackageJSON.kyt.files) || []; if (kytStarterFiles.length) { kytStarterFiles.forEach(file => { const tempFilePath = path.join(tmpDir, file); const filePath = path.join(paths.userRootPath, file); // If the file name isn't one of the kyt copied files then // we should back up any pre-existing files in the user dir. if ( [ '.gitignore', '.stylelintrc.json', '.eslintrc.json', '.editorconfig', 'kyt.config.js', 'prototype.js', ].indexOf(file) === -1 && (shell.test('-f', filePath) || shell.test('-d', filePath)) ) { const fileBackup = path.join(paths.userRootPath, `${file}-${date}-bak`); shell.mv(filePath, fileBackup); logger.info(`Backed up current ${file} to: ${fileBackup}`); } shell.cp('-Rf', tempFilePath, paths.userRootPath); logger.task(`Copied ${file} from Starter-kyt`); }); } }; // Creates prototype file if one exists const createPrototypeFile = () => { const starterProto = `${tmpDir}/prototype.js`; // No need to copy file if it doesn't exist if (!shell.test('-f', starterProto)) return; // Backup user's prototype file if they already have one if (shell.test('-f', paths.userPrototypePath)) { const prototypeBackup = path.join(paths.userRootPath, `prototype-${date}.js.bak`); shell.mv(paths.userPrototypePath, prototypeBackup); logger.info(`Backed up current prototype file to: ${prototypeBackup}`); } // Copy the prototype file from the starter-kyt into the users repo shell.cp(starterProto, paths.userPrototypePath); logger.task('copied prototype.js file into root'); }; // setup tasks for starter-kyts const starterKytSetup = starterName => { let npmName = null; if (starterName) { tmpDir = path.join(tmpDir, starterKyts.supported[starterName].path); npmName = starterKyts.supported[starterName].npmName; } const kytName = starterName || localPath || repoURL; starterName = starterName || 'specified'; logger.task(`Setting up the ${starterName} starter-kyt`); const afterCopy = error => { if (error) { logger.error('There was a problem downloading the starter-kyt'); logger.log(error); bailProcess(); } // eslint-disable-next-line global-require,import/no-dynamic-require tempPackageJSON = require(`${tmpDir}/package.json`); updateUserPackageJSON(false); installUserDependencies(); createESLintFile(); createBabelrc(); createStylelintFile(); createEditorconfigLink(); createKytConfig(); createPrototypeFile(); createSrcDirectory(); createGitignore(); copyStarterKytFiles(); removeTmpStarter(); logger.end(`Done adding starter kyt: ${kytName} ✨`); }; // First, clean any old cloned repositories. removeTmpStarter(); if (localPath) { shell.exec(`cp -R ${localPath} ${tmpStarter}`); afterCopy(); } else if (npmName) { shell.mkdir(tmpStarter); shell.cd(tmpStarter); const fakePkgPath = `${tmpStarter}/package.json`; fs.writeFileSync(fakePkgPath, JSON.stringify(fakePackageJson, null, 2)); let iCmd = 'npm install'; if (ypm === 'yarn') { iCmd = 'yarn add'; } const output = shell.exec(`${iCmd} ${npmName}`); if (output.code !== 0) { throw output.stderr; } shell.cd('..'); afterCopy(); } else { simpleGit.clone(repoURL, tmpStarter, {}, afterCopy); } }; // Checks to see if user would like src backed up before continuing const srcPrompt = starterChoice => { // Check if src already exists if (shell.test('-d', paths.srcPath)) { const question = [ { type: 'confirm', name: 'srcBackup', message: 'You already have a src directory. Would you like kyt to backup src/ and continue?', // eslint-disable-line default: true, }, ]; inquire.prompt(question).then(answer => { if (answer.srcBackup) { starterKytSetup(starterChoice); } else { process.exit(); } }); } else { starterKytSetup(starterChoice); } }; // setup tasks for setup in existing project const existingProjectSetup = () => { logger.start('Setting up kyt'); updateUserPackageJSON(true); createEditorconfigLink(); createESLintFile(); createStylelintFile(); createKytConfig(); createGitignore(); logger.end('Done setting up kyt'); }; const getRepoUrl = repositoryArg => { if (repositoryArg) { repoURL = repositoryArg; srcPrompt(); } else { const question = [ { type: 'input', name: 'repoUrl', message: 'Enter your Repo URL (https or ssh)', validate: answer => { const httpsPass = answer.match(/^https:\/\/.*.git$/); const sshPass = answer.match(/^[email protected]:.*.git$/); if (httpsPass || sshPass) { return true; } return 'Please enter a valid repo url'; }, }, ]; inquire.prompt(question).then(answer => { if (answer.repoUrl !== '') { repoURL = answer.repoUrl; srcPrompt(); } else { logger.error('You did not enter a valid url. exiting...'); process.exit(1); } }); } }; const createDir = dirName => { if (dirName === '') return; const checkAndBail = code => { if (code) { logger.error(`Unable to create directory ${dirName}. Exiting...`); process.exit(1); } }; // Creates project directory if one is specified logger.task(`Creating your new project at ${dirName}`); let output = shell.mkdir(dirName); checkAndBail(output.code); output = shell.cd(dirName); checkAndBail(output.code); }; const setupPaths = () => { paths = require('kyt-utils/paths')(); // eslint-disable-line tmpStarter = path.resolve(paths.userRootPath, '.kyt-tmp'); // eslint-disable-line no-useless-escape // For passed starter-kyts the root of the starter-kyt is the root of the repo tmpDir = tmpStarter; repoURL = 'https://github.com/NYTimes/kyt.git'; }; // Runs through setup questions const setupPrompt = () => { const skList = Object.keys(starterKyts.supported); const ownRepo = 'I have my own url'; const exist = "I don't want a starter-kyt"; skList.push(ownRepo); skList.push(exist); const ypmQ = { type: 'list', name: 'ypm', message: 'Choose an installer', choices: ['yarn', 'npm'], default: 0, }; const dirNameQ = { type: 'input', name: 'dirName', message: 'Enter a new directory name. To install in current directory, leave blank.', }; const skQ = { type: 'list', name: 'starterChoice', message: 'Choose a starter-kyt:', // eslint-disable-line choices: skList, default: 0, }; const questions = []; // Check to see if yarn is installed or user has specified flag if (yarnOrNpm === 'yarn' && !args.packageManager) questions.push(ypmQ); ypm = args.packageManager ? args.packageManager : yarnOrNpm; if (!args.directory) questions.push(dirNameQ); if (!args.repository && !localPath) questions.push(skQ); inquire.prompt(questions).then(answer => { // question 1 ypm = answer.ypm || ypm; // question 2 // Save Local directory Path before moving to new directory if (localPath) { localPath = path.resolve(localPath); } // Create new directory and set up path strings createDir(args.directory || answer.dirName); setupPaths(); // question 3 const choice = answer.starterChoice; if (choice === ownRepo || args.repository) { // add repo question then move on to src prompt getRepoUrl(args.repository); } else if (starterKyts.supported[choice] || localPath) { srcPrompt(choice); } else if (choice === exist) { existingProjectSetup(); } }); }; // Checks to see if user is running current version of kyt-cli // Gives option to exit if version is old // runs setup const checkCliVersionPrompt = () => { const currentVersion = cliPkgJson.version; const output = shell.exec('npm info kyt-cli version'); const latestVersion = output.stdout.trim(); // If kyt-cli is up to date, proceed if (!semver.lt(currentVersion, latestVersion)) { setupPrompt(); } else { const question = [ { type: 'confirm', name: 'cliVersion', message: `You are running version ${currentVersion} of kyt-cli but the latest version is ${latestVersion} \n We recommend you upgrade before you continue. \n Would you like to proceed anyway?`, default: false, }, ]; inquire.prompt(question).then(answer => { if (answer.cliVersion) { setupPrompt(); } else { process.exit(); } }); } }; try { checkCliVersionPrompt(); } catch (err) { bailProcess(err); } };
}
transitions.ts
import type { TransitionConfig } from 'svelte/transition'; import { cubicInOut } from 'svelte/easing'; export function
( node: Element, { delay = 0, duration = 200, baseScale = 0 } ): TransitionConfig { const o = +getComputedStyle(node).opacity; const m = getComputedStyle(node).transform.match(/scale\(([0-9.]+)\)/); const s = m ? +m[1] : 1; const is = 1 - baseScale; return { delay, duration, css: t => { const eased = cubicInOut(t); return `opacity: ${eased * o}; transform: scale(${(eased * s * is) + baseScale})`; } }; }
fadeScale
signing_identity.go
// Code generated by counterfeiter. DO NOT EDIT. package mock import ( sync "sync" token "github.com/hyperledger/udo/token" ) type SigningIdentity struct { GetPublicVersionStub func() token.Identity getPublicVersionMutex sync.RWMutex getPublicVersionArgsForCall []struct { } getPublicVersionReturns struct { result1 token.Identity } getPublicVersionReturnsOnCall map[int]struct { result1 token.Identity } SerializeStub func() ([]byte, error) serializeMutex sync.RWMutex serializeArgsForCall []struct { } serializeReturns struct { result1 []byte result2 error } serializeReturnsOnCall map[int]struct { result1 []byte result2 error } SignStub func([]byte) ([]byte, error) signMutex sync.RWMutex signArgsForCall []struct { arg1 []byte } signReturns struct { result1 []byte result2 error } signReturnsOnCall map[int]struct { result1 []byte result2 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *SigningIdentity) GetPublicVersion() token.Identity { fake.getPublicVersionMutex.Lock() ret, specificReturn := fake.getPublicVersionReturnsOnCall[len(fake.getPublicVersionArgsForCall)] fake.getPublicVersionArgsForCall = append(fake.getPublicVersionArgsForCall, struct { }{}) fake.recordInvocation("GetPublicVersion", []interface{}{}) fake.getPublicVersionMutex.Unlock() if fake.GetPublicVersionStub != nil { return fake.GetPublicVersionStub() } if specificReturn { return ret.result1 } fakeReturns := fake.getPublicVersionReturns return fakeReturns.result1 } func (fake *SigningIdentity) GetPublicVersionCallCount() int { fake.getPublicVersionMutex.RLock() defer fake.getPublicVersionMutex.RUnlock() return len(fake.getPublicVersionArgsForCall) } func (fake *SigningIdentity) GetPublicVersionCalls(stub func() token.Identity) { fake.getPublicVersionMutex.Lock()
} func (fake *SigningIdentity) GetPublicVersionReturns(result1 token.Identity) { fake.getPublicVersionMutex.Lock() defer fake.getPublicVersionMutex.Unlock() fake.GetPublicVersionStub = nil fake.getPublicVersionReturns = struct { result1 token.Identity }{result1} } func (fake *SigningIdentity) GetPublicVersionReturnsOnCall(i int, result1 token.Identity) { fake.getPublicVersionMutex.Lock() defer fake.getPublicVersionMutex.Unlock() fake.GetPublicVersionStub = nil if fake.getPublicVersionReturnsOnCall == nil { fake.getPublicVersionReturnsOnCall = make(map[int]struct { result1 token.Identity }) } fake.getPublicVersionReturnsOnCall[i] = struct { result1 token.Identity }{result1} } func (fake *SigningIdentity) Serialize() ([]byte, error) { fake.serializeMutex.Lock() ret, specificReturn := fake.serializeReturnsOnCall[len(fake.serializeArgsForCall)] fake.serializeArgsForCall = append(fake.serializeArgsForCall, struct { }{}) fake.recordInvocation("Serialize", []interface{}{}) fake.serializeMutex.Unlock() if fake.SerializeStub != nil { return fake.SerializeStub() } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.serializeReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *SigningIdentity) SerializeCallCount() int { fake.serializeMutex.RLock() defer fake.serializeMutex.RUnlock() return len(fake.serializeArgsForCall) } func (fake *SigningIdentity) SerializeCalls(stub func() ([]byte, error)) { fake.serializeMutex.Lock() defer fake.serializeMutex.Unlock() fake.SerializeStub = stub } func (fake *SigningIdentity) SerializeReturns(result1 []byte, result2 error) { fake.serializeMutex.Lock() defer fake.serializeMutex.Unlock() fake.SerializeStub = nil fake.serializeReturns = struct { result1 []byte result2 error }{result1, result2} } func (fake *SigningIdentity) SerializeReturnsOnCall(i int, result1 []byte, result2 error) { fake.serializeMutex.Lock() defer fake.serializeMutex.Unlock() fake.SerializeStub = nil if fake.serializeReturnsOnCall == nil { fake.serializeReturnsOnCall = make(map[int]struct { result1 []byte result2 error }) } fake.serializeReturnsOnCall[i] = struct { result1 []byte result2 error }{result1, result2} } func (fake *SigningIdentity) Sign(arg1 []byte) ([]byte, error) { var arg1Copy []byte if arg1 != nil { arg1Copy = make([]byte, len(arg1)) copy(arg1Copy, arg1) } fake.signMutex.Lock() ret, specificReturn := fake.signReturnsOnCall[len(fake.signArgsForCall)] fake.signArgsForCall = append(fake.signArgsForCall, struct { arg1 []byte }{arg1Copy}) fake.recordInvocation("Sign", []interface{}{arg1Copy}) fake.signMutex.Unlock() if fake.SignStub != nil { return fake.SignStub(arg1) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.signReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *SigningIdentity) SignCallCount() int { fake.signMutex.RLock() defer fake.signMutex.RUnlock() return len(fake.signArgsForCall) } func (fake *SigningIdentity) SignCalls(stub func([]byte) ([]byte, error)) { fake.signMutex.Lock() defer fake.signMutex.Unlock() fake.SignStub = stub } func (fake *SigningIdentity) SignArgsForCall(i int) []byte { fake.signMutex.RLock() defer fake.signMutex.RUnlock() argsForCall := fake.signArgsForCall[i] return argsForCall.arg1 } func (fake *SigningIdentity) SignReturns(result1 []byte, result2 error) { fake.signMutex.Lock() defer fake.signMutex.Unlock() fake.SignStub = nil fake.signReturns = struct { result1 []byte result2 error }{result1, result2} } func (fake *SigningIdentity) SignReturnsOnCall(i int, result1 []byte, result2 error) { fake.signMutex.Lock() defer fake.signMutex.Unlock() fake.SignStub = nil if fake.signReturnsOnCall == nil { fake.signReturnsOnCall = make(map[int]struct { result1 []byte result2 error }) } fake.signReturnsOnCall[i] = struct { result1 []byte result2 error }{result1, result2} } func (fake *SigningIdentity) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.getPublicVersionMutex.RLock() defer fake.getPublicVersionMutex.RUnlock() fake.serializeMutex.RLock() defer fake.serializeMutex.RUnlock() fake.signMutex.RLock() defer fake.signMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *SigningIdentity) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) } var _ token.SigningIdentity = new(SigningIdentity)
defer fake.getPublicVersionMutex.Unlock() fake.GetPublicVersionStub = stub
utils.py
# Author: Leland McInnes <[email protected]> # # License: BSD 2 clause import time import numba from numba.core import types import numba.experimental.structref as structref import numpy as np @numba.njit("void(i8[:], i8)", cache=True) def seed(rng_state, seed): """Seed the random number generator with a given seed.""" rng_state.fill(seed + 0xFFFF) @numba.njit("i4(i8[:])", cache=True) def tau_rand_int(state): """A fast (pseudo)-random number generator. Parameters ---------- state: array of int64, shape (3,) The internal state of the rng Returns ------- A (pseudo)-random int32 value """ state[0] = (((state[0] & 4294967294) << 12) & 0xFFFFFFFF) ^ ( (((state[0] << 13) & 0xFFFFFFFF) ^ state[0]) >> 19 ) state[1] = (((state[1] & 4294967288) << 4) & 0xFFFFFFFF) ^ ( (((state[1] << 2) & 0xFFFFFFFF) ^ state[1]) >> 25 ) state[2] = (((state[2] & 4294967280) << 17) & 0xFFFFFFFF) ^ ( (((state[2] << 3) & 0xFFFFFFFF) ^ state[2]) >> 11 ) return state[0] ^ state[1] ^ state[2] @numba.njit("f4(i8[:])", cache=True) def tau_rand(state): """A fast (pseudo)-random number generator for floats in the range [0,1] Parameters ---------- state: array of int64, shape (3,) The internal state of the rng Returns ------- A (pseudo)-random float32 in the interval [0, 1] """ integer = tau_rand_int(state) return abs(float(integer) / 0x7FFFFFFF) @numba.njit( [ "f4(f4[::1])", numba.types.float32( numba.types.Array(numba.types.float32, 1, "C", readonly=True) ), ], locals={ "dim": numba.types.intp, "i": numba.types.uint32, # "result": numba.types.float32, # This provides speed, but causes errors in corner cases }, fastmath=True, cache=True, ) def norm(vec): """Compute the (standard l2) norm of a vector. Parameters ---------- vec: array of shape (dim,) Returns ------- The l2 norm of vec. """ result = 0.0 dim = vec.shape[0] for i in range(dim): result += vec[i] * vec[i] return np.sqrt(result) @numba.njit(cache=True) def rejection_sample(n_samples, pool_size, rng_state): """Generate n_samples many integers from 0 to pool_size such that no integer is selected twice. The duplication constraint is achieved via rejection sampling. Parameters ---------- n_samples: int The number of random samples to select from the pool pool_size: int The size of the total pool of candidates to sample from rng_state: array of int64, shape (3,) Internal state of the random number generator Returns ------- sample: array of shape(n_samples,) The ``n_samples`` randomly selected elements from the pool. """ result = np.empty(n_samples, dtype=np.int64) for i in range(n_samples): reject_sample = True j = 0 while reject_sample: j = tau_rand_int(rng_state) % pool_size for k in range(i): if j == result[k]: break else: reject_sample = False result[i] = j return result @structref.register class HeapType(types.StructRef): pass class Heap(structref.StructRefProxy): @property def indices(self): return Heap_get_indices(self) @property def distances(self): return Heap_get_distances(self) @property def flags(self): return Heap_get_flags(self) @numba.njit(cache=True) def Heap_get_flags(self): return self.flags @numba.njit(cache=True) def Heap_get_distances(self): return self.distances @numba.njit(cache=True) def Heap_get_indices(self): return self.indices structref.define_proxy(Heap, HeapType, ["indices", "distances", "flags"]) # Heap = namedtuple("Heap", ("indices", "distances", "flags")) @numba.njit(cache=True) def make_heap(n_points, size): """Constructor for the numba enabled heap objects. The heaps are used for approximate nearest neighbor search, maintaining a list of potential neighbors sorted by their distance. We also flag if potential neighbors are newly added to the list or not. Internally this is stored as a single ndarray; the first axis determines whether we are looking at the array of candidate graph_indices, the array of distances, or the flag array for whether elements are new or not. Each of these arrays are of shape (``n_points``, ``size``) Parameters ---------- n_points: int The number of graph_data points to track in the heap. size: int The number of items to keep on the heap for each graph_data point. Returns ------- heap: An ndarray suitable for passing to other numba enabled heap functions. """ indices = np.full((int(n_points), int(size)), -1, dtype=np.int32) distances = np.full((int(n_points), int(size)), np.infty, dtype=np.float32) flags = np.zeros((int(n_points), int(size)), dtype=np.uint8) result = (indices, distances, flags) return result @numba.njit(cache=True) def siftdown(heap1, heap2, elt): """Restore the heap property for a heap with an out of place element at position ``elt``. This works with a heap pair where heap1 carries the weights and heap2 holds the corresponding elements.""" while elt * 2 + 1 < heap1.shape[0]: left_child = elt * 2 + 1 right_child = left_child + 1 swap = elt if heap1[swap] < heap1[left_child]: swap = left_child if right_child < heap1.shape[0] and heap1[swap] < heap1[right_child]: swap = right_child if swap == elt: break else: heap1[elt], heap1[swap] = heap1[swap], heap1[elt] heap2[elt], heap2[swap] = heap2[swap], heap2[elt] elt = swap @numba.njit(parallel=True, cache=False) def deheap_sort(indices, distances): """Given two arrays representing a heap (indices and distances), reorder the arrays by increasing distance. This is effectively just the second half of heap sort (the first half not being required since we already have the graph_data in a heap). Note that this is done in-place. Parameters ---------- indices : array of shape (n_samples, n_neighbors) The graph indices to sort by distance. distances : array of shape (n_samples, n_neighbors) The corresponding edge distance. Returns ------- indices, distances: arrays of shape (n_samples, n_neighbors) The indices and distances sorted by increasing distance. """ for i in numba.prange(indices.shape[0]): # starting from the end of the array and moving back for j in range(indices.shape[1] - 1, 0, -1): indices[i, 0], indices[i, j] = indices[i, j], indices[i, 0] distances[i, 0], distances[i, j] = distances[i, j], distances[i, 0] siftdown(distances[i, :j], indices[i, :j], 0) return indices, distances # @numba.njit() # def smallest_flagged(heap, row): # """Search the heap for the smallest element that is # still flagged. # # Parameters # ---------- # heap: array of shape (3, n_samples, n_neighbors) # The heaps to search # # row: int # Which of the heaps to search # # Returns # ------- # index: int # The index of the smallest flagged element # of the ``row``th heap, or -1 if no flagged # elements remain in the heap. # """ # ind = heap[0][row] # dist = heap[1][row] # flag = heap[2][row] # # min_dist = np.inf # result_index = -1 # # for i in range(ind.shape[0]): # if flag[i] == 1 and dist[i] < min_dist: # min_dist = dist[i] # result_index = i # # if result_index >= 0: # flag[result_index] = 0.0 # return int(ind[result_index]) # else: # return -1 @numba.njit(parallel=True, locals={"idx": numba.types.int64}, cache=False) def new_build_candidates(current_graph, max_candidates, rng_state, n_threads): """Build a heap of candidate neighbors for nearest neighbor descent. For each vertex the candidate neighbors are any current neighbors, and any vertices that have the vertex as one of their nearest neighbors. Parameters ---------- current_graph: heap The current state of the graph for nearest neighbor descent. max_candidates: int The maximum number of new candidate neighbors. rng_state: array of int64, shape (3,) The internal state of the rng Returns ------- candidate_neighbors: A heap with an array of (randomly sorted) candidate neighbors for each vertex in the graph. """ current_indices = current_graph[0] current_flags = current_graph[2] n_vertices = current_indices.shape[0] n_neighbors = current_indices.shape[1] new_candidate_indices = np.full((n_vertices, max_candidates), -1, dtype=np.int32) new_candidate_priority = np.full( (n_vertices, max_candidates), np.inf, dtype=np.float32 ) old_candidate_indices = np.full((n_vertices, max_candidates), -1, dtype=np.int32) old_candidate_priority = np.full( (n_vertices, max_candidates), np.inf, dtype=np.float32 ) for n in numba.prange(n_threads): local_rng_state = rng_state + n for i in range(n_vertices): for j in range(n_neighbors): idx = current_indices[i, j] isn = current_flags[i, j] if idx < 0: continue d = tau_rand(local_rng_state) if isn: if i % n_threads == n: checked_heap_push( new_candidate_priority[i], new_candidate_indices[i], d, idx ) if idx % n_threads == n: checked_heap_push( new_candidate_priority[idx], new_candidate_indices[idx], d, i, ) else: if i % n_threads == n: checked_heap_push( old_candidate_priority[i], old_candidate_indices[i], d, idx ) if idx % n_threads == n: checked_heap_push( old_candidate_priority[idx], old_candidate_indices[idx], d, i, ) indices = current_graph[0] flags = current_graph[2] for i in numba.prange(n_vertices): for j in range(n_neighbors): idx = indices[i, j] for k in range(max_candidates): if new_candidate_indices[i, k] == idx: flags[i, j] = 0 break return new_candidate_indices, old_candidate_indices @numba.njit("b1(u1[::1],i4)", cache=True) def has_been_visited(table, candidate): loc = candidate >> 3 mask = 1 << (candidate & 7) return table[loc] & mask @numba.njit("void(u1[::1],i4)", cache=True) def
(table, candidate): loc = candidate >> 3 mask = 1 << (candidate & 7) table[loc] |= mask return @numba.njit( "i4(f4[::1],i4[::1],f4,i4)", fastmath=True, locals={ "size": numba.types.intp, "i": numba.types.uint16, "ic1": numba.types.uint16, "ic2": numba.types.uint16, "i_swap": numba.types.uint16, }, cache=True, ) def simple_heap_push(priorities, indices, p, n): if p >= priorities[0]: return 0 size = priorities.shape[0] # insert val at position zero priorities[0] = p indices[0] = n # descend the heap, swapping values until the max heap criterion is met i = 0 while True: ic1 = 2 * i + 1 ic2 = ic1 + 1 if ic1 >= size: break elif ic2 >= size: if priorities[ic1] > p: i_swap = ic1 else: break elif priorities[ic1] >= priorities[ic2]: if p < priorities[ic1]: i_swap = ic1 else: break else: if p < priorities[ic2]: i_swap = ic2 else: break priorities[i] = priorities[i_swap] indices[i] = indices[i_swap] i = i_swap priorities[i] = p indices[i] = n return 1 @numba.njit( "i4(f4[::1],i4[::1],f4,i4)", fastmath=True, locals={ "size": numba.types.intp, "i": numba.types.uint16, "ic1": numba.types.uint16, "ic2": numba.types.uint16, "i_swap": numba.types.uint16, }, cache=True, ) def checked_heap_push(priorities, indices, p, n): if p >= priorities[0]: return 0 size = priorities.shape[0] # break if we already have this element. for i in range(size): if n == indices[i]: return 0 # insert val at position zero priorities[0] = p indices[0] = n # descend the heap, swapping values until the max heap criterion is met i = 0 while True: ic1 = 2 * i + 1 ic2 = ic1 + 1 if ic1 >= size: break elif ic2 >= size: if priorities[ic1] > p: i_swap = ic1 else: break elif priorities[ic1] >= priorities[ic2]: if p < priorities[ic1]: i_swap = ic1 else: break else: if p < priorities[ic2]: i_swap = ic2 else: break priorities[i] = priorities[i_swap] indices[i] = indices[i_swap] i = i_swap priorities[i] = p indices[i] = n return 1 @numba.njit( "i4(f4[::1],i4[::1],u1[::1],f4,i4,u1)", fastmath=True, locals={ "size": numba.types.intp, "i": numba.types.uint16, "ic1": numba.types.uint16, "ic2": numba.types.uint16, "i_swap": numba.types.uint16, }, cache=True, ) def checked_flagged_heap_push(priorities, indices, flags, p, n, f): if p >= priorities[0]: return 0 size = priorities.shape[0] # break if we already have this element. for i in range(size): if n == indices[i]: return 0 # insert val at position zero priorities[0] = p indices[0] = n flags[0] = f # descend the heap, swapping values until the max heap criterion is met i = 0 while True: ic1 = 2 * i + 1 ic2 = ic1 + 1 if ic1 >= size: break elif ic2 >= size: if priorities[ic1] > p: i_swap = ic1 else: break elif priorities[ic1] >= priorities[ic2]: if p < priorities[ic1]: i_swap = ic1 else: break else: if p < priorities[ic2]: i_swap = ic2 else: break priorities[i] = priorities[i_swap] indices[i] = indices[i_swap] flags[i] = flags[i_swap] i = i_swap priorities[i] = p indices[i] = n flags[i] = f return 1 @numba.njit( parallel=True, locals={ "p": numba.int32, "q": numba.int32, "d": numba.float32, "added": numba.uint8, "n": numba.uint32, "i": numba.uint32, "j": numba.uint32, }, cache=False, ) def apply_graph_updates_low_memory(current_graph, updates, n_threads): n_changes = 0 priorities = current_graph[1] indices = current_graph[0] flags = current_graph[2] # n_threads = numba.get_num_threads() for n in numba.prange(n_threads): for i in range(len(updates)): for j in range(len(updates[i])): p, q, d = updates[i][j] if p == -1 or q == -1: continue if p % n_threads == n: added = checked_flagged_heap_push( priorities[p], indices[p], flags[p], d, q, 1 ) n_changes += added if q % n_threads == n: added = checked_flagged_heap_push( priorities[q], indices[q], flags[q], d, p, 1 ) n_changes += added return n_changes @numba.njit(locals={"p": numba.types.int64, "q": numba.types.int64}, cache=True) def apply_graph_updates_high_memory(current_graph, updates, in_graph): n_changes = 0 for i in range(len(updates)): for j in range(len(updates[i])): p, q, d = updates[i][j] if p == -1 or q == -1: continue if q in in_graph[p] and p in in_graph[q]: continue elif q in in_graph[p]: pass else: added = checked_flagged_heap_push( current_graph[1][p], current_graph[0][p], current_graph[2][p], d, q, 1, ) if added > 0: in_graph[p].add(q) n_changes += added if p == q or p in in_graph[q]: pass else: added = checked_flagged_heap_push( current_graph[1][p], current_graph[0][p], current_graph[2][p], d, q, 1, ) if added > 0: in_graph[q].add(p) n_changes += added return n_changes @numba.njit(cache=True) def initalize_heap_from_graph_indices(heap, graph_indices, data, metric): for i in range(graph_indices.shape[0]): for idx in range(graph_indices.shape[1]): j = graph_indices[i, idx] if j >= 0: d = metric(data[i], data[j]) checked_flagged_heap_push(heap[1][i], heap[0][i], heap[2][i], d, j, 1) return heap @numba.njit(parallel=True, cache=False) def sparse_initalize_heap_from_graph_indices( heap, graph_indices, data_indptr, data_indices, data_vals, metric ): for i in numba.prange(graph_indices.shape[0]): for idx in range(graph_indices.shape[1]): j = graph_indices[i, idx] ind1 = data_indices[data_indptr[i] : data_indptr[i + 1]] data1 = data_vals[data_indptr[i] : data_indptr[i + 1]] ind2 = data_indices[data_indptr[j] : data_indptr[j + 1]] data2 = data_vals[data_indptr[j] : data_indptr[j + 1]] d = metric(ind1, data1, ind2, data2) checked_flagged_heap_push(heap[1][i], heap[0][i], heap[2][i], d, j, 1) return heap # Generates a timestamp for use in logging messages when verbose=True def ts(): return time.ctime(time.time())
mark_visited
compose.go
package compose import ( "fmt" "regexp" "strings" "github.com/jakewright/home-automation/libraries/go/exe" "github.com/jakewright/home-automation/libraries/go/util" "github.com/jakewright/home-automation/tools/bolt/pkg/config" "github.com/jakewright/home-automation/tools/bolt/pkg/docker" ) // Compose performs docker-compose tasks type Compose struct { f *composeFile } // New returns a new Compose struct func
() (*Compose, error) { f, err := parse(config.Get().DockerComposeFilePath) if err != nil { return nil, fmt.Errorf("failed to parse docker-compose file: %w", err) } return &Compose{f}, nil } // ListAll returns a list of all service names func (c *Compose) ListAll() ([]string, error) { services := make([]string, 0, len(c.f.Services)) for name := range c.f.Services { services = append(services, name) } return services, nil } // Run starts the service, building first if necessary. func (c *Compose) Run(service string) error { args := []string{"up", "-d", "--renew-anon-volumes", "--remove-orphans", service} if err := c.cmd(args...).SetPseudoTTY().Run().Err; err != nil { return fmt.Errorf("failed to cmd docker-compose up: %w", err) } return nil } // IsRunning returns whether the service is currently running func (c *Compose) IsRunning(serviceName string) (bool, error) { containerID, err := c.getContainerID(serviceName) if err != nil { return false, err } else if containerID == "" { return false, nil } return docker.IsContainerRunning(containerID) } // Build builds the service func (c *Compose) Build(services []string) error { args := append([]string{"build", "--pull"}, services...) if err := c.cmd(args...).SetPseudoTTY().Run().Err; err != nil { return err } return nil } // Stop stops the service func (c *Compose) Stop(services []string) error { args := append([]string{"stop"}, services...) if err := c.cmd(args...).SetPseudoTTY().Run().Err; err != nil { return fmt.Errorf("failed to cmd docker-compose stop: %w", err) } return nil } // StopAll stops all docker-compose services func (c *Compose) StopAll() error { if err := c.cmd("stop").SetPseudoTTY().Run().Err; err != nil { return fmt.Errorf("failed to cmd docker-compose stop: %w", err) } return nil } // Exec executes the command inside the service's container func (c *Compose) Exec(serviceName, stdin string, cmd string, args ...string) error { containerID, err := c.getContainerID(serviceName) if err != nil { return fmt.Errorf("failed to get container ID of %s: %w", serviceName, err) } joinedCmd := fmt.Sprintf("%s %s", cmd, strings.Join(args, " ")) dockerArgs := []string{"exec", "-i", containerID, "sh", "-c", joinedCmd} if err := exe.Command("docker", dockerArgs...).SetInput(stdin).Run().Err; err != nil { return fmt.Errorf("failed to docker exec: %w", err) } return nil } // Ports returns the host ports that the service exposes func (c *Compose) Ports(serviceName string) ([]string, error) { raw := c.f.Services[serviceName].Ports var ports []string for _, port := range raw { // This only supports the 3000:3000 syntax re := regexp.MustCompile(`^(\d+):(\d+)$`) matches := re.FindStringSubmatch(port) if len(matches) != 3 { return nil, fmt.Errorf("unsupported port format: %s", port) } ports = append(ports, matches[1]) } return ports, nil } // Logs runs docker-compose logs func (c *Compose) Logs(services []string) error { args := []string{"logs", "--follow", "--timestamps", "--tail=30"} args = append(args, services...) // Ignore the error because it returns a non-zero exit code on Ctrl+c c.cmd(args...).SetPseudoTTY().Run() return nil } // cmd returns a docker-compose command with the // docker-compose file and project name flags set func (c *Compose) cmd(args ...string) *exe.Cmd { a := []string{"-f", config.Get().DockerComposeFilePath, "-p", config.Get().ProjectName} a = append(a, args...) return exe.Command("docker-compose", a...) } func (c *Compose) getContainerID(serviceName string) (string, error) { result := c.cmd("ps", "-q", serviceName).Run() if result.Err != nil { return "", fmt.Errorf("failed to cmd docker-compose ps: %w", result.Err) } lines := strings.Split(result.Stdout, "\n") lines = util.RemoveWhitespaceStrings(lines) if len(lines) == 0 { return "", nil } else if len(lines) > 1 { return "", fmt.Errorf("found multiple containers") } return lines[0], nil }
New
settings-personal.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'settings-personal', templateUrl: './settings-personal.component.html', styleUrls: ['./settings-personal.component.css'] }) export class SettingsPersonalComponent implements OnInit { constructor() { } ngOnInit() { } step = -1; setStep(index: number) { this.step = index; } nextStep() { this.step++; } prevStep() { this.step--; }
}
package.py
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os from spack.util.environment import is_system_path class Tcl(AutotoolsPackage, SourceforgePackage): """Tcl (Tool Command Language) is a very powerful but easy to learn dynamic programming language, suitable for a very wide range of uses, including web and desktop applications, networking, administration, testing and many more. Open source and business-friendly, Tcl is a mature yet evolving language that is truly cross platform, easily deployed and highly extensible.""" homepage = "https://www.tcl.tk/" sourceforge_mirror_path = "tcl/tcl8.6.11-src.tar.gz" version('8.6.12', sha256='26c995dd0f167e48b11961d891ee555f680c175f7173ff8cb829f4ebcde4c1a6') version('8.6.11', sha256='8c0486668586672c5693d7d95817cb05a18c5ecca2f40e2836b9578064088258') version('8.6.10', sha256='5196dbf6638e3df8d5c87b5815c8c2b758496eb6f0e41446596c9a4e638d87ed') version('8.6.8', sha256='c43cb0c1518ce42b00e7c8f6eaddd5195c53a98f94adc717234a65cbcfd3f96a') version('8.6.6', sha256='a265409781e4b3edcc4ef822533071b34c3dc6790b893963809b9fe221befe07') version('8.6.5', sha256='ce26d5b9c7504fc25d2f10ef0b82b14cf117315445b5afa9e673ed331830fb53') version('8.6.4', sha256='9e6ed94c981c1d0c5f5fefb8112d06c6bf4d050a7327e95e71d417c416519c8d') version('8.6.3', sha256='6ce0778de0d50daaa9c345d7c1fd1288fb658f674028812e7eeee992e3051005') version('8.5.19', sha256='d3f04456da873d17f02efc30734b0300fb6c3b85028d445fe284b83253a6db18') extendable = True depends_on('zlib') configure_directory = 'unix' def install(self, spec, prefix): with working_dir(self.build_directory): make('install') # https://wiki.tcl-lang.org/page/kitgen if self.spec.satisfies('@8.6:'): make('install-headers') # Some applications like Expect require private Tcl headers. make('install-private-headers') # Copy source to install tree # A user-provided install option might re-do this # https://github.com/spack/spack/pull/4102/files installed_src = join_path( self.spec.prefix, 'share', self.name, 'src') stage_src = os.path.realpath(self.stage.source_path) install_tree(stage_src, installed_src) # Replace stage dir -> installed src dir in tclConfig filter_file( stage_src, installed_src, join_path(self.spec['tcl'].libs.directories[0], 'tclConfig.sh')) # Don't install binaries in src/ tree with working_dir(join_path(installed_src, self.configure_directory)): make('clean') @run_after('install') def symlink_tclsh(self): with working_dir(self.prefix.bin): symlink('tclsh{0}'.format(self.version.up_to(2)), 'tclsh') # ======================================================================== # Set up environment to make install easy for tcl extensions. # ======================================================================== @property def libs(self): return find_libraries(['libtcl{0}'.format(self.version.up_to(2))], root=self.prefix, recursive=True) @property def command(self): """Returns the tclsh command. Returns: Executable: the tclsh command """ # Although we symlink tclshX.Y to tclsh, we also need to support external # installations that may not have this symlink, or may have multiple versions # of Tcl installed in the same directory. return Executable(os.path.realpath(self.prefix.bin.join( 'tclsh{0}'.format(self.version.up_to(2))))) def setup_run_environment(self, env): """Set TCL_LIBRARY to the directory containing init.tcl. For further info see: * https://wiki.tcl-lang.org/page/TCL_LIBRARY """ # When using tkinter from within spack provided python+tkinter, # python will not be able to find Tcl unless TCL_LIBRARY is set. env.set('TCL_LIBRARY', os.path.dirname( sorted(find(self.prefix, 'init.tcl'))[0])) def setup_dependent_build_environment(self, env, dependent_spec): """Set TCL_LIBRARY to the directory containing init.tcl. Set TCLLIBPATH to include the tcl-shipped directory for extensions and any other tcl extension it depends on. For further info see: * https://wiki.tcl-lang.org/page/TCL_LIBRARY * https://wiki.tcl-lang.org/page/TCLLIBPATH """ env.set('TCL_LIBRARY', os.path.dirname( sorted(find(self.prefix, 'init.tcl'))[0])) # If we set TCLLIBPATH, we must also ensure that the corresponding # tcl is found in the build environment. This to prevent cases # where a system provided tcl is run against the standard libraries # of a Spack built tcl. See issue #7128 that relates to python but # it boils down to the same situation we have here. if not is_system_path(self.prefix.bin): env.prepend_path('PATH', self.prefix.bin) # WARNING: paths in $TCLLIBPATH must be *space* separated, # its value is meant to be a Tcl list, *not* an env list # as explained here: https://wiki.tcl-lang.org/page/TCLLIBPATH: # "TCLLIBPATH is a Tcl list, not some platform-specific # colon-separated or semi-colon separated format" # WARNING: Tcl and Tcl extensions like Tk install their configuration files # in subdirectories like `<prefix>/lib/tcl8.6`. However, Tcl is aware of this, # and $TCLLIBPATH should only contain `<prefix>/lib`. $TCLLIBPATH is only needed # because we install Tcl extensions to different directories than Tcl. See: # https://core.tcl-lang.org/tk/tktview/447bd3e4abe17452d19a80e6840dcc8a2603fcbc env.prepend_path( 'TCLLIBPATH', self.spec['tcl'].libs.directories[0], separator=' ') for d in dependent_spec.traverse(deptype=('build', 'run', 'test')): if d.package.extends(self.spec): # Tcl libraries may be installed in lib or lib64, see #19546 for lib in ['lib', 'lib64']: tcllibpath = join_path(d.prefix, lib) if os.path.exists(tcllibpath): env.prepend_path('TCLLIBPATH', tcllibpath, separator=' ') def
(self, env, dependent_spec): """Set TCLLIBPATH to include the tcl-shipped directory for extensions and any other tcl extension it depends on. For further info see: * https://wiki.tcl-lang.org/page/TCLLIBPATH """ for d in dependent_spec.traverse(deptype=('build', 'run', 'test')): if d.package.extends(self.spec): # Tcl libraries may be installed in lib or lib64, see #19546 for lib in ['lib', 'lib64']: tcllibpath = join_path(d.prefix, lib) if os.path.exists(tcllibpath): env.prepend_path('TCLLIBPATH', tcllibpath, separator=' ')
setup_dependent_run_environment
error.rs
pub struct Error { pub message: String, } impl std::fmt::Debug for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
} impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.message) } } impl std::error::Error for Error {} macro_rules! err { ($($arg:tt)*) => { crate::error::Error { message: format!($($arg)*), } } }
{ write!(f, "{}", self.message) }
button.go
package viber // Button for carousel and keyboards type Button struct { Columns int `json:"Columns,omitempty"` Rows int `json:"Rows,omitempty"` ActionType ActionType `json:"ActionType"` ActionBody string `json:"ActionBody"` Image string `json:"Image,omitempty"` Text string `json:"Text,omitempty"` TextSize TextSize `json:"TextSize,omitempty"` TextVAlign TextVAlign `json:"TextVAlign,omitempty"` TextHAlign TextHAlign `json:"TextHAlign,omitempty"` TextOpacity int8 `json:"TextOpacity,omitempty"` TextBgGradientColor string `json:"TextBgGradientColor,omitempty"` BgColor string `json:"BgColor,omitempty"` BgMediaType string `json:"BgMediaType,omitempty"` BgMedia string `json:"BgMedia,omitempty"` BgLoop bool `json:"BgLoop,omitempty"` Silent bool `json:"Silent,omitempty"` } // NewButton helper function for creating button with text and image func (v *Viber) NewButton(cols, rows int, typ ActionType, actionBody string, text, image string) *Button { return &Button{ Columns: cols, Rows: rows, ActionType: typ, ActionBody: actionBody, Text: text, Image: image, } } // NewImageButton helper function for creating image button struct with common params func (v *Viber) NewImageButton(cols, rows int, typ ActionType, actionBody string, image string) *Button { return &Button{ Columns: cols, Rows: rows, ActionType: typ, ActionBody: actionBody, Image: image, } } // NewTextButton helper function for creating image button struct with common params func (v *Viber) NewTextButton(cols, rows int, t ActionType, actionBody, text string) *Button { return &Button{ Columns: cols, Rows: rows, ActionType: t, ActionBody: actionBody, Text: text, } } // TextSize for carousel buttons // viber.Small // viber.Medium (synonym to regular) // viber.Large // viber.Regular (default) type TextSize string // TextSize values const ( Small = TextSize("small") Medium = TextSize("medium") Large = TextSize("large") Regular = TextSize("regular") ) // TextSizeSmall for button text func (b *Button) TextSizeSmall() *Button { b.TextSize = Small return b } // TextSizeMedium for button text, synonym to Regular func (b *Button) TextSizeMedium() *Button { b.TextSize = Medium return b } // TextSizeRegular for button text, synonym to Medium func (b *Button) TextSizeRegular() *Button { b.TextSize = Regular return b } // TextSizeLarge for button text func (b *Button) TextSizeLarge() *Button { b.TextSize = Large return b } // ActionType for carousel buttons // viber.Reply // viber.OpenURL type ActionType string // ActionType values const ( Reply = ActionType("reply") OpenURL = ActionType("open-url") None = ActionType("none") ) // TextVAlign for carousel buttons // viber.Top // viber.Middle (default) // viber.Bottom type TextVAlign string // TextVAlign values const ( Top = TextVAlign("top") Middle = TextVAlign("middle") Bottom = TextVAlign("bottom") ) // TextVAlignTop vertically align text to the top func (b *Button) TextVAlignTop() *Button { b.TextVAlign = Top return b } // TextVAlignMiddle vertically align text to the middle func (b *Button) TextVAlignMiddle() *Button { b.TextVAlign = Middle return b } // TextVAlignBottom vertically align text to the bottom func (b *Button) TextVAlignBottom() *Button { b.TextVAlign = Bottom return b } // TextHAlign for carousel buttons // viber.Left // viber.Center (default) // viber.Middle type TextHAlign string // TextHAlign values const ( Left = TextHAlign("left") Center = TextHAlign("center") Right = TextHAlign("right") ) // TextHAlignLeft horizontaly center text left func (b *Button) TextHAlignLeft() *Button { b.TextHAlign = Left return b } // TextHAlignCenter horizontaly center text func (b *Button) TextHAlignCenter() *Button { b.TextHAlign = Center return b } // TextHAlignRight horizontaly align text right func (b *Button) TextHAlignRight() *Button { b.TextHAlign = Right return b } // SetSilent response from button func (b *Button) SetSilent() *Button { b.Silent = true return b } // SetBgColor for button func (b *Button) SetBgColor(hex string) *Button { b.BgColor = hex return b } // SetTextOpacity 0-100 func (b *Button) SetTextOpacity(o int8) *Button { if o >= 0 && o <= 100
return b } // BgMediaGIF set BgMedia to GIF with loop param func (b *Button) BgMediaGIF(gifURL string, loop bool) *Button { b.BgMediaType = "gif" b.BgMedia = gifURL b.BgLoop = loop return b } // BgMediaPicture to set background to PNG or JPG. Use BgMediaGIF for GIF background func (b *Button) BgMediaPicture(picURL string) *Button { b.BgMediaType = "picture" b.BgMedia = picURL return b }
{ b.TextOpacity = o }
sdssum.native.js
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var addon = require( './../src/addon.node' ); // MAIN // /** * Computes the sum of single-precision floating-point strided array elements using extended accumulation. * * @param {PositiveInteger} N - number of indexed elements
* @param {Float32Array} x - input array * @param {integer} stride - stride length * @returns {number} sum * * @example * var Float32Array = require( '@stdlib/array/float32' ); * * var x = new Float32Array( [ 1.0, -2.0, 2.0 ] ); * var N = x.length; * * var v = sdssum( N, x, 1 ); * // returns 1.0 */ function sdssum( N, x, stride ) { return addon( N, x, stride ); } // EXPORTS // module.exports = sdssum;
database.go
package db import ( "database/sql" "fmt" "strings" "time" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" ) const ( host = "postgres" port = 5432 user = "postgres" password = "postgres" dbname = "postgres" ) var db *sqlx.DB func init() { psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+ "password=%s dbname=%s sslmode=disable", host, port, user, password, dbname) var err error db, err = sqlx.Open("postgres", psqlInfo) checkError(err) err = db.Ping() checkError(err) fmt.Println("Successfully connected to DB!") migrateDB() } func
(scanType string) int { insert_row := `insert into scans (scan_type, created_on, scan_start_time) values ($1, current_timestamp, current_timestamp) RETURNING id` lastInsertId := 0 err := db.QueryRow(insert_row, scanType).Scan(&lastInsertId) checkError(err) return lastInsertId } func SaveScanMetadata(searchPath string, searchFilter string, scanId int) { insert_row := `insert into scanmetadata (name, search_path, search_filter, scan_id) values ($1, $2, $3, $4) RETURNING id` var err error _, err = db.Exec(insert_row, nil, searchPath, searchFilter, scanId) checkError(err) } func SaveMessageMetadataToDb(scanId int, messageMetaData <-chan MessageMetadata) { for { mmd, more := <-messageMetaData if !more { logCompleteScan(scanId) break } insert_row := `insert into messagemetadata (message_id, thread_id, date, mail_from, mail_to, subject, size_estimate, labels, scan_id) values ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id` var err error _, err = db.Exec(insert_row, mmd.MessageId, mmd.ThreadId, mmd.Date, substr(mmd.From, 500), substr(mmd.To, 500), substr(mmd.Subject, 2000), mmd.SizeEstimate, substr(strings.Join(mmd.LabelIds, ","), 500), scanId) checkError(err, fmt.Sprintf("While inserting to messagemetadata messageId:%v", mmd.MessageId)) } } func SavePhotosMediaItemToDb(scanId int, photosMediaItem <-chan PhotosMediaItem) { for { pmi, more := <-photosMediaItem if !more { logCompleteScan(scanId) break } insert_row := `insert into photosmediaitem (media_item_id, product_url, mime_type, filename, size, scan_id, file_mod_time, contributor_display_name, md5hash) values ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id` var err error lastInsertId := 0 err = db.QueryRow(insert_row, pmi.MediaItemId, pmi.ProductUrl, pmi.MimeType, pmi.Filename, pmi.Size, scanId, pmi.FileModTime, pmi.ContributorDisplayName, pmi.Md5hash).Scan(&lastInsertId) checkError(err, fmt.Sprintf("While inserting to photosmediaitem mediaItemId:%v", pmi.MediaItemId)) switch pmi.MimeType[:5] { case "image": //e.g. image/jpeg image/png image/gif insert_photo_row := `insert into photometadata (photos_media_item_id, camera_make, camera_model, focal_length, f_number, iso, exposure_time) values ($1, $2, $3, $4, $5, $6, $7) RETURNING id` _, err = db.Exec(insert_photo_row, lastInsertId, pmi.CameraMake, pmi.CameraModel, pmi.FocalLength, pmi.FNumber, pmi.Iso, pmi.ExposureTime) checkError(err, fmt.Sprintf("While inserting to photometadata mediaItemId:%v", pmi.MediaItemId)) case "video": //e.g. video/mp4 insert_video_row := `insert into videometadata (photos_media_item_id, camera_make, camera_model, fps) values ($1, $2, $3, $4) RETURNING id` _, err = db.Exec(insert_video_row, lastInsertId, pmi.CameraMake, pmi.CameraModel, pmi.Fps) checkError(err, fmt.Sprintf("While inserting to videometadata mediaItemId:%v", pmi.MediaItemId)) default: fmt.Println("Unsupported mime type.") } } } func SaveStatToDb(scanId int, scanData <-chan FileData) { for { fd, more := <-scanData if !more { logCompleteScan(scanId) break } insert_row := `insert into scandata (name, path, size, file_mod_time, md5hash, scan_id, is_dir, file_count) values ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id` var err error if fd.IsDir { _, err = db.Exec(insert_row, fd.FileName, fd.FilePath, fd.Size, fd.ModTime, fd.Md5Hash, scanId, fd.IsDir, fd.FileCount) } else { _, err = db.Exec(insert_row, fd.FileName, fd.FilePath, fd.Size, fd.ModTime, fd.Md5Hash, scanId, fd.IsDir, nil) } checkError(err) } } func GetScansFromDb(pageNo int) ([]Scan, int) { limit := 10 offset := limit * (pageNo - 1) count_rows := `select count(*) from scans` read_row := `select S.id, scan_type, created_on AT TIME ZONE 'UTC' AT TIME ZONE 'America/Los_Angeles' as created_on, scan_start_time AT TIME ZONE 'UTC' AT TIME ZONE 'America/Los_Angeles' as scan_start_time, scan_end_time, CONCAT(search_path, search_filter) as metadata, date_trunc('millisecond', COALESCE(scan_end_time,current_timestamp)-scan_start_time) as duration from scans S LEFT JOIN scanmetadata SM ON S.id = SM.scan_id order by id limit $1 OFFSET $2 ` scans := []Scan{} var count int err := db.Select(&scans, read_row, limit, offset) checkError(err) err = db.Get(&count, count_rows) checkError(err) return scans, count } func GetMessageMetadataFromDb(scanId int, pageNo int) ([]MessageMetadataRead, int) { limit := 10 offset := limit * (pageNo - 1) count_rows := `select count(*) from messagemetadata where scan_id = $1` read_row := `select id, message_id, thread_id, date, mail_from, mail_to, subject, size_estimate, labels, scan_id from messagemetadata where scan_id = $1 order by id limit $2 offset $3` messageMetadata := []MessageMetadataRead{} var count int err := db.Get(&count, count_rows, scanId) checkError(err) err = db.Select(&messageMetadata, read_row, scanId, limit, offset) checkError(err) return messageMetadata, count } func GetPhotosMediaItemFromDb(scanId int, pageNo int) ([]PhotosMediaItemRead, int) { limit := 10 offset := limit * (pageNo - 1) count_rows := `select count(*) from photosmediaitem where scan_id = $1` read_row := `select id, media_item_id, product_url, mime_type, filename, size, file_mod_time, md5hash, scan_id, contributor_display_name from photosmediaitem where scan_id = $1 order by id limit $2 offset $3` photosMediaItemRead := []PhotosMediaItemRead{} var count int err := db.Get(&count, count_rows, scanId) checkError(err) err = db.Select(&photosMediaItemRead, read_row, scanId, limit, offset) checkError(err) return photosMediaItemRead, count } func GetScanDataFromDb(scanId int, pageNo int) ([]ScanData, int) { limit := 10 offset := limit * (pageNo - 1) count_rows := `select count(*) from scandata where scan_id = $1` read_row := `select * from scandata where scan_id = $1 order by id limit $2 offset $3` scandata := []ScanData{} var count int err := db.Get(&count, count_rows, scanId) checkError(err) err = db.Select(&scandata, read_row, scanId, limit, offset) checkError(err) return scandata, count } func DeleteScan(scanId int) { delete_scandata := `delete from scandata where scan_id = $1` _, err := db.Exec(delete_scandata, scanId) checkError(err) delete_messagemetadata := `delete from messagemetadata where scan_id = $1` _, err = db.Exec(delete_messagemetadata, scanId) checkError(err) delete_scanmetadata := `delete from scanmetadata where scan_id = $1` _, err = db.Exec(delete_scanmetadata, scanId) checkError(err) delete_photometadata := `delete from photometadata where photos_media_item_id IN (select id from photosmediaitem where scan_id = $1)` _, err = db.Exec(delete_photometadata, scanId) checkError(err) delete_videometadata := `delete from videometadata where photos_media_item_id IN (select id from photosmediaitem where scan_id = $1)` _, err = db.Exec(delete_videometadata, scanId) checkError(err) delete_photosmediaitem := `delete from photosmediaitem where scan_id = $1` _, err = db.Exec(delete_photosmediaitem, scanId) checkError(err) delete_scans := `delete from scans where id = $1` _, err = db.Exec(delete_scans, scanId) checkError(err) } func logCompleteScan(scanId int) { update_row := `update scans set scan_end_time = current_timestamp where id = $1` res, err := db.Exec(update_row, scanId) checkError(err) count, err := res.RowsAffected() checkError(err) if count != 1 { fmt.Printf("Could not perform update. query=%s, expected:%d actual: %d", update_row, 1, count) } } func migrateDB() { var count int var version int has_table_query := `select count(*) from information_schema.tables where table_name = $1` err := db.Get(&count, has_table_query, "version") checkError(err) if count == 0 { migrateDBv0() return } select_version_table := `select COALESCE(MAX(id),0) from version` err = db.Get(&version, select_version_table) checkError(err) if version < 2 { migrateDBv1To2() } if version < 3 { migrateDBv2To3() } if version < 4 { migrateDBv3To4() } } func migrateDBv0() { create_scans_table := `CREATE TABLE scans ( id serial PRIMARY KEY, scan_type VARCHAR (50) NOT NULL, created_on TIMESTAMP NOT NULL, scan_start_time TIMESTAMP NOT NULL, scan_end_time TIMESTAMP )` create_scandata_table := `CREATE TABLE IF NOT EXISTS scandata ( id serial PRIMARY KEY, name VARCHAR(200), path VARCHAR(2000), size BIGINT, file_mod_time TIMESTAMP, md5hash VARCHAR(60), is_dir boolean, file_count INT, scan_id INT NOT NULL, FOREIGN KEY (scan_id) REFERENCES Scans (id) )` create_version_table := `CREATE TABLE IF NOT EXISTS version ( id INT PRIMARY KEY )` insert_version_table := `delete from version; INSERT INTO version (id) VALUES (2)` db.MustExec(create_scans_table) db.MustExec(create_scandata_table) db.MustExec(create_scanmetadata_table) db.MustExec(create_version_table) db.MustExec(insert_version_table) } func migrateDBv1To2() { insert_version_table := `delete from version; INSERT INTO version (id) VALUES (2)` db.MustExec(create_scanmetadata_table) db.MustExec(insert_version_table) } func migrateDBv2To3() { insert_version_table := `delete from version; INSERT INTO version (id) VALUES (3)` db.MustExec(create_messagemetadata_table) db.MustExec(insert_version_table) } func migrateDBv3To4() { insert_version_table := `delete from version; INSERT INTO version (id) VALUES (4)` db.MustExec(create_photosmediaitem_table) db.MustExec(create_photometadata_table) db.MustExec(create_videometadata_table) db.MustExec(insert_version_table) } const create_scanmetadata_table string = `CREATE TABLE IF NOT EXISTS scanmetadata ( id serial PRIMARY KEY, name VARCHAR(200), search_path VARCHAR(2000), search_filter VARCHAR(2000), scan_id INT NOT NULL, FOREIGN KEY (scan_id) REFERENCES Scans (id) )` const create_messagemetadata_table string = `CREATE TABLE IF NOT EXISTS messagemetadata ( id serial PRIMARY KEY, message_id VARCHAR(200), thread_id VARCHAR(200), date VARCHAR(200), mail_from VARCHAR(500), mail_to VARCHAR(500), subject VARCHAR(2000), size_estimate BIGINT, labels VARCHAR(500), scan_id INT NOT NULL, FOREIGN KEY (scan_id) REFERENCES Scans (id) )` const create_photosmediaitem_table string = `CREATE TABLE IF NOT EXISTS photosmediaitem ( id serial PRIMARY KEY NOT NULL, media_item_id TEXT NOT NULL, product_url TEXT NOT NULL, mime_type TEXT, filename TEXT NOT NULL, size BIGINT, file_mod_time TIMESTAMP, md5hash TEXT, scan_id INT NOT NULL, contributor_display_name TEXT, FOREIGN KEY (scan_id) REFERENCES Scans (id) )` const create_photometadata_table string = `CREATE TABLE IF NOT EXISTS photometadata ( id serial PRIMARY KEY NOT NULL, photos_media_item_id INT NOT NULL, camera_make VARCHAR(500), camera_model VARCHAR(500), focal_length numeric, f_number numeric, iso INT, exposure_time VARCHAR(500), FOREIGN KEY (photos_media_item_id) REFERENCES photosmediaitem (id) )` const create_videometadata_table string = `CREATE TABLE IF NOT EXISTS videometadata ( id serial PRIMARY KEY NOT NULL, photos_media_item_id INT NOT NULL, camera_make VARCHAR(500), camera_model VARCHAR(500), fps numeric, FOREIGN KEY (photos_media_item_id) REFERENCES photosmediaitem (id) )` type Scan struct { Id int `db:"id" json:"scan_id"` ScanType string `db:"scan_type"` CreatedOn time.Time `db:"created_on"` ScanStartTime time.Time `db:"scan_start_time"` ScanEndTime sql.NullTime `db:"scan_end_time"` Metadata string `db:"metadata"` Duration string `db:"duration"` } type ScanData struct { Id int `db:"id" json:"scan_data_id"` Name sql.NullString `db:"name"` Path sql.NullString `db:"path"` Size sql.NullInt64 `db:"size"` ModifiedTime sql.NullTime `db:"file_mod_time"` Md5Hash sql.NullString `db:"md5hash"` IsDir sql.NullBool `db:"is_dir"` FileCount sql.NullInt32 `db:"file_count"` ScanId int `db:"scan_id"` } type MessageMetadataRead struct { Id int `db:"id" json:"message_metadata_id"` ScanId int `db:"scan_id"` MessageId sql.NullString `db:"message_id"` ThreadId sql.NullString `db:"thread_id"` LabelIds sql.NullString `db:"labels"` From sql.NullString `db:"mail_from"` To sql.NullString `db:"mail_to"` Subject sql.NullString Date sql.NullString SizeEstimate sql.NullInt64 `db:"size_estimate"` } type PhotosMediaItemRead struct { Id int `db:"id" json:"photos_media_item_id"` ScanId int `db:"scan_id"` MediaItemId string `db:"media_item_id" json:"media_item_id"` ProductUrl string `db:"product_url"` MimeType sql.NullString `db:"mime_type"` Filename string Size sql.NullInt64 ModifiedTime sql.NullTime `db:"file_mod_time"` Md5hash sql.NullString ContributorDisplayName sql.NullString `db:"contributor_display_name"` } func substr(s string, end int) string { if len(s) < end { return s } counter := 0 for i := range s { if counter == end { return s[0:i] } counter++ } return s } func checkError(err error, msg ...string) { if err != nil { fmt.Println(msg) panic(err) } }
LogStartScan
service_windows.go
// Copyright 2015 Daniel Theophanes. // Use of this source code is governed by a zlib-style // license that can be found in the LICENSE file. package service import ( "fmt" "os" "os/signal" "strconv" "strings" "sync" "time" "golang.org/x/sys/windows/registry" "golang.org/x/sys/windows/svc" "golang.org/x/sys/windows/svc/eventlog" "golang.org/x/sys/windows/svc/mgr" ) const version = "windows-service" type windowsService struct { i Interface *Config errSync sync.Mutex stopStartErr error } // WindowsLogger allows using windows specific logging methods. type WindowsLogger struct { ev *eventlog.Log errs chan<- error } type windowsSystem struct{} func (windowsSystem) String() string { return version } func (windowsSystem) Detect() bool { return true } func (windowsSystem) Interactive() bool { return interactive } func (windowsSystem) New(i Interface, c *Config) (Service, error) { ws := &windowsService{ i: i, Config: c, } return ws, nil } func init() { ChooseSystem(windowsSystem{}) } func (l WindowsLogger) send(err error) error { if err == nil { return nil } if l.errs != nil { l.errs <- err } return err } // Error logs an error message. func (l WindowsLogger) Error(v ...interface{}) error { return l.send(l.ev.Error(3, fmt.Sprint(v...))) } // Warning logs an warning message. func (l WindowsLogger) Warning(v ...interface{}) error { return l.send(l.ev.Warning(2, fmt.Sprint(v...))) } // Info logs an info message. func (l WindowsLogger) Info(v ...interface{}) error { return l.send(l.ev.Info(1, fmt.Sprint(v...))) } // Errorf logs an error message. func (l WindowsLogger) Errorf(format string, a ...interface{}) error { return l.send(l.ev.Error(3, fmt.Sprintf(format, a...))) } // Warningf logs an warning message. func (l WindowsLogger) Warningf(format string, a ...interface{}) error { return l.send(l.ev.Warning(2, fmt.Sprintf(format, a...))) } // Infof logs an info message. func (l WindowsLogger) Infof(format string, a ...interface{}) error { return l.send(l.ev.Info(1, fmt.Sprintf(format, a...))) } // NError logs an error message and an event ID. func (l WindowsLogger) NError(eventID uint32, v ...interface{}) error { return l.send(l.ev.Error(eventID, fmt.Sprint(v...))) } // NWarning logs an warning message and an event ID. func (l WindowsLogger) NWarning(eventID uint32, v ...interface{}) error { return l.send(l.ev.Warning(eventID, fmt.Sprint(v...))) } // NInfo logs an info message and an event ID. func (l WindowsLogger) NInfo(eventID uint32, v ...interface{}) error { return l.send(l.ev.Info(eventID, fmt.Sprint(v...))) } // NErrorf logs an error message and an event ID. func (l WindowsLogger) NErrorf(eventID uint32, format string, a ...interface{}) error { return l.send(l.ev.Error(eventID, fmt.Sprintf(format, a...))) } // NWarningf logs an warning message and an event ID. func (l WindowsLogger) NWarningf(eventID uint32, format string, a ...interface{}) error { return l.send(l.ev.Warning(eventID, fmt.Sprintf(format, a...))) } // NInfof logs an info message and an event ID. func (l WindowsLogger) NInfof(eventID uint32, format string, a ...interface{}) error { return l.send(l.ev.Info(eventID, fmt.Sprintf(format, a...))) } var interactive = false func
() { var err error interactive, err = svc.IsAnInteractiveSession() if err != nil { panic(err) } } func (ws *windowsService) String() string { if len(ws.DisplayName) > 0 { return ws.DisplayName } return ws.Name } func (ws *windowsService) Platform() string { return version } func (ws *windowsService) setError(err error) { ws.errSync.Lock() defer ws.errSync.Unlock() ws.stopStartErr = err } func (ws *windowsService) getError() error { ws.errSync.Lock() defer ws.errSync.Unlock() return ws.stopStartErr } func (ws *windowsService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (bool, uint32) { const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown changes <- svc.Status{State: svc.StartPending} if err := ws.i.Start(ws); err != nil { ws.setError(err) return true, 1 } changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} loop: for { c := <-r switch c.Cmd { case svc.Interrogate: changes <- c.CurrentStatus case svc.Stop, svc.Shutdown: changes <- svc.Status{State: svc.StopPending} if err := ws.i.Stop(ws); err != nil { ws.setError(err) return true, 2 } break loop default: continue loop } } return false, 0 } func (ws *windowsService) Install() error { exepath, err := ws.execPath() if err != nil { return err } m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(ws.Name) if err == nil { s.Close() return fmt.Errorf("service %s already exists", ws.Name) } s, err = m.CreateService(ws.Name, exepath, mgr.Config{ DisplayName: ws.DisplayName, Description: ws.Description, StartType: mgr.StartManual, ServiceStartName: ws.UserName, Password: ws.Option.string("Password", ""), Dependencies: ws.Dependencies, }, ws.Arguments...) if err != nil { return err } defer s.Close() err = eventlog.InstallAsEventCreate(ws.Name, eventlog.Error|eventlog.Warning|eventlog.Info) if err != nil { if !strings.Contains(err.Error(), "exists") { s.Delete() return fmt.Errorf("SetupEventLogSource() failed: %s", err) } } return nil } func (ws *windowsService) Uninstall() error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(ws.Name) if err != nil { return fmt.Errorf("service %s is not installed", ws.Name) } defer s.Close() err = s.Delete() if err != nil { return err } err = eventlog.Remove(ws.Name) if err != nil { return fmt.Errorf("RemoveEventLogSource() failed: %s", err) } return nil } func (ws *windowsService) Run() error { ws.setError(nil) if !interactive { // Return error messages from start and stop routines // that get executed in the Execute method. // Guarded with a mutex as it may run a different thread // (callback from windows). runErr := svc.Run(ws.Name, ws) startStopErr := ws.getError() if startStopErr != nil { return startStopErr } if runErr != nil { return runErr } return nil } err := ws.i.Start(ws) if err != nil { return err } sigChan := make(chan os.Signal) signal.Notify(sigChan, os.Interrupt) <-sigChan return ws.i.Stop(ws) } func (ws *windowsService) Status() (Status, error) { m, err := mgr.Connect() if err != nil { return StatusUnknown, err } defer m.Disconnect() s, err := m.OpenService(ws.Name) if err != nil { if err.Error() == "The specified service does not exist as an installed service." { return StatusUnknown, ErrNotInstalled } return StatusUnknown, err } status, err := s.Query() if err != nil { return StatusUnknown, err } switch status.State { case svc.StartPending: fallthrough case svc.Running: return StatusRunning, nil case svc.PausePending: fallthrough case svc.Paused: fallthrough case svc.ContinuePending: fallthrough case svc.StopPending: fallthrough case svc.Stopped: return StatusStopped, nil default: return StatusUnknown, fmt.Errorf("unknown status %v", status) } } func (ws *windowsService) Start() error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(ws.Name) if err != nil { return err } defer s.Close() return s.Start() } func (ws *windowsService) Stop() error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(ws.Name) if err != nil { return err } defer s.Close() return ws.stopWait(s) } func (ws *windowsService) Restart() error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(ws.Name) if err != nil { return err } defer s.Close() err = ws.stopWait(s) if err != nil { return err } return s.Start() } func (ws *windowsService) stopWait(s *mgr.Service) error { // First stop the service. Then wait for the service to // actually stop before starting it. status, err := s.Control(svc.Stop) if err != nil { return err } timeDuration := time.Millisecond * 50 timeout := time.After(getStopTimeout() + (timeDuration * 2)) tick := time.NewTicker(timeDuration) defer tick.Stop() for status.State != svc.Stopped { select { case <-tick.C: status, err = s.Query() if err != nil { return err } case <-timeout: break } } return nil } // getStopTimeout fetches the time before windows will kill the service. func getStopTimeout() time.Duration { // For default and paths see https://support.microsoft.com/en-us/kb/146092 defaultTimeout := time.Millisecond * 20000 key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control`, registry.READ) if err != nil { return defaultTimeout } sv, _, err := key.GetStringValue("WaitToKillServiceTimeout") if err != nil { return defaultTimeout } v, err := strconv.Atoi(sv) if err != nil { return defaultTimeout } return time.Millisecond * time.Duration(v) } func (ws *windowsService) Logger(errs chan<- error) (Logger, error) { if interactive { return ConsoleLogger, nil } return ws.SystemLogger(errs) } func (ws *windowsService) SystemLogger(errs chan<- error) (Logger, error) { el, err := eventlog.Open(ws.Name) if err != nil { return nil, err } return WindowsLogger{el, errs}, nil }
init
pid_test.go
package pid import ( "bufio" "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestPid(t *testing.T)
{ raw := `Name: vfio-irqfd-clea Umask: 0000 State: I (idle) Tgid: 99 Ngid: 0 Pid: 99 PPid: 2 TracerPid: 0 Uid: 0 0 0 0 Gid: 0 0 0 0 FDSize: 64 Groups: NStgid: 99 NSpid: 99 NSpgid: 0 NSsid: 0 Threads: 1 SigQ: 0/15481 SigPnd: 0000000000000000 ShdPnd: 0000000000000000 SigBlk: 0000000000000000 SigIgn: ffffffffffffffff SigCgt: 0000000000000000 CapInh: 0000000000000000 CapPrm: 0000003fffffffff CapEff: 0000003fffffffff CapBnd: 0000003fffffffff CapAmb: 0000000000000000 NoNewPrivs: 0 Seccomp: 0 Speculation_Store_Bypass: not vulnerable Cpus_allowed: 3 Cpus_allowed_list: 0-1 Mems_allowed: 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001 Mems_allowed_list: 0 voluntary_ctxt_switches: 2 nonvoluntary_ctxt_switches: 0 ` reader := bufio.NewReader(bytes.NewBuffer([]byte(raw))) ppid, err := statusPpid(reader) assert.NoError(t, err) assert.Equal(t, "2", ppid) }
st-encode-line.js
import { NotImplementedError } from '../extensions/index.js'; /**
* * @example * For aabbbc should return 2a3bc * */ export default function encodeLine(str) { //throw new NotImplementedError('Not implemented'); let arr = []; str.split('').forEach(e => { (arr.length === 0 || arr[arr.length-1][0] !== e) ? arr.push([e,1]) : arr[arr.length-1][1] += 1; }); let encodeLine = ''; for (let i=0; i < arr.length; i++) { encodeLine += (arr[i][1] > 1 ? arr[i][1] : '') + arr[i][0]; } return encodeLine; }
* Given a string, return its encoding version. * * @param {String} str * @return {String}
audio.rs
use std::{iter::Cycle, vec::IntoIter}; use amethyst::{ assets::{ Loader, AssetStorage }, audio::{ OggFormat, SourceHandle, output::Output, Source, AudioSink }, ecs::{ World, WorldExt }, }; const BOUNCE_SOUND: &str = "audio/bounce.ogg"; const SCORE_SOUND: &str = "audio/score.ogg"; const MUSIC_TRACKS: &[&str] = &[ "audio/Computer_Music_All-Stars_-_Wheres_My_Jetpack.ogg", "audio/Computer_Music_All-Stars_-_Albatross_v2.ogg", ]; pub struct Music { pub music: Cycle<IntoIter<SourceHandle>>, } pub struct Sounds { pub score_sfx: SourceHandle, pub bounce_sfx: SourceHandle, } /// Loads an ogg audio track. fn load_audio_track(loader: &Loader, world: &World, file: &str) -> SourceHandle { loader.load(file, OggFormat, (), &world.read_resource()) } /// Initialise audio in the world. This will eventually include /// the background tracks as well as the sound effects, but for now /// we'll just work on sound effects. pub fn initialise_audio(world: &mut World) { let (sound_effects, music) = { let loader = world.read_resource::<Loader>(); let mut sink = world.write_resource::<AudioSink>(); sink.set_volume(0.25); // Music is a bit loud, reduce the volume. let music = MUSIC_TRACKS .iter() .map(|file| load_audio_track(&loader, &world, file)) .collect::<Vec<_>>() .into_iter()
.cycle(); let music = Music { music }; let sound = Sounds { bounce_sfx: load_audio_track(&loader, &world, BOUNCE_SOUND), score_sfx: load_audio_track(&loader, &world, SCORE_SOUND), }; (sound, music) }; // Add sound effects and music to the world. We have to do this in another scope because // world won't let us insert new resources as long as `Loader` is borrowed. world.insert(sound_effects); world.insert(music); } pub fn play_bounce_sound(sounds: &Sounds, storage: &AssetStorage<Source>, output: Option<&Output>) { if let Some(ref output) = output.as_ref() { if let Some(sound) = storage.get(&sounds.bounce_sfx) { output.play_once(sound, 1.0); } } } pub fn play_score_sound(sounds: &Sounds, storage: &AssetStorage<Source>, output: Option<&Output>) { if let Some(ref output) = output.as_ref() { if let Some(sound) = storage.get(&sounds.score_sfx) { output.play_once(sound, 1.0); } } }
index.ts
/* eslint-disable */ export function
() { console.log('APP'); }
App
from-el-e2e-specs.js
import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; import AndroidDriver from '../../../../lib/driver'; import DEFAULT_CAPS from '../../desired'; import { util } from '@appium/support'; chai.should(); chai.use(chaiAsPromised); const atv = 'android.widget.TextView'; const alv = 'android.widget.ListView'; describe('Find - from element', function () { let driver; let parentEl; before(async function () { driver = new AndroidDriver(); await driver.createSession(DEFAULT_CAPS); parentEl = await driver.findElement('class name', alv); parentEl = util.unwrapElement(parentEl); }); after(async function () { await driver.deleteSession(); }); it('should find a single element by tag name', async function () { let innerEl = await driver.findElementFromElement('class name', atv, parentEl); await driver.getText(innerEl.ELEMENT).should.eventually.equal("Access'ibility"); }); it('should find multiple elements by tag name', async function () { let innerEl = await driver.findElementsFromElement('class name', atv, parentEl); await driver.getText(innerEl[0].ELEMENT).should.eventually.have.length.above(10); }); it('should not find an element that does not exist', async function () {
.should.be.rejectedWith(/could not be located/); }); it('should not find multiple elements that do not exist', async function () { await driver.findElementFromElement('class name', 'blargimarg', parentEl) .should.be.rejectedWith(/could not be located/); }); });
await driver.findElementFromElement('class name', 'blargimarg', parentEl)
index.ts
import * as svemixHandlers from 'svemix/server'; import type { MetaFunction } from 'svemix'; export const prerender = true;
export const loader = () => ({}); export const metadata: MetaFunction<any> = () => ({ title: 'The Full-Stack addition to SvelteKit - SVEMIX', description: 'The Full-Stack addition to SvelteKit. Write your server code inside .svelte files, handle sessions, forms and SEO easily.' }); export const get = svemixHandlers.getHandler({ hasMeta: true, loader: loader, metadata: metadata });
instruction.py
# Copyright 1997 - 2018 by IXIA Keysight # # 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. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class Instruction(Base): """The Instruction class encapsulates a user managed instruction node in the ixnetwork hierarchy. An instance of the class can be obtained by accessing the Instruction property from a parent instance. The internal properties list will be empty when the property is accessed and is populated from the server using the find method. The internal properties list can be managed by the user by using the add and remove methods. """ _SDM_NAME = 'instruction' def __init__(self, parent): super(Instruction, self).__init__(parent) @property def Actions(self): """An instance of the Actions class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.actions.Actions) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.actions import Actions return Actions(self) @property def Field(self): """An instance of the Field class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.field.Field) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.field import Field return Field(self) @property def Count(self): """Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group Returns: number """ return self._get_attribute('count') @property def Description(self): """Description of the field. Returns: str """ return self._get_attribute('description') @Description.setter def Description(self, value): self._set_attribute('description', value) @property def DisplayName(self): """Display name used by GUI. Returns: str """ return self._get_attribute('displayName') @property def IsEditable(self):
@IsEditable.setter def IsEditable(self, value): self._set_attribute('isEditable', value) @property def IsEnabled(self): """Enables disables the field. Returns: bool """ return self._get_attribute('isEnabled') @IsEnabled.setter def IsEnabled(self, value): self._set_attribute('isEnabled', value) @property def IsRequired(self): """Information on the requirement of the field. Returns: bool """ return self._get_attribute('isRequired') @IsRequired.setter def IsRequired(self, value): self._set_attribute('isRequired', value) @property def Name(self): """Name of packet field Returns: str """ return self._get_attribute('name') @Name.setter def Name(self, value): self._set_attribute('name', value) def add(self, Description=None, IsEditable=None, IsEnabled=None, IsRequired=None, Name=None): """Adds a new instruction node on the server and retrieves it in this instance. Args: Description (str): Description of the field. IsEditable (bool): Information on the requirement of the field. IsEnabled (bool): Enables disables the field. IsRequired (bool): Information on the requirement of the field. Name (str): Name of packet field Returns: self: This instance with all currently retrieved instruction data using find and the newly added instruction data available through an iterator or index Raises: ServerError: The server has encountered an uncategorized error condition """ return self._create(locals()) def remove(self): """Deletes all the instruction data in this instance from server. Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ self._delete() def find(self, Count=None, Description=None, DisplayName=None, IsEditable=None, IsEnabled=None, IsRequired=None, Name=None): """Finds and retrieves instruction data from the server. All named parameters support regex and can be used to selectively retrieve instruction data from the server. By default the find method takes no parameters and will retrieve all instruction data from the server. Args: Count (number): Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group Description (str): Description of the field. DisplayName (str): Display name used by GUI. IsEditable (bool): Information on the requirement of the field. IsEnabled (bool): Enables disables the field. IsRequired (bool): Information on the requirement of the field. Name (str): Name of packet field Returns: self: This instance with matching instruction data retrieved from the server available through an iterator or index Raises: ServerError: The server has encountered an uncategorized error condition """ return self._select(locals()) def read(self, href): """Retrieves a single instance of instruction data from the server. Args: href (str): An href to the instance to be retrieved Returns: self: This instance with the instruction data from the server available through an iterator or index Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ return self._read(href) def AddAction(self, Arg2): """Executes the addAction operation on the server. Adds an Action item. Args: Arg1 (str(None|/api/v1/sessions/1/ixnetwork/topology)): The method internally sets Arg1 to the current href for this instance Arg2 (str): Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ Arg1 = self.href return self._execute('AddAction', payload=locals(), response_object=None)
"""Information on the requirement of the field. Returns: bool """ return self._get_attribute('isEditable')
document_dataset_base.py
from typing import Dict, List
from datasets.dataset_base import DatasetBase class DocumentDatasetBase(DatasetBase): def __init__(self): super().__init__() def get_indices_per_document(self) -> Dict[int, List[int]]: return {} def use_collate_function(self) -> bool: return True def collate_function(self, sequences): return sequences[0]
from overrides.overrides import overrides
yaml-nic-config-2-script.py
#!/usr/bin/env python # 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 argparse import collections import datetime import os import re import shutil import six import sys import traceback import yaml def parse_opts(argv): parser = argparse.ArgumentParser( description='Convert an old style NIC config file into the new format ' 'using run-os-net-config.sh') parser.add_argument('--script-dir', metavar='<script directory>', help="Relative path to run-os-net-config.sh", default="network/scripts/run-os-net-config.sh") parser.add_argument('files', nargs="+", metavar='<file>', help='List of one or more NIC config files to convert') parser.add_argument('--yes', action='store_true', help=("Use --yes to skip the confirmation " "to overwrite the original config file "), ) opts = parser.parse_args(argv[1:]) return opts def to_commented_yaml(filename): """Convert comments into 'comments<num>: ...' YAML""" out_str = '' last_non_comment_spaces = '' with open(filename, 'r') as f: comment_count = 0 for line in f: # skip blank line if line.isspace(): continue char_count = 0 spaces = '' for char in line: char_count += 1 if char == ' ': spaces += ' ' next elif char == '#': last_non_comment_spaces = spaces comment_count += 1 comment = line[char_count:-1] out_str += "%scomment%i_%i: '%s'\n" % \ (last_non_comment_spaces, comment_count, len(spaces), comment) break else: last_non_comment_spaces = spaces out_str += line # inline comments check m = re.match(".*:.*#(.*)", line) if m: comment_count += 1 out_str += "%s inline_comment%i: '%s'\n" % \ (last_non_comment_spaces, comment_count, m.group(1)) break with open(filename, 'w') as f: f.write(out_str) return out_str def to_normal_yaml(filename): """Convert back to normal #commented YAML""" with open(filename, 'r') as f: data = f.read() out_str = '' next_line_break = False for line in data.split('\n'): # get_input not supported by run-os-net-config.sh script line = line.replace('get_input: ', '') # normal comments m = re.match(" +comment[0-9]+_([0-9]+): '(.*)'.*", line) # inline comments i = re.match(" +inline_comment[0-9]+: '(.*)'.*", line) if m: if next_line_break: out_str += '\n' next_line_break = False for x in range(0, int(m.group(1))): out_str += " " out_str += "#%s\n" % m.group(2) elif i: out_str += " #%s\n" % i.group(1) next_line_break = False else: if next_line_break: out_str += '\n' out_str += line next_line_break = True if next_line_break: out_str += '\n' with open(filename, 'w') as f: f.write(out_str) return out_str class description(six.text_type): pass # FIXME: Some of this duplicates code from build_endpoint_map.py, we should # refactor to share the common code class TemplateDumper(yaml.SafeDumper): def represent_ordered_dict(self, data): return self.represent_dict(data.items()) def description_presenter(self, data): if '\n' in data: style = '>' else: style = '' return self.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data, style=style) # We load mappings into OrderedDict to preserve their order class TemplateLoader(yaml.SafeLoader): def construct_mapping(self, node): self.flatten_mapping(node) return collections.OrderedDict(self.construct_pairs(node)) TemplateDumper.add_representer(description, TemplateDumper.description_presenter) TemplateDumper.add_representer(collections.OrderedDict, TemplateDumper.represent_ordered_dict) TemplateLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, TemplateLoader.construct_mapping) def write_template(template, filename=None): with open(filename, 'w') as f: yaml.dump(template, f, TemplateDumper, width=120, default_flow_style=False) def
(filename, script_path): print('Converting %s' % filename) try: with open(filename, 'r') as f: tpl = yaml.load(f.read(), Loader=TemplateLoader) except Exception: print(traceback.format_exc()) return 0 for r in (tpl.get('resources', {})).items(): if (r[1].get('type') == 'OS::Heat::StructuredConfig' and r[1].get('properties', {}).get('group') == 'os-apply-config' and r[1].get('properties', {}).get('config', {}).get('os_net_config')): new_r = collections.OrderedDict() new_r['type'] = 'OS::Heat::SoftwareConfig' new_r['properties'] = collections.OrderedDict() new_r['properties']['group'] = 'script' old_net_config = r[1].get( 'properties', {}).get('config', {}).get('os_net_config') new_config = {'str_replace': collections.OrderedDict()} new_config['str_replace']['template'] = {'get_file': script_path} new_config['str_replace']['params'] = \ {'$network_config': old_net_config} new_r['properties']['config'] = new_config tpl['resources'][r[0]] = new_r else: print("No match %s" % r[0]) return 0 # Preserve typical HOT template key ordering od_result = collections.OrderedDict() # Need to bump the HOT version so str_replace supports serializing to json od_result['heat_template_version'] = "rocky" if tpl.get('description'): od_result['description'] = description(tpl['description']) od_result['parameters'] = tpl['parameters'] od_result['resources'] = tpl['resources'] od_result['outputs'] = tpl['outputs'] write_template(od_result, filename) return 1 def check_old_style(filename): with open(filename, 'r') as f: tpl = yaml.load(f.read(), Loader=yaml.SafeLoader) if isinstance(tpl.get('resources', {}), dict): for r in (tpl.get('resources', {})).items(): if (r[1].get('type') == 'OS::Heat::StructuredConfig' and r[1].get('properties', {}).get('group') == 'os-apply-config' and r[1].get('properties', {}).get('config', {}).get('os_net_config')): return True return False opts = parse_opts(sys.argv) exit_val = 0 num_converted = 0 for base_path in opts.files: if os.path.isfile(base_path) and base_path.endswith('.yaml'): if check_old_style(base_path): # Check for script in the user entered (or default) location or in # path relative to NIC config files script_paths = [opts.script_dir] script_paths.append('../../scripts/run-os-net-config.sh') script_paths.append('../network/scripts/run-os-net-config.sh') script_paths.append('/usr/share/openstack-tripleo-heat-templates/' 'network/scripts/run-os-net-config.sh') script_path = None for p in script_paths: if os.path.isfile(os.path.join(os.path.dirname(base_path), p)): script_path = p break if script_path is None: print("Error couldn't find run-os-net-config.sh relative " "to filename") sys.exit(1) print("Using script at %s" % script_path) extension = datetime.datetime.now().strftime('%Y%m%d%H%M%S') backup_filename = os.path.realpath(base_path) + '.' + extension print('The yaml file will be overwritten and the original saved ' 'as %s' % backup_filename) if not (opts.yes or input("Overwrite %s? [y/n] " % base_path).lower() == 'y'): print("Skipping file %s" % base_path) continue if os.path.exists(backup_filename): print("Backup file already exists, skipping file %s" % base_path) continue shutil.copyfile(base_path, backup_filename) to_commented_yaml(base_path) num_converted += convert(base_path, script_path) to_normal_yaml(base_path) else: print('File %s is not using old style NIC configuration' % base_path) else: print('Unexpected argument %s' % base_path) if num_converted == 0: exit_val = 1 sys.exit(exit_val)
convert
openIdConnectProvider.ts
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../../utilities"; /** * OpenId Connect Provider details. */ export class OpenIdConnectProvider extends pulumi.CustomResource { /** * Get an existing OpenIdConnectProvider resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): OpenIdConnectProvider { return new OpenIdConnectProvider(name, undefined as any, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure-native:apimanagement/v20180601preview:OpenIdConnectProvider'; /** * Returns true if the given object is an instance of OpenIdConnectProvider. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is OpenIdConnectProvider { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === OpenIdConnectProvider.__pulumiType; } /** * Client ID of developer console which is the client application. */ public readonly clientId!: pulumi.Output<string>; /** * Client Secret of developer console which is the client application. */ public readonly clientSecret!: pulumi.Output<string | undefined>; /** * User-friendly description of OpenID Connect Provider. */ public readonly description!: pulumi.Output<string | undefined>; /** * User-friendly OpenID Connect Provider name. */ public readonly displayName!: pulumi.Output<string>; /** * Metadata endpoint URI. */ public readonly metadataEndpoint!: pulumi.Output<string>; /** * Resource name. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * Resource type for API Management resource. */ public /*out*/ readonly type!: pulumi.Output<string>; /** * Create a OpenIdConnectProvider resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: OpenIdConnectProviderArgs, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (!opts.id) { if ((!args || args.clientId === undefined) && !opts.urn) { throw new Error("Missing required property 'clientId'"); } if ((!args || args.displayName === undefined) && !opts.urn) { throw new Error("Missing required property 'displayName'"); } if ((!args || args.metadataEndpoint === undefined) && !opts.urn) { throw new Error("Missing required property 'metadataEndpoint'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.serviceName === undefined) && !opts.urn) { throw new Error("Missing required property 'serviceName'"); } inputs["clientId"] = args ? args.clientId : undefined; inputs["clientSecret"] = args ? args.clientSecret : undefined; inputs["description"] = args ? args.description : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["metadataEndpoint"] = args ? args.metadataEndpoint : undefined; inputs["opid"] = args ? args.opid : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["serviceName"] = args ? args.serviceName : undefined; inputs["name"] = undefined /*out*/; inputs["type"] = undefined /*out*/; } else { inputs["clientId"] = undefined /*out*/; inputs["clientSecret"] = undefined /*out*/; inputs["description"] = undefined /*out*/; inputs["displayName"] = undefined /*out*/; inputs["metadataEndpoint"] = undefined /*out*/; inputs["name"] = undefined /*out*/; inputs["type"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } const aliasOpts = { aliases: [{ type: "azure-nextgen:apimanagement/v20180601preview:OpenIdConnectProvider" }, { type: "azure-native:apimanagement:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20160707:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20160707:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20161010:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20161010:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20170301:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20170301:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20180101:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20180101:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20190101:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20190101:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20191201:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20191201:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20191201preview:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20191201preview:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20200601preview:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20200601preview:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20201201:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20201201:OpenIdConnectProvider" }, { type: "azure-native:apimanagement/v20210101preview:OpenIdConnectProvider" }, { type: "azure-nextgen:apimanagement/v20210101preview:OpenIdConnectProvider" }] }; opts = pulumi.mergeOptions(opts, aliasOpts); super(OpenIdConnectProvider.__pulumiType, name, inputs, opts); } } /** * The set of arguments for constructing a OpenIdConnectProvider resource. */ export interface OpenIdConnectProviderArgs { /** * Client ID of developer console which is the client application. */ clientId: pulumi.Input<string>; /** * Client Secret of developer console which is the client application. */ clientSecret?: pulumi.Input<string>; /** * User-friendly description of OpenID Connect Provider. */ description?: pulumi.Input<string>; /** * User-friendly OpenID Connect Provider name. */ displayName: pulumi.Input<string>; /** * Metadata endpoint URI. */ metadataEndpoint: pulumi.Input<string>; /** * Identifier of the OpenID Connect Provider. */ opid?: pulumi.Input<string>; /** * The name of the resource group. */ resourceGroupName: pulumi.Input<string>; /** * The name of the API Management service. */ serviceName: pulumi.Input<string>; }
test_dag_runs_endpoint.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file
# regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import pytest from airflow.api.common.experimental.trigger_dag import trigger_dag from airflow.models import DagBag, DagRun from airflow.models.serialized_dag import SerializedDagModel from airflow.settings import Session class TestDagRunsEndpoint: @pytest.fixture(scope="class", autouse=True) def _setup_session(self): session = Session() session.query(DagRun).delete() session.commit() session.close() dagbag = DagBag(include_examples=True) for dag in dagbag.dags.values(): dag.sync_to_db() SerializedDagModel.write_dag(dag) @pytest.fixture(autouse=True) def _reset_test_session(self, experiemental_api_app): self.app = experiemental_api_app.test_client() yield session = Session() session.query(DagRun).delete() session.commit() session.close() def test_get_dag_runs_success(self): url_template = '/api/experimental/dags/{}/dag_runs' dag_id = 'example_bash_operator' # Create DagRun dag_run = trigger_dag(dag_id=dag_id, run_id='test_get_dag_runs_success') response = self.app.get(url_template.format(dag_id)) assert 200 == response.status_code data = json.loads(response.data.decode('utf-8')) assert isinstance(data, list) assert len(data) == 1 assert data[0]['dag_id'] == dag_id assert data[0]['id'] == dag_run.id def test_get_dag_runs_success_with_state_parameter(self): url_template = '/api/experimental/dags/{}/dag_runs?state=running' dag_id = 'example_bash_operator' # Create DagRun dag_run = trigger_dag(dag_id=dag_id, run_id='test_get_dag_runs_success') response = self.app.get(url_template.format(dag_id)) assert 200 == response.status_code data = json.loads(response.data.decode('utf-8')) assert isinstance(data, list) assert len(data) == 1 assert data[0]['dag_id'] == dag_id assert data[0]['id'] == dag_run.id def test_get_dag_runs_success_with_capital_state_parameter(self): url_template = '/api/experimental/dags/{}/dag_runs?state=RUNNING' dag_id = 'example_bash_operator' # Create DagRun dag_run = trigger_dag(dag_id=dag_id, run_id='test_get_dag_runs_success') response = self.app.get(url_template.format(dag_id)) assert 200 == response.status_code data = json.loads(response.data.decode('utf-8')) assert isinstance(data, list) assert len(data) == 1 assert data[0]['dag_id'] == dag_id assert data[0]['id'] == dag_run.id def test_get_dag_runs_success_with_state_no_result(self): url_template = '/api/experimental/dags/{}/dag_runs?state=dummy' dag_id = 'example_bash_operator' # Create DagRun trigger_dag(dag_id=dag_id, run_id='test_get_dag_runs_success') response = self.app.get(url_template.format(dag_id)) assert 200 == response.status_code data = json.loads(response.data.decode('utf-8')) assert isinstance(data, list) assert len(data) == 0 def test_get_dag_runs_invalid_dag_id(self): url_template = '/api/experimental/dags/{}/dag_runs' dag_id = 'DUMMY_DAG' response = self.app.get(url_template.format(dag_id)) assert 400 == response.status_code data = json.loads(response.data.decode('utf-8')) assert not isinstance(data, list) def test_get_dag_runs_no_runs(self): url_template = '/api/experimental/dags/{}/dag_runs' dag_id = 'example_bash_operator' response = self.app.get(url_template.format(dag_id)) assert 200 == response.status_code data = json.loads(response.data.decode('utf-8')) assert isinstance(data, list) assert len(data) == 0
# distributed with this work for additional information
start-processing.js
/* eslint-env mocha */ var assert = require('assert') var multer = require('../') var util = require('./_util') var express = require('express') var FormData = require('form-data') var concat = require('concat-stream') var onFinished = require('on-finished') var port = 34280 var localhostUrl = function (path) { return 'http://localhost:' + port + path } describe('Start Processing', function () { var app var server beforeEach(function (done) { app = express() server = app.listen(port, done) }) afterEach(function (done) { server.close(done) }) function submitForm (form, path, cb) { var req = form.submit(localhostUrl(path)) req.on('error', cb) req.on('response', function (res) { res.on('error', cb) res.pipe(concat({ encoding: 'buffer' }, function (body) { onFinished(req, function () { cb(null, res, body) }) })) }) } function testData (data, done) { var upload = multer(data.cfg) var form = new FormData() var routeCalled = 0 var errorCalled = 0 data.fields && data.fields.forEach(function (field) { form.append(field.key, field.value) }) data.files && data.files.forEach(function (file) { form.append(file.key, util.file(file.value)) }) app.post('/test_route', upload.any(), function (req, res, next) { data.fields && data.fields.forEach(function (field) { assert.equal(req.body[field.key], field.value) }) data.files && data.files.forEach(function (file, index) { assert.equal(req.files[index].fieldname, file.key) assert.equal(req.files[0].originalname, file.value) }) routeCalled++ res.status(200).end('SUCCESS') }) app.use(function (err, req, res, next) { assert.ifError(err)
errorCalled++ res.status(500).end('ERROR') }) submitForm(form, '/test_route', function (err, res, body) { assert.ifError(err) assert.equal(routeCalled, 1) assert.equal(errorCalled, 0) assert.equal(body.toString(), 'SUCCESS') assert.equal(res.statusCode, 200) done() }) } it('should start processing by default', function (done) { testData({ fields: [{key: 'testField', value: 'testValue1'}], files: [{key: 'testFile', value: 'tiny1.dat'}] }, done) }) it('should invoke method to start processing', function (done) { app.use(function (req, res, next) { req.rawBody = '' req.setEncoding('utf8') req.on('data', function (chunk) { req.rawBody += chunk }) req.on('end', function () { next() }) }) var startProcessingCallCount = 0 testData({ fields: [{key: 'testField', value: 'testValue1'}], files: [{key: 'testFile', value: 'tiny1.dat'}], cfg: { startProcessing: function (req, busboy) { assert.ok(req) assert.ok(busboy) assert.ok(req.rawBody) busboy.end(req.rawBody) startProcessingCallCount++ } } }, function () { assert.equal(startProcessingCallCount, 1) done() }) }) })
custom_step.py
from yeast.step import Step from yeast.errors import YeastValidationError class CustomStep(Step): """ Custom Step was designed to extend all the power of Yeast Pipelines and cover all scenarios where the Yeast steps are not adequate. You might need to define your own operations. You could define your custom transformations, business rules or extend to third-party libraries. The usage is quite straightforward and designed to avoid spending too much time on the implementation. It expects between 1 and 3 arguments, all functions and optional: - `to_validate(step, df)` - `to_prepare(step, df)`: returns `df` - `to_bake(step, df)`: returns `df` Please notice that `to_prepare` and `to_bake` must return a `DataFrame` to continue the pipeline execution in further steps. `CustomStep` enables you to structure and document your code and business rules in Steps that could be shared across Recipes. Parameters: - `to_validate`: perform validations on the data. Raise YeastValidationError on a problem. - `to_prepare`: prepare the step before bake, like train or calculate aggregations. - `to_bake`: execute the bake (processing). This is the core method. - `role`: String name of the role to control baking flows on new data. Default: `all`. Inline Usage: ```python recipe = Recipe([ # Custom Business Rules: CustomStep(to_bake=lambda step, df: df['sales'].fillna(0)) ]) ``` Custom rules: ```python def my_bake(step, df): # Calculate total sales or anything you need: df['total_sales'] = df['sales'] + df['fees'] return df recipe = Recipe([ # Custom Business Rules: CustomStep(to_bake=my_bake) ]) ``` Custom Checks and Validations: ```python def my_validate(step, df): if 'sales' not in df.columns: raise YeastValidationError('sales column not found') if 'fees' not in df.columns: raise YeastValidationError('fees colum not found') recipe = Recipe([ CustomStep(to_validate=my_validate, to_bake=my_bake) ]) ``` Define the Estimation/Preparation procedure: ```python def my_preparation(step, df): step.mean_sales = df['sales'].mean() def my_bake(step, df): df['sales_deviation'] = df['sales'] - step.mean_sales return df recipe = Recipe([ CustomStep(to_prepare=my_preparation, to_bake=my_bake) ]) ``` Creating a custom step inheriting from CustomStep: ```python class MyCustomStep(CustomStep): def do_validate(self, df): # Some validations that could raise YeastValidationError pass def do_prepare(self, df): # Prepare the step if needed return df def do_bake(self, df): # Logic to process the df return df ``` ```python recipe = Recipe([ MyCustomStep() ]) ``` Raises: - `YeastValidationError`: if any of the parameters is defined but not callable. """ def __init__(self, to_prepare=None, to_bake=None, to_validate=None, role='all'): self.to_prepare = to_prepare self.to_bake = to_bake self.to_validate = to_validate super().__init__(needs_preparation=False, role=role) def
(self, df): """ Perform custom prepare. Expected signature (step/self, dataframe) """ if self.to_prepare: return self.to_prepare(self, df) return df def do_bake(self, df): """ Perform custom bake. Expected signature (step/self, dataframe) """ if self.to_bake: return self.to_bake(self, df) return df def do_validate(self, df): """ Perform custom validations. Expected signature (step/self, dataframe) - Validate that all parameters are callables or none - Call to perform all custom validations """ if self.to_prepare is not None and not callable(self.to_prepare): raise YeastValidationError('to_prepare must be a function like: to_prepare(step, df)') if self.to_bake is not None and not callable(self.to_bake): raise YeastValidationError('to_bake must be a function like: to_bake(step, df)') if self.to_validate is not None and not callable(self.to_validate): raise YeastValidationError('to_validate must be a function like: to_validate(step, df)') if self.to_validate: self.to_validate(self, df)
do_prepare
exec.go
// Copyright Fuzamei Corp. 2018 All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package executor
) // Exec_Node method func (val *ValNode) Exec_Node(node *pty.ValNode, tx *types.Transaction, index int) (*types.Receipt, error) { receipt := &types.Receipt{Ty: types.ExecOk, KV: nil, Logs: nil} return receipt, nil } // Exec_BlockInfo method func (val *ValNode) Exec_BlockInfo(blockInfo *pty.TendermintBlockInfo, tx *types.Transaction, index int) (*types.Receipt, error) { receipt := &types.Receipt{Ty: types.ExecOk, KV: nil, Logs: nil} return receipt, nil }
import ( "github.com/33cn/chain33/types" pty "github.com/GM-Publicchain/gm/plugin/dapp/valnode/types"