// Cropping and resizing each frame based on config
cropAndResizeFrame(img: Tensor3D): Tensor3D {
    const expandedImage: Tensor4D = img.toFloat().expandDims(0);
    let resizedImage;
    resizedImage = image.cropAndResize(
        expandedImage, this.cropBox, this.cropBoxInd, this.cropSize,
        'bilinear');
    // Extract image from batch cropping.
    const shape = resizedImage.shape;
    return resizedImage.reshape(shape.slice(1) as [number, number, number]);
  }


// Capture one frame from the video stream, and extract the value from
// iterator.next() result.
async capture(): Promise<Tensor3D> {
    return (await this.next()).value;
  }


// Stop the video stream and pause webcam iterator.
stop(): void {
    const tracks = this.stream.getTracks();

    tracks.forEach(track => track.stop());

    try {
      this.webcamVideoElement.srcObject = null;
    } catch (error) {
      console.log(error);
      this.webcamVideoElement.src = null;
    }
    this.isClosed = true;
  }


// Override toArray() function to prevent collecting.
toArray(): Promise<Tensor3D[]> {
    throw new Error('Can not convert infinite video stream to array.');
  }


export class ObjectRegistry {
    public static doDebug = false;
    public static registries: any = gRegistries;

    private _objectType: any;
    private readonly _cache: any;

    constructor(objectType?: any) {
        this._objectType = objectType;
        this._cache = {};
        gRegistries.push(this);
    }

    public getClassName(): string {
        return this._objectType ? this._objectType.name : "<???>";
    }

    public register(obj: any): void {
        if (!this._objectType) {
            this._objectType = obj.constructor;
        }

        if (!obj._____hash) {
            obj._____hash = hashCounter;
            hashCounter += 1;
            this._cache[obj._____hash] = obj;
        }

        // istanbul ignore next
        if (ObjectRegistry.doDebug) {
            obj._____trace = traceFromThisProjectOnly();
        }
    }

    public unregister(obj: any): void {
        this._cache[obj._____hash] = null;
        obj._____trace = null;
        delete this._cache[obj._____hash];
    }

    public count(): number {
        return Object.keys(this._cache).length;
    }

    public toString(): string {
        const className = this.getClassName();
        let str = " className :" + className + " found => " + this.count() + " object leaking\n";

        for (const obj of Object.values(this._cache) as any[]) {
            str += obj.constructor.name + " " + obj.toString() + "\n";
        }

        if (ObjectRegistry.doDebug) {
            for (const [key, cachedObject] of Object.entries(this._cache) as any[]) {
                assert(cachedObject.hasOwnProperty("_____trace"));
                str += "   " + key + cachedObject._____trace + "\n";
            }
        }
        return str;
    }
}


public getClassName(): string {
        return this._objectType ? this._objectType.name : "<???>";
    }


public register(obj: any): void {
        if (!this._objectType) {
            this._objectType = obj.constructor;
        }

        if (!obj._____hash) {
            obj._____hash = hashCounter;
            hashCounter += 1;
            this._cache[obj._____hash] = obj;
        }

        // istanbul ignore next
        if (ObjectRegistry.doDebug) {
            obj._____trace = traceFromThisProjectOnly();
        }
    }


public unregister(obj: any): void {
        this._cache[obj._____hash] = null;
        obj._____trace = null;
        delete this._cache[obj._____hash];
    }


public count(): number {
        return Object.keys(this._cache).length;
    }


public toString(): string {
        const className = this.getClassName();
        let str = " className :" + className + " found => " + this.count() + " object leaking\n";

        for (const obj of Object.values(this._cache) as any[]) {
            str += obj.constructor.name + " " + obj.toString() + "\n";
        }

        if (ObjectRegistry.doDebug) {
            for (const [key, cachedObject] of Object.entries(this._cache) as any[]) {
                assert(cachedObject.hasOwnProperty("_____trace"));
                str += "   " + key + cachedObject._____trace + "\n";
            }
        }
        return str;
    }


() => {
  const httpClient = useHttpClient();

  return useQuery(QUERY_KEYS.getRoles, async () => {
    const response = await httpClient.get<RoleResponseListData>('roles');

    return response.data.data;
  });
}


async () => {
    const response = await httpClient.get<RoleResponseListData>('roles');

    return response.data.data;
  }


() => {
                this.SliderChange();
            }


export class CustomSlider {

        constructor(private _target: any, private _min: number, private _max: number, private _defaultValue: number, private _onSliderChange: Function) {
            var sliderChange = () => {
                this.SliderChange();
            };

            // Build slider with default values
            this._target.slider({
                orientation: "horizontal",
                range: "min",
                min: this._min,
                max: this._max,
                value: this._defaultValue,
                animate: true,
                slide: sliderChange,
                change: sliderChange
            });

            // This essentially triggers the onSliderChange event with the default values
            this.SliderChange();
        }

        // Take an outside value and update the slider (this is used for things like animating)
        public UpdateSlider(val: number): void {
            this._target.slider("value", val);
        }

        private SliderChange(): void {
            this._onSliderChange(parseInt(this._target.slider("value")));
        }
    }


// Take an outside value and update the slider (this is used for things like animating)
public UpdateSlider(val: number): void {
            this._target.slider("value", val);
        }


private SliderChange(): void {
            this._onSliderChange(parseInt(this._target.slider("value")));
        }


