/**
             * @description: 脚本定价计划
             */
interface PricePlan {
                /**
                 * @description: 计划名称（默认为 `免费` ）
                 */
                readonly name: string;
                /**
                 * @description: 定价模式，可以是下列值之一：
                 *  - `free`
                 *  - `flatRate`
                 * （默认为 `free` ）
                 */
                readonly mode: "free" | "flatRate";
                /**
                 * @description: 是否处于免费试用期（默认为 `false` ）
                 */
                readonly onFreeTrial: boolean;
            }


/**
             * @description: 消息选项
             */
interface MessageOptions {
                telemetry: boolean;  // TODO： 询问这个键的意义

                /**
                 * @description: 消息数据
                 */
                data: MessageData | object;
            }


/**
             * @description: 消息数据（包括消息标题和消息附件）
             */
interface MessageData {
                /**
                 * @description: 消息标题
                 */
                title: string;

                /**
                 * @description: 存放附件的数组
                 */
                attachments: MessageAttachment[];
            }


/**
             * @description: 消息附件
             */
interface MessageAttachment {
                /**
                 * @description: 附件类型，根据实际需要选择使用。可选值：
                 * - `text` - 文本类型
                 * - `json` - JSON类型
                 * - `image` - 图片类型
                 */
                type: "text" | "json" | "image";

                /**
                 * @description: 附件内容
                 */
                data: string;
            }