() => {
  let component: OverlayComponent;
  let fixture: ComponentFixture<OverlayComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [OverlayComponent],
      providers: [Overlay]
    })
      .compileComponents();

  });

  beforeEach(() => {
    fixture = TestBed.createComponent(OverlayComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

    it('should create', () => {
      expect(component).toBeTruthy();
    });

    it('should show overlay', () => {

      component.createGlobalOverlay();

    });
}


async () => {
    await TestBed.configureTestingModule({
      declarations: [OverlayComponent],
      providers: [Overlay]
    })
      .compileComponents();

  }


() => {
    fixture = TestBed.createComponent(OverlayComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }


() => {
      expect(component).toBeTruthy();
    }


() => {

      component.createGlobalOverlay();

    }


paramMap => {
      if (paramMap.has('placeId')) {
        this._placesService.getPlaceAPIObservable(paramMap.get('placeId')).subscribe(data => {
          let thisPlace = { id: data.id, ...(data.data() as {}) } as Place;
          this.createEditForm(thisPlace);
        });
      }
    }


data => {
          let thisPlace = { id: data.id, ...(data.data() as {}) } as Place;
          this.createEditForm(thisPlace);
        }


checkbox => checkbox.nativeElement.innerHTML[0] === i && checkbox.nativeElement.innerHTML[2] === j


checkbox => checkbox.nativeElement.checked = true


val => {
      this.nrRows.next([...Array(val)]);
    }


val => {
      this.nrCols.next([...Array(val)]);
    }


checkbox => checkbox.nativeElement.checked


checkbox => {
          const i = checkbox.nativeElement.innerHTML[0];
          const j = checkbox.nativeElement.innerHTML[2];
          return {i, j};
      }


(data) => this.router.navigateByUrl('/admin-places')


@Component({
  selector: 'app-add-edit-place',
  templateUrl: './add-edit-place.component.html',
  styleUrls: ['./add-edit-place.component.scss'],
})
export class AdminAddEditPlaceComponent implements OnInit, AfterViewInit {

  addEditPlaceForm;
  addOrEdit: 'add' | 'edit' | null = null;
  nrRows: BehaviorSubject<number[]> = new BehaviorSubject([...Array(1)]);
  nrCols: BehaviorSubject<number[]> = new BehaviorSubject([...Array(1)]);
  @ViewChildren('checkboxes', {read: ElementRef}) checkboxes: QueryList<any>;

  constructor(
    private formBuilder: FormBuilder,
    private _placesService: PlacesService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private ref: ChangeDetectorRef
    ) { }

  ngOnInit() {
    this.createAddForm();
  }

  ngAfterViewInit() {
    this.activatedRoute.paramMap.subscribe(paramMap => {
      if (paramMap.has('placeId')) {
        this._placesService.getPlaceAPIObservable(paramMap.get('placeId')).subscribe(data => {
          let thisPlace = { id: data.id, ...(data.data() as {}) } as Place;
          this.createEditForm(thisPlace);
        });
      }
    });
  }

  createAddForm() {
    this.addOrEdit = 'add';

    this.addEditPlaceForm = this.formBuilder.group({
      title: ['', Validators.required],
      description: ['', [Validators.required, Validators.maxLength(200)]],
      schedule: ['', Validators.required],
      imageUrl: ['', Validators.required],
      openDays:
        this.formBuilder.group({
          week: [false],
          saturday: [false],
          sunday: [false]
        }),
      defaultTableSize: ['', Validators.required],
      availableGridRows: [1, Validators.required],
      availableGridCols: [1, Validators.required],
      availableSeats: [''],
    });
    this.onGridValueChanges();
  }

  createEditForm(thisPlace: Place) {
    this.addOrEdit = 'edit';
    this.nrRows.next([...Array(thisPlace.availableGridRows)]);
    this.nrCols.next([...Array(thisPlace.availableGridCols)]);
    this.ref.detectChanges();

    this.addEditPlaceForm = this.formBuilder.group({
      id: [thisPlace.id, Validators.required],
      title: [thisPlace.title, Validators.required],
      description: [thisPlace.description, [Validators.required, Validators.maxLength(200)]],
      schedule: [thisPlace.schedule, Validators.required],
      imageUrl: [thisPlace.imageUrl, Validators.required],
      openDays:
        this.formBuilder.group({
          week: [thisPlace.openDays.week],
          saturday: [thisPlace.openDays.saturday],
          sunday: [thisPlace.openDays.sunday]
        }),
      defaultTableSize: [thisPlace.defaultTableSize, Validators.required],
      availableGridRows: [thisPlace.availableGridRows, Validators.required],
      availableGridCols: [thisPlace.availableGridCols, Validators.required],
      availableSeats: [''],
    });
    this.onGridValueChanges();

    // This should be separate function !
    for (var seat of thisPlace.availableSeats) {
      const i = seat['i'];
      const j = seat['j'];

      this.checkboxes
        .filter(checkbox => checkbox.nativeElement.innerHTML[0] === i && checkbox.nativeElement.innerHTML[2] === j)
        .map(checkbox => checkbox.nativeElement.checked = true);
    }
  }

  onGridValueChanges() {
    this.addEditPlaceForm?.controls.availableGridRows.valueChanges.subscribe( val => {
      this.nrRows.next([...Array(val)]);
    });

    this.addEditPlaceForm?.controls.availableGridCols.valueChanges.subscribe( val => {
      this.nrCols.next([...Array(val)]);
    });
  }

  onAddOrEditPlace() {
    if(this.addEditPlaceForm.invalid || !this.addOrEdit)
    {
      return;
    }

    // This should be separate function !
    this.addEditPlaceForm.value.availableSeats = this.checkboxes
      .filter(checkbox => checkbox.nativeElement.checked)
      .map(checkbox => {
          const i = checkbox.nativeElement.innerHTML[0];
          const j = checkbox.nativeElement.innerHTML[2];
          return {i, j};
      });

    if (this.addOrEdit === 'add') {
      this._placesService.createPlaceAPIPromise(this.addEditPlaceForm.value as Place)
        .then(
          (data) => this.router.navigateByUrl('/admin-places')
        );
    } else if (this.addOrEdit === 'edit') {
      this._placesService.updatePlaceAPIPromise(this.addEditPlaceForm.value as Place)
      .then(
        (data) => this.router.navigateByUrl('/admin-places')
      );
    }
  }

}


ngOnInit() {
    this.createAddForm();
  }


ngAfterViewInit() {
    this.activatedRoute.paramMap.subscribe(paramMap => {
      if (paramMap.has('placeId')) {
        this._placesService.getPlaceAPIObservable(paramMap.get('placeId')).subscribe(data => {
          let thisPlace = { id: data.id, ...(data.data() as {}) } as Place;
          this.createEditForm(thisPlace);
        });
      }
    });
  }


createAddForm() {
    this.addOrEdit = 'add';

    this.addEditPlaceForm = this.formBuilder.group({
      title: ['', Validators.required],
      description: ['', [Validators.required, Validators.maxLength(200)]],
      schedule: ['', Validators.required],
      imageUrl: ['', Validators.required],
      openDays:
        this.formBuilder.group({
          week: [false],
          saturday: [false],
          sunday: [false]
        }),
      defaultTableSize: ['', Validators.required],
      availableGridRows: [1, Validators.required],
      availableGridCols: [1, Validators.required],
      availableSeats: [''],
    });
    this.onGridValueChanges();
  }


createEditForm(thisPlace: Place) {
    this.addOrEdit = 'edit';
    this.nrRows.next([...Array(thisPlace.availableGridRows)]);
    this.nrCols.next([...Array(thisPlace.availableGridCols)]);
    this.ref.detectChanges();

    this.addEditPlaceForm = this.formBuilder.group({
      id: [thisPlace.id, Validators.required],
      title: [thisPlace.title, Validators.required],
      description: [thisPlace.description, [Validators.required, Validators.maxLength(200)]],
      schedule: [thisPlace.schedule, Validators.required],
      imageUrl: [thisPlace.imageUrl, Validators.required],
      openDays:
        this.formBuilder.group({
          week: [thisPlace.openDays.week],
          saturday: [thisPlace.openDays.saturday],
          sunday: [thisPlace.openDays.sunday]
        }),
      defaultTableSize: [thisPlace.defaultTableSize, Validators.required],
      availableGridRows: [thisPlace.availableGridRows, Validators.required],
      availableGridCols: [thisPlace.availableGridCols, Validators.required],
      availableSeats: [''],
    });
    this.onGridValueChanges();

    // This should be separate function !
    for (var seat of thisPlace.availableSeats) {
      const i = seat['i'];
      const j = seat['j'];

      this.checkboxes
        .filter(checkbox => checkbox.nativeElement.innerHTML[0] === i && checkbox.nativeElement.innerHTML[2] === j)
        .map(checkbox => checkbox.nativeElement.checked = true);
    }
  }


onGridValueChanges() {
    this.addEditPlaceForm?.controls.availableGridRows.valueChanges.subscribe( val => {
      this.nrRows.next([...Array(val)]);
    });

    this.addEditPlaceForm?.controls.availableGridCols.valueChanges.subscribe( val => {
      this.nrCols.next([...Array(val)]);
    });
  }


onAddOrEditPlace() {
    if(this.addEditPlaceForm.invalid || !this.addOrEdit)
    {
      return;
    }

    // This should be separate function !
    this.addEditPlaceForm.value.availableSeats = this.checkboxes
      .filter(checkbox => checkbox.nativeElement.checked)
      .map(checkbox => {
          const i = checkbox.nativeElement.innerHTML[0];
          const j = checkbox.nativeElement.innerHTML[2];
          return {i, j};
      });

    if (this.addOrEdit === 'add') {
      this._placesService.createPlaceAPIPromise(this.addEditPlaceForm.value as Place)
        .then(
          (data) => this.router.navigateByUrl('/admin-places')
        );
    } else if (this.addOrEdit === 'edit') {
      this._placesService.updatePlaceAPIPromise(this.addEditPlaceForm.value as Place)
      .then(
        (data) => this.router.navigateByUrl('/admin-places')
      );
    }
  }


({ isStrikethrough }) => (isStrikethrough ? 0.3 : 1)


({ isStrikethrough }) =>
    isStrikethrough ? 'line-through' : 'normal'


({ product }: Props) => {
  const [removeButtonHovered, setRemoveButtonHovered] = useState(false);
  const [productHovered, setProductHovered] = useState(false);
  const { removeProductFromCart } = useCart();

  const setTrue = useCallback(
    (callback: (value: boolean) => void) => () => {
      callback(true);
    },
    []
  );

  const setFalse = useCallback(
    (callback: (value: boolean) => void) => () => {
      callback(false);
    },
    []
  );

  return (
    <Container
      onMouseEnter={setTrue(setProductHovered)}
      onMouseLeave={setFalse(setProductHovered)}
    >
      <Image isStrikethrough={removeButtonHovered} src={product.image} />
      <InfoContainer isStrikethrough={removeButtonHovered}>
        <InfoTitle>{product.title}</InfoTitle>
        <InfoSubtitle>
          {product.availableSizes[0]}
          {product.description && `| ${product.description}`}
        </InfoSubtitle>
        <InfoSubtitle>Quantidade: {product.count}</InfoSubtitle>
      </InfoContainer>
      <ControlContainer>
        <RemoveButton
          onClick={() => removeProductFromCart(product.id)}
          onMouseEnter={setTrue(setRemoveButtonHovered)}
          onMouseLeave={setFalse(setRemoveButtonHovered)}
        >
          <TimesIcon fill={productHovered ? '#fff' : '#000'} />
        </RemoveButton>
        <Price currencyFormat={product.currencyFormat} price={product.price} />
      </ControlContainer>
    </Container>


(callback: (value: boolean) => void) => () => {
      callback(true);
    }


() => {
      callback(true);
    }


(callback: (value: boolean) => void) => () => {
      callback(false);
    }


() => {
      callback(false);
    }


() => removeProductFromCart(product.id)


type Props = {
  product: ProductCart;
};


setTrue(setProductHovered)


setFalse(setProductHovered)


setTrue(setRemoveButtonHovered)


setFalse(setRemoveButtonHovered)


export class CardView extends BaseImageCardView<IHybridWorkCheckinAdaptiveCardExtensionProps, IHybridWorkCheckinAdaptiveCardExtensionState> {
  /**
   * Buttons will not be visible if card size is 'Medium' with Image Card View.
   * It will support up to two buttons for 'Large' card size.
   */
  public get cardButtons(): [ICardButton] | [ICardButton, ICardButton] | undefined {
    return [
      {
        title: strings.QuickViewButton,
        action: {
          type: 'QuickView',
          parameters: {
            view: FORM_VIEW_REGISTRY_ID
          }
        }
      }
    ];
  }

  public get data(): IImageCardParameters {
    return {
      primaryText: strings.PrimaryText,
      imageUrl: require('../assets/MicrosoftLogo.png')
    };
  }

  public get onCardSelection(): IQuickViewCardAction | IExternalLinkCardAction | undefined {
    return;
    // {
    //   type: 'ExternalLink',
    //   parameters: {
    //     target: 'https://www.bing.com'
    //   }
    // };
  }
}


() => import(/* webpackChunkName: "about" */ '@/views/About.vue')


() => import(/* webpackChunkName: "account" */ '@/views/Account.vue')


() => import(/* webpackChunkName: "auth" */ '@/npuser-auth/Auth.vue')


() => import(/* webpackChunkName: "dashboard" */ '@/views/UserDash.vue')


(to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in ... if not, redirect to login page.
    if (!authenticated()) {
      next({
        path: '/auth',
        query: { redirect: to.fullPath }
      })
      return
    }
  }
  // make sure to always call next()!
  next()
}


record => record.meta.requiresAuth


(item: any) => {
        item.healthState = item.health.state
            ? item.health.state === 'healthy'
              ? 'Up'
              : item.health.state === 'unknown'
              ? 'Unknown'
              : 'Down'
            : 'Down';
      }


export class AlicloudLoadBalancerTransformer {
  public static $inject = ['$q'];
  constructor(private $q: IQService) {}
  public normalizeLoadBalancer(loadBalancer: any): any {
    loadBalancer.serverGroups.forEach(function(serverGroup: any) {
      serverGroup.account = loadBalancer.account;
      serverGroup.region = loadBalancer.region;
      if (serverGroup.detachedInstances) {
        serverGroup.detachedInstances = serverGroup.detachedInstances.map(function(instanceId: any) {
          return { id: instanceId };
        });
        serverGroup.instances = serverGroup.instances.concat(serverGroup.detachedInstances);
      } else {
        serverGroup.detachedInstances = [];
      }
      serverGroup.instances.forEach((item: any) => {
        item.healthState = item.health.state
            ? item.health.state === 'healthy'
              ? 'Up'
              : item.health.state === 'unknown'
              ? 'Unknown'
              : 'Down'
            : 'Down';
      });
    });
    loadBalancer.provider = loadBalancer.type;
    return this.$q.resolve(loadBalancer);
  }

  public convertLoadBalancerForEditing(loadBalancer: any) {
    const toEdit: any = {
      region: loadBalancer.region,
      credentials: loadBalancer.account,
      name: loadBalancer.name,
      stack: loadBalancer.stack,
      detail: loadBalancer.detail,
      vnet: loadBalancer.vnet,
      masterZoneId: loadBalancer.masterZoneId,
      address: loadBalancer.elb.results.attributes.address,
      addressIPVersion: loadBalancer.elb.results.attributes.addressIPVersion,
      addressType: loadBalancer.elb.results.attributes.addressType,
      deleteProtection: loadBalancer.elb.results.attributes.deleteProtection,
      loadBalancerSpec: loadBalancer.elb.results.attributes.loadBalancerSpec,
      vSwitchId: loadBalancer.elb.results.vswitchId,
      vSwitchName: loadBalancer.elb.results.vswitchName || '',
      subnet: loadBalancer.subnet,
      probes: [],
      loadBalancingRules: [],
      listenerPortsAndProtocal: loadBalancer.elb.results.attributes.listenerPortsAndProtocal,
      listeners: loadBalancer.elb.results.attributes.listenerPortsAndProtocal,
    };
    if (loadBalancer.elb) {
      const elb: any = loadBalancer.elb;
      toEdit.securityGroups = elb.securityGroups;
      toEdit.vnet = elb.vnet;
      toEdit.probes = elb.probes;
    }
    return toEdit;
  }

  public constructNewLoadBalancerTemplate(application: any) {
    const defaultCredentials: string =
        application.defaultCredentials.alicloud || AliCloudProviderSettings.defaults.account,
      defaultRegion: string = application.defaultRegions.alicloud || AliCloudProviderSettings.defaults.region;
    return {
      stack: '',
      detail: 'frontend',
      credentials: defaultCredentials,
      region: defaultRegion,
      cloudProvider: 'alicloud',
      vnet: '',
      subnetId: '',
      masterZoneId: '',
      vSwitchId: '',
      vSwitchName: '',
      address: '',
      addressIPVersion: 'ipv4',
      addressType: 'intranet',
      deleteProtection: 'on',
      loadBalancerSpec: 'slb.s1.small',
      probes: [
        {
          probeName: '',
          probeProtocol: 'HTTP',
          probePort: 'www.bing.com',
          probePath: '/',
          probeInterval: 30,
          unhealthyThreshold: 8,
          timeout: 120,
        },
      ],
      listeners: [
        {
          listenerProtocal: 'HTTP',
          healthCheck: 'on',
          healthCheckTimeout: 5,
          unhealthyThreshold: 4,
          healthyThreshold: 4,
          healthCheckInterval: 2,
          healthCheckURI: '',
          listenerPort: 80,
          bandwidth: -1,
          stickySession: 'on',
          backendServerPort: 80,
          gzip: 'on',
          stickySessionType: 'server',
          cookie: '',
          cookieTimeout: 500,
          scheduler: 'wrr',
          requestTimeout: 60,
          idleTimeout: 15,
          healthCheckHttpCode: 'http_2xx',
        },
      ],
      loadBalancingRules: [
        {
          ruleName: '',
          protocol: 'HTTP',
          externalPort: 80,
          backendPort: 80,
          probeName: '',
          persistence: 'None',
          idleTimeout: 4,
        },
      ],
    };
  }
}


public normalizeLoadBalancer(loadBalancer: any): any {
    loadBalancer.serverGroups.forEach(function(serverGroup: any) {
      serverGroup.account = loadBalancer.account;
      serverGroup.region = loadBalancer.region;
      if (serverGroup.detachedInstances) {
        serverGroup.detachedInstances = serverGroup.detachedInstances.map(function(instanceId: any) {
          return { id: instanceId };
        });
        serverGroup.instances = serverGroup.instances.concat(serverGroup.detachedInstances);
      } else {
        serverGroup.detachedInstances = [];
      }
      serverGroup.instances.forEach((item: any) => {
        item.healthState = item.health.state
            ? item.health.state === 'healthy'
              ? 'Up'
              : item.health.state === 'unknown'
              ? 'Unknown'
              : 'Down'
            : 'Down';
      });
    });
    loadBalancer.provider = loadBalancer.type;
    return this.$q.resolve(loadBalancer);
  }


public convertLoadBalancerForEditing(loadBalancer: any) {
    const toEdit: any = {
      region: loadBalancer.region,
      credentials: loadBalancer.account,
      name: loadBalancer.name,
      stack: loadBalancer.stack,
      detail: loadBalancer.detail,
      vnet: loadBalancer.vnet,
      masterZoneId: loadBalancer.masterZoneId,
      address: loadBalancer.elb.results.attributes.address,
      addressIPVersion: loadBalancer.elb.results.attributes.addressIPVersion,
      addressType: loadBalancer.elb.results.attributes.addressType,
      deleteProtection: loadBalancer.elb.results.attributes.deleteProtection,
      loadBalancerSpec: loadBalancer.elb.results.attributes.loadBalancerSpec,
      vSwitchId: loadBalancer.elb.results.vswitchId,
      vSwitchName: loadBalancer.elb.results.vswitchName || '',
      subnet: loadBalancer.subnet,
      probes: [],
      loadBalancingRules: [],
      listenerPortsAndProtocal: loadBalancer.elb.results.attributes.listenerPortsAndProtocal,
      listeners: loadBalancer.elb.results.attributes.listenerPortsAndProtocal,
    };
    if (loadBalancer.elb) {
      const elb: any = loadBalancer.elb;
      toEdit.securityGroups = elb.securityGroups;
      toEdit.vnet = elb.vnet;
      toEdit.probes = elb.probes;
    }
    return toEdit;
  }


public constructNewLoadBalancerTemplate(application: any) {
    const defaultCredentials: string =
        application.defaultCredentials.alicloud || AliCloudProviderSettings.defaults.account,
      defaultRegion: string = application.defaultRegions.alicloud || AliCloudProviderSettings.defaults.region;
    return {
      stack: '',
      detail: 'frontend',
      credentials: defaultCredentials,
      region: defaultRegion,
      cloudProvider: 'alicloud',
      vnet: '',
      subnetId: '',
      masterZoneId: '',
      vSwitchId: '',
      vSwitchName: '',
      address: '',
      addressIPVersion: 'ipv4',
      addressType: 'intranet',
      deleteProtection: 'on',
      loadBalancerSpec: 'slb.s1.small',
      probes: [
        {
          probeName: '',
          probeProtocol: 'HTTP',
          probePort: 'www.bing.com',
          probePath: '/',
          probeInterval: 30,
          unhealthyThreshold: 8,
          timeout: 120,
        },
      ],
      listeners: [
        {
          listenerProtocal: 'HTTP',
          healthCheck: 'on',
          healthCheckTimeout: 5,
          unhealthyThreshold: 4,
          healthyThreshold: 4,
          healthCheckInterval: 2,
          healthCheckURI: '',
          listenerPort: 80,
          bandwidth: -1,
          stickySession: 'on',
          backendServerPort: 80,
          gzip: 'on',
          stickySessionType: 'server',
          cookie: '',
          cookieTimeout: 500,
          scheduler: 'wrr',
          requestTimeout: 60,
          idleTimeout: 15,
          healthCheckHttpCode: 'http_2xx',
        },
      ],
      loadBalancingRules: [
        {
          ruleName: '',
          protocol: 'HTTP',
          externalPort: 80,
          backendPort: 80,
          probeName: '',
          persistence: 'None',
          idleTimeout: 4,
        },
      ],
    };
  }


(
  subject: string,
  options: {
    name?: string;
    email?: string;
    labels?: string[];
    username?: string;
    packages?: string[];
  } = {}
): IExtendedCommit => ({
  hash: 'foo',
  labels: options.labels || [],
  authorName: options.name || 'Adam Dierkens',
  authorEmail: options.email || 'adam@dierkens.com',
  authors: [
    {
      name: options.name || 'Adam Dierkens',
      email: options.email || 'adam@dierkens.com'
    }
  ],
  subject,
  packages: options.packages
})


() => {
  render(<CustomRenderer />)
}


// ngx-translate - required for AOT compilation
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}


@NgModule({
  declarations: [],
  imports: [
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  exports: [
    TranslateModule
  ],
})
export class LanguageTranslationModule {
  constructor(
    private translate: TranslateService,
  ) {
    // Gets Default language from browser if available, otherwise set English ad default
    this.translate.addLangs(['en', 'fr', 'ur', 'es', 'it', 'fa', 'de', 'zh-CHS']);
    this.translate.setDefaultLang('en');
    const browserLang = this.translate.getBrowserLang();
    this.translate.use(browserLang.match(/en|fr|ur|es|it|fa|de|zh-CHS/) ? browserLang : 'en');
  }
}


@Entity()
export class Contact{
    @ObjectIdColumn()
    id: string;
    @Column()
    name:string;
    @Column()
    workId:string
    @Column()
    department:string
}


() => {
    let appController: AppController;

    beforeEach(async () => {
        const app: TestingModule = await Test.createTestingModule({
            controllers: [AppController],
            providers: [AppService]
        }).compile();

        appController = app.get<AppController>(AppController);
    });

    describe('root', () => {
        it('should exist', () => {
            expect(appController).toBeDefined();
        });
    });
}


async () => {
        const app: TestingModule = await Test.createTestingModule({
            controllers: [AppController],
            providers: [AppService]
        }).compile();

        appController = app.get<AppController>(AppController);
    }


() => {
        it('should exist', () => {
            expect(appController).toBeDefined();
        });
    }


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


() => {
    const [position, setPosition] = useState({x: 0, y: 0 })
    useEffect(() => {
        const updateMouse = (e:any) => {
            setPosition({ x: e.clientX, y: e.clientY })
        }
        document.addEventListener('mousemove', updateMouse)
        return () => {
            document.removeEventListener('mousemove', updateMouse)
        }
    })
    return position
}


() => {
        const updateMouse = (e:any) => {
            setPosition({ x: e.clientX, y: e.clientY })
        }
        document.addEventListener('mousemove', updateMouse)
        return () => {
            document.removeEventListener('mousemove', updateMouse)
        }
    }


(e:any) => {
            setPosition({ x: e.clientX, y: e.clientY })
        }


() => {
            document.removeEventListener('mousemove', updateMouse)
        }


(ws) => ws.registerExpress(app)


export interface IPluginLedgerConnectorQuorumOptions
  extends ICactusPluginOptions {
  rpcApiHttpHost: string;
  logLevel?: LogLevelDesc;
  prometheusExporter?: PrometheusExporter;
  pluginRegistry: PluginRegistry;
}


public getPrometheusExporter(): PrometheusExporter {
    return this.prometheusExporter;
  }


public async getPrometheusExporterMetrics(): Promise<string> {
    const res: string = await this.prometheusExporter.getPrometheusMetrics();
    this.log.debug(`getPrometheusExporterMetrics() response: %o`, res);
    return res;
  }


public getInstanceId(): string {
    return this.instanceId;
  }


public getHttpServer(): Optional<Server | SecureServer> {
    return Optional.ofNullable(this.httpServer);
  }


public async shutdown(): Promise<void> {
    const serverMaybe = this.getHttpServer();
    if (serverMaybe.isPresent()) {
      const server = serverMaybe.get();
      await promisify(server.close.bind(server))();
    }
  }


public async onPluginInit(): Promise<unknown> {
    return;
  }


async registerWebServices(app: Express): Promise<IWebServiceEndpoint[]> {
    const webServices = await this.getOrCreateWebServices();
    await Promise.all(webServices.map((ws) => ws.registerExpress(app)));
    return webServices;
  }


public async getOrCreateWebServices(): Promise<IWebServiceEndpoint[]> {
    if (Array.isArray(this.endpoints)) {
      return this.endpoints;
    }
    const endpoints: IWebServiceEndpoint[] = [];
    {
      const endpoint = new DeployContractSolidityBytecodeEndpoint({
        connector: this,
        logLevel: this.options.logLevel,
      });
      endpoints.push(endpoint);
    }
    {
      const endpoint = new RunTransactionEndpoint({
        connector: this,
        logLevel: this.options.logLevel,
      });
      endpoints.push(endpoint);
    }
    {
      const endpoint = new InvokeContractEndpoint({
        connector: this,
        logLevel: this.options.logLevel,
      });
      endpoints.push(endpoint);
    }
    {
      const opts: IGetPrometheusExporterMetricsEndpointV1Options = {
        connector: this,
        logLevel: this.options.logLevel,
      };
      const endpoint = new GetPrometheusExporterMetricsEndpointV1(opts);
      endpoints.push(endpoint);
    }
    this.endpoints = endpoints;
    return endpoints;
  }


public getPackageName(): string {
    return `@hyperledger/cactus-plugin-ledger-connector-quorum`;
  }


public async getConsensusAlgorithmFamily(): Promise<
    ConsensusAlgorithmFamily
  > {
    return ConsensusAlgorithmFamily.Authority;
  }


public async hasTransactionFinality(): Promise<boolean> {
    const currentConsensusAlgorithmFamily = await this.getConsensusAlgorithmFamily();

    return consensusHasTransactionFinality(currentConsensusAlgorithmFamily);
  }


public async invokeContract(
    req: InvokeContractV1Request,
  ): Promise<InvokeContractV1Response> {
    const fnTag = `${this.className}#invokeContract()`;
    const contractName = req.contractName;
    let contractInstance: InstanceType<typeof Contract>;

    if (req.keychainId != undefined) {
      const networkId = await this.web3.eth.net.getId();
      const keychainPlugin = this.pluginRegistry.findOneByKeychainId(
        req.keychainId,
      );
      Checks.truthy(
        keychainPlugin,
        `${fnTag} keychain for ID:"${req.keychainId}"`,
      );
      if (!keychainPlugin.has(contractName)) {
        throw new Error(
          `${fnTag} Cannot create an instance of the contract because the contractName and the contractName of the JSON doesn't match`,
        );
      }
      const contractStr = await keychainPlugin.get(contractName);
      const contractJSON = JSON.parse(contractStr);
      if (
        contractJSON.networks === undefined ||
        contractJSON.networks[networkId] === undefined ||
        contractJSON.networks[networkId].address === undefined
      ) {
        if (isWeb3SigningCredentialNone(req.signingCredential)) {
          throw new Error(`${fnTag} Cannot deploy contract with pre-signed TX`);
        }
        const web3SigningCredential = req.signingCredential as
          | Web3SigningCredentialPrivateKeyHex
          | Web3SigningCredentialCactusKeychainRef;

        const receipt = await this.transact({
          transactionConfig: {
            data: `0x${contractJSON.bytecode}`,
            from: web3SigningCredential.ethAccount,
            gas: req.gas,
            gasPrice: req.gasPrice,
          },
          web3SigningCredential,
        });

        const address = {
          address: receipt.transactionReceipt.contractAddress,
        };
        const network = { [networkId]: address };
        contractJSON.networks = network;
        keychainPlugin.set(contractName, JSON.stringify(contractJSON));
      }
      const contract = new this.web3.eth.Contract(
        contractJSON.abi,
        contractJSON.networks[networkId].address,
      );
      this.contracts[contractName] = contract;
    } else if (
      req.keychainId == undefined &&
      req.contractAbi == undefined &&
      req.contractAddress == undefined
    ) {
      throw new Error(
        `${fnTag} Cannot invoke a contract without contract instance, the keychainId param is needed`,
      );
    }

    contractInstance = this.contracts[contractName];
    if (req.contractAbi != undefined) {
      let abi;
      if (typeof req.contractAbi === "string") {
        abi = JSON.parse(req.contractAbi);
      } else {
        abi = req.contractAbi;
      }

      const { contractAddress } = req;
      contractInstance = new this.web3.eth.Contract(abi, contractAddress);
    }

    const methodRef = contractInstance.methods[req.methodName];
    Checks.truthy(methodRef, `${fnTag} YourContract.${req.methodName}`);

    const method: ContractSendMethod = methodRef(...req.params);
    if (req.invocationType === EthContractInvocationType.Call) {
      contractInstance.methods[req.methodName];
      const callOutput = await (method as any).call();
      const success = true;
      return { success, callOutput };
    } else if (req.invocationType === EthContractInvocationType.Send) {
      if (isWeb3SigningCredentialNone(req.signingCredential)) {
        throw new Error(`${fnTag} Cannot deploy contract with pre-signed TX`);
      }
      const web3SigningCredential = req.signingCredential as
        | Web3SigningCredentialPrivateKeyHex
        | Web3SigningCredentialCactusKeychainRef;
      const payload = (method.send as any).request();
      const { params } = payload;
      const [transactionConfig] = params;
      if (req.gas == undefined) {
        req.gas = await this.web3.eth.estimateGas(transactionConfig);
      }
      transactionConfig.from = web3SigningCredential.ethAccount;
      transactionConfig.gas = req.gas;
      transactionConfig.gasPrice = req.gasPrice;
      transactionConfig.value = req.value;
      transactionConfig.nonce = req.nonce;

      const txReq: RunTransactionRequest = {
        transactionConfig,
        web3SigningCredential,
        timeoutMs: req.timeoutMs || 60000,
      };
      const out = await this.transact(txReq);
      const success = out.transactionReceipt.status;
      const data = { success, out };
      return data;
    } else {
      throw new Error(
        `${fnTag} Unsupported invocation type ${req.invocationType}`,
      );
    }
  }


public async transact(
    req: RunTransactionRequest,
  ): Promise<RunTransactionResponse> {
    const fnTag = `${this.className}#transact()`;

    switch (req.web3SigningCredential.type) {
      case Web3SigningCredentialType.CactusKeychainRef: {
        return this.transactCactusKeychainRef(req);
      }
      case Web3SigningCredentialType.GethKeychainPassword: {
        return this.transactGethKeychain(req);
      }
      case Web3SigningCredentialType.PrivateKeyHex: {
        return this.transactPrivateKey(req);
      }
      case Web3SigningCredentialType.None: {
        if (req.transactionConfig.rawTransaction) {
          return this.transactSigned(req.transactionConfig.rawTransaction);
        } else {
          throw new Error(
            `${fnTag} Expected pre-signed raw transaction ` +
              ` since signing credential is specified as` +
              `Web3SigningCredentialType.NONE`,
          );
        }
      }
      default: {
        throw new Error(
          `${fnTag} Unrecognized Web3SigningCredentialType: ` +
            `${req.web3SigningCredential.type} Supported ones are: ` +
            `${Object.values(Web3SigningCredentialType).join(";")}`,
        );
      }
    }
  }


public async transactSigned(
    rawTransaction: string,
  ): Promise<RunTransactionResponse> {
    const fnTag = `${this.className}#transactSigned()`;

    const receipt = await this.web3.eth.sendSignedTransaction(rawTransaction);

    if (receipt instanceof Error) {
      this.log.debug(`${fnTag} Web3 sendSignedTransaction failed`, receipt);
      throw receipt;
    } else {
      this.prometheusExporter.addCurrentTransaction();
      return { transactionReceipt: receipt };
    }
  }


public async transactGethKeychain(
    txIn: RunTransactionRequest,
  ): Promise<RunTransactionResponse> {
    const fnTag = `${this.className}#transactGethKeychain()`;
    const { sendTransaction } = this.web3.eth.personal;
    const { transactionConfig, web3SigningCredential } = txIn;
    const {
      secret,
    } = web3SigningCredential as Web3SigningCredentialGethKeychainPassword;
    try {
      const txHash = await sendTransaction(transactionConfig, secret);
      const transactionReceipt = await this.pollForTxReceipt(txHash);
      return { transactionReceipt };
    } catch (ex) {
      throw new Error(
        `${fnTag} Failed to invoke web3.eth.personal.sendTransaction(). ` +
          `InnerException: ${ex.stack}`,
      );
    }
  }


public async transactPrivateKey(
    req: RunTransactionRequest,
  ): Promise<RunTransactionResponse> {
    const fnTag = `${this.className}#transactPrivateKey()`;
    const { transactionConfig, web3SigningCredential } = req;
    const {
      secret,
    } = web3SigningCredential as Web3SigningCredentialPrivateKeyHex;

    const signedTx = await this.web3.eth.accounts.signTransaction(
      transactionConfig,
      secret,
    );

    if (signedTx.rawTransaction) {
      return this.transactSigned(signedTx.rawTransaction);
    } else {
      throw new Error(
        `${fnTag} Failed to sign eth transaction. ` +
          `signedTransaction.rawTransaction is blank after .signTransaction().`,
      );
    }
  }


public async transactCactusKeychainRef(
    req: RunTransactionRequest,
  ): Promise<RunTransactionResponse> {
    const fnTag = `${this.className}#transactCactusKeychainRef()`;
    const { transactionConfig, web3SigningCredential } = req;
    const {
      ethAccount,
      keychainEntryKey,
      keychainId,
    } = web3SigningCredential as Web3SigningCredentialCactusKeychainRef;

    // locate the keychain plugin that has access to the keychain backend
    // denoted by the keychainID from the request.
    const keychainPlugin = this.pluginRegistry.findOneByKeychainId(keychainId);

    Checks.truthy(keychainPlugin, `${fnTag} keychain for ID:"${keychainId}"`);

    // Now use the found keychain plugin to actually perform the lookup of
    // the private key that we need to run the transaction.
    const privateKeyHex = await keychainPlugin.get(keychainEntryKey);

    return this.transactPrivateKey({
      transactionConfig,
      web3SigningCredential: {
        ethAccount,
        type: Web3SigningCredentialType.PrivateKeyHex,
        secret: privateKeyHex,
      },
    });
  }


public async pollForTxReceipt(
    txHash: string,
    timeoutMs = 60000,
  ): Promise<TransactionReceipt> {
    const fnTag = `${this.className}#pollForTxReceipt()`;
    let txReceipt;
    let timedOut = false;
    let tries = 0;
    const startedAt = new Date();

    do {
      txReceipt = await this.web3.eth.getTransactionReceipt(txHash);
      tries++;
      timedOut = Date.now() >= startedAt.getTime() + timeoutMs;
    } while (!timedOut && !txReceipt);

    if (!txReceipt) {
      throw new Error(`${fnTag} Timed out ${timeoutMs}ms, polls=${tries}`);
    } else {
      return txReceipt;
    }
  }


public async deployContract(
    req: DeployContractSolidityBytecodeV1Request,
  ): Promise<RunTransactionResponse> {
    const fnTag = `${this.className}#deployContract()`;
    Checks.truthy(req, `${fnTag} req`);

    if (isWeb3SigningCredentialNone(req.web3SigningCredential)) {
      throw new Error(`${fnTag} Cannot deploy contract with pre-signed TX`);
    }
    if (req.keychainId != undefined && req.contractName != undefined) {
      const keychainPlugin = this.pluginRegistry.findOneByKeychainId(
        req.keychainId,
      );
      Checks.truthy(
        keychainPlugin,
        `${fnTag} keychain for ID:"${req.keychainId}"`,
      );
      if (!keychainPlugin.has(req.contractName)) {
        throw new Error(
          `${fnTag} Cannot create an instance of the contract because the contractName and the contractName of the JSON doesn't match`,
        );
      }
      const networkId = await this.web3.eth.net.getId();

      const web3SigningCredential = req.web3SigningCredential as
        | Web3SigningCredentialGethKeychainPassword
        | Web3SigningCredentialPrivateKeyHex;
      const receipt = await this.transact({
        transactionConfig: {
          data: `0x${req.bytecode}`,
          from: web3SigningCredential.ethAccount,
          gas: req.gas,
          gasPrice: req.gasPrice,
        },
        web3SigningCredential,
      });
      if (
        receipt.transactionReceipt.status &&
        receipt.transactionReceipt.contractAddress != undefined &&
        receipt.transactionReceipt.contractAddress != null
      ) {
        const address = { address: receipt.transactionReceipt.contractAddress };
        const contractStr = await keychainPlugin.get(req.contractName);
        const contractJSON = JSON.parse(contractStr);
        this.log.info(JSON.stringify(contractJSON));
        const contract = new this.web3.eth.Contract(
          contractJSON.abi,
          receipt.transactionReceipt.contractAddress,
        );
        this.contracts[req.contractName] = contract;

        const network = { [networkId]: address };
        contractJSON.networks = network;

        keychainPlugin.set(req.contractName, JSON.stringify(contractJSON));
      }

      return receipt;
    }
    throw new Error(
      `${fnTag} Cannot deploy contract without keychainId and the contractName`,
    );
  }


(state = initialState.ui, action) => {
  switch (action.type) {
    case TOGGLE_VIDEO_DIALOG:
      return Object.assign({}, state, {
        videoDialog: Object.assign({}, state.videoDialog, action.value),
      });
    case SET_VIEWPORT_SIZE:
      return Object.assign({}, state, {
        viewport: Object.assign({}, state.viewport, action.value),
      });
    case SET_HERO_SETTINGS:
      return Object.assign({}, state, {
        heroSettings: Object.assign({}, state.heroSettings, action.value),
      });
    default:
      return state;
  }
}


(state = initialState.routing, action) => {
  switch (action.type) {
    case SET_ROUTE:
      return Object.assign({}, state, {
        route: action.route,
        subRoute: null,
      });
    case SET_SUB_ROUTE:
      return Object.assign({}, state, {
        subRoute: action.subRoute,
      });
    default:
      return state;
  }
}


(state = initialState.dialogs, action) => {
  switch (action.type) {
    case OPEN_DIALOG:
    case SET_DIALOG_DATA:
      return Object.assign({}, state, action.dialog);

    case SET_DIALOG_ERROR: {
      const dialog = state[action.payload.dialogName];

      return Object.assign({}, state, {
        [action.payload.dialogName]: {
          isOpened: dialog.isOpened,
          data: Object.assign({}, dialog.data, { errorOccurred: true }),
        },
      });
    }

    case CLOSE_DIALOG:
      return Object.assign({}, state, {
        [action.dialogName]: initialState.dialogs[action.dialogName],
      });
    default:
      return state;
  }
}


(state = initialState.feedback, action) => {
  switch (action.type) {
    case FETCH_PREVIOUS_FEEDBACK:
      return Object.assign({}, state, {
        fetching: true,
        fetchingError: null,
      });

    case FETCH_PREVIOUS_FEEDBACK_FAILURE:
      return Object.assign({}, state, {
        fetching: false,
        fetchingError: action.payload.error,
      });

    case FETCH_PREVIOUS_FEEDBACK_SUCCESS:
      return Object.assign({}, state, {
        fetching: false,
        [action.payload.collection]: Object.assign({}, state[action.payload.collection], {
          [action.payload.dbItem]: action.payload.previousFeedback,
        }),
      });

    case SEND_FEEDBACK:
      return Object.assign({}, state, {
        adding: true,
        addingError: null,
      });

    case SEND_FEEDBACK_FAILURE:
      return Object.assign({}, state, {
        adding: false,
        addingError: action.payload.error,
      });

    case SEND_FEEDBACK_SUCCESS:
      return Object.assign({}, state, {
        adding: false,
        [action.payload.collection]: Object.assign({}, state[action.payload.collection], {
          [action.payload.dbItem]: {
            contentRating: action.payload.contentRating,
            styleRating: action.payload.styleRating,
            comment: action.payload.comment,
          },
        }),
      });

    case DELETE_FEEDBACK:
      return Object.assign({}, state, {
        deleting: true,
        deletingError: null,
      });

    case DELETE_FEEDBACK_FAILURE:
      return Object.assign({}, state, {
        deleting: false,
        deletingError: action.payload.error,
      });

    case DELETE_FEEDBACK_SUCCESS:
      return Object.assign({}, state, {
        deleting: false,
        [action.payload.collection]: {
          [action.payload.dbItem]: null,
        },
      });

    case WIPE_PREVIOUS_FEEDBACK:
      return initialState.feedback;

    default:
      return state;
  }
}


(state = initialState.videos, action) => {
  switch (action.type) {
    case FETCH_VIDEOS:
      return Object.assign({}, state, {
        fetching: true,
        fetchingError: null,
        list: [],
      });

    case FETCH_VIDEOS_FAILURE:
      return Object.assign({}, state, {
        fetching: false,
        fetchingError: action.payload.error,
      });

    case FETCH_VIDEOS_SUCCESS:
      return Object.assign({}, state, {
        fetching: false,
        list: action.payload.list,
      });

    default:
      return state;
  }
}


(state = initialState.blog, action) => {
  switch (action.type) {
    case FETCH_BLOG_LIST:
      return Object.assign({}, state, {
        fetching: true,
        fetchingError: null,
        list: [],
        obj: {},
      });

    case FETCH_BLOG_LIST_FAILURE:
      return Object.assign({}, state, {
        fetching: false,
        fetchingError: action.payload.error,
      });

    case FETCH_BLOG_LIST_SUCCESS:
      return Object.assign({}, state, {
        fetching: false,
        list: action.payload.list,
        obj: action.payload.obj,
      });

    default:
      return state;
  }
}


(state = initialState.opini, action) => {
  switch (action.type) {
    case FETCH_OPINI_LIST:
      return Object.assign({}, state, {
        fetching: true,
        fetchingError: null,
        list: [],
        obj: {},
      });

    case FETCH_OPINI_LIST_FAILURE:
      return Object.assign({}, state, {
        fetching: false,
        fetchingError: action.payload.error,
      });

    case FETCH_OPINI_LIST_SUCCESS:
      return Object.assign({}, state, {
        fetching: false,
        list: action.payload.list,
        obj: action.payload.obj,
      });

    default:
      return state;
  }
}


(state = initialState.speakers, action) => {
  switch (action.type) {
    case FETCH_SPEAKERS:
      return Object.assign({}, state, {
        fetching: true,
        fetchingError: null,
        list: [],
        obj: {},
      });

    case FETCH_SPEAKERS_FAILURE:
      return Object.assign({}, state, {
        fetching: false,
        fetchingError: action.payload.error,
      });

    case FETCH_SPEAKERS_SUCCESS:
      return Object.assign({}, state, {
        fetching: false,
        list: action.payload.list,
        obj: action.payload.obj,
      });

    default:
      return state;
  }
}


(state = initialState.sessions, action) => {
  switch (action.type) {
    case FETCH_SESSIONS:
      return Object.assign({}, state, {
        fetching: true,
        fetchingError: null,
        list: [],
        obj: {},
        objBySpeaker: {},
      });

    case FETCH_SESSIONS_FAILURE:
      return Object.assign({}, state, {
        fetching: false,
        fetchingError: action.payload.error,
      });

    case FETCH_SESSIONS_SUCCESS:
      return Object.assign({}, state, {
        fetching: false,
        list: action.payload.list,
        obj: action.payload.obj,
        objBySpeaker: action.payload.objBySpeaker,
      });

    case UPDATE_SESSIONS:
      return Object.assign({}, state, {
        list: action.payload.list,
        obj: action.payload.obj,
        objBySpeaker: action.payload.objBySpeaker,
      });

    case FETCH_USER_FEATURED_SESSIONS:
    case SET_USER_FEATURED_SESSIONS:
      return Object.assign({}, state, {
        featuredError: null,
        featuredFetching: true,
      });

    case FETCH_USER_FEATURED_SESSIONS_FAILURE:
    case SET_USER_FEATURED_SESSIONS_FAILURE:
      return Object.assign({}, state, {
        featuredError: action.payload.error,
        featuredFetching: false,
      });

    case FETCH_USER_FEATURED_SESSIONS_SUCCESS:
    case SET_USER_FEATURED_SESSIONS_SUCCESS:
      return Object.assign({}, state, {
        featured: action.payload.featuredSessions || {},
        featuredFetching: false,
      });

    default:
      return state;
  }
}


(state = initialState.schedule, action) => {
  switch (action.type) {
    case FETCH_SCHEDULE_SUCCESS:
      return action.data;
    default:
      return state;
  }
}


(state = initialState.gallery, action) => {
  switch (action.type) {
    case FETCH_GALLERY:
      return Object.assign({}, state, {
        fetching: true,
        fetchingError: null,
        list: [],
      });

    case FETCH_GALLERY_FAILURE:
      return Object.assign({}, state, {
        fetching: false,
        fetchingError: action.payload.error,
      });

    case FETCH_GALLERY_SUCCESS:
      return Object.assign({}, state, {
        fetching: false,
        list: action.payload.list,
      });

    default:
      return state;
  }
}


(state = initialState.user, action) => {
  switch (action.type) {
    case SIGN_IN:
    case SIGN_OUT:
      return action.user;
    default:
      return state;
  }
}


(state = initialState.pendaftaran, action) => {
  switch (action.type) {
    case DAFTAR_SUCCESS:
      return action.pendaftaran;
    case DAFTAR_FAILURE:
      return action.pendaftaran;
    default:
      return state;
  }
}


(state = initialState.toast, action) => {
  switch (action.type) {
    case SHOW_TOAST:
      return action.toast;
    case HIDE_TOAST:
      return initialState.toast;
    default:
      return state;
  }
}


(state = initialState.notifications, action) => {
  switch (action.type) {
    case UPDATE_NOTIFICATIONS_STATUS:
      return Object.assign({}, state, {
        status: action.status,
        token: action.token,
      });
    default:
      return state;
  }
}


(state = initialState.filters, action) => {
  switch (action.type) {
    case SET_FILTERS:
      return Object.assign({}, state, action.payload);
    default:
      return state;
  }
}


(state = initialState, action) => {
  return {
    ui: uiReducer(state.ui, action),
    routing: routingReducer(state.routing, action),
    dialogs: dialogsReducer(state.dialogs, action),
    feedback: feedbackReducer(state.feedback, action),
    videos: videosReducer(state.videos, action),
    blog: blogReducer(state.blog, action),
    opini: opiniReducer(state.opini, action),
    speakers: speakersReducer(state.speakers, action),
    sessions: sessionsReducer(state.sessions, action),
    schedule: scheduleReducer(state.schedule, action),
    gallery: galleryReducer(state.gallery, action),
    user: userReducer(state.user, action),
    pendaftaran: daftarReducer(state.pendaftaran, action),
    toast: toastReducer(state.toast, action),
    notifications: notificationsReducer(state.notifications, action),
    filters: filtersReducer(state.filters, action),
  };
}


({disabled, fieldName, labelText, listItems, refObject, validationRules}) => {
  const { control } = useFormContext();
  return (
    <FormField fieldName={fieldName}>
      <InputLabel htmlFor={fieldName} shrink={true}>{labelText}</InputLabel>
      <Controller
        as={
          <Select disabled={disabled} ref={refObject}>
            {listItems.map((e, key) => {
              return <MenuItem key={key} value={e.value} disabled={disabled}>{e.name}</MenuItem>;
            })}
          </Select>
        }


(e, key) => {
              return <MenuItem key={key} value={e.value} disabled={disabled}>{e.name}</MenuItem>;
            }


interface ListFormFieldProps extends FormFieldProps {
  labelText?: string;
  listItems: NameValuePair[];
  refObject?: any;
}


export interface Item {
    id?: string;
    name: string;
    description?: string;
    itemNumber: number;
}


interface MyObject {
  total: number;
  type: boolean;
}


interface Usage {
  flat?: string;
  my_str?: string;
  my_objects: MyObject;
}


fetch() {
    const testString = '123';

    return {
      flat: 'hello',
      my_str: testString,
      my_objects: {
        total: SOME_NUMBER,
        type: true,
      },
    };
  }


export declare class Scene extends IdentifyByKey {
    static DEFAULT_SCENE_ID: string;
    container: Three.Scene | undefined;
    pickingContainer: Three.Scene;
    layers: Layer<any, any>[];
    sortIsDirty: boolean;
    viewById: Map<string, View>;
    constructor(options: ISceneOptions);
    addLayer<T extends Instance, U extends ILayerProps<T>>(layer: Layer<T, U>): void;
    addView(view: View): void;
    destroy(): void;
    removeLayer(layer: Layer<any, any>): void;
    sortLayers(): void;
}


export interface ISceneOptions extends IdentifyByKeyOptions {
    views: IViewOptions[];
}


addLayer<T extends Instance, U extends ILayerProps<T>>(layer: Layer<T, U>): void;


addView(view: View): void;


removeLayer(layer: Layer<any, any>): void;


sortLayers(): void;


props => props.theme.code.fontSize


props => props.theme.code.fontFamily


props => transparentize(0.85, props.theme.colors.text)


(scheme, idx) => {
      return (

          {scheme.id}
          {scheme.scopes.length > 0 && ' ('}
          {scheme.scopes.map(scope => <ScopeName key={scope}>{scope}</ScopeName>)}
          {scheme.scopes.length > 0 && ') '}
          {idx < security.schemes.length - 1 && ' and '}

      );
    }


scope => <ScopeName key


props => props.theme.schemaView.defaultDetailsWidth


(security, idx) => (
                <SecurityRequirement key={idx}


export class SecurityRequirement extends React.PureComponent<SecurityRequirementProps> {
  render() {
    const security = this.props.security;
    return security.schemes.map((scheme, idx) => {
      return (

          {scheme.id}
          {scheme.scopes.length > 0 && ' ('}
          {scheme.scopes.map(scope => <ScopeName key={scope}>{scope}</ScopeName>)}
          {scheme.scopes.length > 0 && ') '}
          {idx < security.schemes.length - 1 && ' and '}

      );
    });
  }
}


export class SecurityRequirements extends React.PureComponent<SecurityRequirementsProps> {
  render() {
    const securities = this.props.securities;
    if (!securities.length) {
      return null;
    }
    return (

            <AuthHeaderColumn>
              <AuthHeader>Authorizations: </AuthHeader>
            </AuthHeaderColumn>
            <SecuritiesColumn>
              {securities.map((security, idx) => (
                <SecurityRequirement key={idx} security={security} />
              ))}
            </SecuritiesColumn>

    );
  }
}


export interface SecurityRequirementProps {
  security: SecurityRequirementModel;
}


export interface SecurityRequirementsProps {
  securities: SecurityRequirementModel[];
}


render() {
    const security = this.props.security;
    return security.schemes.map((scheme, idx) => {
      return (

          {scheme.id}
          {scheme.scopes.length > 0 && ' ('}
          {scheme.scopes.map(scope => <ScopeName key={scope}>{scope}</ScopeName>)}
          {scheme.scopes.length > 0 && ') '}
          {idx < security.schemes.length - 1 && ' and '}

      );
    });
  }


idx < security


render() {
    const securities = this.props.securities;
    if (!securities.length) {
      return null;
    }
    return (

            <AuthHeaderColumn>
              <AuthHeader>Authorizations: </AuthHeader>
            </AuthHeaderColumn>
            <SecuritiesColumn>
              {securities.map((security, idx) => (
                <SecurityRequirement key={idx} security={security} />
              ))}
            </SecuritiesColumn>

    );
  }


async function getTodos() {
      await axios
        .get<Array<Todo>>(`api/todos?account_id=${account_id}`)
        .then((res) => {
          if (isEmpty(res.data)) {
            setTodos([]);
            setCompletedTodos([]);
          } else {
            const notCompletedTodos = filter(res.data, (todo) => {
              return !todo.completed
            });
            const completedTodos = filter(res.data, (todo) => {
              return todo.completed || false
            });
            setTodos(notCompletedTodos);
            setCompletedTodos(completedTodos)
          }
        })
        .catch(() =>
          showMessage({ title: "todoの取得に失敗しました", status: "error" })
        )
        .finally(() => {
          setLoading(false);
        });
    }


() => {
  const { showMessage } = useMessage();

  const [loading, setLoading] = useState(false);
  const [todos, setTodos] = useState<Array<Todo>>([]);
  const [completedTodos, setCompletedTodos] = useState<Array<Todo>>([]);

  const getTodos = useCallback((loading: boolean, account_id: number) => {
    setLoading(loading);
    async function getTodos() {
      await axios
        .get<Array<Todo>>(`api/todos?account_id=${account_id}`)
        .then((res) => {
          if (isEmpty(res.data)) {
            setTodos([]);
            setCompletedTodos([]);
          } else {
            const notCompletedTodos = filter(res.data, (todo) => {
              return !todo.completed
            });
            const completedTodos = filter(res.data, (todo) => {
              return todo.completed || false
            });
            setTodos(notCompletedTodos);
            setCompletedTodos(completedTodos)
          }
        })
        .catch(() =>
          showMessage({ title: "todoの取得に失敗しました", status: "error" })
        )
        .finally(() => {
          setLoading(false);
        });
    }
    getTodos();
  }, []);
  return { getTodos, loading, todos, completedTodos };
}


(loading: boolean, account_id: number) => {
    setLoading(loading);
    async function getTodos() {
      await axios
        .get<Array<Todo>>(`api/todos?account_id=${account_id}`)
        .then((res) => {
          if (isEmpty(res.data)) {
            setTodos([]);
            setCompletedTodos([]);
          } else {
            const notCompletedTodos = filter(res.data, (todo) => {
              return !todo.completed
            });
            const completedTodos = filter(res.data, (todo) => {
              return todo.completed || false
            });
            setTodos(notCompletedTodos);
            setCompletedTodos(completedTodos)
          }
        })
        .catch(() =>
          showMessage({ title: "todoの取得に失敗しました", status: "error" })
        )
        .finally(() => {
          setLoading(false);
        });
    }
    getTodos();
  }


(res) => {
          if (isEmpty(res.data)) {
            setTodos([]);
            setCompletedTodos([]);
          } else {
            const notCompletedTodos = filter(res.data, (todo) => {
              return !todo.completed
            });
            const completedTodos = filter(res.data, (todo) => {
              return todo.completed || false
            });
            setTodos(notCompletedTodos);
            setCompletedTodos(completedTodos)
          }
        }


(todo) => {
              return !todo.completed
            }


(todo) => {
              return todo.completed || false
            }


() =>
          showMessage({ title: "todoの取得に失敗しました", status: "error" })


() => {
          setLoading(false);
        }


/* eslint-disable no-bitwise */
// The TransformerVersion and TransformerPlatform enums use bit flags to easily combine
// values. For example, if a schema is only supported on JS and iOS, this can be represented
// as (TransformerPlatform.js | TransformerPlatform.ios). Similarly, if a schema is supported
// on all platforms but Flutter with DataStore enabled, the flags can be set like this:
// (TransformerPlatform.all & ~TransformerPlatform.flutterDataStore). Ideally, we should be
// working toward a state where TransformerPlatform.all is the only value needed.
export const enum TransformerVersion {
  v1 = 1 << 0,
  v2 = 1 << 1,
  all = ~0,
}


export const enum TransformerPlatform {
  none = 0,
  api = 1 << 0,
  dataStore = 1 << 1,
  js = 1 << 2,
  jsDataStore = 1 << 3,
  ios = 1 << 4,
  iosDataStore = 1 << 5,
  android = 1 << 6,
  androidDataStore = 1 << 7,
  flutter = 1 << 8,
  flutterDataStore = 1 << 9,
  all = ~0,
}


export type TransformerSchema = {
  description: string;
  transformerVersion: TransformerVersion;
  supportedPlatforms: TransformerPlatform;
  sdl: string;
};


(c): boolean => c.ID === this.Command.ID


(c): boolean => c.ID === header.commandIdentifier


(condition): boolean => {
                if (condition.type === 'statusEquals') {
                    return entry.status !== condition.value;
                } else if (condition.type == 'statusNotEquals') {
                    return entry.status === condition.value;
                } else if (condition.type == 'directionEquals') {
                    return entry.direction !== condition.value;
                } else if (remainingBufferBytes != null && condition.type == 'minimumRemainingBufferBytes') {
                    return remainingBufferBytes < condition.value;
                } else  {
                    /* istanbul ignore else */
                    if (condition.type == 'dataTypeValueTypeEquals') {
                        return Utils.IsDataTypeAnalogOrDiscrete(entry.dataType) !== condition.value;
                    }
                }
            }


interface ZclHeader {
    frameControl: FrameControl;
    manufacturerCode: number;
    transactionSequenceNumber: number;
    commandIdentifier: number;
}


// eslint-disable-next-line
type ZclPayload = any;


/**
     * Creating
     */
public static create(
        frameType: FrameType, direction: Direction, disableDefaultResponse: boolean, manufacturerCode: number,
        transactionSequenceNumber: number, commandKey: number | string, clusterID: number,
        payload: ZclPayload, reservedBits = 0
    ): ZclFrame {
        const cluster = Utils.getCluster(clusterID, manufacturerCode != null ? manufacturerCode : null);
        let command: TsType.Command = null;
        if (frameType === FrameType.GLOBAL) {
            command = Utils.getGlobalCommand(commandKey);
        } else {
            command = direction === Direction.CLIENT_TO_SERVER ?
                cluster.getCommand(commandKey) : cluster.getCommandResponse(commandKey);
        }

        const header: ZclHeader = {
            frameControl: {
                reservedBits, frameType, direction, disableDefaultResponse,
                manufacturerSpecific: manufacturerCode != null,
            },
            transactionSequenceNumber,
            manufacturerCode,
            commandIdentifier: command.ID,
        };

        return new ZclFrame(header, payload, cluster, command);
    }


public toBuffer(): Buffer {
        const buffalo = new BuffaloZcl(Buffer.alloc(250));
        this.writeHeader(buffalo);

        if (this.Header.frameControl.frameType === FrameType.GLOBAL) {
            this.writePayloadGlobal(buffalo);
        } else if (this.Header.frameControl.frameType === FrameType.SPECIFIC) {
            this.writePayloadCluster(buffalo);
        } else {
            throw new Error(`Frametype '${this.Header.frameControl.frameType}' not valid`);
        }

        return buffalo.getBuffer().slice(0, buffalo.getPosition());
    }


private writeHeader(buffalo: BuffaloZcl): void {
        const frameControl = (
            (this.Header.frameControl.frameType & 0x03) |
            (((this.Header.frameControl.manufacturerSpecific ? 1 : 0) << 2) & 0x04) |
            ((this.Header.frameControl.direction << 3) & 0x08) |
            (((this.Header.frameControl.disableDefaultResponse ? 1 : 0) << 4) & 0x10) |
            ((this.Header.frameControl.reservedBits << 5) & 0xE0)
        );

        buffalo.writeUInt8(frameControl);

        if (this.Header.frameControl.manufacturerSpecific) {
            buffalo.writeUInt16(this.Header.manufacturerCode);
        }

        buffalo.writeUInt8(this.Header.transactionSequenceNumber);
        buffalo.writeUInt8(this.Header.commandIdentifier);
    }


private writePayloadGlobal(buffalo: BuffaloZcl): void {
        const command = Object.values(Foundation).find((c): boolean => c.ID === this.Command.ID);

        if (command.parseStrategy === 'repetitive') {
            for (const entry of this.Payload) {
                for (const parameter of command.parameters) {
                    const options: TsType.BuffaloZclOptions = {};

                    if (!ZclFrame.conditionsValid(parameter, entry, null)) {
                        continue;
                    }

                    if (parameter.type === BuffaloZclDataType.USE_DATA_TYPE && typeof entry.dataType === 'number') {
                        // We need to grab the dataType to parse useDataType
                        options.dataType = DataType[entry.dataType];
                    }

                    const typeStr = ZclFrame.getDataTypeString(parameter.type);
                    buffalo.write(typeStr, entry[parameter.name], options);
                }
            }
        } else if (command.parseStrategy === 'flat') {
            for (const parameter of command.parameters) {
                buffalo.write(DataType[parameter.type], this.Payload[parameter.name], {});
            }
        } else {
            /* istanbul ignore else */
            if (command.parseStrategy === 'oneof') {
                /* istanbul ignore else */
                if (command === Foundation.discoverRsp) {
                    buffalo.writeUInt8(this.Payload.discComplete);

                    for (const entry of this.Payload.attrInfos) {
                        for (const parameter of command.parameters) {
                            buffalo.write(DataType[parameter.type], entry[parameter.name], {});
                        }
                    }
                }
            }
        }
    }


private writePayloadCluster(buffalo: BuffaloZcl): void {
        for (const parameter of this.Command.parameters) {
            if (!ZclFrame.conditionsValid(parameter, this.Payload, null)) {
                continue;
            }

            if (!this.Payload.hasOwnProperty(parameter.name)) {
                throw new Error(`Parameter '${parameter.name}' is missing`);
            }

            const typeStr = ZclFrame.getDataTypeString(parameter.type);
            buffalo.write(typeStr, this.Payload[parameter.name], {});
        }
    }


/**
     * Parsing
     */
public static fromBuffer(clusterID: number, buffer: Buffer): ZclFrame {
        if (buffer.length < MINIMAL_FRAME_LENGTH) {
            throw new Error("ZclFrame length is lower than minimal length");
        }

        const buffalo = new BuffaloZcl(buffer);
        const header = this.parseHeader(buffalo);

        let command: TsType.Command = null;
        if (header.frameControl.frameType === FrameType.GLOBAL) {
            command = Utils.getGlobalCommand(header.commandIdentifier);
        } else {
            const cluster = Utils.getCluster(clusterID, header.manufacturerCode);
            command = header.frameControl.direction === Direction.CLIENT_TO_SERVER ?
                cluster.getCommand(header.commandIdentifier) : cluster.getCommandResponse(header.commandIdentifier);
        }

        const cluster = Utils.getCluster(
            clusterID,
            header.frameControl.manufacturerSpecific ? header.manufacturerCode : null
        );
        const payload = this.parsePayload(header, cluster, buffalo);

        return new ZclFrame(header, payload, cluster, command);
    }


private static parseHeader(buffalo: BuffaloZcl): ZclHeader {
        const frameControlValue = buffalo.readUInt8();
        const frameControl = {
            frameType: frameControlValue & 0x03,
            manufacturerSpecific: ((frameControlValue >> 2) & 0x01) === 1,
            direction: (frameControlValue >> 3) & 0x01,
            disableDefaultResponse: ((frameControlValue >> 4) & 0x01) === 1,
            reservedBits: frameControlValue >> 5,
        };

        let manufacturerCode = null;
        if (frameControl.manufacturerSpecific) {
            manufacturerCode = buffalo.readUInt16();
        }

        const transactionSequenceNumber = buffalo.readUInt8();
        const commandIdentifier = buffalo.readUInt8();

        return {frameControl, transactionSequenceNumber, manufacturerCode, commandIdentifier};
    }


private static parsePayload(header: ZclHeader, cluster: TsType.Cluster, buffalo: BuffaloZcl): ZclPayload {
        if (header.frameControl.frameType === FrameType.GLOBAL) {
            return this.parsePayloadGlobal(header, buffalo);
        } else if (header.frameControl.frameType === FrameType.SPECIFIC) {
            return this.parsePayloadCluster(header, cluster, buffalo);
        } else {
            throw new Error(`Unsupported frameType '${header.frameControl.frameType}'`);
        }
    }


private static parsePayloadCluster(header: ZclHeader, cluster: TsType.Cluster,  buffalo: BuffaloZcl): ZclPayload {
        const command = header.frameControl.direction === Direction.CLIENT_TO_SERVER ?
            cluster.getCommand(header.commandIdentifier) : cluster.getCommandResponse(header.commandIdentifier);
        const payload: ZclPayload = {};

        for (const parameter of command.parameters) {
            const options: BuffaloTsType.Options = {payload};

            if (ListTypes.includes(parameter.type)) {
                const lengthParameter = command.parameters[command.parameters.indexOf(parameter) - 1];
                const length = payload[lengthParameter.name];

                /* istanbul ignore else */
                if (typeof length === 'number') {
                    options.length = length;
                }
            }

            const typeStr = ZclFrame.getDataTypeString(parameter.type);
            payload[parameter.name] = buffalo.read(typeStr, options);
        }

        return payload;
    }


private static parsePayloadGlobal(header: ZclHeader, buffalo: BuffaloZcl): ZclPayload {
        const command = Object.values(Foundation).find((c): boolean => c.ID === header.commandIdentifier);

        if (command.parseStrategy === 'repetitive') {
            const payload = [];

            while (buffalo.getPosition() < buffalo.getBuffer().length) {
                const entry: {[s: string]: BuffaloTsType.Value} = {};

                for (const parameter of command.parameters) {
                    const options: TsType.BuffaloZclOptions = {};

                    if (!this.conditionsValid(parameter, entry, buffalo.getBuffer().length - buffalo.getPosition())) {
                        continue;
                    }

                    if (parameter.type === BuffaloZclDataType.USE_DATA_TYPE && typeof entry.dataType === 'number') {
                        // We need to grab the dataType to parse useDataType
                        options.dataType = DataType[entry.dataType];

                        if (entry.dataType === DataType.charStr && entry.hasOwnProperty('attrId')) {
                            // For Xiaomi struct parsing we need to pass the attributeID.
                            options.attrId = entry.attrId;
                        }
                    }

                    const typeStr = DataType[parameter.type] != null ?
                        DataType[parameter.type] : BuffaloZclDataType[parameter.type];
                    entry[parameter.name] = buffalo.read(typeStr, options);

                    // TODO: not needed, but temp workaroudn to make payload equal to that of zcl-packet
                    if (parameter.type === BuffaloZclDataType.USE_DATA_TYPE && entry.dataType === DataType.struct) {
                        entry['structElms'] = entry.attrData;
                        entry['numElms'] = entry.attrData.length;
                    }
                }

                payload.push(entry);
            }

            return payload;
        } else if (command.parseStrategy === 'flat') {
            const payload: {[s: string]: BuffaloTsType.Value} = {};

            for (const parameter of command.parameters) {
                payload[parameter.name] = buffalo.read(DataType[parameter.type], {});
            }

            return payload;
        } else {
            /* istanbul ignore else */
            if (command.parseStrategy === 'oneof') {
                /* istanbul ignore else */
                if (command === Foundation.discoverRsp) {
                    const payload: {[s: string]: BuffaloTsType.Value} = {};
                    payload.discComplete = buffalo.readUInt8();
                    payload.attrInfos = [];

                    while (buffalo.getPosition() < buffalo.getBuffer().length) {
                        const entry: {[s: string]: BuffaloTsType.Value} = {};

                        for (const parameter of command.parameters) {
                            entry[parameter.name] = buffalo.read(DataType[parameter.type], {});
                        }

                        payload.attrInfos.push(entry);
                    }

                    return payload;
                }
            }
        }
    }


/**
     * Utils
     */
private static getDataTypeString(dataType: DataType | BuffaloZclDataType): string {
        return DataType[dataType] != null ? DataType[dataType] : BuffaloZclDataType[dataType];
    }


private static conditionsValid(
        parameter: DefinitionTsType.ParameterDefinition,
        entry: ZclPayload,
        remainingBufferBytes: number
    ): boolean {
        if (parameter.conditions) {
            const failedCondition = parameter.conditions.find((condition): boolean => {
                if (condition.type === 'statusEquals') {
                    return entry.status !== condition.value;
                } else if (condition.type == 'statusNotEquals') {
                    return entry.status === condition.value;
                } else if (condition.type == 'directionEquals') {
                    return entry.direction !== condition.value;
                } else if (remainingBufferBytes != null && condition.type == 'minimumRemainingBufferBytes') {
                    return remainingBufferBytes < condition.value;
                } else  {
                    /* istanbul ignore else */
                    if (condition.type == 'dataTypeValueTypeEquals') {
                        return Utils.IsDataTypeAnalogOrDiscrete(entry.dataType) !== condition.value;
                    }
                }
            });

            if (failedCondition) {
                return false;
            }
        }

        return true;
    }


public isSpecific(): boolean {
        return this.Header.frameControl.frameType === FrameType.SPECIFIC;
    }


public isGlobal(): boolean {
        return this.Header.frameControl.frameType === FrameType.GLOBAL;
    }


// List of clusters is not completed, feel free to add more.
public isCluster(clusterName: 'genTime' | 'genAnalogInput' | 'genBasic' | 'genGroups' | 'ssIasZone'): boolean {
        return this.Cluster.name === clusterName;
    }


// List of commands is not completed, feel free to add more.
public isCommand(
        commandName: 'read' | 'report' | 'readRsp' | 'remove' | 'add' | 'write' | 'enrollReq' | 'configReport'
    ): boolean {
        return this.getCommand().name === commandName;
    }


public getCommand(): TsType.Command {
        let command: TsType.Command = null;
        if (this.Header.frameControl.frameType === FrameType.GLOBAL) {
            command = Utils.getGlobalCommand(this.Header.commandIdentifier);
        } else {
            command = this.Header.frameControl.direction === Direction.CLIENT_TO_SERVER ?
                this.Cluster.getCommand(this.Header.commandIdentifier) :
                this.Cluster.getCommandResponse(this.Header.commandIdentifier);
        }
        return command;
    }


export function rep<TKind, TResult>(p: Parser<TKind, TResult>): Parser<TKind, TResult[]> {
    const reprParser = repr(p);
    return {
        parse(token: Token<TKind>): ParserOutput<TKind, TResult[]> {
            const output = reprParser.parse(token);
            if (output.successful) {
                return {
                    candidates: output.candidates.reverse(),
                    successful: true,
                    error: output.error
                };
            } else {
                return output;
            }
        }
    };
}


export function rep_sc<TKind, TResult>(p: Parser<TKind, TResult>): Parser<TKind, TResult[]> {
    return {
        parse(token: Token<TKind>): ParserOutput<TKind, TResult[]> {
            let error: ParseError | undefined;
            let result: ParseResult<TKind, TResult[]>[] = [{ nextToken: token, result: [] }];

            while (true) {
                const steps = result;
                result = [];
                for (const step of steps) {
                    const output = p.parse(step.nextToken);
                    error = betterError(error, output.error);

                    if (output.successful) {
                        for (const candidate of output.candidates) {
                            if (candidate.nextToken !== step.nextToken) {
                                result.push({
                                    nextToken: candidate.nextToken,
                                    result: step.result.concat([candidate.result])
                                });
                            }
                        }
                    }
                }

                if (result.length === 0) {
                    result = steps;
                    break;
                }
            }
            return resultOrError(result, error, true);
        }
    };
}


export function repr<TKind, TResult>(p: Parser<TKind, TResult>): Parser<TKind, TResult[]> {
    return {
        parse(token: Token<TKind>): ParserOutput<TKind, TResult[]> {
            let error: ParseError | undefined;
            const result: ParseResult<TKind, TResult[]>[] = [{ nextToken: token, result: [] }];

            for (let i = 0; i < result.length; i++) {
                const step = result[i];
                const output = p.parse(step.nextToken);
                error = betterError(error, output.error);

                if (output.successful) {
                    for (const candidate of output.candidates) {
                        if (candidate.nextToken !== step.nextToken) {
                            result.push({
                                nextToken: candidate.nextToken,
                                result: step.result.concat([candidate.result])
                            });
                        }
                    }
                }
            }
            return resultOrError(result, error, true);
        }
    };
}


function applyList<TResult, TSeparator>(value: [TResult, [TSeparator, TResult][]]): TResult[] {
    return [value[0]].concat(value[1].map((pair: [TSeparator, TResult]) => { return pair[1]; }));
}


export function list<TKind, TResult, TSeparator>(p: Parser<TKind, TResult>, s: Parser<TKind, TSeparator>): Parser<TKind, TResult[]> {
    return apply(seq(p, rep(seq(s, p))), applyList);
}


export function list_sc<TKind, TResult, TSeparator>(p: Parser<TKind, TResult>, s: Parser<TKind, TSeparator>): Parser<TKind, TResult[]> {
    return apply(seq(p, rep_sc(seq(s, p))), applyList);
}


function applyLrec<TResult, TFirst extends TResult, TSecond>(callback: (a: TResult, b: TSecond) => TResult): (value: [TFirst, TSecond[]]) => TResult {
    return (value: [TFirst, TSecond[]]): TResult => {
        let result: TResult = value[0];
        for (const tail of value[1]) {
            result = callback(result, tail);
        }
        return result;
    };
}


export function lrec<TKind, TResult, TFirst extends TResult, TSecond>(p: Parser<TKind, TFirst>, q: Parser<TKind, TSecond>, callback: (a: TResult, b: TSecond) => TResult): Parser<TKind, TResult> {
    return apply(seq(p, rep(q)), applyLrec(callback));
}


export function lrec_sc<TKind, TResult, TFirst extends TResult, TSecond>(p: Parser<TKind, TFirst>, q: Parser<TKind, TSecond>, callback: (a: TResult, b: TSecond) => TResult): Parser<TKind, TResult> {
    return apply(seq(p, rep_sc(q)), applyLrec(callback));
}


(pair: [TSeparator, TResult]) => { return pair[1]; }


(value: [TFirst, TSecond[]]): TResult => {
        let result: TResult = value[0];
        for (const tail of value[1]) {
            result = callback(result, tail);
        }
        return result;
    }


parse(token: Token<TKind>): ParserOutput<TKind, TResult[]> {
            const output = reprParser.parse(token);
            if (output.successful) {
                return {
                    candidates: output.candidates.reverse(),
                    successful: true,
                    error: output.error
                };
            } else {
                return output;
            }
        }


parse(token: Token<TKind>): ParserOutput<TKind, TResult[]> {
            let error: ParseError | undefined;
            let result: ParseResult<TKind, TResult[]>[] = [{ nextToken: token, result: [] }];

            while (true) {
                const steps = result;
                result = [];
                for (const step of steps) {
                    const output = p.parse(step.nextToken);
                    error = betterError(error, output.error);

                    if (output.successful) {
                        for (const candidate of output.candidates) {
                            if (candidate.nextToken !== step.nextToken) {
                                result.push({
                                    nextToken: candidate.nextToken,
                                    result: step.result.concat([candidate.result])
                                });
                            }
                        }
                    }
                }

                if (result.length === 0) {
                    result = steps;
                    break;
                }
            }
            return resultOrError(result, error, true);
        }


parse(token: Token<TKind>): ParserOutput<TKind, TResult[]> {
            let error: ParseError | undefined;
            const result: ParseResult<TKind, TResult[]>[] = [{ nextToken: token, result: [] }];

            for (let i = 0; i < result.length; i++) {
                const step = result[i];
                const output = p.parse(step.nextToken);
                error = betterError(error, output.error);

                if (output.successful) {
                    for (const candidate of output.candidates) {
                        if (candidate.nextToken !== step.nextToken) {
                            result.push({
                                nextToken: candidate.nextToken,
                                result: step.result.concat([candidate.result])
                            });
                        }
                    }
                }
            }
            return resultOrError(result, error, true);
        }


@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(CommentEntity)
    private readonly comment: Repository<CommentEntity>,
    @InjectRepository(ItemEntity) private readonly item: Repository<ItemEntity>,
  ) {}

  async register(
    owner: UserEntity,
    { itemId, content }: CommentRegisterInputDto,
  ) {
    try {
      const item = await this.item.findOne({
        where: {
          pk: itemId,
        },
      })
      if (!item) {
        return {
          access: false,
          message: 'Not found item',
        }
      }
      const comment = await this.comment.create({
        content,
      })
      comment.owner = owner
      comment.item = item
      await this.comment.save(comment)
      return {
        access: true,
        message: 'Success register comment',
      }
    } catch (e) {
      throw new InternalServerErrorException(e.message)
    }
  }

  async getAll({ itemId, size, page }: CommentsGetInputDto) {
    try {
      const item = await this.item.findOne({
        where: {
          pk: itemId,
        },
      })
      if (!item) {
        return {
          access: false,
          message: 'Not found item',
        }
      }
      const [comments, commentsCount] = await this.comment.findAndCount({
        relations: ['owner'],
        where: {
          item: {
            pk: itemId,
          },
        },
        take: size,
        skip: (page - 1) * size,
        order: {
          createAt: 'DESC',
        },
      })
      return {
        access: true,
        message: 'Success',
        comments,
        pageCount: Math.ceil(commentsCount / size),
        commentsCount,
      }
    } catch (e) {
      throw new InternalServerErrorException(e.message)
    }
  }

  async getMy(owner: UserEntity, { size, page }: CommentsMyInputDto) {
    try {
      const [comments, commentsCount] = await this.comment.findAndCount({
        where: {
          owner: {
            pk: owner.pk,
          },
        },
        take: size,
        skip: (page - 1) * size,
        order: {
          createAt: 'DESC',
        },
      })
      return {
        access: true,
        message: 'Success',
        comments,
        pageCount: Math.ceil(commentsCount / size),
        commentsCount,
      }
    } catch (e) {
      throw new InternalServerErrorException(e.message)
    }
  }
}


async register(
    owner: UserEntity,
    { itemId, content }: CommentRegisterInputDto,
  ) {
    try {
      const item = await this.item.findOne({
        where: {
          pk: itemId,
        },
      })
      if (!item) {
        return {
          access: false,
          message: 'Not found item',
        }
      }
      const comment = await this.comment.create({
        content,
      })
      comment.owner = owner
      comment.item = item
      await this.comment.save(comment)
      return {
        access: true,
        message: 'Success register comment',
      }
    } catch (e) {
      throw new InternalServerErrorException(e.message)
    }
  }


async getAll({ itemId, size, page }: CommentsGetInputDto) {
    try {
      const item = await this.item.findOne({
        where: {
          pk: itemId,
        },
      })
      if (!item) {
        return {
          access: false,
          message: 'Not found item',
        }
      }
      const [comments, commentsCount] = await this.comment.findAndCount({
        relations: ['owner'],
        where: {
          item: {
            pk: itemId,
          },
        },
        take: size,
        skip: (page - 1) * size,
        order: {
          createAt: 'DESC',
        },
      })
      return {
        access: true,
        message: 'Success',
        comments,
        pageCount: Math.ceil(commentsCount / size),
        commentsCount,
      }
    } catch (e) {
      throw new InternalServerErrorException(e.message)
    }
  }


async getMy(owner: UserEntity, { size, page }: CommentsMyInputDto) {
    try {
      const [comments, commentsCount] = await this.comment.findAndCount({
        where: {
          owner: {
            pk: owner.pk,
          },
        },
        take: size,
        skip: (page - 1) * size,
        order: {
          createAt: 'DESC',
        },
      })
      return {
        access: true,
        message: 'Success',
        comments,
        pageCount: Math.ceil(commentsCount / size),
        commentsCount,
      }
    } catch (e) {
      throw new InternalServerErrorException(e.message)
    }
  }


async function main(url: string) {
	const res = await superagent
		.post(url)
		.send({ a: 'b' })
		.set('Accept', '*/*')
		.timeout(3 * 1000)
		.agent(url.startsWith('https:') ? httpsAgent : httpAgent)
		.catch(error => {
			// ステータスエラーとかはそのままthrowされるとちょっと長い
			throw `name=${error.name} message=${error.message} status=${error.status} code=${error.code}`;
			// name=Error message=Not Found status=404 statusCode=404 code='ECONNABORTED'
			// name=Error message=Timeout of 3000ms exceeded status=undefined code='ECONNABORTED'
			// name=Error message=Hostname/IP does not match certificate's altnames: IP: 127.0.0.1 is not in the cert's list:  status=undefined code=ERR_TLS_CERT_ALTNAME_INVALID
			// name=Error message=ENOTFOUND example.comx status=undefined code=ENOTFOUND
		});

	// 'Accept-Encoding': 'gzip, deflate' がデフォルト
	// レスポンスパースJSONを強制することが出来ないので、非標準のContent-Typeで返ってくる時はカスタムパーサーが必要

	console.log(inspect(res.body));
}


error => {
			// ステータスエラーとかはそのままthrowされるとちょっと長い
			throw `name=${error.name} message=${error.message} status=${error.status} code=${error.code}`;
			// name=Error message=Not Found status=404 statusCode=404 code='ECONNABORTED'
			// name=Error message=Timeout of 3000ms exceeded status=undefined code='ECONNABORTED'
			// name=Error message=Hostname/IP does not match certificate's altnames: IP: 127.0.0.1 is not in the cert's list:  status=undefined code=ERR_TLS_CERT_ALTNAME_INVALID
			// name=Error message=ENOTFOUND example.comx status=undefined code=ENOTFOUND
		}


e => {
	console.log(inspect(e));
}


()=>{
  let completedAssignmentComponent: CompletedAssignmentComponent;
  let completedAssignmentFixture : ComponentFixture<CompletedAssignmentComponent>;

  beforeEach(()=>{
    TestBed.configureTestingModule({
      declarations: [CompletedAssignmentComponent],
      imports : [CommonModule,
         MaterialModule,
         BrowserAnimationsModule,
         PipesModule
         ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        {provide: DialogService, useClass: MockDialogService},
        {provide: ItemRepository, useClass: MockItemRepository}
      ]
    }).compileComponents();

    completedAssignmentFixture = TestBed.createComponent(CompletedAssignmentComponent);
    completedAssignmentComponent = completedAssignmentFixture.componentInstance;
    completedAssignmentComponent.assignment = new ItemProxy('Action', MockAction());

    completedAssignmentFixture.detectChanges();

  })

  afterEach(() => {
    completedAssignmentFixture.destroy();
    TestBed.resetTestingModule();
  })

  it('instantiates the completedAssignment component', ()=>{
    expect(completedAssignmentComponent).toBeTruthy();
  })
}


()=>{
    TestBed.configureTestingModule({
      declarations: [CompletedAssignmentComponent],
      imports : [CommonModule,
         MaterialModule,
         BrowserAnimationsModule,
         PipesModule
         ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        {provide: DialogService, useClass: MockDialogService},
        {provide: ItemRepository, useClass: MockItemRepository}
      ]
    }).compileComponents();

    completedAssignmentFixture = TestBed.createComponent(CompletedAssignmentComponent);
    completedAssignmentComponent = completedAssignmentFixture.componentInstance;
    completedAssignmentComponent.assignment = new ItemProxy('Action', MockAction());

    completedAssignmentFixture.detectChanges();

  }


() => {
    completedAssignmentFixture.destroy();
    TestBed.resetTestingModule();
  }


()=>{
    expect(completedAssignmentComponent).toBeTruthy();
  }


function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}


function setSession(sessionId: string, update: Partial<EditorSession>) {
  const { editorSessions } = getState();
  const session = getState().getSession(sessionId);
  if (!session) {
    return setState({
      editorSessions: {
        ...editorSessions,
        [sessionId]: { ...INITIAL_SESSION, ...update },
      },
    });
  }
  setState({
    editorSessions: {
      ...editorSessions,
      [sessionId]: { ...session, ...update },
    },
  });
}


function setBatch(sessionId: string, batchId: string, batch: Batch) {
  const { batches, statements } = getState();
  const { selectedStatementId } = getState().getSession(sessionId) || {};

  const updatedStatements = {
    ...statements,
  };

  if (batch?.statements) {
    for (const statement of batch.statements) {
      updatedStatements[statement.id] = statement;
    }
    if (batch.statements.length === 1) {
      const onlyStatementId = batch.statements[0].id;
      if (selectedStatementId !== onlyStatementId) {
        setSession(sessionId, { selectedStatementId: onlyStatementId });
      }
    }
  }

  setState({
    statements: updatedStatements,
    batches: {
      ...batches,
      [batchId]: batch,
    },
  });
}


export function toggleShowQueryModal() {
  const { showQueryModal } = getState();
  setState({ showQueryModal: !showQueryModal });
}


export function setMouseOverResultPane(mouseOverResultPane: boolean) {
  setState({ mouseOverResultPane });
}


/**
 * Reset state (on signout for example)
 */
export async function resetState() {
  setState({ ...INITIAL_STATE });
}


/**
 * Open a connection client for the currently selected connection if supported
 */
export async function connectConnectionClient() {
  const { focusedSessionId } = getState();
  const { connectionClient, connectionId } = getState().getFocusedSession();

  // If a connectionClient is already open or selected connection id doesn't exist, do nothing
  if (connectionClient || !connectionId) {
    return;
  }

  // Regular users are not allowed to get connections by id, but they can get list of connections
  // May want to store selected connection instead of just id
  const { data: connections } = await api.getConnections();
  const connection = (connections || []).find(
    (connection) => connection.id === connectionId
  );

  if (connection) {
    setAsynchronousDriver(connection.isAsynchronous);
  }

  const supportedAndEnabled =
    connection &&
    connection.supportsConnectionClient &&
    connection.multiStatementTransactionEnabled;

  if (!supportedAndEnabled) {
    return;
  }

  const json = await api.post('/api/connection-clients', {
    connectionId,
  });
  if (json.error) {
    return message.error('Problem connecting to database');
  }

  setSession(focusedSessionId, {
    connectionClient: json.data,
    isDriverAsynchronous: connection ? connection.isAsynchronous : false,
  });
}