() => {
	return (
		<AbsoluteFill
			style={{
				backgroundColor: 'white',
				boxShadow: '0 15px 20px rgba(0, 0, 0, 0.07)',
			}}


(string: string) => {
    const map: { [key: string]: string } = {
        '&': '&',
        '<': '<',
        '>': '>',
        '"': '"',
        "'": ''',
        '`': '`',
        '/': '/',
    };
    const reg = /[&<>"'/`]/gi;
    return string.replace(reg, (match) => map[match]);
}


(match) => map[match]


(lookupObject: any, defaultCase = '_default') =>
    (expression: string) =>
        (lookupObject[expression] || lookupObject[defaultCase])()


(expression: string) =>
        (lookupObject[expression] || lookupObject[defaultCase])()


() => {
  it('should match a snapshot where category undefined and not sidebar', () => {
    expect(shallow(<CategorySection category={undefined} />)).toMatchSnapshot()
  })

  it('should match a snapshot where category is defined and is sidebar', () => {
    expect(shallow(<CategorySection category={appDetailDataStub.data?.category} isSidebar />)).toMatchSnapshot()
  })
}


() => {
    expect(shallow(<CategorySection category={undefined} />)).toMatchSnapshot()
  }


() => {
    expect(shallow(<CategorySection category={appDetailDataStub.data?.category} isSidebar />)).toMatchSnapshot()
  }


() => {
  it('should match a snapshot where desktopIntegrationTypes empty and not sidebar', () => {
    expect(shallow(<DesktopIntegrationSection desktopIntegrationTypes={[]} />)).toMatchSnapshot()
  })

  it('should match a snapshot where desktopIntegrationTypes hasLength and is sidebar', () => {
    expect(
      shallow(
        <DesktopIntegrationSection
          desktopIntegrationTypes={integrationTypesStub.data as DesktopIntegrationTypeModel[]}
          isSidebar
        />,
      ),
    ).toMatchSnapshot()
  })
}


() => {
    expect(shallow(<DesktopIntegrationSection desktopIntegrationTypes={[]} />)).toMatchSnapshot()
  }


() => {
    expect(
      shallow(
        <DesktopIntegrationSection
          desktopIntegrationTypes={integrationTypesStub.data as DesktopIntegrationTypeModel[]}
          isSidebar
        />,
      ),
    ).toMatchSnapshot()
  }


() => {
  it('should match a snapshot where limitToClientIds empty and not sidebar', () => {
    expect(shallow(<PrivateAppSection limitToClientIds={[]} />)).toMatchSnapshot()
  })

  it('should match a snapshot where limitToClientIds hasLength and is sidebar', () => {
    expect(shallow(<PrivateAppSection limitToClientIds={['ID_ONE', 'ID_TWO']} isSidebar />)).toMatchSnapshot()
  })
}


() => {
    expect(shallow(<PrivateAppSection limitToClientIds={[]} />)).toMatchSnapshot()
  }


() => {
    expect(shallow(<PrivateAppSection limitToClientIds={['ID_ONE', 'ID_TWO']} isSidebar />)).toMatchSnapshot()
  }


() => {
  it('should match a snapshot where isDirectApi false and not sidebar', () => {
    expect(shallow(<DirectApiSection isDirectApi={false} />)).toMatchSnapshot()
  })

  it('should match a snapshot where isDirectApi true and is sidebar', () => {
    expect(shallow(<DirectApiSection isDirectApi isSidebar />)).toMatchSnapshot()
  })
}


() => {
    expect(shallow(<DirectApiSection isDirectApi={false} />)).toMatchSnapshot()
  }


() => {
    expect(shallow(<DirectApiSection isDirectApi isSidebar />)).toMatchSnapshot()
  }


() => {
  it('should match a snapshot where isListed false and not sidebar', () => {
    expect(shallow(<StatusSection isListed={false} />)).toMatchSnapshot()
  })

  it('should match a snapshot where isListed true and is sidebar', () => {
    expect(shallow(<StatusSection isListed isSidebar />)).toMatchSnapshot()
  })
}


() => {
    expect(shallow(<StatusSection isListed={false} />)).toMatchSnapshot()
  }


() => {
    expect(shallow(<StatusSection isListed isSidebar />)).toMatchSnapshot()
  }


() => {
  it('should match a snapshot', () => {
    expect(shallow(<BackToAppsSection onClick={jest.fn()} />)).toMatchSnapshot()
  })

  it('should respond to a button click', () => {
    const onClick = jest.fn()
    const button = shallow(<BackToAppsSection onClick={onClick} />)
      .find(Button)
      .first()

    button.simulate('click')
    expect(onClick).toHaveBeenCalledTimes(1)
  })
}


() => {
    expect(shallow(<BackToAppsSection onClick={jest.fn()} />)).toMatchSnapshot()
  }


() => {
    const onClick = jest.fn()
    const button = shallow(<BackToAppsSection onClick={onClick} />)
      .find(Button)
      .first()

    button.simulate('click')
    expect(onClick).toHaveBeenCalledTimes(1)
  }


() => {
  it('should match a snapshot', () => {
    expect(shallow(<ListingPreviewSection onClick={jest.fn()} isSidebar />)).toMatchSnapshot()
  })

  it('should respond to a link click', () => {
    const onClick = jest.fn()
    const link = mount(<ListingPreviewSection onClick={onClick} />)
      .find('a')
      .first()

    link.simulate('click')
    expect(onClick).toHaveBeenCalledTimes(1)
  })
}


() => {
    expect(shallow(<ListingPreviewSection onClick={jest.fn()} isSidebar />)).toMatchSnapshot()
  }


() => {
    const onClick = jest.fn()
    const link = mount(<ListingPreviewSection onClick={onClick} />)
      .find('a')
      .first()

    link.simulate('click')
    expect(onClick).toHaveBeenCalledTimes(1)
  }


() => {
  it('should match a snapshot where authFlow is CLIENT_SECRET and not sidebar', () => {
    expect(
      shallow(<AuthenticationSection authFlow="CLIENT_SECRET" id="SOME_ID" externalId="SOME_ID" />),
    ).toMatchSnapshot()
  })

  it('should match a snapshot where authFlow is USER_SESSION sidebar', () => {
    expect(
      shallow(<AuthenticationSection authFlow="USER_SESSION" id="SOME_ID" externalId="SOME_ID" isSidebar />),
    ).toMatchSnapshot()
  })
}


() => {
    expect(
      shallow(<AuthenticationSection authFlow="CLIENT_SECRET" id="SOME_ID" externalId="SOME_ID" />),
    ).toMatchSnapshot()
  }


() => {
    expect(
      shallow(<AuthenticationSection authFlow="USER_SESSION" id="SOME_ID" externalId="SOME_ID" isSidebar />),
    ).toMatchSnapshot()
  }


() => {
  it('should match a snapshot', () => {
    expect(shallow(<SummarySection summary="Lorem ipsum" />)).toMatchSnapshot()
  })
}


() => {
    expect(shallow(<SummarySection summary="Lorem ipsum" />)).toMatchSnapshot()
  }


() => {
  it('should render a table and match a snapshot when has data', () => {
    const wrapper = mount(
      <InstallationsTableSection data={installationsStub.data as InstallationModel[]} columns={[]} />,
    )
    expect(wrapper.find('[data-test="render-installations-table"]').length).toBe(1)
    expect(wrapper).toMatchSnapshot()
  })

  it('should not render a table when has no data', () => {
    const wrapper = mount(<InstallationsTableSection data={[]} columns={[]} />)
    expect(wrapper.find('[data-test="render-installations-table-empty-text"]').length).toBe(1)
    expect(wrapper).toMatchSnapshot()
  })
}


() => {
    const wrapper = mount(
      <InstallationsTableSection data={installationsStub.data as InstallationModel[]} columns={[]} />,
    )
    expect(wrapper.find('[data-test="render-installations-table"]').length).toBe(1)
    expect(wrapper).toMatchSnapshot()
  }


() => {
    const wrapper = mount(<InstallationsTableSection data={[]} columns={[]} />)
    expect(wrapper.find('[data-test="render-installations-table-empty-text"]').length).toBe(1)
    expect(wrapper).toMatchSnapshot()
  }


() => {
  it('should match a snapshot', () => {
    expect(shallow(<DeveloperAboutSection isSidebar />)).toMatchSnapshot()
  })
}


() => {
    expect(shallow(<DeveloperAboutSection isSidebar />)).toMatchSnapshot()
  }


() => {
  it('should match a snapshot where has images', () => {
    expect(
      shallow(
        <AdditionalImagesSection
          images={appDetailDataStub.data?.media as MediaModel[]}
          splitIndex={0}
          numberImages={2}
        />,
      ),
    ).toMatchSnapshot()
  })

  it('should match a snapshot where has no images', () => {
    expect(shallow(<AdditionalImagesSection images={[]} splitIndex={0} numberImages={2} />)).toMatchSnapshot()
  })
}


() => {
    expect(
      shallow(
        <AdditionalImagesSection
          images={appDetailDataStub.data?.media as MediaModel[]}
          splitIndex={0}
          numberImages={2}
        />,
      ),
    ).toMatchSnapshot()
  }


() => {
    expect(shallow(<AdditionalImagesSection images={[]} splitIndex={0} numberImages={2} />)).toMatchSnapshot()
  }


() => {
  it('should match a snapshot where has permissions', () => {
    expect(
      shallow(<PermissionsSection permissions={appDetailDataStub.data?.scopes as ScopeModel[]} />),
    ).toMatchSnapshot()
  })

  it('should match a snapshot where has no permissions', () => {
    expect(shallow(<PermissionsSection permissions={[]} />)).toMatchSnapshot()
  })
}


() => {
    expect(
      shallow(<PermissionsSection permissions={appDetailDataStub.data?.scopes as ScopeModel[]} />),
    ).toMatchSnapshot()
  }


() => {
    expect(shallow(<PermissionsSection permissions={[]} />)).toMatchSnapshot()
  }


() => {
  it('should match a snapshot', () => {
    expect(shallow(<DescriptionSection description="Lorem ipsum" />)).toMatchSnapshot()
  })
}


() => {
    expect(shallow(<DescriptionSection description="Lorem ipsum" />)).toMatchSnapshot()
  }


@Module({
  imports: [RenderModule, CacheModule, ConfigModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}


(authClient) => {
  _authClient = authClient;
}


() => _authClient


(appState) => {
  if (isClient) {
    console.log({redirect: appState.targetUrl})

    window.history.replaceState(
      {},
      document.title,
      appState && appState.targetUrl
        ? appState.targetUrl
        : window.location.pathname
    );
  }
}


({ children }) => {
  const dispatch = useDispatch();
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState();
  const [auth0Client, setAuth0] = useState(null);
  const [loading, setLoading] = useState(true);
  const [popupOpen, setPopupOpen] = useState(false);

  useEffect(() => {
    const initAuth0 = async () => {
      // @ts-ignore
      const auth0FromHook = await createAuth0Client(auth0Config);
      setAuth0(auth0FromHook);
      if (window.location.search.includes("code=")) {
        const { appState } = await auth0FromHook.handleRedirectCallback();
        onRedirectCallback(appState);
      }

      const isAuthenticated = await auth0FromHook.isAuthenticated();

      setIsAuthenticated(isAuthenticated);

      if (isAuthenticated) {
        const user = await auth0FromHook.getUser();
        setUser(user);
      }

      setLoading(false);
    };
    initAuth0().then(console.log).catch(console.error);
  }, []);

  const loginWithPopup = async (params = {}) => {
    setPopupOpen(true);
    try {
      await auth0Client.loginWithPopup(params);
    } catch (error) {
      console.error(error);
    } finally {
      setPopupOpen(false);
    }
    const user = await auth0Client.getUser();
    setUser(user);
    setIsAuthenticated(true);

    return user;
  };
  const logout = (...p) => auth0Client.logout(...p);
  const getIdTokenClaims = (...p) => auth0Client.getIdTokenClaims(...p);
  const loginWithRedirect = (...p) => auth0Client.loginWithRedirect(...p);
  const getTokenSilently = (...p) => auth0Client.getTokenSilently(...p);
  const getTokenWithPopup = (...p) => auth0Client.getTokenWithPopup(...p);

  const handleRedirectCallback = async () => {
    setLoading(true);
    await auth0Client.handleRedirectCallback();
    const user = await auth0Client.getUser();
    setLoading(false);
    setIsAuthenticated(true);
    setUser(user);
  };

  useEffect(() => {
    if (auth0Client) {
      setAuthClient({ ...auth0Client, loginWithPopup, logout });
    }
  }, [auth0Client]);
  useEffect(() => {
    if (user) {
      dispatch(userReceived(user).setMeta({ record: true }));
      auth0Client?.getTokenSilently().then((token) => {
        localStorage.setItem("token", token);
      });
    }
  }, [user]);

  return (
    <AuthContext.Provider
      value={{
        isAuthenticated,
        user,
        loading,
        popupOpen,
        loginWithPopup,
        handleRedirectCallback,
        getIdTokenClaims,
        loginWithRedirect,
        getTokenSilently,
        getTokenWithPopup,
        logout,
      }}


() => {
    const initAuth0 = async () => {
      // @ts-ignore
      const auth0FromHook = await createAuth0Client(auth0Config);
      setAuth0(auth0FromHook);
      if (window.location.search.includes("code=")) {
        const { appState } = await auth0FromHook.handleRedirectCallback();
        onRedirectCallback(appState);
      }

      const isAuthenticated = await auth0FromHook.isAuthenticated();

      setIsAuthenticated(isAuthenticated);

      if (isAuthenticated) {
        const user = await auth0FromHook.getUser();
        setUser(user);
      }

      setLoading(false);
    };
    initAuth0().then(console.log).catch(console.error);
  }


async () => {
      // @ts-ignore
      const auth0FromHook = await createAuth0Client(auth0Config);
      setAuth0(auth0FromHook);
      if (window.location.search.includes("code=")) {
        const { appState } = await auth0FromHook.handleRedirectCallback();
        onRedirectCallback(appState);
      }

      const isAuthenticated = await auth0FromHook.isAuthenticated();

      setIsAuthenticated(isAuthenticated);

      if (isAuthenticated) {
        const user = await auth0FromHook.getUser();
        setUser(user);
      }

      setLoading(false);
    }


async (params = {}) => {
    setPopupOpen(true);
    try {
      await auth0Client.loginWithPopup(params);
    } catch (error) {
      console.error(error);
    } finally {
      setPopupOpen(false);
    }
    const user = await auth0Client.getUser();
    setUser(user);
    setIsAuthenticated(true);

    return user;
  }


(...p) => auth0Client.logout(...p)


(...p) => auth0Client.getIdTokenClaims(...p)


(...p) => auth0Client.loginWithRedirect(...p)


(...p) => auth0Client.getTokenSilently(...p)


(...p) => auth0Client.getTokenWithPopup(...p)


async () => {
    setLoading(true);
    await auth0Client.handleRedirectCallback();
    const user = await auth0Client.getUser();
    setLoading(false);
    setIsAuthenticated(true);
    setUser(user);
  }


() => {
    if (auth0Client) {
      setAuthClient({ ...auth0Client, loginWithPopup, logout });
    }
  }


() => {
    if (user) {
      dispatch(userReceived(user).setMeta({ record: true }));
      auth0Client?.getTokenSilently().then((token) => {
        localStorage.setItem("token", token);
      });
    }
  }


(token) => {
        localStorage.setItem("token", token);
      }


declare function asDiagram(arg: string): Function;


function project(): any[] {
      throw 'error';
    }


() => {
    const e1 =    hot('--1-----3--5-------|');
    const e1subs =    '^                  !';
    const e2 =   cold('x-x-x|              ', {x: 10});
    const expected =  '--x-x-x-y-yz-z-z---|';
    const values = {x: 10, y: 30, z: 50};

    const result = e1.pipe(switchMap(x => e2.pipe(map(i => i * +x))));

    expectObservable(result).toBe(expected, values);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


x => e2.pipe(map(i => i * +x))


i => i * +x


() => {
    const results: Array<number[]> = [];

    of(1, 2, 3).pipe(
      switchMap(
        x => of(x, x + 1, x + 2),
        (a, b, i, ii) => [a, b, i, ii]
      )
    )
    .subscribe({
      next (value) {
        results.push(value);
      },
      error(err) {
        throw err;
      },
      complete() {
        expect(results).to.deep.equal([
          [1, 1, 0, 0],
          [1, 2, 0, 1],
          [1, 3, 0, 2],
          [2, 2, 1, 0],
          [2, 3, 1, 1],
          [2, 4, 1, 2],
          [3, 3, 2, 0],
          [3, 4, 2, 1],
          [3, 5, 2, 2],
        ]);
      }
    });
  }


x => of(x, x + 1, x + 2)


(a, b, i, ii) => [a, b, i, ii]


() => {
    const results: number[] = [];

    of(1, 2, 3).pipe(
      switchMap(
        x => of(x, x + 1, x + 2),
        void 0
      )
    )
    .subscribe({
      next (value) {
        results.push(value);
      },
      error(err) {
        throw err;
      },
      complete() {
        expect(results).to.deep.equal([
          1, 2, 3, 2, 3, 4, 3, 4, 5
        ]);
      }
    });
  }


() => {
    const unsubbed: string[] = [];

    of('a', 'b').pipe(
      switchMap(x =>
        new Observable<string>((subscriber) => {
          subscriber.complete();
          return () => {
            unsubbed.push(x);
          };
        })
      )
    ).subscribe();

    expect(unsubbed).to.deep.equal(['a', 'b']);
  }


x =>
        new Observable<string>((subscriber) => {
          subscriber.complete();
          return () => {
            unsubbed.push(x);
          };
        })


(subscriber) => {
          subscriber.complete();
          return () => {
            unsubbed.push(x);
          };
        }


() => {
            unsubbed.push(x);
          }


() => {
    const x =   cold(         '--a--b--c--d--e--|           ');
    const xsubs =    '         ^         !                  ';
    const y =   cold(                   '---f---g---h---i--|');
    const ysubs =    '                   ^                 !';
    const e1 =   hot('---------x---------y---------|        ');
    const e1subs =   '^                            !        ';
    const expected = '-----------a--b--c----f---g---h---i--|';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


value => observableLookup[value]


() => {
    const e1 =   hot('-------x-----y---|');
    const e1subs =   '^      !          ';
    const expected = '-------#          ';
    function project(): any[] {
      throw 'error';
    }

    expectObservable(e1.pipe(switchMap(project))).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x =   cold(         '--a--b--c--d--e--|           ');
    const xsubs =    '         ^         !                  ';
    const y =   cold(                   '---f---g---h---i--|');
    const ysubs =    '                   ^ !                ';
    const e1 =   hot('---------x---------y---------|        ');
    const e1subs =   '^                    !                ';
    const unsub =    '                     !                ';
    const expected = '-----------a--b--c----                ';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result, unsub).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x =   cold(         '--a--b--c--d--e--|           ');
    const xsubs =    '         ^         !                  ';
    const y =   cold(                   '---f---g---h---i--|');
    const ysubs =    '                   ^ !                ';
    const e1 =   hot('---------x---------y---------|        ');
    const e1subs =   '^                    !                ';
    const expected = '-----------a--b--c----                ';
    const unsub =    '                     !                ';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(
      mergeMap(x => of(x)),
      switchMap(value => observableLookup[value]),
      mergeMap(x => of(x)),
    );

    expectObservable(result, unsub).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


x => of(x)


() => {
    const x =   cold(         '--a--b--c--d--e--|           ');
    const xsubs =    '         ^         !                  ';
    const y =   cold(                   '---f---g---h---i--|');
    const ysubs =    '                   ^ !                ';
    const e1 =   hot('---------x---------y---------|        ');
    const e1subs =   '^                    !                ';
    const expected = '-----------a--b--c----                ';
    const unsub =    '                     !                ';

    const observableLookup = { x: x, y: y };

    // This test is the same as the previous test, but the observable is
    // manipulated to make it look like an interop observable - an observable
    // from a foreign library. Interop subscribers are treated differently:
    // they are wrapped in a safe subscriber. This test ensures that
    // unsubscriptions are chained all the way to the interop subscriber.

    const result = e1.pipe(
      mergeMap(x => of(x)),
      switchMap(value => asInteropObservable(observableLookup[value])),
      mergeMap(x => of(x)),
    );

    expectObservable(result, unsub).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


value => asInteropObservable(observableLookup[value])


() => {
    const sideEffects: number[] = [];
    const synchronousObservable = concat(
      defer(() => {
        sideEffects.push(1);
        return of(1);
      }),
      defer(() => {
        sideEffects.push(2);
        return of(2);
      }),
      defer(() => {
        sideEffects.push(3);
        return of(3);
      })
    );

    of(null).pipe(
      switchMap(() => synchronousObservable),
      takeWhile((x) => x != 2) // unsubscribe at the second side-effect
    ).subscribe(() => { /* noop */ });

    expect(sideEffects).to.deep.equal([1, 2]);
  }


() => {
        sideEffects.push(1);
        return of(1);
      }


() => {
        sideEffects.push(2);
        return of(2);
      }


() => {
        sideEffects.push(3);
        return of(3);
      }


() => synchronousObservable


(x) => x != 2


() => { /* noop */ }


() => {
    const x =   cold(         '--a--b--c--d--e--|          ');
    const xsubs =    '         ^         !                 ';
    const y =   cold(                   '---f---g---h---i--');
    const ysubs =    '                   ^                 ';
    const e1 =   hot('---------x---------y---------|       ');
    const e1subs =   '^                            !       ';
    const expected = '-----------a--b--c----f---g---h---i--';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x =   cold(         '--a--b--c--d--e--|   ');
    const xsubs =    '         (^!)                 ';
    const y =   cold(         '---f---g---h---i--|  ');
    const ysubs =    '         ^                 !  ';
    const e1 =   hot('---------(xy)----------------|');
    const e1subs =   '^                            !';
    const expected = '------------f---g---h---i----|';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x =   cold(         '--a--b--#--d--e--|          ');
    const xsubs =    '         ^       !                   ';
    const y =   cold(                   '---f---g---h---i--');
    const ysubs: string[] = [];
    const e1 =   hot('---------x---------y---------|       ');
    const e1subs =   '^                !                   ';
    const expected = '-----------a--b--#                   ';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x =    hot('-----a--b--c--d--e--|                 ');
    const xsubs =    '         ^         !                  ';
    const y =    hot('--p-o-o-p-------------f---g---h---i--|');
    const ysubs =    '                   ^                 !';
    const e1 =   hot('---------x---------y---------|        ');
    const e1subs =   '^                            !        ';
    const expected = '-----------c--d--e----f---g---h---i--|';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x = cold('|');
    const y = cold('|');
    const xsubs =    '         (^!)                 ';
    const ysubs =    '                   (^!)       ';
    const e1 =   hot('---------x---------y---------|');
    const e1subs =   '^                            !';
    const expected = '-----------------------------|';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x = cold('|');
    const y = cold('-');
    const xsubs =    '         (^!)                 ';
    const ysubs =    '                   ^          ';
    const e1 =   hot('---------x---------y---------|');
    const e1subs =   '^                            !';
    const expected = '------------------------------';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x = cold('-');
    const y = cold('|');
    const xsubs =    '         ^         !          ';
    const ysubs =    '                   (^!)       ';
    const e1 =   hot('---------x---------y---------|');
    const e1subs =   '^                            !';
    const expected = '-----------------------------|';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x = cold('-');
    const y = cold('#', null, 'sad');
    const xsubs =    '         ^         !          ';
    const ysubs =    '                   (^!)       ';
    const e1 =   hot('---------x---------y---------|');
    const e1subs =   '^                  !          ';
    const expected = '-------------------#          ';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected, undefined, 'sad');
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x = cold('|');
    const y = cold('#', null, 'sad');
    const xsubs =    '         (^!)                 ';
    const ysubs =    '                   (^!)       ';
    const e1 =   hot('---------x---------y---------|');
    const e1subs =   '^                  !          ';
    const expected = '-------------------#          ';

    const observableLookup = { x: x, y: y };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected, undefined, 'sad');
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(y.subscriptions).toBe(ysubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const e1 =  cold('|');
    const e1subs =   '(^!)';
    const expected = '|';

    const result = e1.pipe(switchMap(value => of(value)));

    expectObservable(result).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


value => of(value)


() => {
    const e1 =  cold('-');
    const e1subs =   '^';
    const expected = '-';

    const result = e1.pipe(switchMap(value => of(value)));

    expectObservable(result).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const e1 =  cold('#');
    const e1subs =   '(^!)';
    const expected = '#';

    const result = e1.pipe(switchMap(value => of(value)));

    expectObservable(result).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


() => {
    const x =   cold(         '--a--b--c--d--e--|');
    const xsubs =    '         ^         !       ';
    const e1 =   hot('---------x---------#       ');
    const e1subs =   '^                  !       ';
    const expected = '-----------a--b--c-#       ';

    const observableLookup = { x: x };

    const result = e1.pipe(switchMap(value => observableLookup[value]));

    expectObservable(result).toBe(expected);
    expectSubscriptions(x.subscriptions).toBe(xsubs);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  }


next (value) {
        results.push(value);
      }


error(err) {
        throw err;
      }


complete() {
        expect(results).to.deep.equal([
          [1, 1, 0, 0],
          [1, 2, 0, 1],
          [1, 3, 0, 2],
          [2, 2, 1, 0],
          [2, 3, 1, 1],
          [2, 4, 1, 2],
          [3, 3, 2, 0],
          [3, 4, 2, 1],
          [3, 5, 2, 2],
        ]);
      }


complete() {
        expect(results).to.deep.equal([
          1, 2, 3, 2, 3, 4, 3, 4, 5
        ]);
      }


export function CreateAccountAction({ onCreateAccount }: CreateAccountActionProps) {
  return (
    <Box pt="base" pb="loose" px="loose">
      <Button onClick={() => onCreateAccount()}>Create an account</Button>
    </Box>
  );
}


() => onCreateAccount()


interface CreateAccountActionProps {
  onCreateAccount(): void;
}


()=> {
	const duration  = writable(0);
  const { subscribe, set, update } = duration
	return {
		subscribe,
		setTime: (h: number, m: number, s: number, ms: number = 0) => set(((h*60 + m) * 60 + s) * 1000 + ms),
    reset: () => set(0),
	};
}


(h: number, m: number, s: number, ms: number = 0) => set(((h*60 + m) * 60 + s) * 1000 + ms)


() => set(0)


()=> {
  const duration  = writable(0);
  const { subscribe, set, update } = duration
  const hms = derived(duration, $d => toHMS($d))

  return {
    subscribe,
    pause: () => set(0),
    resume: () => set(0),
    elapsed: () => {}
  };
}


$d => toHMS($d)


function reInitPins() {
    pin = new GpioStandard(GpioPins.GPIO01, PinMode.OUT, PinState.LOW);
}


async () => {
    const led = new LedComponent(pin);
    expect(led.isDisposed).toBeFalsy();

    await led.dispose();
    expect(led.isDisposed).toBeTruthy();

    await led.dispose();  // Again for coverage.
}


async () => {
    reInitPins();
    const led = new LedComponent(pin);
    await led.begin();
    await led.dispose();

    const err = new ObjectDisposedException('LedComponent');
    await expect(led.begin()).rejects.toThrow(err);
}


async () => {
    reInitPins();
    let led = new LedComponent(pin);
    await led.begin();
    expect(led.isOn).toBeFalsy();

    await led.turnOn();
    expect(led.isOn).toBeTruthy();

    await led.turnOff();
    expect(led.isOff).toBeTruthy();

    await led.toggle();
    expect(led.isOn).toBeTruthy();

    await led.toggle();
    expect(led.isOff).toBeTruthy();

    pin.mode = PinMode.IN;
    const invOpErr = new InvalidOperationException('Pin is not configured as an output.');
    await expect(led.turnOn()).rejects.toThrow(invOpErr);
    await expect(led.turnOff()).rejects.toThrow(invOpErr);

    pin.mode = PinMode.OUT;
    const err = new ObjectDisposedException('LedComponent');
    await led.dispose();
    await expect(led.turnOn()).rejects.toThrow(err);
    await expect(led.turnOff()).rejects.toThrow(err);
}


async () => {
    reInitPins();
    const led = new LedComponent(pin);
    await led.begin();
    await led.pulse(3);

    const err = new ObjectDisposedException('LedComponent');
    await led.dispose();
    await expect(led.pulse(3)).rejects.toThrow(err);
}


async () => {
    reInitPins();
    const led = new LedComponent(pin);
    await led.begin();

    await led.blink(3, 120);
    await led.blink(3, 0);

    const err = new ObjectDisposedException('LedComponent');
    await led.dispose();
    await expect(led.blink(1, 1)).rejects.toThrow(err);
}


async () => {
    reInitPins();
    const led = new LedComponent(pin);
    await led.begin();
    const event = led.addStateChangeEventListener((evt: LightStateChangeEvent) => {
        expect(evt.isOn).toBeTruthy();
    });

    await led.turnOn();
}


(evt: LightStateChangeEvent) => {
        expect(evt.isOn).toBeTruthy();
    }


/**
 * Returns an effect that, if evaluated, will return the cached result of
 * this effect. Cached results will expire after `timeToLive` duration.
 *
 * @dataFirst cached_
 */
export function cached(ttl: number, __trace?: string) {
  return <R, E, A>(fa: Effect<R, E, A>) => cached_(fa, ttl)
}


/**
 * Returns an effect that, if evaluated, will return the cached result of
 * this effect. Cached results will expire after `timeToLive` duration.
 */
export function cached_<R, E, A>(
  fa: Effect<R, E, A>,
  ttl: number,
  __trace?: string
): RIO<R & Has<Clock>, IO<E, A>> {
  return pipe(
    cachedInvalidate_(fa, ttl, __trace),
    map(([cachedEffect, _]) => cachedEffect)
  )
}


<R, E, A>(fa: Effect<R, E, A>) => cached_(fa, ttl)


([cachedEffect, _]) => cachedEffect


({
  optionValues,
  createOptionValue,
  updateOptionValue,
  deleteOptionValue,
}) => {
  const valueRows = optionValues.map((value, index) => (
    <OptionValueEdit
      key={index}
      value={value}
      onChange={updateOptionValue}
      onDelete={deleteOptionValue}
    />
  ))

  return (
    <Paper className="paper-box" elevation={1}>
      <div className="blue-title" style={{ padding: "20px 30px" }}


(value, index) => (
    <OptionValueEdit
      key={index}


() => {
    let wrapper: ShallowWrapper<any, Readonly<{}>, React.Component<{}, {}, any>>;

    afterEach(() => {
        wrapper && wrapper.unmount();
    });

    it('should change input value after change props', () => {
        wrapper = shallow(<DatePicker
            format='MMM D, YYYY'
            value={ null }
            onValueChange={ () => { } }
        />, {});

        wrapper.setProps({ value: '2017-01-22' });
        expect(wrapper.state('inputValue')).toEqual('Jan 22, 2017');
        expect(wrapper.state('selectedDate')).toEqual('2017-01-22');
    }


() => {
        wrapper = shallow(<DatePicker
            format='MMM D, YYYY'
            value={ null }
            onValueChange={ () => { } }


() => {
        let newState: any = {};
        wrapper = shallow(<DatePicker
            value={ null }
            onValueChange={ (nV: any) => newState = nV }


() => {
        let baseValue = '2019-10-47';
        let newState: any = { inputValue: baseValue, value: baseValue };
        wrapper = shallow(<DatePicker
            value={ baseValue }
            onValueChange={ (nV: any) => newState.value = nV }


() => {
        let testValue = '2019-10-10';
        const inputFormat = 'DD-MM-YYYY';
        const inputTestValue = toCustomDateFormat(testValue, inputFormat);
        const displayedTestDate = dayjs(testValue);

        const onValueChangeSpy = jest.fn((nV: any) => null);
        const setStateSpy = jest.fn((nextState) => null);

        const pickerSetState = DatePicker.prototype.setState;
        DatePicker.prototype.setState = setStateSpy;

        wrapper = shallow(<DatePicker
            value={ null }
            onValueChange={ onValueChangeSpy }
            format={ inputFormat }
        />, {});
        const instance: any = wrapper.instance();

        instance.setSelectedDate(testValue);

        expect(onValueChangeSpy).toHaveBeenLastCalledWith(testValue);
        expect(setStateSpy).toHaveBeenLastCalledWith({
            inputValue: inputTestValue,
            selectedDate: testValue,
        });

        DatePicker.prototype.setState = pickerSetState;
    }


() => {
        let newValue = '2019-09-10';
        const defaultFormat = 'MMM D, YYYY';

        wrapper = shallow(<DatePicker
            value={ '' }
            onValueChange={ () => {} }


() => {
        let baseValue = '10-10-2019';
        const defaultFormat = 'DD-MM-YYYY';

        const onValueChangeSpy = jest.fn((nV: any) => null);
        const setStateSpy = jest.fn((nextState) => null);

        const pickerSetState = DatePicker.prototype.setState;
        DatePicker.prototype.setState = setStateSpy;

        wrapper = shallow(<DatePicker
            value={ null }
            onValueChange={ onValueChangeSpy }
            format={ defaultFormat }
        />, {});
        const instance: any = wrapper.instance();

        instance.handleInputChange(baseValue);

        expect(onValueChangeSpy).toHaveBeenLastCalledWith(toValueDateFormat(baseValue, defaultFormat));

        DatePicker.prototype.setState = pickerSetState;
    }


() => {
        const defaultFormat = 'DD-MM-YYYY';

        wrapper = shallow(<DatePicker
            value={ null }
            onValueChange={ () => { } }


() => {
        const defaultFormat = 'DD-MM-YYYY';
        let baseValue = '2019-10-10';

        wrapper = shallow(<DatePicker
            value={ baseValue }
            onValueChange={ () => { } }


export default function Message({
  showAttachments = true,
  message,
  children,
  mobileView,
  reverse,
  itemableProvider: Itemable,
  scrollable,
  ...rest
}: MessageProps) {
  const [editing, setEditing] = useState(false);
  const [hovered, setHovered] = useState(false);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const keepActionsVisible = ({ isOpen }) => {
    setIsDropdownOpen(isOpen);
  };
  if (isOnlyEmojis(message.body)) {
    return (
      <StyledMessageEmoji className={classNames('message mt-2', {})}>
        <span>{message.body}</span>
      </StyledMessageEmoji>
    );
  }

  return (
    <>
      <StyledMessage
        className="message mt-1 position-relative"
        onMouseEnter={() => setHovered(true)}


() => import('./MessageAttachments')


() => import('./MessageReactions')


({ reverse }) => (reverse ? '#dbeafd' : '#f1f2f3')


({ isOpen }) => {
    setIsDropdownOpen(isOpen);
  }


(attachment) => ({
                      ...attachment,
                      author: message.messager,
                    })


classNames('message mt-2', {})


moment(message


editing ? (
              <MessageForm
                {...rest}
                attachments={message.attachments}
                message={message}
                onDismiss={() => setEditing


static fromArray(array: (number | bigint | string)[]): StcSangvis {
        return new StcSangvis(array[0] as number,
                              array[1] as string,
                              array[2] as string,
                              array[3] as string,
                              array[4] as string,
                              array[5] as string,
                              array[6] as string,
                              array[7] as string,
                              array[8] as number,
                              array[9] as number,
                              array[10] as string,
                              array[11] as number,
                              array[12] as number,
                              array[13] as string,
                              array[14] as number,
                              array[15] as number,
                              array[16] as number,
                              array[17] as number,
                              array[18] as number,
                              array[19] as number,
                              array[20] as number,
                              array[21] as number,
                              array[22] as string,
                              array[23] as string,
                              array[24] as string,
                              array[25] as number,
                              array[26] as number,
                              array[27] as number,
                              array[28] as number,
                              array[29] as number,
                              array[30] as number,
                              array[31] as number,
                              array[32] as number,
                              array[33] as number,
                              array[34] as number,
                              array[35] as number,
                              array[36] as number,
                              array[37] as number,
                              array[38] as number,
                              array[39] as number,
                              array[40] as number,
                              array[41] as number,
                              array[42] as number,
                              array[43] as number,
                              array[44] as number,
                              array[45] as number,
                              array[46] as string,
                              array[47] as string,
                              array[48] as string,
                              array[49] as string,
                              array[50] as number,
                              array[51] as number,
                              array[52] as number,
                              array[53] as string,
                              array[54] as string,
                              array[55] as number,
                              array[56] as string,
                              array[57] as string,
                              array[58] as number,
                              array[59] as number)
    }


export class PlayDate {
    date: Date;

    constructor(date: Date) {
        this.date = date;
    }
}


async function initStore(store) {
    store.dispatch(initBasicStore() as any)
}


async function initHighlights(store) {
    await store.dispatch(sidebarActs.setAnnotationsManager(annotationsManager))
    rootStore.dispatch(fetchAnnotationsForPageUrl(false, true) as any)
}


(material) => {
                super.set(material.Name, data[material.Name] ?? 0);
            }


(material) => {
                super.set(material.Name, 0);
            }


(name) => {
            const material = Server.Get().Registry.MaterialRegistry.get(name);
            if (material == undefined) {
                data.push({ success: false, name: name, quantity: -1, material: null, error: MAT_NOT_FOUND });
            } else {
                const quantity = this.get(material.Name);
                data.push({ success: true, name: material.Name, quantity: quantity || 0, material: material });
            }
        }


(amount, name) => {
            const Material = Server.Get().Registry.MaterialRegistry.get(name)!;
            total += (new SellableDecorator(Material).PriceData.cost || 0) * amount;
        }


(acc, val, key) => acc + (Client.Reg.ResolveMaterialFromName(key)?.Weight ?? 0) * val


(i) => 10 ** 1.9 - Math.abs(centralRarity - i.GetMaterialRarity() ** 1.8)


(val) =>
                val.Cost != undefined &&
                val.TechLevel <= maxTech &&
                val.TechLevel >= minTech &&
                val.GetMaterialRarity() <= maxRarity &&
                val.GetMaterialRarity() >= minRarity


(val) => maxRarity - minRarity - Math.abs(centralRarity - val.GetMaterialRarity()) + 1


export class MaterialCollection extends GameCollectionBase {
    public static WEIGHTS?: number[] = [];

    public constructor(options?: IMaterialCollectionOptions) {
        super();
        //Create map with all empty material values, but set defined materials to the given value.
        if (options?.data) {
            let data: any;
            if (options.data instanceof Map) data = Object.fromEntries(options.data);
            else data = options.data;

            Server.Get().Registry.MaterialRegistry.forEach((material) => {
                super.set(material.Name, data[material.Name] ?? 0);
            });
        } else {
            Server.Get().Registry.MaterialRegistry.forEach((material) => {
                super.set(material.Name, 0);
            });
        }
    }
    /**@deprecated*/
    public DataFromName(name: string): IMaterialQuantity {
        const material = Server.Get().Registry.MaterialRegistry.get(name);
        if (material == undefined)
            return { success: false, name: name, quantity: -1, material: null, error: MAT_NOT_FOUND };

        const quantity = this.get(material.Name);
        return { success: true, name: material.Name, quantity: quantity || 0, material: material };
    }
    /**@deprecated*/
    public DataFromNames(names: string[]): IMaterialQuantity[] {
        let data = new Array<IMaterialQuantity>();
        names.forEach((name) => {
            const material = Server.Get().Registry.MaterialRegistry.get(name);
            if (material == undefined) {
                data.push({ success: false, name: name, quantity: -1, material: null, error: MAT_NOT_FOUND });
            } else {
                const quantity = this.get(material.Name);
                data.push({ success: true, name: material.Name, quantity: quantity || 0, material: material });
            }
        });
        return data;
    }
    /**@deprecated*/
    public DataFromMaterial(material: Material): IMaterialQuantity {
        const quantity = this.get(material.Name);
        if (quantity == undefined) {
            return { success: false, name: material.Name, quantity: -1, material: null, error: MAT_NOT_FOUND };
        }
        return { success: true, name: material.Name, quantity: quantity || 0, material: material };
    }

    public GetCollectionValue(): number {
        let total = 0;
        this.forEach((amount, name) => {
            const Material = Server.Get().Registry.MaterialRegistry.get(name)!;
            total += (new SellableDecorator(Material).PriceData.cost || 0) * amount;
        });
        return total;
    }

    /**
     * Gets the size of the collection (the sum of all the weights)
     * @override
     */
    public get CollectionSize(): number {
        return ~~this.reduce((acc, val, key) => acc + (Client.Reg.ResolveMaterialFromName(key)?.Weight ?? 0) * val, 0);
    }

    public static GenerateMineableCollection(value: number, central = 0): MaterialCollection {
        const Template = Array.from(Server.Get().Registry.MineableMaterialRegistry.values());
        if (Template.length == 0) {
            throw new Error("No Mineable Materials");
        }
        const weights = this.GenerateMiningWeights(Template, central);
        const flatArray: Material[] = [];
        for (let i = 0; i < Template.length; ++i) for (let j = 0; j < weights[i]; ++j) flatArray.push(Template[i]);

        const MineableCollection = new MaterialCollection();
        let currentPrice = 0;
        do {
            const Selected = util.chooseFrom<Material>(Template);
            const Material = new SellableDecorator(Selected.item);
            const ExistingAmount = MineableCollection.get(Selected.item.Name) ?? 0;
            MineableCollection.set(Selected.item.Name, ExistingAmount + 1);
            currentPrice += Material.PriceData.cost ?? 0;
        } while (currentPrice < value);
        return MineableCollection;
    }

    private static GenerateMiningWeights(items: Material[], centralRarity: number): number[] {
        if (this.WEIGHTS?.length == items.length) {
            return this.WEIGHTS;
        }
        const weights = items.map((i) => 10 ** 1.9 - Math.abs(centralRarity - i.GetMaterialRarity() ** 1.8));
        this.WEIGHTS = weights;
        return this.WEIGHTS;
    }

    public static RefreshMiningWeightCache() {
        this.WEIGHTS = [];
    }

    /** @override */
    public GetCompatibleItems({
        minRarity,
        maxRarity,
        minTech,
        maxTech,
    }: ICompatible): MapCollection<string, Material> {
        return Server.Reg.MaterialRegistry.filter(
            (val) =>
                val.Cost != undefined &&
                val.TechLevel <= maxTech &&
                val.TechLevel >= minTech &&
                val.GetMaterialRarity() <= maxRarity &&
                val.GetMaterialRarity() >= minRarity
        );
    }

    /** @override */
    public GenerateWeights(items: Material[], centralRarity: number, minRarity: number, maxRarity: number): number[] {
        return items.map((val) => maxRarity - minRarity - Math.abs(centralRarity - val.GetMaterialRarity()) + 1);
    }
}


export interface IMaterialCollectionOptions {
    data?: Map<string, number>;
}


interface IMaterialQuantity {
    success: boolean;
    name: string;
    quantity: number;
    material: Material | null;
    error?: string;
}


/**@deprecated*/
public DataFromName(name: string): IMaterialQuantity {
        const material = Server.Get().Registry.MaterialRegistry.get(name);
        if (material == undefined)
            return { success: false, name: name, quantity: -1, material: null, error: MAT_NOT_FOUND };

        const quantity = this.get(material.Name);
        return { success: true, name: material.Name, quantity: quantity || 0, material: material };
    }


/**@deprecated*/
public DataFromNames(names: string[]): IMaterialQuantity[] {
        let data = new Array<IMaterialQuantity>();
        names.forEach((name) => {
            const material = Server.Get().Registry.MaterialRegistry.get(name);
            if (material == undefined) {
                data.push({ success: false, name: name, quantity: -1, material: null, error: MAT_NOT_FOUND });
            } else {
                const quantity = this.get(material.Name);
                data.push({ success: true, name: material.Name, quantity: quantity || 0, material: material });
            }
        });
        return data;
    }


/**@deprecated*/
public DataFromMaterial(material: Material): IMaterialQuantity {
        const quantity = this.get(material.Name);
        if (quantity == undefined) {
            return { success: false, name: material.Name, quantity: -1, material: null, error: MAT_NOT_FOUND };
        }
        return { success: true, name: material.Name, quantity: quantity || 0, material: material };
    }


public GetCollectionValue(): number {
        let total = 0;
        this.forEach((amount, name) => {
            const Material = Server.Get().Registry.MaterialRegistry.get(name)!;
            total += (new SellableDecorator(Material).PriceData.cost || 0) * amount;
        });
        return total;
    }


public static GenerateMineableCollection(value: number, central = 0): MaterialCollection {
        const Template = Array.from(Server.Get().Registry.MineableMaterialRegistry.values());
        if (Template.length == 0) {
            throw new Error("No Mineable Materials");
        }
        const weights = this.GenerateMiningWeights(Template, central);
        const flatArray: Material[] = [];
        for (let i = 0; i < Template.length; ++i) for (let j = 0; j < weights[i]; ++j) flatArray.push(Template[i]);

        const MineableCollection = new MaterialCollection();
        let currentPrice = 0;
        do {
            const Selected = util.chooseFrom<Material>(Template);
            const Material = new SellableDecorator(Selected.item);
            const ExistingAmount = MineableCollection.get(Selected.item.Name) ?? 0;
            MineableCollection.set(Selected.item.Name, ExistingAmount + 1);
            currentPrice += Material.PriceData.cost ?? 0;
        } while (currentPrice < value);
        return MineableCollection;
    }


private static GenerateMiningWeights(items: Material[], centralRarity: number): number[] {
        if (this.WEIGHTS?.length == items.length) {
            return this.WEIGHTS;
        }
        const weights = items.map((i) => 10 ** 1.9 - Math.abs(centralRarity - i.GetMaterialRarity() ** 1.8));
        this.WEIGHTS = weights;
        return this.WEIGHTS;
    }


public static RefreshMiningWeightCache() {
        this.WEIGHTS = [];
    }


/** @override */
public GetCompatibleItems({
        minRarity,
        maxRarity,
        minTech,
        maxTech,
    }: ICompatible): MapCollection<string, Material> {
        return Server.Reg.MaterialRegistry.filter(
            (val) =>
                val.Cost != undefined &&
                val.TechLevel <= maxTech &&
                val.TechLevel >= minTech &&
                val.GetMaterialRarity() <= maxRarity &&
                val.GetMaterialRarity() >= minRarity
        );
    }


/** @override */
public GenerateWeights(items: Material[], centralRarity: number, minRarity: number, maxRarity: number): number[] {
        return items.map((val) => maxRarity - minRarity - Math.abs(centralRarity - val.GetMaterialRarity()) + 1);
    }


export class InterceptorContext {
  readonly url: string;
  readonly method: HttpMethod;
  readonly headers: HttpHeaders;

  constructor(context: InterceptorContextInit) {
    this.url = context.url;
    this.method = context.method;
    this.headers = new HttpHeaders(context.headers);
  }
}


export class RequestInterceptorContext extends InterceptorContext {
  constructor(context: InterceptorContextInit) {
    super(context);
  }
}


export class ResponseInterceptorContext<T = unknown> extends InterceptorContext {
  readonly status: HttpStatusCode;
  readonly data: T;
  readonly ok: boolean;

  constructor(context: ResponseInterceptorInit<T>) {
    super(context);

    this.status = context.status;
    this.data = context.data;
    this.ok = this.is2xx();
  }

  is2xx(): boolean {
    return this.status >= 200 && this.status <= 299;
  }

  is3xx(): boolean {
    return this.status >= 300 && this.status <= 399;
  }

  is4xx(): boolean {
    return this.status >= 400 && this.status <= 499;
  }

  is5xx(): boolean {
    return this.status >= 500 && this.status <= 599;
  }
}


interface InterceptorContextInit {
  readonly url: string;
  readonly method: HttpMethod;
  readonly headers: HttpHeaders;
}


interface ResponseInterceptorInit<T> extends InterceptorContextInit {
  status: HttpStatusCode;
  data: T;
}


is2xx(): boolean {
    return this.status >= 200 && this.status <= 299;
  }


is3xx(): boolean {
    return this.status >= 300 && this.status <= 399;
  }


is4xx(): boolean {
    return this.status >= 400 && this.status <= 499;
  }


is5xx(): boolean {
    return this.status >= 500 && this.status <= 599;
  }


({ description, members, tags }: Props) => {
  const { locale } = useContext(LanguageContext);
  const { t } = useTranslation();

  const link = ({ mark: { href }, children }) => (
    <CommonLink href={href}>{children}</CommonLink>


({ mark: { href }, children }) => (
    <CommonLink href={href}>{children}</CommonLink>


(member, index) => (
          <Fragment key={member._id}>
            <a
              className


(tag, index) => (
          <div key={index}


type Props = {
  description: any;
  members: any[];
  tags: string[];
};


t('createdBy')


export declare class LayoutReplacer {
    private tokens;
    private timezoneOffset;
    constructor(tokens: TokensHandlers, timezoneOffset: number);
    /**
     *
     * @param loggingEvent
     * @param specifier
     * @returns {any}
     */
    categoryName: (loggingEvent: LogEvent, specifier: string) => string;
    /**
     *
     * @param loggingEvent
     * @param specifier
     * @returns {any}
     */
    formatAsDate: (loggingEvent: LogEvent, specifier: string) => string;
    /**
     *
     * @returns {string}
     */
    hostname: () => string;
    /**
     *
     * @param loggingEvent
     * @returns {any}
     */
    formatMessage: (loggingEvent: LogEvent) => string;
    /**
     *
     * @returns {string|string}
     */
    endOfLine: () => string;
    /**
     *
     * @param loggingEvent
     * @returns {string}
     */
    logLevel: (loggingEvent: LogEvent) => string;
    /**
     *
     * @param loggingEvent
     * @returns {any}
     */
    startTime: (loggingEvent: LogEvent) => string;
    /**
     *
     * @param loggingEvent
     * @returns {string}
     */
    startColour: (loggingEvent: LogEvent) => string;
    /**
     *
     * @param loggingEvent
     * @returns {string}
     */
    endColour: (loggingEvent: LogEvent) => string;
    /**
     *
     * @returns {string}
     */
    percent: () => string;
    /**
     *
     * @param loggingEvent
     * @returns {string}
     */
    pid: (loggingEvent?: LogEvent | undefined) => string;
    /**
     *
     * @param loggingEvent
     * @param specifier
     * @returns {any}
     */
    clusterInfo: (loggingEvent: LogEvent, specifier: string) => string;
    /**
     *
     * @param loggingEvent
     * @param specifier
     * @returns {any}
     */
    userDefined: (loggingEvent: LogEvent, specifier: string) => any;
    build(): IReplacers;
}


build(): IReplacers;


c => errors.set(c.id, c)


export class Set implements ISet {
    private constructor(
        readonly id:        string,
        readonly name:      string,
        readonly index:     number,
        readonly cells:     ICell[]
    ) { }

    static create(board: IBoard, name: string, index: number): ISet {
        const id = `${board.id}-${name}`;
        const cells:ICell[] = [];

        return new Set(id, name, index, cells);
    }

    validate(): ISetValidationResult {
        const result : { valid: boolean, errors: ICell[] } = { valid: true, errors: [] };
        const values: Map<number, ICell[]> = new Map();

        for (const cell of this.cells) {
            let value = cell.getValue();
            if (value === 0) {
                continue;
            }

            let existing = values.get(value);
            if (existing === undefined) {
                existing = [];
                values.set(value, existing)
            }
            existing.push(cell);
        }

        for (const v of values.values()) {
            if (v.length > 1) {
                result.errors = result.errors.concat(v);
            }
        }

        return result;
    }

    static validateAll(...sets: ISet[]): ISetValidationResult {
        let valid = true;
        const errors: Map<string, ICell> = new Map();

        for (let set of sets) {
            let result = set.validate();
            if (!result.valid) {
                valid = false;
                result.errors.forEach(c => errors.set(c.id, c));
            }
        }

        return { valid : valid, errors : Array.from(errors.values()) };
    }
}


/* Data structure for validating uniqueness of cell members in a group such as a row, column, or box. It is not a
 * primary model in the sense that it does not require its own event store -- it's more in line of being a sub-component.
 *
 * Despite being named a set, it is not intended to prohibit non-distinct values from existing within it. Instead,
 * duplicate values should trigger an invalid state along with a reference to all non-unique cells.
 * */
export interface ISet {
    id:         string;
    name:       string;
    index:      number;
    cells:      ICell[];
    validate:   () => ISetValidationResult;
}


export interface ISetValidationResult {
    valid:      boolean;
    errors?:    ICell[];
}


static create(board: IBoard, name: string, index: number): ISet {
        const id = `${board.id}-${name}`;
        const cells:ICell[] = [];

        return new Set(id, name, index, cells);
    }


validate(): ISetValidationResult {
        const result : { valid: boolean, errors: ICell[] } = { valid: true, errors: [] };
        const values: Map<number, ICell[]> = new Map();

        for (const cell of this.cells) {
            let value = cell.getValue();
            if (value === 0) {
                continue;
            }

            let existing = values.get(value);
            if (existing === undefined) {
                existing = [];
                values.set(value, existing)
            }
            existing.push(cell);
        }

        for (const v of values.values()) {
            if (v.length > 1) {
                result.errors = result.errors.concat(v);
            }
        }

        return result;
    }


static validateAll(...sets: ISet[]): ISetValidationResult {
        let valid = true;
        const errors: Map<string, ICell> = new Map();

        for (let set of sets) {
            let result = set.validate();
            if (!result.valid) {
                valid = false;
                result.errors.forEach(c => errors.set(c.id, c));
            }
        }

        return { valid : valid, errors : Array.from(errors.values()) };
    }


export function App({ Component, pageProps }: AppProps): JSX.Element {
  return (
    <StrictMode>
      <AuthenticationProvider session={pageProps.session}>
        <Component {...pageProps} />
      </AuthenticationProvider>
    </StrictMode>
  )
}


@NgModule({
    imports: [
        FormsModule,
        ThemeModule,
        NbCardModule,
        NbUserModule,
        NbButtonModule,
        NbTabsetModule,
        NbActionsModule,
        NbRadioModule,
        NbSelectModule,
        NbListModule,
        NbIconModule,
        NbButtonModule,
        NgxEchartsModule,
    ],
    declarations: [
        DashboardComponent,
        StatusCardComponent,
        TemperatureDraggerComponent,
        ContactsComponent,
        RoomSelectorComponent,
        TemperatureComponent,
        RoomsComponent,
        KittenComponent,
        SecurityCamerasComponent,
        ElectricityComponent,
        ElectricityChartComponent,
        WeatherComponent,
        PlayerComponent,
        SolarComponent,
        TrafficComponent,
        TrafficChartComponent,
    ],
    exports: [
        StatusCardComponent
    ]
})
export class DashboardModule { }


(c, i) => {
            this.companies.push({ id: i, name: c });
        }


@Component({
    selector: 'tags-custom-example',
    templateUrl: './tags-custom-example.component.html',
    styleUrls: ['./tags-custom-example.component.scss']
})
export class TagsCustomExampleComponent implements OnInit {

    selectedCompanies;
    companies: any[] = [];
    companiesNames = ['Uber', 'Microsoft', 'Flexigen'];

    ngOnInit() {
        this.companiesNames.forEach((c, i) => {
            this.companies.push({ id: i, name: c });
        });
    }

    addTagFn(name) {
        return { name: name, tag: true };
    }
}


ngOnInit() {
        this.companiesNames.forEach((c, i) => {
            this.companies.push({ id: i, name: c });
        });
    }


addTagFn(name) {
        return { name: name, tag: true };
    }


export default class CityBuildingLayer extends BaseLayer {
  public type: string = 'PolygonLayer';
  public buildModels() {
    this.layerModel = new CityBuildModel(this);
    this.models = this.layerModel.buildModels();
  }
  public setLight(t: number) {
    this.updateLayerConfig({
      time: t,
    });
  }
  protected getConfigSchema() {
    return {
      properties: {
        opacity: {
          type: 'number',
          minimum: 0,
          maximum: 1,
        },
      },
    };
  }

  protected getModelType(): string {
    return 'citybuilding';
  }
}


public buildModels() {
    this.layerModel = new CityBuildModel(this);
    this.models = this.layerModel.buildModels();
  }


public setLight(t: number) {
    this.updateLayerConfig({
      time: t,
    });
  }


protected getConfigSchema() {
    return {
      properties: {
        opacity: {
          type: 'number',
          minimum: 0,
          maximum: 1,
        },
      },
    };
  }


protected getModelType(): string {
    return 'citybuilding';
  }


() => {
            // Nothing to see here.
        }


class Builder implements OperatorBuilder<Cons> {
    create($: ExtensionEnv): Operator<Cons> {
        return new Op($);
    }
}


/**
 * a * (b * c) => (a * b) * c
 */
class Op extends Function2<U, BCons<Sym, U, U>> implements Operator<Cons> {
    readonly name = 'mul_2_any_mul_2_any_any';
    constructor($: ExtensionEnv) {
        super(MATH_MUL, is_any, and(is_cons, is_mul_2_any_any), $, () => {
            // Nothing to see here.
        });
    }
    transform2(opr: Sym, lhs: U, rhs: BCons<Sym, U, U>, orig: BCons<Sym, U, BCons<Sym, U, U>>): [boolean, U] {
        const $ = this.$;
        if ($.isAssocL(MATH_MUL)) {
            const a = lhs;
            const b = rhs.lhs;
            const c = rhs.rhs;
            const ab = makeList(opr, a, b);
            return [true, makeList(rhs.opr, ab, c)];
        }
        return [false, orig];
    }
}


create($: ExtensionEnv): Operator<Cons> {
        return new Op($);
    }


transform2(opr: Sym, lhs: U, rhs: BCons<Sym, U, U>, orig: BCons<Sym, U, BCons<Sym, U, U>>): [boolean, U] {
        const $ = this.$;
        if ($.isAssocL(MATH_MUL)) {
            const a = lhs;
            const b = rhs.lhs;
            const c = rhs.rhs;
            const ab = makeList(opr, a, b);
            return [true, makeList(rhs.opr, ab, c)];
        }
        return [false, orig];
    }


() => {
  jest.resetModules()
}


() => {
  mockedAthenaClientClass.isConfigSufficient.mockReturnValue(true)
  app = appWithAllRoutes({})
}


() => {
  jest.resetAllMocks()
}


() => {
  it('renders sample charts', () => {
    mockedS3Client.getObject.mockReturnValue(readFile('data/bar-chart.vg.json', { encoding: 'utf8' }))
    mockedS3Client.selectObjectContent.mockResolvedValue([
      { category: 'X', amount: 10 },
      { category: 'Y', amount: 20 },
      { category: 'Z', amount: 30 },
    ])

    return request(app)
      .get('/')
      .expect('Content-Type', /html/)
      .expect(res => {
        const responseContent = res.text
        expect(responseContent).toContain('Manage My Prison – Behaviour entries')
        expect(responseContent).toContain('with 8 values: A, B, C, D, E, ending with H') // from mocked S3 object for viz 1
        expect(responseContent).toContain('with 3 values: X, Y, Z') // from mocked S3 select for viz 2
        expect(responseContent).toContain('with 9 values: A, B, C, D, E, ending with I') // from unmocked viz 3
      })
  })
}


() => {
    mockedS3Client.getObject.mockReturnValue(readFile('data/bar-chart.vg.json', { encoding: 'utf8' }))
    mockedS3Client.selectObjectContent.mockResolvedValue([
      { category: 'X', amount: 10 },
      { category: 'Y', amount: 20 },
      { category: 'Z', amount: 30 },
    ])

    return request(app)
      .get('/')
      .expect('Content-Type', /html/)
      .expect(res => {
        const responseContent = res.text
        expect(responseContent).toContain('Manage My Prison – Behaviour entries')
        expect(responseContent).toContain('with 8 values: A, B, C, D, E, ending with H') // from mocked S3 object for viz 1
        expect(responseContent).toContain('with 3 values: X, Y, Z') // from mocked S3 select for viz 2
        expect(responseContent).toContain('with 9 values: A, B, C, D, E, ending with I') // from unmocked viz 3
      })
  }


res => {
        const responseContent = res.text
        expect(responseContent).toContain('Manage My Prison – Behaviour entries')
        expect(responseContent).toContain('with 8 values: A, B, C, D, E, ending with H') // from mocked S3 object for viz 1
        expect(responseContent).toContain('with 3 values: X, Y, Z') // from mocked S3 select for viz 2
        expect(responseContent).toContain('with 9 values: A, B, C, D, E, ending with I') // from unmocked viz 3
      }


() => {
  it('renders sample Athena chart', () => {
    mockedAthenaClient.startExecution.mockResolvedValueOnce('11111111-2222-3333-4444-555555555555')
    mockedAthenaClient.executionCompletion.mockResolvedValueOnce(QueryExecutionState.SUCCEEDED)
    mockedAthenaClient.executionResults = async function* results() {
      yield ['date', 'min', 'avg', 'max']
      yield ['2021-07-01', '0.0', '1.0', '23.2']
      yield ['2021-08-01', '1.0', '5.2', '32.0']
      yield ['2021-09-01', '0.0', '4.5', '23.2']
    } as never

    return request(app)
      .get('/athena-sample')
      .expect(res => {
        const responseContent = res.text
        expect(responseContent).toContain('Manage My Prison – Athena Sample')
        expect(responseContent).toContain('Date: Jul 2021; Precipitation: 1')
        expect(responseContent).toContain('Date: Aug 2021; Precipitation: 5.2')
        expect(responseContent).toContain('Date: Sep 2021; Precipitation: 4.5')
      })
  })

  it('presents an error if query fails', () => {
    mockedAthenaClient.startExecution.mockResolvedValueOnce('11111111-2222-3333-4444-555555555555')
    mockedAthenaClient.executionCompletion.mockResolvedValueOnce(QueryExecutionState.FAILED)

    return request(app)
      .get('/athena-sample')
      .use(overrideLoggerForRequest())
      .expect(res => {
        const responseContent = res.text
        expect(responseContent).toContain('Manage My Prison – Error')
        expect(responseContent).toContain('Athena could not execute query: FAILED')
      })
  })
}


() => {
    mockedAthenaClient.startExecution.mockResolvedValueOnce('11111111-2222-3333-4444-555555555555')
    mockedAthenaClient.executionCompletion.mockResolvedValueOnce(QueryExecutionState.SUCCEEDED)
    mockedAthenaClient.executionResults = async function* results() {
      yield ['date', 'min', 'avg', 'max']
      yield ['2021-07-01', '0.0', '1.0', '23.2']
      yield ['2021-08-01', '1.0', '5.2', '32.0']
      yield ['2021-09-01', '0.0', '4.5', '23.2']
    } as never

    return request(app)
      .get('/athena-sample')
      .expect(res => {
        const responseContent = res.text
        expect(responseContent).toContain('Manage My Prison – Athena Sample')
        expect(responseContent).toContain('Date: Jul 2021; Precipitation: 1')
        expect(responseContent).toContain('Date: Aug 2021; Precipitation: 5.2')
        expect(responseContent).toContain('Date: Sep 2021; Precipitation: 4.5')
      })
  }


res => {
        const responseContent = res.text
        expect(responseContent).toContain('Manage My Prison – Athena Sample')
        expect(responseContent).toContain('Date: Jul 2021; Precipitation: 1')
        expect(responseContent).toContain('Date: Aug 2021; Precipitation: 5.2')
        expect(responseContent).toContain('Date: Sep 2021; Precipitation: 4.5')
      }


() => {
    mockedAthenaClient.startExecution.mockResolvedValueOnce('11111111-2222-3333-4444-555555555555')
    mockedAthenaClient.executionCompletion.mockResolvedValueOnce(QueryExecutionState.FAILED)

    return request(app)
      .get('/athena-sample')
      .use(overrideLoggerForRequest())
      .expect(res => {
        const responseContent = res.text
        expect(responseContent).toContain('Manage My Prison – Error')
        expect(responseContent).toContain('Athena could not execute query: FAILED')
      })
  }


res => {
        const responseContent = res.text
        expect(responseContent).toContain('Manage My Prison – Error')
        expect(responseContent).toContain('Athena could not execute query: FAILED')
      }


() => {
  it('redirects to MoJ security guidance', () => {
    return request(app)
      .get('/.well-known/security.txt')
      .redirects(0)
      .expect(302)
      .expect(
        'Location',
        'https://raw.githubusercontent.com/ministryofjustice/security-guidance/main/contact/vulnerability-disclosure-security.txt'
      )
  })
}


() => {
    return request(app)
      .get('/.well-known/security.txt')
      .redirects(0)
      .expect(302)
      .expect(
        'Location',
        'https://raw.githubusercontent.com/ministryofjustice/security-guidance/main/contact/vulnerability-disclosure-security.txt'
      )
  }


class WebpackWorker extends Worker {
        constructor();
    }


(res: Quotes) => {
      this.quotes = res;
    }


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  constructor(private dataService: DataService) {}
  public quotes: Quotes;

  ngOnInit(): void {}

  getQuotes() {
    this.dataService.getQuotesForDay().subscribe((res: Quotes) => {
      this.quotes = res;
    });
  }
}


ngOnInit(): void {}


getQuotes() {
    this.dataService.getQuotesForDay().subscribe((res: Quotes) => {
      this.quotes = res;
    });
  }


() => {
  test('example', () => {
    expect(Hub).toBeDefined();
  });
}


() => {
    expect(Hub).toBeDefined();
  }


export class FirebaseMessaging {
  private constructor();
  deleteToken(token: string): Promise<boolean>;
  getToken(): Promise<string | null>;
  onMessage(
    nextOrObserver: NextFn<object> | Observer<object, Error>,
    error?: (e: Error) => void,
    completed?: () => void
  ): Unsubscribe;
  onTokenRefresh(
    nextOrObserver: NextFn<object> | Observer<object, Error>,
    error?: (e: Error) => void,
    completed?: () => void
  ): Unsubscribe;
  requestPermission(): Promise<void>;
  setBackgroundMessageHandler(callback: (a: object) => Promise<void>): void;
  useServiceWorker(registration: ServiceWorkerRegistration): void;
  usePublicVapidKey(b64PublicKey: string): void;
}


deleteToken(token: string): Promise<boolean>;


getToken(): Promise<string | null>;


onMessage(
    nextOrObserver: NextFn<object> | Observer<object, Error>,
    error?: (e: Error) => void,
    completed?: () => void
  ): Unsubscribe;


onTokenRefresh(
    nextOrObserver: NextFn<object> | Observer<object, Error>,
    error?: (e: Error) => void,
    completed?: () => void
  ): Unsubscribe;


requestPermission(): Promise<void>;


setBackgroundMessageHandler(callback: (a: object) => Promise<void>): void;


useServiceWorker(registration: ServiceWorkerRegistration): void;


usePublicVapidKey(b64PublicKey: string): void;


@Injectable({
  providedIn: 'root'
})
export class AssocommercestatsService {

  constructor(private http: HttpClient) { }

  getAllStats(typeDuree: string): Observable<AssoCommercantStats> {
    const params = new HttpParams().set('typeDuree', typeDuree);
    return this.http.get<AssoCommercantStats>(`${environment.shopdataURL}/assoCommercant/stats`, {params})
  }

}


getAllStats(typeDuree: string): Observable<AssoCommercantStats> {
    const params = new HttpParams().set('typeDuree', typeDuree);
    return this.http.get<AssoCommercantStats>(`${environment.shopdataURL}/assoCommercant/stats`, {params})
  }


export class Utilities {
	public static removeUndefined(obj: any) {
		const res: object = (Object).assign({}, obj);

		for (const key of Object.keys(obj)) {
			if (obj[key] === undefined) {
				delete obj[key];
			}
		}
		return res;
	}

	public static generateQuerySting(queryObject: object) {
		const builder: string[] = [];
		for (const key in queryObject) {
			if (queryObject.hasOwnProperty(key) && !Utilities.isObjectEmpty(queryObject[key])) {
				builder.push(`${key}=${queryObject[key]}`);
			}
		}

		return `${encodeURI(builder.join('&'))}`;
	}

	public static isObjectEmpty(obj: any) {
		if (obj === undefined || obj === null || obj === '') {
			return true;
		}
		return false;
	}
}


public static removeUndefined(obj: any) {
		const res: object = (Object).assign({}, obj);

		for (const key of Object.keys(obj)) {
			if (obj[key] === undefined) {
				delete obj[key];
			}
		}
		return res;
	}


public static generateQuerySting(queryObject: object) {
		const builder: string[] = [];
		for (const key in queryObject) {
			if (queryObject.hasOwnProperty(key) && !Utilities.isObjectEmpty(queryObject[key])) {
				builder.push(`${key}=${queryObject[key]}`);
			}
		}

		return `${encodeURI(builder.join('&'))}`;
	}


public static isObjectEmpty(obj: any) {
		if (obj === undefined || obj === null || obj === '') {
			return true;
		}
		return false;
	}


function printDiffs (
  pkgsDiff: PackageDiff[],
  opts: {
    prefix: string,
  },
) {
  // Sorts by alphabet then by removed/added
  // + ava 0.10.0
  // - chalk 1.0.0
  // + chalk 2.0.0
  pkgsDiff.sort((a, b) => (a.name.localeCompare(b.name) * 10 + (Number(!b.added) - Number(!a.added))))
  const msg = pkgsDiff.map((pkg) => {
    let result = pkg.added
      ? ADDED_CHAR
      : REMOVED_CHAR
    if (!pkg.realName || pkg.name === pkg.realName) {
      result += ` ${pkg.name}`
    } else {
      result += ` ${pkg.name} <- ${pkg.realName}`
    }
    if (pkg.version) {
      result += ` ${chalk.grey(pkg.version)}`
      if (pkg.latest && semver.lt(pkg.version, pkg.latest)) {
        result += ` ${chalk.grey(`(${pkg.latest} is available)`)}`
      }
    }
    if (pkg.deprecated) {
      result += ` ${chalk.red('deprecated')}`
    }
    if (pkg.from) {
      result += ` ${chalk.grey(`<- ${pkg.from && path.relative(opts.prefix, pkg.from) || '???'}`)}`
    }
    return result
  }).join(EOL)
  return msg
}


(
  log$: {
    deprecation: most.Stream<DeprecationLog>,
    summary: most.Stream<SummaryLog>,
    root: most.Stream<RootLog>,
    packageJson: most.Stream<PackageJsonLog>,
  },
  opts: {
    cwd: string,
    pnpmConfigs?: PnpmConfigs,
  },
) => {
  const pkgsDiff$ = getPkgsDiff(log$, { prefix: opts.cwd })

  const summaryLog$ = log$.summary
    .take(1)

  return most.combine(
    (pkgsDiff) => {
      let msg = ''
      for (const depType of ['prod', 'optional', 'peer', 'dev', 'nodeModulesOnly']) {
        const diffs = R.values(pkgsDiff[depType])
        if (diffs.length) {
          msg += EOL
          if (opts.pnpmConfigs && opts.pnpmConfigs.global) {
            msg += chalk.cyanBright(`${opts.cwd}:`)
          } else {
            msg += chalk.cyanBright(`${propertyByDependencyType[depType]}:`)
          }
          msg += EOL
          msg += printDiffs(diffs, { prefix: opts.cwd })
          msg += EOL
        }
      }
      return { msg }
    },
    pkgsDiff$,
    summaryLog$,
  )
  .take(1)
  .map(most.of)
}


(pkgsDiff) => {
      let msg = ''
      for (const depType of ['prod', 'optional', 'peer', 'dev', 'nodeModulesOnly']) {
        const diffs = R.values(pkgsDiff[depType])
        if (diffs.length) {
          msg += EOL
          if (opts.pnpmConfigs && opts.pnpmConfigs.global) {
            msg += chalk.cyanBright(`${opts.cwd}:`)
          } else {
            msg += chalk.cyanBright(`${propertyByDependencyType[depType]}:`)
          }
          msg += EOL
          msg += printDiffs(diffs, { prefix: opts.cwd })
          msg += EOL
        }
      }
      return { msg }
    }


(a, b) => (a.name.localeCompare(b.name) * 10 + (Number(!b.added) - Number(!a.added)))


(pkg) => {
    let result = pkg.added
      ? ADDED_CHAR
      : REMOVED_CHAR
    if (!pkg.realName || pkg.name === pkg.realName) {
      result += ` ${pkg.name}`
    } else {
      result += ` ${pkg.name} <- ${pkg.realName}`
    }
    if (pkg.version) {
      result += ` ${chalk.grey(pkg.version)}`
      if (pkg.latest && semver.lt(pkg.version, pkg.latest)) {
        result += ` ${chalk.grey(`(${pkg.latest} is available)`)}`
      }
    }
    if (pkg.deprecated) {
      result += ` ${chalk.red('deprecated')}`
    }
    if (pkg.from) {
      result += ` ${chalk.grey(`<- ${pkg.from && path.relative(opts.prefix, pkg.from) || '???'}`)}`
    }
    return result
  }


/**
 * Defines websocket state changed event.
 */
export class RpcTransportStateChangedEvent extends Event {

  state: RpcTransportState;

  /**
   * @hidden
   */
  constructor(cancelable: boolean, target: Session, type: string, state: RpcTransportState) {
    super(cancelable, target, type);
    this.state = state;
  }

  /**
   * @hidden
   */
  callDefaultBehavior() {
    // Does nothing.
  }
}


/**
   * @hidden
   */
callDefaultBehavior() {
    // Does nothing.
  }


/**
 * Memory based storage provider for a bot.
 *
 * @remarks
 * This provider is most useful for simulating production storage when running locally against the
 * emulator or as part of a unit test. It has the following characteristics:
 *
 * - Starts off completely empty when the bot is run.
 * - Anything written to the store will be forgotten when the process exits.
 * - Objects that are read and written to the store are cloned to properly simulate network based
 *   storage providers.
 * - Cloned objects are serialized using `JSON.stringify()` to catch any possible serialization
 *   related issues that might occur when using a network based storage provider.
 *
 * ```JavaScript
 * const { MemoryStorage } = require('botbuilder');
 *
 * const storage = new MemoryStorage();
 * ```
 */
export declare class MemoryStorage implements Storage {
    protected memory: {
        [k: string]: string;
    };
    protected etag: number;
    /**
     * Creates a new MemoryStorage instance.
     * @param memory (Optional) memory to use for storing items. By default it will create an empty JSON object `{}`.
     */
    constructor(memory?: {
        [k: string]: string;
    });
    /**
     * Reads storage items from storage.
     * @param keys Keys of the [StoreItems](xref:botbuilder-core.StoreItems) objects to read.
     * @returns The read items.
     */
    read(keys: string[]): Promise<StoreItems>;
    /**
     * Writes storage items to storage.
     * @param changes The [StoreItems](xref:botbuilder-core.StoreItems) to write, indexed by key.
     */
    write(changes: StoreItems): Promise<void>;
    /**
     * Deletes storage items from storage.
     * @param keys Keys of the [StoreItems](xref:botbuilder-core.StoreItems) objects to delete.
     */
    delete(keys: string[]): Promise<void>;
}


/**
     * Reads storage items from storage.
     * @param keys Keys of the [StoreItems](xref:botbuilder-core.StoreItems) objects to read.
     * @returns The read items.
     */
read(keys: string[]): Promise<StoreItems>;


/**
     * Writes storage items to storage.
     * @param changes The [StoreItems](xref:botbuilder-core.StoreItems) to write, indexed by key.
     */
write(changes: StoreItems): Promise<void>;


/**
     * Deletes storage items from storage.
     * @param keys Keys of the [StoreItems](xref:botbuilder-core.StoreItems) objects to delete.
     */
delete(keys: string[]): Promise<void>;


function mapHelper (h1: number, h2: number): string {
    return String(h1) + "," + String(h2)
}


function part2(inpt: inptLine[]) : number {
    let lineMap =  new Map<string, number>();

    for (let line of inpt) {
        if (line.x1 == line.x2) {
            for (let index of range(line.y1, line.y2)){
                lineMap.set(mapHelper(line.x1,index), lineMap.has(mapHelper(line.x1, index)) ? lineMap.get(mapHelper(line.x1, index)) + 1 : 1);
            }
        } else if (line.y1 == line.y2) {
            for (let index of range(line.x1, line.x2)){
                lineMap.set(mapHelper(index, line.y1), lineMap.has(mapHelper(index, line.y1)) ? lineMap.get(mapHelper(index, line.y1)) + 1: 1);
            }
        // Added for part 2
        } else {
            let x_range = range(line.x1, line.x2)
            let y_range = range(line.y1, line.y2)
            for (let index in x_range){
                    lineMap.set(mapHelper(x_range[index], y_range[index]), lineMap.has(mapHelper(x_range[index], y_range[index])) ? lineMap.get(mapHelper(x_range[index], y_range[index])) + 1: 1);
            }
        }
    }

    // console.log(lineMap)
    let counter = 0;
    for (let v of lineMap.values()){
        if (v > 1) {
            counter += 1
        }
    }

    return counter
}


(inputFile: string): inptLine[] => readFileLines(inputFile)
    .map(row => row.match(/\d+/g)).map(result => {return {x1: Number(result[0]), y1: Number(result[1]), x2: Number(result[2]), y2: Number(result[3])}})


row => row.match(/\d+/g)


result => {return {x1: Number(result[0]), y1: Number(result[1]), x2: Number(result[2]), y2: Number(result[3])}}


elem => elem.x1 == elem.x2 || elem.y1 == elem.y2


type inptLine = {
    x1: number;
    x2: number;
    y1: number;
    y2: number;

}


interface Observable<T> {
    skipLast: typeof skipLast;
  }


/**
 * Get a blob endpoint URL from incoming blob or dfs endpoint URLs.
 * Only handle known host name pair patterns, add more patterns into ToBlobEndpointHostMappings in constants.ts.
 *
 * Expected input and outputs:
 * http://account.blob.core.windows.net     - http://account.blob.core.windows.net
 * http://account.dfs.core.windows.net      - http://account.blob.core.windows.net
 * http://127.0.0.1:10000                   - http://127.0.0.1:10000
 * http://account.blob.core.windows.net/abc - http://account.blob.core.windows.net/abc
 * http://account.dfs.core.windows.net/abc  - http://account.blob.core.windows.net/abc
 * http://127.0.0.1:10000/abc               - http://127.0.0.1:10000/abc
 *
 * @param url -
 */
export function toBlobEndpointUrl(url: string): string {
  const urlParsed = URLBuilder.parse(url);

  let host = urlParsed.getHost();
  if (host === undefined) {
    throw RangeError(`toBlobEndpointUrl() parameter url ${url} doesn't include valid host.`);
  }

  for (const mapping of ToBlobEndpointHostMappings) {
    if (host.includes(mapping[0])) {
      host = host.replace(mapping[0], mapping[1]);
      break;
    }
  }

  urlParsed.setHost(host);
  return urlParsed.toString();
}


/**
 * Get a dfs endpoint URL from incoming blob or dfs endpoint URLs.
 * Only handle known host name pair patterns, add more patterns into ToDfsEndpointHostMappings in constants.ts.
 *
 * Expected input and outputs:
 * http://account.blob.core.windows.net     - http://account.dfs.core.windows.net
 * http://account.dfs.core.windows.net      - http://account.dfs.core.windows.net
 * http://127.0.0.1:10000                   - http://127.0.0.1:10000
 * http://account.blob.core.windows.net/abc - http://account.dfs.core.windows.net/abc
 * http://account.dfs.core.windows.net/abc  - http://account.dfs.core.windows.net/abc
 * http://127.0.0.1:10000/abc               - http://127.0.0.1:10000/abc
 *
 * @param url -
 */
export function toDfsEndpointUrl(url: string): string {
  const urlParsed = URLBuilder.parse(url);

  let host = urlParsed.getHost();
  if (host === undefined) {
    throw RangeError(`toDfsEndpointUrl() parameter url ${url} doesn't include valid host.`);
  }

  for (const mapping of ToDfsEndpointHostMappings) {
    if (host.includes(mapping[0])) {
      host = host.replace(mapping[0], mapping[1]);
      break;
    }
  }

  urlParsed.setHost(host);
  return urlParsed.toString();
}


function toFileSystemAsyncIterableIterator(
  iter: AsyncIterableIterator<ServiceListContainersSegmentResponse>
): AsyncIterableIterator<ServiceListFileSystemsSegmentResponse> {
  return {
    async next() {
      const rawResult = await iter.next();
      if (rawResult.value) {
        rawResult.value.fileSystemItems = rawResult.value.containerItems.map(
          (val: ContainerItem): FileSystemItem => {
            return {
              ...val,
              versionId: val.version,
              properties: {
                ...val.properties,
                publicAccess: toPublicAccessType(val.properties.publicAccess)
              }
            };
          }
        );
      }
      return rawResult as any;
    },
    [Symbol.asyncIterator]() {
      return this;
    }
  };
}


export function toFileSystemPagedAsyncIterableIterator(
  iter: PagedAsyncIterableIterator<ContainerItem, ServiceListContainersSegmentResponse>
): PagedAsyncIterableIterator<FileSystemItem, ServiceListFileSystemsSegmentResponse> {
  return {
    async next(): Promise<{ done?: boolean; value: FileSystemItem }> {
      const rawResult = await iter.next();
      const result = rawResult as { done?: boolean; value: FileSystemItem };
      if (result.value) {
        result.value.properties.publicAccess = toPublicAccessType(
          rawResult.value.properties.publicAccess
        );
        result.value.versionId = rawResult.value.version;
      }
      return result;
    },
    [Symbol.asyncIterator](): PagedAsyncIterableIterator<
      FileSystemItem,
      ServiceListFileSystemsSegmentResponse
    > {
      return this;
    },
    byPage(
      settings: PageSettings = {}
    ): AsyncIterableIterator<ServiceListFileSystemsSegmentResponse> {
      return toFileSystemAsyncIterableIterator(iter.byPage(settings));
    }
  };
}


export function toContainerPublicAccessType(
  publicAccessType?: PublicAccessType
): ContainerPublicAccessType | undefined {
  if (!publicAccessType) {
    return undefined;
  }

  switch (publicAccessType) {
    case "filesystem":
      return "container";
    case "file":
      return "blob";
    default:
      throw TypeError(
        `toContainerPublicAccessType() parameter ${publicAccessType} is not recognized.`
      );
  }
}


export function toPublicAccessType(
  containerPublicAccessType?: ContainerPublicAccessType
): PublicAccessType | undefined {
  if (!containerPublicAccessType) {
    return undefined;
  }

  switch (containerPublicAccessType) {
    case "container":
      return "filesystem";
    case "blob":
      return "file";
    default:
      throw TypeError(
        `toPublicAccessType() parameter ${containerPublicAccessType} is not recognized.`
      );
  }
}


export function toProperties(metadata?: Metadata): string | undefined {
  if (metadata === undefined) {
    return undefined;
  }

  const properties = [];
  for (const key in metadata) {
    if (metadata.hasOwnProperty(key)) {
      const value = metadata[key];
      properties.push(`${key}=${base64encode(value)}`);
    }
  }

  return properties.join(",");
}


export function toPathGetAccessControlResponse(
  response: PathGetPropertiesResponse
): PathGetAccessControlResponse {
  return {
    ...response,
    _response: response._response,
    permissions: toPermissions(response.permissions),
    acl: toAcl(response.acl)
  };
}


export function toRolePermissions(
  permissionsString: string,
  allowStickyBit: boolean = false
): RolePermissions {
  const error = new RangeError(
    `toRolePermissions() Invalid role permissions string ${permissionsString}`
  );
  if (permissionsString.length !== 3) {
    throw error;
  }

  permissionsString = permissionsString.toLowerCase();

  let read = false;
  if (permissionsString[0] === "r") {
    read = true;
  } else if (permissionsString[0] !== "-") {
    throw error;
  }

  let write = false;
  if (permissionsString[1] === "w") {
    write = true;
  } else if (permissionsString[1] !== "-") {
    throw error;
  }

  let execute = false;
  if (permissionsString[2] === "x") {
    execute = true;
  } else if (allowStickyBit) {
    if (permissionsString[2] === "t") {
      execute = true;
    } else if (permissionsString[2] !== "-") {
      throw error;
    }
  } else if (permissionsString[2] !== "-") {
    throw error;
  }

  return { read, write, execute };
}


export function toPermissions(permissionsString?: string): PathPermissions | undefined {
  if (permissionsString === undefined || permissionsString === "" || permissionsString === null) {
    return undefined;
  }

  if (permissionsString.length !== 9 && permissionsString.length !== 10) {
    throw RangeError(`toPermissions() Invalid permissions string ${permissionsString}`);
  }

  // Case insensitive
  permissionsString = permissionsString.toLowerCase();

  let stickyBit = false;
  if (permissionsString[8] === "t") {
    stickyBit = true;
  }

  let extendedAcls = false;
  if (permissionsString.length === 10) {
    if (permissionsString[9] === "+") {
      extendedAcls = true;
    } else {
      throw RangeError(
        `toPermissions() Invalid extendedAcls bit ${permissionsString[9]} in permissions string ${permissionsString}`
      );
    }
  }

  const owner = toRolePermissions(permissionsString.substr(0, 3), false);
  const group = toRolePermissions(permissionsString.substr(3, 3), false);
  const other = toRolePermissions(permissionsString.substr(6, 3), true);

  return {
    owner,
    group,
    other,
    stickyBit,
    extendedAcls
  };
}


export function toAccessControlItem(aclItemString: string): PathAccessControlItem {
  const error = new RangeError(
    `toAccessControlItem() Parameter access control item string ${aclItemString} is not valid.`
  );
  if (aclItemString === "") {
    throw error;
  }

  aclItemString = aclItemString.toLowerCase();

  const parts = aclItemString.split(":");
  if (parts.length < 3 || parts.length > 4) {
    throw error;
  }

  let defaultScope = false;
  let index = 0;
  if (parts.length === 4) {
    if (parts[index] !== "default") {
      throw error;
    }
    defaultScope = true;
    index++;
  }

  const accessControlType = parts[index++];
  if (
    accessControlType !== "user" &&
    accessControlType !== "group" &&
    accessControlType !== "mask" &&
    accessControlType !== "other"
  ) {
    throw error;
  }

  const entityId = parts[index++];
  const permissions = toRolePermissions(parts[index++]);

  return {
    defaultScope,
    accessControlType,
    entityId,
    permissions
  };
}


export function toRemoveAccessControlItem(aclItemString: string): RemovePathAccessControlItem {
  const error = new RangeError(
    `toAccessControlItem() Parameter access control item string "${aclItemString}" is not valid.`
  );
  if (aclItemString === "") {
    throw error;
  }

  aclItemString = aclItemString.toLowerCase();

  const parts = aclItemString.split(":");
  if (parts.length < 1 || parts.length > 3) {
    throw error;
  }

  if (parts.length === 3) {
    if (parts[0] !== "default") {
      throw error;
    }
  }

  let defaultScope = false;
  let index = 0;
  if (parts[index] === "default") {
    defaultScope = true;
    index++;
  }

  const accessControlType = parts[index++];
  if (
    accessControlType !== "user" &&
    accessControlType !== "group" &&
    accessControlType !== "mask" &&
    accessControlType !== "other"
  ) {
    throw error;
  }

  const entityId = parts[index++];

  return {
    defaultScope,
    accessControlType,
    entityId
  };
}


export function toAcl(aclString?: string): PathAccessControlItem[] {
  if (aclString === undefined || aclString === "" || aclString === null) {
    return [];
  }

  const acls = [];
  const aclParts = aclString.split(",");
  for (const aclPart of aclParts) {
    acls.push(toAccessControlItem(aclPart));
  }

  return acls;
}


export function toRemoveAcl(aclString?: string): RemovePathAccessControlItem[] {
  if (aclString === undefined || aclString === "" || aclString === null) {
    return [];
  }

  const acls = [];
  const aclParts = aclString.split(",");
  for (const aclPart of aclParts) {
    acls.push(toRemoveAccessControlItem(aclPart));
  }

  return acls;
}


export function toAccessControlItemString(item: PathAccessControlItem): string {
  const entityIdString = item.entityId !== undefined ? `:${item.entityId}` : "";
  const permissionsString =
    item.permissions !== undefined ? `:${toRolePermissionsString(item.permissions)}` : "";
  return `${item.defaultScope ? "default:" : ""}${
    item.accessControlType
  }${entityIdString}${permissionsString}`;
}


export function toAclString(acl: PathAccessControlItem[]): string {
  return acl.map(toAccessControlItemString).join(",");
}


export function toRolePermissionsString(p: RolePermissions, stickyBit: boolean = false): string {
  return `${p.read ? "r" : "-"}${p.write ? "w" : "-"}${stickyBit ? "t" : p.execute ? "x" : "-"}`;
}


export function toPermissionsString(permissions: PathPermissions): string {
  return `${toRolePermissionsString(permissions.owner)}${toRolePermissionsString(
    permissions.group
  )}${toRolePermissionsString(permissions.other, permissions.stickyBit)}${
    permissions.extendedAcls ? "+" : ""
  }`;
}


export function toAccessControlChangeFailureArray(
  aclFailedEntry: AclFailedEntry[] = []
): AccessControlChangeError[] {
  return aclFailedEntry.map((aclFailedEntry: AclFailedEntry) => {
    return {
      name: aclFailedEntry.name || "",
      isDirectory: (aclFailedEntry.type || "").toLowerCase() === "directory",
      message: aclFailedEntry.errorMessage || ""
    };
  });
}


(val: ContainerItem): FileSystemItem => {
            return {
              ...val,
              versionId: val.version,
              properties: {
                ...val.properties,
                publicAccess: toPublicAccessType(val.properties.publicAccess)
              }
            };
          }


(aclFailedEntry: AclFailedEntry) => {
    return {
      name: aclFailedEntry.name || "",
      isDirectory: (aclFailedEntry.type || "").toLowerCase() === "directory",
      message: aclFailedEntry.errorMessage || ""
    };
  }