() => {
    const versions = ['1.0.0', '2.0', '3', '1.0.0-beta', '2.0-beta', '2-beta']
    const result = normalizeVersionsToSemver(versions)
    expect(result)
      .to.be.an('array')
      .deep.equal([
        '1.0.0',
        '2.0.0',
        '3.0.0',
        '1.0.0-beta',
        '2.0.0-beta',
        '2.0.0-beta',
      ])
  }


export class TestContract__factory extends ContractFactory {
  constructor(signer?: Signer) {
    super(_abi, _bytecode, signer);
  }

  deploy(
    _amount: BigNumberish,
    overrides?: Overrides & { from?: string | Promise<string> }
  ): Promise<TestContract> {
    return super.deploy(_amount, overrides || {}) as Promise<TestContract>;
  }
  getDeployTransaction(
    _amount: BigNumberish,
    overrides?: Overrides & { from?: string | Promise<string> }
  ): TransactionRequest {
    return super.getDeployTransaction(_amount, overrides || {});
  }
  attach(address: string): TestContract {
    return super.attach(address) as TestContract;
  }
  connect(signer: Signer): TestContract__factory {
    return super.connect(signer) as TestContract__factory;
  }
  static readonly bytecode = _bytecode;
  static readonly abi = _abi;
  static createInterface(): TestContractInterface {
    return new utils.Interface(_abi) as TestContractInterface;
  }
  static connect(
    address: string,
    signerOrProvider: Signer | Provider
  ): TestContract {
    return new Contract(address, _abi, signerOrProvider) as TestContract;
  }
}


deploy(
    _amount: BigNumberish,
    overrides?: Overrides & { from?: string | Promise<string> }
  ): Promise<TestContract> {
    return super.deploy(_amount, overrides || {}) as Promise<TestContract>;
  }


getDeployTransaction(
    _amount: BigNumberish,
    overrides?: Overrides & { from?: string | Promise<string> }
  ): TransactionRequest {
    return super.getDeployTransaction(_amount, overrides || {});
  }


attach(address: string): TestContract {
    return super.attach(address) as TestContract;
  }


connect(signer: Signer): TestContract__factory {
    return super.connect(signer) as TestContract__factory;
  }


static createInterface(): TestContractInterface {
    return new utils.Interface(_abi) as TestContractInterface;
  }


static connect(
    address: string,
    signerOrProvider: Signer | Provider
  ): TestContract {
    return new Contract(address, _abi, signerOrProvider) as TestContract;
  }


@Component({
  selector: 'app-advantages-panel',
  templateUrl: './advantages-panel.component.html',
  styleUrls: ['./advantages-panel.component.scss']
})
export class AdvantagesPanelComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


(event) => {
    if (event.target == foundOrderModal) {
     $(()=>{ $('#foundOrderModal').fadeOut();})
    }
    else if(event.target == orderModal){
      $(()=>{ $('#orderModal').fadeOut();})
    }
  }


()=>{ $('#foundOrderModal').fadeOut();}


()=>{ $('#orderModal').fadeOut();}


()=>{
      if(mode == 'in'){
        $('#orderModal').fadeIn();
      }
      else if(mode == 'out'){
        $('#orderModal').fadeOut();
      }
    }


()=>{
      if(mode == 'in'){
        $('#foundOrderModal').fadeIn();
      }
      else if(mode == 'out'){
        $('#foundOrderModal').fadeOut();
      }
    }


()=>{
    if(event == 'foundOrderModal'){
       $('#foundOrderModal').fadeOut();
    }
    else if(event == 'orderModal'){
      $('#orderModal').fadeOut();
    }
   }


(authorizedUser:any)=>{
         if(authorizedUser.success == true){
           this.ordersService.makeOrder(authorizedUser.userId,orderName,orderDescription).subscribe((res:any)=>{
             if(res.success == false){
               this.notificationService.showError(res.message,"Ordering failed");
             }
             else if(res.success == true){
              if(this.url != null && this.orderImage != ""){
                 this.ordersService.addOrderImage(res.order.insertId,this.orderImage).subscribe((result:any)=>{
                 if(result.success != true){
                  this.notificationService.showError('Error! Image not uploaded',"Upload image unsuccessful")
                  }
               })
              }
              this.onFetchUserOrders();
              this.notificationService.showSuccess('You have made an order','Ordering successful');
              this.clearFields();
             }
           })
         }
       }


(res:any)=>{
             if(res.success == false){
               this.notificationService.showError(res.message,"Ordering failed");
             }
             else if(res.success == true){
              if(this.url != null && this.orderImage != ""){
                 this.ordersService.addOrderImage(res.order.insertId,this.orderImage).subscribe((result:any)=>{
                 if(result.success != true){
                  this.notificationService.showError('Error! Image not uploaded',"Upload image unsuccessful")
                  }
               })
              }
              this.onFetchUserOrders();
              this.notificationService.showSuccess('You have made an order','Ordering successful');
              this.clearFields();
             }
           }


(result:any)=>{
                 if(result.success != true){
                  this.notificationService.showError('Error! Image not uploaded',"Upload image unsuccessful")
                  }
               }


()=>{
      $(`#${fieldName}`).addClass('dangerField');
    }


()=> $(`#${fieldName}`).removeClass('dangerField')


(_event) => {
      this.msg = "";
      this.url = reader.result;
    }


()=>{
       $('#orderName').val("");
       $('#description').val("")
      }


(user:any)=>{
      if(user.success == true){
        this.orders.splice(0,this.orders.length);
        this.ordersService.getUserOrders(user.userId).subscribe((res:any)=>{
          res.orders.forEach(order => {
            this.ordersService.isOrderFound(order.order_id).subscribe((isFound:any)=>{
              if(isFound.success == true && isFound.status == 200){
                  this.pushInOrders(order,true);
              }
              else if(isFound.success == true && isFound.status==404){
                this.pushInOrders(order,false);
              }
            })
            // this.pushInOrders(order);
          });

        })
      }
    }


(res:any)=>{
          res.orders.forEach(order => {
            this.ordersService.isOrderFound(order.order_id).subscribe((isFound:any)=>{
              if(isFound.success == true && isFound.status == 200){
                  this.pushInOrders(order,true);
              }
              else if(isFound.success == true && isFound.status==404){
                this.pushInOrders(order,false);
              }
            })
            // this.pushInOrders(order);
          });

        }


order => {
            this.ordersService.isOrderFound(order.order_id).subscribe((isFound:any)=>{
              if(isFound.success == true && isFound.status == 200){
                  this.pushInOrders(order,true);
              }
              else if(isFound.success == true && isFound.status==404){
                this.pushInOrders(order,false);
              }
            })
            // this.pushInOrders(order);
          }


(isFound:any)=>{
              if(isFound.success == true && isFound.status == 200){
                  this.pushInOrders(order,true);
              }
              else if(isFound.success == true && isFound.status==404){
                this.pushInOrders(order,false);
              }
            }


(res:any)=>{
    if(res.success == true){
      var index =  this.orders.findIndex(order =>{
        return order.orderId == orderId;
      })
      this.orders.splice(index,1);
      this.notificationService.showSuccess(`Order was deleted`, 'One Order removed successfully');
      }
   }


order =>{
        return order.orderId == orderId;
      }


(isVendor:any)=>{
     if(isVendor.success == true){
       vendorId = isVendor.sellerId;
     }
    }


(res:any)=>{
      this.orders.splice(0,this.orders.length);
       if(res.success == true){
             this.vendorCheckedOrders.splice(0,this.vendorCheckedOrders.length);
             res.orders.forEach(order => {
              this.ordersService.isOrderChecked(vendorId,order.order_id).subscribe((isChecked: any)=>{
                if(isChecked.success == true && isChecked.status == 200){
                //  this.vendorCheckedOrders.push(order);
                 this.getVendorCheckedOuts(order);
                }
                else if(isChecked.success == false && isChecked.status == 200){
                  this.pushInOrders(order,false);
                }
              })
            });
          }
     }


order => {
              this.ordersService.isOrderChecked(vendorId,order.order_id).subscribe((isChecked: any)=>{
                if(isChecked.success == true && isChecked.status == 200){
                //  this.vendorCheckedOrders.push(order);
                 this.getVendorCheckedOuts(order);
                }
                else if(isChecked.success == false && isChecked.status == 200){
                  this.pushInOrders(order,false);
                }
              })
            }


(isChecked: any)=>{
                if(isChecked.success == true && isChecked.status == 200){
                //  this.vendorCheckedOrders.push(order);
                 this.getVendorCheckedOuts(order);
                }
                else if(isChecked.success == false && isChecked.status == 200){
                  this.pushInOrders(order,false);
                }
              }


()=>{
       if(event == 'open'){
        this.wasChecked=false;
        this.orders.forEach(order => {
          if(order.orderId == orderId){
          this.exploreOrder = Object.assign({},order)
          }
        })
         $('#exploreOrderModal').fadeIn()
       }
       else if(event == 'close'){
        $('#exploreOrderModal').fadeOut()
        }
       window.onclick = (event) => {
         if(event.target == document.getElementById('exploreOrderModal')){
          $('#exploreOrderModal').fadeOut()
         }
       }
    }


order => {
          if(order.orderId == orderId){
          this.exploreOrder = Object.assign({},order)
          }
        }


(event) => {
         if(event.target == document.getElementById('exploreOrderModal')){
          $('#exploreOrderModal').fadeOut()
         }
       }


order=> {
     if(order.orderId == orderId){
      this.exploreOrder = Object.assign({},order);
     }
   }


(res:any)=>{
    res.foundOrder.forEach(foundOrder => {
        this.vendorsService.getVendorInfo(foundOrder.seller).subscribe((vendor:any)=>{
            this.foundOrder.orderName= this.exploreOrder.orderName;
            this.foundOrder.orderedDate=this.exploreOrder.orderDate;
            this.foundOrder.checkedSellers.splice(1,this.foundOrder.checkedSellers.length);
            this.foundOrder.checkedSellers.push({
              sellerName:vendor.info.seller_name,
              email: vendor.info.seller_email,
              contactPhone: vendor.info.seller_contact_phone,
              whatsappPhone: vendor.info.seller_watsapp_phone,
              country: vendor.info.seller_country,
              district: vendor.info.seller_district,
              sector: vendor.info.seller_sector,
              town: vendor.info.seller_town,
              logo: vendor.info.sellerLogo
            }

            )
        })
      });
    }


foundOrder => {
        this.vendorsService.getVendorInfo(foundOrder.seller).subscribe((vendor:any)=>{
            this.foundOrder.orderName= this.exploreOrder.orderName;
            this.foundOrder.orderedDate=this.exploreOrder.orderDate;
            this.foundOrder.checkedSellers.splice(1,this.foundOrder.checkedSellers.length);
            this.foundOrder.checkedSellers.push({
              sellerName:vendor.info.seller_name,
              email: vendor.info.seller_email,
              contactPhone: vendor.info.seller_contact_phone,
              whatsappPhone: vendor.info.seller_watsapp_phone,
              country: vendor.info.seller_country,
              district: vendor.info.seller_district,
              sector: vendor.info.seller_sector,
              town: vendor.info.seller_town,
              logo: vendor.info.sellerLogo
            }

            )
        })
      }


(vendor:any)=>{
            this.foundOrder.orderName= this.exploreOrder.orderName;
            this.foundOrder.orderedDate=this.exploreOrder.orderDate;
            this.foundOrder.checkedSellers.splice(1,this.foundOrder.checkedSellers.length);
            this.foundOrder.checkedSellers.push({
              sellerName:vendor.info.seller_name,
              email: vendor.info.seller_email,
              contactPhone: vendor.info.seller_contact_phone,
              whatsappPhone: vendor.info.seller_watsapp_phone,
              country: vendor.info.seller_country,
              district: vendor.info.seller_district,
              sector: vendor.info.seller_sector,
              town: vendor.info.seller_town,
              logo: vendor.info.sellerLogo
            }

            )
        }


(result:any)=>{
     if(result.success == true){
       this.usersService.getUserProfile(result.order.user).subscribe((res:any)=>{
         if(res.success == true){
             this.ordererProfile= Object.assign({},res.user);
            }
       })
     }
   }


(res:any)=>{
         if(res.success == true){
             this.ordererProfile= Object.assign({},res.user);
            }
       }


(vendor:any)=>{
      if(vendor.success == true){
        this.ordersService.checkoutOrder(vendor.sellerId,this.exploreOrder.orderId).subscribe((res:any)=>{
          if(res.success == true){
            this.onFetchVendorDisplayOrders();
            this.notificationService.showSuccess('Order checked','You added a new Order in checkouts');
            this.wasChecked=true;
          }
        })
      }
    }


(res:any)=>{
          if(res.success == true){
            this.onFetchVendorDisplayOrders();
            this.notificationService.showSuccess('Order checked','You added a new Order in checkouts');
            this.wasChecked=true;
          }
        }


(res:any)=>{
     if(res.success == true){
     this.vendorCheckedOrders.push({
          order:{
            orderId:orderObj.order_id,
            orderName: orderObj.order_name,
            description: orderObj.description,
            orderDate:orderObj.order_date,
            orderImageURL: orderObj.orderImage
          },
          customer:{
            firstname: res.user.firstname,
            lastname: res.user.lastname,
            email: res.user.email,
            phone: res.user.phone
          }
       })
     }
   }


(auth:any)=>{
       this.ordersService.uncheckOrder(auth.sellerId,orderId).subscribe((res:any)=>{
         if(res.success == true){
            let removeIndex = 0;
            for(let i = 0; i < this.vendorCheckedOrders.length; i++){
              if(this.vendorCheckedOrders[i].orderId == orderId){
                removeIndex = i;
              }
            }
            this.vendorCheckedOrders.splice(removeIndex,1);
            this.notificationService.showSuccess('You unchecked the order','1 order unchecked');
            this.onFetchVendorDisplayOrders();
         }
       })
    }


(res:any)=>{
         if(res.success == true){
            let removeIndex = 0;
            for(let i = 0; i < this.vendorCheckedOrders.length; i++){
              if(this.vendorCheckedOrders[i].orderId == orderId){
                removeIndex = i;
              }
            }
            this.vendorCheckedOrders.splice(removeIndex,1);
            this.notificationService.showSuccess('You unchecked the order','1 order unchecked');
            this.onFetchVendorDisplayOrders();
         }
       }


(auth:any)=>{
    if(auth.email == 'NULL'){
        // this.toastrService.error(
        //   'Error: Email is required',
        //   'You need to have an email before ordering. Go to -> Dashboard -> Add Email to add your email'
        //   ,)
        alert("Error: You need to have an email before ordering. Go to '-> Dashboard -> Add Email' to add your email")
      }
      else{
      this.fadePendingProductModal('in');
     }

    }


triggerOrderModal(orderId,task){
    if(task=="addOrder"){
      this.newOrder=true;
      this.firstCheckEmail();
   }
   else if(task=="exploreOrder" && this.orderIsFound != true){
    this.newOrder=false;
    this.fadePendingProductModal('in');
   }
   else if(task=="exploreOrder" && this.orderIsFound == true){
    this.newOrder=false;
    this.fadeFoundProductModal('in');
    this.fetchFoundOrderDetails(orderId)
   }
   var orderModal = document.getElementById("orderModal");
   var foundOrderModal = document.getElementById("foundOrderModal");

   window.onclick = (event) => {
    if (event.target == foundOrderModal) {
     $(()=>{ $('#foundOrderModal').fadeOut();})
    }
    else if(event.target == orderModal){
      $(()=>{ $('#orderModal').fadeOut();})
    }
  }
   }


fadePendingProductModal(mode){
    $(()=>{
      if(mode == 'in'){
        $('#orderModal').fadeIn();
      }
      else if(mode == 'out'){
        $('#orderModal').fadeOut();
      }
    })
  }


fadeFoundProductModal(mode){
    $(()=>{
      if(mode == 'in'){
        $('#foundOrderModal').fadeIn();
      }
      else if(mode == 'out'){
        $('#foundOrderModal').fadeOut();
      }
    })
  }


closeModal(event){
   $(()=>{
    if(event == 'foundOrderModal'){
       $('#foundOrderModal').fadeOut();
    }
    else if(event == 'orderModal'){
      $('#orderModal').fadeOut();
    }
   })

  }


onCreateOrder(orderName,orderDescription){
    var noSpaceOrderName = orderName.replace(/\s+/g, '').length;
    var noSpaceDescription = orderDescription.replace(/\s+/g, '').length;
    if(noSpaceOrderName == 0 || orderName.length > 50 || orderName.length < 2){
      (noSpaceOrderName == 0) ? this.createOrderErrorHolder[0]="  Order name is required"  :
      (orderName.length < 2 || orderName.length > 30) ? this.createOrderErrorHolder[0]= " Name should be 2 - 30 characters" :
      this.createOrderErrorHolder[0]=""
      this.makeFieldDanger('orderName');
    }
    else{ this.createOrderErrorHolder[0]==""}

    if(noSpaceDescription == 0 || orderDescription.length < 10 || orderDescription.length > 150){
      (noSpaceDescription == 0) ? this.createOrderErrorHolder[1]=" Please Describe your order"  :
      (orderDescription.length < 10 || orderDescription.length > 150) ? this.createOrderErrorHolder[1]= " Description should be between 10 - 150 characters" :
      this.createOrderErrorHolder[1]=""
      this.makeFieldDanger('description');
    }
    else{this.createOrderErrorHolder[1]=""}

    if(this.createOrderErrorHolder[0]=="" && this.createOrderErrorHolder[1]==""){
       this.authService.authenticateUser().subscribe((authorizedUser:any)=>{
         if(authorizedUser.success == true){
           this.ordersService.makeOrder(authorizedUser.userId,orderName,orderDescription).subscribe((res:any)=>{
             if(res.success == false){
               this.notificationService.showError(res.message,"Ordering failed");
             }
             else if(res.success == true){
              if(this.url != null && this.orderImage != ""){
                 this.ordersService.addOrderImage(res.order.insertId,this.orderImage).subscribe((result:any)=>{
                 if(result.success != true){
                  this.notificationService.showError('Error! Image not uploaded',"Upload image unsuccessful")
                  }
               })
              }
              this.onFetchUserOrders();
              this.notificationService.showSuccess('You have made an order','Ordering successful');
              this.clearFields();
             }
           })
         }
       })
    }
  }


makeFieldDanger(fieldName){
    $(()=>{
      $(`#${fieldName}`).addClass('dangerField');
    })
  }


resetField(fieldName, errorId){
    this.createOrderErrorHolder[errorId]="";
    $(()=> $(`#${fieldName}`).removeClass('dangerField'));
  }


selectFile(event) {
   if(!event.target.files[0] || event.target.files[0].length == 0) {
      this.msg = 'You can add order image for better ordering';
      return;
    }

    var mimeType = event.target.files[0].type;

    if (mimeType.match(/image\/*/) == null) {
      this.msg = "Only images are supported";
      return;
    }

    var reader = new FileReader();
    reader.readAsDataURL(event.target.files[0]);

    reader.onload = (_event) => {
      this.msg = "";
      this.url = reader.result;
    }
    if(event.target.files.length > 0){
      const file = event.target.files[0];
      this.orderImage = file;
    }

   }


clearFields(){
     $(()=>{
       $('#orderName').val("");
       $('#description').val("")
      })
      this.url="";
      this.orderImage="";
      this.msg="";
   }


onFetchUserOrders(){
    this.authService.authenticateUser().subscribe((user:any)=>{
      if(user.success == true){
        this.orders.splice(0,this.orders.length);
        this.ordersService.getUserOrders(user.userId).subscribe((res:any)=>{
          res.orders.forEach(order => {
            this.ordersService.isOrderFound(order.order_id).subscribe((isFound:any)=>{
              if(isFound.success == true && isFound.status == 200){
                  this.pushInOrders(order,true);
              }
              else if(isFound.success == true && isFound.status==404){
                this.pushInOrders(order,false);
              }
            })
            // this.pushInOrders(order);
          });

        })
      }
    })
  }


onRemoveOrder(orderId){
   this.ordersService.deleteOrder(orderId).subscribe((res:any)=>{
    if(res.success == true){
      var index =  this.orders.findIndex(order =>{
        return order.orderId == orderId;
      })
      this.orders.splice(index,1);
      this.notificationService.showSuccess(`Order was deleted`, 'One Order removed successfully');
      }
   })
  }


onFetchVendorDisplayOrders(){
   let vendorId = this.authService.authenticateVendor().subscribe((isVendor:any)=>{
     if(isVendor.success == true){
       vendorId = isVendor.sellerId;
     }
    })
    this.ordersService.fetchAllOrders().subscribe((res:any)=>{
      this.orders.splice(0,this.orders.length);
       if(res.success == true){
             this.vendorCheckedOrders.splice(0,this.vendorCheckedOrders.length);
             res.orders.forEach(order => {
              this.ordersService.isOrderChecked(vendorId,order.order_id).subscribe((isChecked: any)=>{
                if(isChecked.success == true && isChecked.status == 200){
                //  this.vendorCheckedOrders.push(order);
                 this.getVendorCheckedOuts(order);
                }
                else if(isChecked.success == false && isChecked.status == 200){
                  this.pushInOrders(order,false);
                }
              })
            });
          }
     })

  }


pushInOrders(order,foundStatus:boolean){
     this.orders.push({
      orderId: order.order_id,
      orderName: order.order_name,
      description: order.description,
      imageURL: order.orderImage,
      foundStatus: foundStatus,
      orderDate: order.order_date

    })
  }


deterMineAccoutType(){
    if(this.route.snapshot.params.accountType == 'selleraccount'){
       this.isVendor = true;
       this.onFetchVendorDisplayOrders();
     }
     else if(this.route.snapshot.params.accountType == 'buyeraccount'){
       this.onFetchUserOrders();
     }
     else{
     this.router.navigate(['index']);
     }
  }


triggerExploreOrderModal(orderId,event){
    if(this.isVendor == true && orderId != -1){
    this.getOrdererDetails(orderId);
    }
     $(()=>{
       if(event == 'open'){
        this.wasChecked=false;
        this.orders.forEach(order => {
          if(order.orderId == orderId){
          this.exploreOrder = Object.assign({},order)
          }
        })
         $('#exploreOrderModal').fadeIn()
       }
       else if(event == 'close'){
        $('#exploreOrderModal').fadeOut()
        }
       window.onclick = (event) => {
         if(event.target == document.getElementById('exploreOrderModal')){
          $('#exploreOrderModal').fadeOut()
         }
       }
    })
  }


fetchFoundOrderDetails(orderId){
   this.orders.forEach(order=> {
     if(order.orderId == orderId){
      this.exploreOrder = Object.assign({},order);
     }
   })

    this.ordersService.isOrderFound(orderId).subscribe((res:any)=>{
    res.foundOrder.forEach(foundOrder => {
        this.vendorsService.getVendorInfo(foundOrder.seller).subscribe((vendor:any)=>{
            this.foundOrder.orderName= this.exploreOrder.orderName;
            this.foundOrder.orderedDate=this.exploreOrder.orderDate;
            this.foundOrder.checkedSellers.splice(1,this.foundOrder.checkedSellers.length);
            this.foundOrder.checkedSellers.push({
              sellerName:vendor.info.seller_name,
              email: vendor.info.seller_email,
              contactPhone: vendor.info.seller_contact_phone,
              whatsappPhone: vendor.info.seller_watsapp_phone,
              country: vendor.info.seller_country,
              district: vendor.info.seller_district,
              sector: vendor.info.seller_sector,
              town: vendor.info.seller_town,
              logo: vendor.info.sellerLogo
            }

            )
        })
      });
    })
  }


getOrdererDetails(orderId){
   this.ordersService.getOrderDetails(orderId).subscribe((result:any)=>{
     if(result.success == true){
       this.usersService.getUserProfile(result.order.user).subscribe((res:any)=>{
         if(res.success == true){
             this.ordererProfile= Object.assign({},res.user);
            }
       })
     }
   })

  }


checkOrderOut(){
    this.authService.authenticateVendor().subscribe((vendor:any)=>{
      if(vendor.success == true){
        this.ordersService.checkoutOrder(vendor.sellerId,this.exploreOrder.orderId).subscribe((res:any)=>{
          if(res.success == true){
            this.onFetchVendorDisplayOrders();
            this.notificationService.showSuccess('Order checked','You added a new Order in checkouts');
            this.wasChecked=true;
          }
        })
      }
    })
  }


getVendorCheckedOuts(orderObj){
   this.usersService.getUserProfile(orderObj.user).subscribe((res:any)=>{
     if(res.success == true){
     this.vendorCheckedOrders.push({
          order:{
            orderId:orderObj.order_id,
            orderName: orderObj.order_name,
            description: orderObj.description,
            orderDate:orderObj.order_date,
            orderImageURL: orderObj.orderImage
          },
          customer:{
            firstname: res.user.firstname,
            lastname: res.user.lastname,
            email: res.user.email,
            phone: res.user.phone
          }
       })
     }
   })
  }


triggerVendorCheckedOutModal(){
   this.fadeFoundProductModal('in');
    // (()=>{
    //   $('#foundOrderModal').fadeIn();
    // })
  }


removeCheckout(orderId){
   this.authService.authenticateVendor().subscribe((auth:any)=>{
       this.ordersService.uncheckOrder(auth.sellerId,orderId).subscribe((res:any)=>{
         if(res.success == true){
            let removeIndex = 0;
            for(let i = 0; i < this.vendorCheckedOrders.length; i++){
              if(this.vendorCheckedOrders[i].orderId == orderId){
                removeIndex = i;
              }
            }
            this.vendorCheckedOrders.splice(removeIndex,1);
            this.notificationService.showSuccess('You unchecked the order','1 order unchecked');
            this.onFetchVendorDisplayOrders();
         }
       })
    })
  }


onDirectCancelCheckout(){
    this.removeCheckout(this.exploreOrder.orderId);
    this.wasChecked=false;
  }


firstCheckEmail(){
    this.authService.authenticateUser().subscribe((auth:any)=>{
    if(auth.email == 'NULL'){
        // this.toastrService.error(
        //   'Error: Email is required',
        //   'You need to have an email before ordering. Go to -> Dashboard -> Add Email to add your email'
        //   ,)
        alert("Error: You need to have an email before ordering. Go to '-> Dashboard -> Add Email' to add your email")
      }
      else{
      this.fadePendingProductModal('in');
     }

    })
  }


ngOnInit() {
    this.deterMineAccoutType();
  }


() => {
  let component: SamUploadComponentV2;
  let host: any;
  let fixture: any;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        TestHostComponent,
        SamUploadComponentV2,
        SamDragDropDirective,
        SamProgress,
        FilesizePipe
      ],
      imports: [ FormsModule, ReactiveFormsModule, SamModalModule, SamToggleSwitchModule ],
      providers: [
        { provide: HttpClient, useClass: MockHttpClient },
      ]

    });

    fixture = TestBed.createComponent(TestHostComponent);
    host = fixture.component;
    component = fixture.debugElement.query(By.directive(SamUploadComponentV2)).injector.get(SamUploadComponentV2);
    fixture.detectChanges();
  });

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

  it('the model object should be in the Done state after upload', () => {
    const url = 'http://localhost/upload';
    const file = { name: 'sample.jpeg', size: 1001 };
    const req = new HttpRequest('POST', url, file, { reportProgress: true });
    const list = { 0: file, length: 1, item: () => { return file; } };

    component.uploadRequest = () => req;
    component.onFilesChange(<any>list);
    let wasOneUpload = false;
    component._model.forEach(uf => {
      wasOneUpload = true;
      expect(uf.upload.status).toEqual(UploadStatus.Done);
    });
    expect(wasOneUpload).toBe(true);
  });

  xit('should delete the upload if the upload was a success and delete is clicked', () => {
    const url = 'http://localhost/upload';
    const file = { name: 'sample.jpeg', size: 1001 };
    const request = new HttpRequest('POST', url, file, { reportProgress: true });
    const deleteRequest = new HttpRequest('DELETE', 'files/1');
    const list = { 0: file, length: 1, item: () => { return file; } };

    component.uploadRequest = () => request;
    component.deleteRequest = () => deleteRequest;
    component.onFilesChange(<any>list);
    const firstFile = component.fileCtrlConfig[0];
    expect(firstFile).toBeTruthy();
    component.onRemoveClick("",0)
    fixture.detectChanges();
    component.onRemoveModalSubmit(0);
    fixture.detectChanges();
    expect(component.fileCtrlConfig.length).toBe(0);
  });
}


() => {
    TestBed.configureTestingModule({
      declarations: [
        TestHostComponent,
        SamUploadComponentV2,
        SamDragDropDirective,
        SamProgress,
        FilesizePipe
      ],
      imports: [ FormsModule, ReactiveFormsModule, SamModalModule, SamToggleSwitchModule ],
      providers: [
        { provide: HttpClient, useClass: MockHttpClient },
      ]

    });

    fixture = TestBed.createComponent(TestHostComponent);
    host = fixture.component;
    component = fixture.debugElement.query(By.directive(SamUploadComponentV2)).injector.get(SamUploadComponentV2);
    fixture.detectChanges();
  }


() => {
    const url = 'http://localhost/upload';
    const file = { name: 'sample.jpeg', size: 1001 };
    const req = new HttpRequest('POST', url, file, { reportProgress: true });
    const list = { 0: file, length: 1, item: () => { return file; } };

    component.uploadRequest = () => req;
    component.onFilesChange(<any>list);
    let wasOneUpload = false;
    component._model.forEach(uf => {
      wasOneUpload = true;
      expect(uf.upload.status).toEqual(UploadStatus.Done);
    });
    expect(wasOneUpload).toBe(true);
  }


() => { return file; }


() => req


uf => {
      wasOneUpload = true;
      expect(uf.upload.status).toEqual(UploadStatus.Done);
    }


() => {
    const url = 'http://localhost/upload';
    const file = { name: 'sample.jpeg', size: 1001 };
    const request = new HttpRequest('POST', url, file, { reportProgress: true });
    const deleteRequest = new HttpRequest('DELETE', 'files/1');
    const list = { 0: file, length: 1, item: () => { return file; } };

    component.uploadRequest = () => request;
    component.deleteRequest = () => deleteRequest;
    component.onFilesChange(<any>list);
    const firstFile = component.fileCtrlConfig[0];
    expect(firstFile).toBeTruthy();
    component.onRemoveClick("",0)
    fixture.detectChanges();
    component.onRemoveModalSubmit(0);
    fixture.detectChanges();
    expect(component.fileCtrlConfig.length).toBe(0);
  }


() => request


() => deleteRequest


class MockHttpClient {
  request() {
    return of('success');
  }
}


@Component({
  template: `
    <form [formGroup]="form">
      <sam-upload-v2 formControlName="upload"></sam-upload-v2>
    </form>
  `
})
class TestHostComponent {
  public form: FormGroup = new FormGroup({
    upload: new FormControl('')
  });
}


request() {
    return of('success');
  }


({ onCreate, onClose }) => {
  const { t } = useTranslation(['Labels']);

  const onSubmit = (values: any, actions: FormikHelpers<any>) => {
    onCreate(values.name)
      .then(res => {
        if (! res.ok) {
          actions.setErrors(res.errors);
        }
      });
  }

  return (
    <Formik
      initialValues={{
        name: ''
      }}


(values: any, actions: FormikHelpers<any>) => {
    onCreate(values.name)
      .then(res => {
        if (! res.ok) {
          actions.setErrors(res.errors);
        }
      });
  }


res => {
        if (! res.ok) {
          actions.setErrors(res.errors);
        }
      }


interface ICreateApiKeyFormProps {
  onCreate(name: string): Promise<any>,
  onClose(): void
}


t('Labels:Name')


t('Labels:CreateButton')


t('Labels:CancelButton')


function badgeColor(type: BadgeType, theme: Theme) {
  switch (type) {
    case 'primary':
      return theme.colors.primary
    case 'secondary':
      return theme.colors.secondary
    default:
      return theme.colors.tertiaryDark
  }
}


({ type, theme }) => ({
  display: 'inline-block',
  padding: calcRem(3, 7),
  backgroundColor: badgeColor(type, theme),
  borderRadius: calcRem(10),
  color: '#fff',
  fontSize: calcRem(12),
  fontWeight: theme.weights.bold,
  lineHeight: 1,
  textAlign: 'center',
  whiteSpace: 'nowrap',
})


interface StyledBadgeProps {
  type: BadgeType
}


function LandingPage(props: LandingPageProps) {
  const { fetchLocations, fetchCurrentLocation } = props;

  useEffect(() => fetchLocations(), [fetchLocations]);

  useEffect(() => fetchCurrentLocation(), [fetchCurrentLocation]);

  return (
    <View accessibilityLabel={'Home screen'} style={styles.screenStyle}>
      <LocationDropdown />
      <AirQualityInfo />
      <LandingPageCarousel />
    </View>
  );
}


() => fetchLocations()


() => fetchCurrentLocation()


(dispatch: Dispatch<RootAction>) => {
  return {
    fetchLocations: () => {
      getLocations(dispatch);
    },
    fetchCurrentLocation: () => {
      getCurrentLocation(dispatch);
    },
  };
}


() => {
      getLocations(dispatch);
    }


() => {
      getCurrentLocation(dispatch);
    }


type LandingPageProps = ReturnType<typeof mapDispatchToProps>;


type of this


(data, [root, args, ctx, info]) => ctx.req.user


export class GqlAuthGuard extends AuthGuard('jwt') {
  public getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }
}


public getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }


(props: AntdIconProps, context: SetupContext) => {
  const p = { ...props, ...context.attrs };
  return <AntdIcon {...p} icon={Heart3FillSvg}></AntdIcon>;
}


() => {
	it("renders status with appropriate class", () => {
		const type = "information";
		const wrapper = shallowMount(VEcoDot, {
			props: { type },
		});
		expect(wrapper.find(".dot").exists()).toBe(true);
		expect(wrapper.find(`.dot--${type}`).exists()).toBe(true);
	});
}


() => {
		const type = "information";
		const wrapper = shallowMount(VEcoDot, {
			props: { type },
		});
		expect(wrapper.find(".dot").exists()).toBe(true);
		expect(wrapper.find(`.dot--${type}`).exists()).toBe(true);
	}


(theme: any) => {
  return {
    className: css`
      color: ${theme.palette.surface.on};
      margin-top: 16px;
    `,
  };
}


(theme: any) => merge({ palette: { surface: { on: 'white' } } }, theme)


class StQueriesNUserstateImpl extends React.PureComponent<StQueriesNUserstateProps> {
  render() {
    const { theme: incomingTheme, ...defaultHostProps } = this.props;
    const theme = defaultTheme(incomingTheme);
    const titleProps = mergeProps(PaddingProps(theme), themeToTitleStyles(theme));
    return (
      <div {...defaultHostProps}>
        <div {...containerStyles}>
          <div {...childStyles}>
            <Typography {...titleProps} scale={'Subtitle1'}>
              Queries
            </Typography>
            <StQueriesManager />
          </div>
          <div {...childStyles}>
            <Typography {...titleProps} scale={'Subtitle1'}>
              User-state
            </Typography>
            <StUserstateManager />
          </div>
        </div>
      </div>
    );
  }
}


interface StQueriesNUserstateProps extends React.HTMLAttributes<HTMLDivElement> {
  theme?: any;
}


render() {
    const { theme: incomingTheme, ...defaultHostProps } = this.props;
    const theme = defaultTheme(incomingTheme);
    const titleProps = mergeProps(PaddingProps(theme), themeToTitleStyles(theme));
    return (
      <div {...defaultHostProps}>
        <div {...containerStyles}>
          <div {...childStyles}>
            <Typography {...titleProps} scale={'Subtitle1'}>
              Queries
            </Typography>
            <StQueriesManager />
          </div>
          <div {...childStyles}>
            <Typography {...titleProps} scale={'Subtitle1'}>
              User-state
            </Typography>
            <StUserstateManager />
          </div>
        </div>
      </div>
    );
  }


export function DataLoader<T>(props: DataLoaderProps<T>) {
  const [data, setData] = useState<T | undefined>();

  useFetch(
    () => props.loader(),
    (result) => setData(result),
    props.deps || []
  );

  if (data) {
    if (props.children instanceof Function) {
      return props.children(data);
    }
    return props.children;
  }
  return (
    <div className="pf-u-text-align-center">
      <Spinner />
    </div>
  );
}


() => props.loader()


(result) => setData(result)


type DataLoaderProps<T> = {
  loader: () => Promise<T>;
  deps?: DependencyList;
  children: ((arg: T) => any) | React.ReactNode;
};


export declare function setRootDomAdapter(adapter: DomAdapter): void;


/**
 * Provides DOM operations in an environment-agnostic way.
 */
export declare class DomAdapter {
    hasProperty(element: any, name: string): boolean;
    setProperty(el: Element, name: string, value: any): void;
    getProperty(el: Element, name: string): any;
    invoke(el: Element, methodName: string, args: List<any>): any;
    logError(error: any): void;
    log(error: any): void;
    logGroup(error: any): void;
    logGroupEnd(): void;
    /**
     * Maps attribute names to their corresponding property names for cases
     * where attribute name doesn't match property name.
     */
    attrToPropMap: StringMap<string, string>;
    parse(templateHtml: string): void;
    query(selector: string): any;
    querySelector(el: any, selector: string): HTMLElement;
    querySelectorAll(el: any, selector: string): List<any>;
    on(el: any, evt: any, listener: any): void;
    onAndCancel(el: any, evt: any, listener: any): Function;
    dispatchEvent(el: any, evt: any): void;
    createMouseEvent(eventType: any): any;
    createEvent(eventType: string): any;
    preventDefault(evt: any): void;
    getInnerHTML(el: any): string;
    getOuterHTML(el: any): string;
    nodeName(node: any): string;
    nodeValue(node: any): string;
    type(node: any): string;
    content(node: any): any;
    firstChild(el: any): Node;
    nextSibling(el: any): Node;
    parentElement(el: any): Node;
    childNodes(el: any): List<Node>;
    childNodesAsList(el: any): List<Node>;
    clearNodes(el: any): void;
    appendChild(el: any, node: any): void;
    removeChild(el: any, node: any): void;
    replaceChild(el: any, newNode: any, oldNode: any): void;
    remove(el: any): Node;
    insertBefore(el: any, node: any): void;
    insertAllBefore(el: any, nodes: any): void;
    insertAfter(el: any, node: any): void;
    setInnerHTML(el: any, value: any): void;
    getText(el: any): string;
    setText(el: any, value: string): void;
    getValue(el: any): string;
    setValue(el: any, value: string): void;
    getChecked(el: any): boolean;
    setChecked(el: any, value: boolean): void;
    createTemplate(html: any): HTMLElement;
    createElement(tagName: any, doc?: any): HTMLElement;
    createTextNode(text: string, doc?: any): Text;
    createScriptTag(attrName: string, attrValue: string, doc?: any): HTMLElement;
    createStyleElement(css: string, doc?: any): HTMLStyleElement;
    createShadowRoot(el: any): any;
    getShadowRoot(el: any): any;
    getHost(el: any): any;
    getDistributedNodes(el: any): List<Node>;
    clone(node: Node): Node;
    getElementsByClassName(element: any, name: string): List<HTMLElement>;
    getElementsByTagName(element: any, name: string): List<HTMLElement>;
    classList(element: any): List<any>;
    addClass(element: any, classname: string): void;
    removeClass(element: any, classname: string): void;
    hasClass(element: any, classname: string): boolean;
    setStyle(element: any, stylename: string, stylevalue: string): void;
    removeStyle(element: any, stylename: string): void;
    getStyle(element: any, stylename: string): string;
    tagName(element: any): string;
    attributeMap(element: any): Map<string, string>;
    hasAttribute(element: any, attribute: string): boolean;
    getAttribute(element: any, attribute: string): string;
    setAttribute(element: any, name: string, value: string): void;
    removeAttribute(element: any, attribute: string): void;
    templateAwareRoot(el: any): void;
    createHtmlDocument(): HTMLDocument;
    defaultDoc(): HTMLDocument;
    getBoundingClientRect(el: any): void;
    getTitle(): string;
    setTitle(newTitle: string): void;
    elementMatches(n: any, selector: string): boolean;
    isTemplateElement(el: any): boolean;
    isTextNode(node: any): boolean;
    isCommentNode(node: any): boolean;
    isElementNode(node: any): boolean;
    hasShadowRoot(node: any): boolean;
    isShadowRoot(node: any): boolean;
    importIntoDoc(node: Node): Node;
    isPageRule(rule: any): boolean;
    isStyleRule(rule: any): boolean;
    isMediaRule(rule: any): boolean;
    isKeyframesRule(rule: any): boolean;
    getHref(element: any): string;
    getEventKey(event: any): string;
    resolveAndSetHref(element: any, baseUrl: string, href: string): void;
    cssToRules(css: string): List<any>;
    supportsDOMEvents(): boolean;
    supportsNativeShadowDOM(): boolean;
    getGlobalEventTarget(target: string): any;
    getHistory(): History;
    getLocation(): Location;
    getBaseHref(): string;
    getUserAgent(): string;
    setData(element: any, name: string, value: string): void;
    getData(element: any, name: string): string;
    setGlobalVar(name: string, value: any): void;
}


hasProperty(element: any, name: string): boolean;


setProperty(el: Element, name: string, value: any): void;


getProperty(el: Element, name: string): any;


invoke(el: Element, methodName: string, args: List<any>): any;


logError(error: any): void;


log(error: any): void;


logGroup(error: any): void;


logGroupEnd(): void;


parse(templateHtml: string): void;


query(selector: string): any;


querySelector(el: any, selector: string): HTMLElement;


querySelectorAll(el: any, selector: string): List<any>;


on(el: any, evt: any, listener: any): void;


onAndCancel(el: any, evt: any, listener: any): Function;


dispatchEvent(el: any, evt: any): void;


createMouseEvent(eventType: any): any;


createEvent(eventType: string): any;


preventDefault(evt: any): void;


getInnerHTML(el: any): string;


getOuterHTML(el: any): string;


nodeName(node: any): string;


nodeValue(node: any): string;


type(node: any): string;


content(node: any): any;


firstChild(el: any): Node;


nextSibling(el: any): Node;


parentElement(el: any): Node;


childNodes(el: any): List<Node>;


childNodesAsList(el: any): List<Node>;


clearNodes(el: any): void;


appendChild(el: any, node: any): void;


removeChild(el: any, node: any): void;


replaceChild(el: any, newNode: any, oldNode: any): void;


remove(el: any): Node;


insertBefore(el: any, node: any): void;


insertAllBefore(el: any, nodes: any): void;


insertAfter(el: any, node: any): void;


setInnerHTML(el: any, value: any): void;


getText(el: any): string;


setText(el: any, value: string): void;


getValue(el: any): string;


setValue(el: any, value: string): void;


getChecked(el: any): boolean;


setChecked(el: any, value: boolean): void;


createTemplate(html: any): HTMLElement;


createElement(tagName: any, doc?: any): HTMLElement;


createTextNode(text: string, doc?: any): Text;


createScriptTag(attrName: string, attrValue: string, doc?: any): HTMLElement;


createStyleElement(css: string, doc?: any): HTMLStyleElement;


createShadowRoot(el: any): any;


getShadowRoot(el: any): any;


getHost(el: any): any;


getDistributedNodes(el: any): List<Node>;


clone(node: Node): Node;


getElementsByClassName(element: any, name: string): List<HTMLElement>;


getElementsByTagName(element: any, name: string): List<HTMLElement>;


classList(element: any): List<any>;


addClass(element: any, classname: string): void;


removeClass(element: any, classname: string): void;


hasClass(element: any, classname: string): boolean;


setStyle(element: any, stylename: string, stylevalue: string): void;


removeStyle(element: any, stylename: string): void;


getStyle(element: any, stylename: string): string;


tagName(element: any): string;


attributeMap(element: any): Map<string, string>;


hasAttribute(element: any, attribute: string): boolean;


getAttribute(element: any, attribute: string): string;


setAttribute(element: any, name: string, value: string): void;


removeAttribute(element: any, attribute: string): void;


templateAwareRoot(el: any): void;


createHtmlDocument(): HTMLDocument;


defaultDoc(): HTMLDocument;


getBoundingClientRect(el: any): void;


getTitle(): string;


setTitle(newTitle: string): void;


elementMatches(n: any, selector: string): boolean;


isTemplateElement(el: any): boolean;


isTextNode(node: any): boolean;


isCommentNode(node: any): boolean;


isElementNode(node: any): boolean;


hasShadowRoot(node: any): boolean;


isShadowRoot(node: any): boolean;


importIntoDoc(node: Node): Node;


isPageRule(rule: any): boolean;


isStyleRule(rule: any): boolean;


isMediaRule(rule: any): boolean;


isKeyframesRule(rule: any): boolean;


getHref(element: any): string;


getEventKey(event: any): string;


resolveAndSetHref(element: any, baseUrl: string, href: string): void;


cssToRules(css: string): List<any>;


supportsDOMEvents(): boolean;


supportsNativeShadowDOM(): boolean;


getGlobalEventTarget(target: string): any;


getHistory(): History;


getLocation(): Location;


getBaseHref(): string;


getUserAgent(): string;


setData(element: any, name: string, value: string): void;


getData(element: any, name: string): string;


setGlobalVar(name: string, value: any): void;


(res: Industry[]) => {
      this.industries = res;
      this.findSubcategories(this.rowData?.industry);
    }


(industry) => industry.name === value


(res: Customer) => {
          this.sharedService.customer.next(res);
        }


(res: Customer) => {
          this.sharedService.customer.next(res);
          this.sharedService.isUpdated.next(true);
        }


@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss'],
})
export class FormComponent implements OnInit, OnChanges {
  @Input() rowData: Customer;
  @Input() optionNum: number;
  @Output() showForms = new EventEmitter();
  industries: Industry[] = [];
  subcategories: string[] = [];
  maxDate: string;
  formGroup: FormGroup;

  constructor(
    private industryService: IndustryService,
    private sharedService: SharedService,
    private customerService: CustomerService,
  ) {}

  ngOnChanges() {
    this.formGroup = new FormGroup({
      name: new FormControl(this.rowData?.name ?? '', [Validators.required]),
      surname: new FormControl(this.rowData?.surname ?? '', [Validators.required]),
      birthDate: new FormControl(this.rowData?.birthDate.replace(/\./g, '-') ?? '', [
        Validators.required,
      ]),
      industry: new FormControl(this.rowData?.industry ?? '', [Validators.required]),
      subcategory: new FormControl(this.rowData?.subcategory ?? '', [Validators.required]),
      phoneNumber: new FormControl(this.rowData?.phoneNumber ?? '', [Validators.required]),
      email: new FormControl(this.rowData?.email ?? '', [Validators.required]),
    });
  }

  ngOnInit() {
    this.maxDate = this.sharedService.setMaxDate();
    this.allIndustries();
  }

  hideForm() {
    this.showForms.emit(false);
  }

  allIndustries() {
    this.industryService.industries().subscribe((res: Industry[]) => {
      this.industries = res;
      this.findSubcategories(this.rowData?.industry);
    });
  }

  isVisibility() {
    return this.optionNum === 0;
  }

  onChange(event) {
    this.findSubcategories(event);
  }

  checkError(data: FormGroup, controlName: string, errorName: string) {
    return this.sharedService.checkError(data, controlName, errorName);
  }

  findSubcategories(value) {
    this.subcategories = this.industries.find((industry) => industry.name === value)?.subcategories;
  }

  createCustomer() {
    const customer = {
      id: 0,
      name: this.formGroup.get('name').value,
      surname: this.formGroup.get('surname').value,
      birthDate: this.formGroup.get('birthDate').value.replace(/-/g, '.'),
      industry: this.formGroup.get('industry').value,
      subcategory: this.formGroup.get('subcategory').value,
      phoneNumber: this.formGroup.get('phoneNumber').value,
      email: this.formGroup.get('email').value,
    };

    switch (this.optionNum) {
      case 0:
        this.customerService.create(customer).subscribe((res: Customer) => {
          this.sharedService.customer.next(res);
        });
        break;
      case 1:
        customer.id = this.rowData.id;
        this.customerService.update(customer).subscribe((res: Customer) => {
          this.sharedService.customer.next(res);
          this.sharedService.isUpdated.next(true);
        });
        break;
      default:
        break;
    }
  }
}


ngOnChanges() {
    this.formGroup = new FormGroup({
      name: new FormControl(this.rowData?.name ?? '', [Validators.required]),
      surname: new FormControl(this.rowData?.surname ?? '', [Validators.required]),
      birthDate: new FormControl(this.rowData?.birthDate.replace(/\./g, '-') ?? '', [
        Validators.required,
      ]),
      industry: new FormControl(this.rowData?.industry ?? '', [Validators.required]),
      subcategory: new FormControl(this.rowData?.subcategory ?? '', [Validators.required]),
      phoneNumber: new FormControl(this.rowData?.phoneNumber ?? '', [Validators.required]),
      email: new FormControl(this.rowData?.email ?? '', [Validators.required]),
    });
  }


ngOnInit() {
    this.maxDate = this.sharedService.setMaxDate();
    this.allIndustries();
  }


hideForm() {
    this.showForms.emit(false);
  }


allIndustries() {
    this.industryService.industries().subscribe((res: Industry[]) => {
      this.industries = res;
      this.findSubcategories(this.rowData?.industry);
    });
  }


isVisibility() {
    return this.optionNum === 0;
  }


onChange(event) {
    this.findSubcategories(event);
  }


checkError(data: FormGroup, controlName: string, errorName: string) {
    return this.sharedService.checkError(data, controlName, errorName);
  }


findSubcategories(value) {
    this.subcategories = this.industries.find((industry) => industry.name === value)?.subcategories;
  }


createCustomer() {
    const customer = {
      id: 0,
      name: this.formGroup.get('name').value,
      surname: this.formGroup.get('surname').value,
      birthDate: this.formGroup.get('birthDate').value.replace(/-/g, '.'),
      industry: this.formGroup.get('industry').value,
      subcategory: this.formGroup.get('subcategory').value,
      phoneNumber: this.formGroup.get('phoneNumber').value,
      email: this.formGroup.get('email').value,
    };

    switch (this.optionNum) {
      case 0:
        this.customerService.create(customer).subscribe((res: Customer) => {
          this.sharedService.customer.next(res);
        });
        break;
      case 1:
        customer.id = this.rowData.id;
        this.customerService.update(customer).subscribe((res: Customer) => {
          this.sharedService.customer.next(res);
          this.sharedService.isUpdated.next(true);
        });
        break;
      default:
        break;
    }
  }


export class BaseModel {
  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;

  @PrimaryGeneratedColumn('uuid')
  id: string;

  @DeleteDateColumn()
  deletedAt?: Date;
}


export function main(domElement: HTMLElement, options: IWorkbenchConstructionOptions): Promise<IWorkbench> {
	const workbench = new BrowserMain(domElement, options);

	return workbench.open();
}


accessor => {
			const commandService = accessor.get(ICommandService);
			const lifecycleService = accessor.get(ILifecycleService);
			const timerService = accessor.get(ITimerService);

			return {
				commands: {
					executeCommand: (command, ...args) => commandService.executeCommand(command, ...args)
				},
				env: {
					async retrievePerformanceMarks() {
						await timerService.whenReady();

						return timerService.getPerformanceMarks();
					}
				},
				shutdown: () => lifecycleService.shutdown()
			};
		}


(command, ...args) => commandService.executeCommand(command, ...args)


() => lifecycleService.shutdown()


event => {
			if (storageService.hasPendingUpdate) {
				event.veto(true, 'veto.pendingStorageUpdate'); // prevent data loss from pending storage update
			}
		}


() => storageService.close()


service => {

				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);

				// Configuration
				serviceCollection.set(IWorkbenchConfigurationService, service);

				return service;
			}


service => {

				// Storage
				serviceCollection.set(IStorageService, service);

				return service;
			}


() => configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkpaceTrusted())


async () => {
			let indexedDBLogProvider: IFileSystemProvider | null = null;
			try {
				indexedDBLogProvider = await indexedDB.createFileSystemProvider(logsPath.scheme, INDEXEDDB_LOGS_OBJECT_STORE);
			} catch (error) {
				onUnexpectedError(error);
			}

			if (indexedDBLogProvider) {
				fileService.registerProvider(logsPath.scheme, indexedDBLogProvider);
			} else {
				fileService.registerProvider(logsPath.scheme, new InMemoryFileSystemProvider());
			}

			logService.logger = new MultiplexLogService(coalesce([
				new ConsoleLogger(logService.getLevel()),
				new FileLogger('window', environmentService.logFile, logService.getLevel(), fileService),
				// Extension development test CLI: forward everything to test runner
				environmentService.isExtensionDevelopment && !!environmentService.extensionTestsLocationURI ? new ConsoleLogInAutomationLogger(logService.getLevel()) : undefined
			]));
		}


private init(): void {

		// Browser config
		setFullscreen(!!detectFullscreen());
	}


async open(): Promise<IWorkbench> {

		// Init services and wait for DOM to be ready in parallel
		const [services] = await Promise.all([this.initServices(), domContentLoaded()]);

		// Create Workbench
		const workbench = new Workbench(this.domElement, services.serviceCollection, services.logService);

		// Listeners
		this.registerListeners(workbench, services.storageService, services.logService);

		// Startup
		const instantiationService = workbench.startup();

		// Window
		this._register(instantiationService.createInstance(BrowserWindow));

		// Logging
		services.logService.trace('workbench configuration', JSON.stringify(this.configuration));

		// Return API Facade
		return instantiationService.invokeFunction(accessor => {
			const commandService = accessor.get(ICommandService);
			const lifecycleService = accessor.get(ILifecycleService);
			const timerService = accessor.get(ITimerService);

			return {
				commands: {
					executeCommand: (command, ...args) => commandService.executeCommand(command, ...args)
				},
				env: {
					async retrievePerformanceMarks() {
						await timerService.whenReady();

						return timerService.getPerformanceMarks();
					}
				},
				shutdown: () => lifecycleService.shutdown()
			};
		});
	}


async retrievePerformanceMarks() {
						await timerService.whenReady();

						return timerService.getPerformanceMarks();
					}


private registerListeners(workbench: Workbench, storageService: BrowserStorageService, logService: ILogService): void {

		// Workbench Lifecycle
		this._register(workbench.onBeforeShutdown(event => {
			if (storageService.hasPendingUpdate) {
				event.veto(true, 'veto.pendingStorageUpdate'); // prevent data loss from pending storage update
			}
		}));
		this._register(workbench.onWillShutdown(() => storageService.close()));
		this._register(workbench.onDidShutdown(() => this.dispose()));
	}


private async initServices(): Promise<{ serviceCollection: ServiceCollection, configurationService: IWorkbenchConfigurationService, logService: ILogService, storageService: BrowserStorageService }> {
		const serviceCollection = new ServiceCollection();

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		// NOTE: DO NOT ADD ANY OTHER SERVICE INTO THE COLLECTION HERE.
		// CONTRIBUTE IT VIA WORKBENCH.WEB.MAIN.TS AND registerSingleton().
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

		const payload = this.resolveWorkspaceInitializationPayload();

		// Product
		const productService: IProductService = { _serviceBrand: undefined, ...product, ...this.configuration.productConfiguration };
		serviceCollection.set(IProductService, productService);

		// Environment
		const logsPath = URI.file(toLocalISOString(new Date()).replace(/-|:|\.\d+Z$/g, '')).with({ scheme: 'vscode-log' });
		const environmentService = new BrowserWorkbenchEnvironmentService({ workspaceId: payload.id, logsPath, ...this.configuration }, productService);
		serviceCollection.set(IWorkbenchEnvironmentService, environmentService);

		// Log
		const logService = new BufferLogService(getLogLevel(environmentService));
		serviceCollection.set(ILogService, logService);

		// Remote
		const connectionToken = environmentService.options.connectionToken || getCookieValue('vscode-tkn');
		const remoteAuthorityResolverService = new RemoteAuthorityResolverService(connectionToken, this.configuration.resourceUriProvider);
		serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);

		// Signing
		const signService = new SignService(connectionToken);
		serviceCollection.set(ISignService, signService);

		// Remote Agent
		const remoteAgentService = this._register(new RemoteAgentService(this.configuration.webSocketFactory, environmentService, productService, remoteAuthorityResolverService, signService, logService));
		serviceCollection.set(IRemoteAgentService, remoteAgentService);

		// Files
		const fileService = this._register(new FileService(logService));
		serviceCollection.set(IFileService, fileService);
		await this.registerFileSystemProviders(environmentService, fileService, remoteAgentService, logService, logsPath);

		// IURIIdentityService
		const uriIdentityService = new UriIdentityService(fileService);
		serviceCollection.set(IUriIdentityService, uriIdentityService);

		// Long running services (workspace, config, storage)
		const [configurationService, storageService] = await Promise.all([
			this.createWorkspaceService(payload, environmentService, fileService, remoteAgentService, uriIdentityService, logService).then(service => {

				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);

				// Configuration
				serviceCollection.set(IWorkbenchConfigurationService, service);

				return service;
			}),

			this.createStorageService(payload, environmentService, fileService, logService).then(service => {

				// Storage
				serviceCollection.set(IStorageService, service);

				return service;
			})
		]);

		// Workspace Trust Service
		const workspaceTrustManagementService = new WorkspaceTrustManagementService(configurationService, environmentService, storageService, uriIdentityService, configurationService);
		serviceCollection.set(IWorkspaceTrustManagementService, workspaceTrustManagementService);

		// Update workspace trust so that configuration is updated accordingly
		configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkpaceTrusted());
		this._register(workspaceTrustManagementService.onDidChangeTrust(() => configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkpaceTrusted())));

		// Request Service
		const requestService = new BrowserRequestService(remoteAgentService, configurationService, logService);
		serviceCollection.set(IRequestService, requestService);

		// Userdata Sync Store Management Service
		const userDataSyncStoreManagementService = new UserDataSyncStoreManagementService(productService, configurationService, storageService);
		serviceCollection.set(IUserDataSyncStoreManagementService, userDataSyncStoreManagementService);

		// Userdata Initialize Service
		const userDataInitializationService = new UserDataInitializationService(environmentService, userDataSyncStoreManagementService, fileService, storageService, productService, requestService, logService);
		serviceCollection.set(IUserDataInitializationService, userDataInitializationService);

		if (await userDataInitializationService.requiresInitialization()) {
			mark('code/willInitRequiredUserData');

			// Initialize required resources - settings & global state
			await userDataInitializationService.initializeRequiredResources();

			// Important: Reload only local user configuration after initializing
			// Reloading complete configuraiton blocks workbench until remote configuration is loaded.
			await configurationService.reloadLocalUserConfiguration();

			mark('code/didInitRequiredUserData');
		}

		return { serviceCollection, configurationService, logService, storageService };
	}


private async registerFileSystemProviders(environmentService: IWorkbenchEnvironmentService, fileService: IFileService, remoteAgentService: IRemoteAgentService, logService: BufferLogService, logsPath: URI): Promise<void> {
		const indexedDB = new IndexedDB();

		// Logger
		(async () => {
			let indexedDBLogProvider: IFileSystemProvider | null = null;
			try {
				indexedDBLogProvider = await indexedDB.createFileSystemProvider(logsPath.scheme, INDEXEDDB_LOGS_OBJECT_STORE);
			} catch (error) {
				onUnexpectedError(error);
			}

			if (indexedDBLogProvider) {
				fileService.registerProvider(logsPath.scheme, indexedDBLogProvider);
			} else {
				fileService.registerProvider(logsPath.scheme, new InMemoryFileSystemProvider());
			}

			logService.logger = new MultiplexLogService(coalesce([
				new ConsoleLogger(logService.getLevel()),
				new FileLogger('window', environmentService.logFile, logService.getLevel(), fileService),
				// Extension development test CLI: forward everything to test runner
				environmentService.isExtensionDevelopment && !!environmentService.extensionTestsLocationURI ? new ConsoleLogInAutomationLogger(logService.getLevel()) : undefined
			]));
		})();

		const connection = remoteAgentService.getConnection();
		if (connection) {

			// Remote file system
			const remoteFileSystemProvider = this._register(new RemoteFileSystemProvider(remoteAgentService));
			fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider);
		}

		// User data
		let indexedDBUserDataProvider: IIndexedDBFileSystemProvider | null = null;
		try {
			indexedDBUserDataProvider = await indexedDB.createFileSystemProvider(Schemas.userData, INDEXEDDB_USERDATA_OBJECT_STORE);
		} catch (error) {
			onUnexpectedError(error);
		}

		let userDataProvider: IFileSystemProvider | undefined;
		if (indexedDBUserDataProvider) {
			userDataProvider = indexedDBUserDataProvider;
		} else {
			logService.info('using in-memory user data provider');
			userDataProvider = new InMemoryFileSystemProvider();
		}

		fileService.registerProvider(Schemas.userData, userDataProvider);

		if (indexedDBUserDataProvider) {
			registerAction2(class ResetUserDataAction extends Action2 {
				constructor() {
					super({
						id: 'workbench.action.resetUserData',
						title: { original: 'Reset User Data', value: localize('reset', "Reset User Data") },
						category: CATEGORIES.Developer,
						menu: {
							id: MenuId.CommandPalette
						}
					});
				}

				async run(accessor: ServicesAccessor): Promise<void> {
					const dialogService = accessor.get(IDialogService);
					const hostService = accessor.get(IHostService);
					const result = await dialogService.confirm({
						message: localize('reset user data message', "Would you like to reset your data (settings, keybindings, extensions, snippets and UI State) and reload?")
					});

					if (result.confirmed) {
						await indexedDBUserDataProvider?.reset();
					}

					hostService.reload();
				}
			});
		}

		fileService.registerProvider(Schemas.file, new HTMLFileSystemProvider());
		fileService.registerProvider(Schemas.inMemory, new InMemoryFileSystemProvider());
	}


async run(accessor: ServicesAccessor): Promise<void> {
					const dialogService = accessor.get(IDialogService);
					const hostService = accessor.get(IHostService);
					const result = await dialogService.confirm({
						message: localize('reset user data message', "Would you like to reset your data (settings, keybindings, extensions, snippets and UI State) and reload?")
					});

					if (result.confirmed) {
						await indexedDBUserDataProvider?.reset();
					}

					hostService.reload();
				}


private async createStorageService(payload: IWorkspaceInitializationPayload, environmentService: IWorkbenchEnvironmentService, fileService: IFileService, logService: ILogService): Promise<BrowserStorageService> {
		const storageService = new BrowserStorageService(payload, environmentService, fileService);

		try {
			await storageService.initialize();

			return storageService;
		} catch (error) {
			onUnexpectedError(error);
			logService.error(error);

			return storageService;
		}
	}


private async createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: IWorkbenchEnvironmentService, fileService: FileService, remoteAgentService: IRemoteAgentService, uriIdentityService: IUriIdentityService, logService: ILogService): Promise<WorkspaceService> {
		const workspaceService = new WorkspaceService({ remoteAuthority: this.configuration.remoteAuthority, configurationCache: new ConfigurationCache() }, environmentService, fileService, remoteAgentService, uriIdentityService, logService);

		try {
			await workspaceService.initialize(payload);

			return workspaceService;
		} catch (error) {
			onUnexpectedError(error);
			logService.error(error);

			return workspaceService;
		}
	}


private resolveWorkspaceInitializationPayload(): IWorkspaceInitializationPayload {
		let workspace: IWorkspace | undefined = undefined;
		if (this.configuration.workspaceProvider) {
			workspace = this.configuration.workspaceProvider.workspace;
		}

		// Multi-root workspace
		if (workspace && isWorkspaceToOpen(workspace)) {
			return getWorkspaceIdentifier(workspace.workspaceUri);
		}

		// Single-folder workspace
		if (workspace && isFolderToOpen(workspace)) {
			return getSingleFolderWorkspaceIdentifier(workspace.folderUri);
		}

		return { id: 'empty-window' };
	}


// ref:
// https://github.com/google/mediapipe/blob/350fbb2100ad531bc110b93aaea23d96af5a5064/mediapipe/calculators/tflite/ssd_anchors_calculator.cc
export function createSsdAnchors(config: AnchorConfig): Rect[] {
  // Set defaults.
  if (config.reduceBoxesInLowestLayer == null) {
    config.reduceBoxesInLowestLayer = false;
  }
  if (config.interpolatedScaleAspectRatio == null) {
    config.interpolatedScaleAspectRatio = 1.0;
  }
  if (config.fixedAnchorSize == null) {
    config.fixedAnchorSize = false;
  }

  const anchors: Rect[] = [];
  let layerId = 0;
  while (layerId < config.numLayers) {
    const anchorHeight = [];
    const anchorWidth = [];
    const aspectRatios = [];
    const scales = [];

    // For same strides, we merge the anchors in the same order.
    let lastSameStrideLayer = layerId;
    while (lastSameStrideLayer < config.strides.length &&
           config.strides[lastSameStrideLayer] === config.strides[layerId]) {
      const scale = calculateScale(
          config.minScale, config.maxScale, lastSameStrideLayer,
          config.strides.length);
      if (lastSameStrideLayer === 0 && config.reduceBoxesInLowestLayer) {
        // For first layer, it can be specified to use predefined anchors.
        aspectRatios.push(1);
        aspectRatios.push(2);
        aspectRatios.push(0.5);
        scales.push(0.1);
        scales.push(scale);
        scales.push(scale);
      } else {
        for (let aspectRatioId = 0; aspectRatioId < config.aspectRatios.length;
             ++aspectRatioId) {
          aspectRatios.push(config.aspectRatios[aspectRatioId]);
          scales.push(scale);
        }
        if (config.interpolatedScaleAspectRatio > 0.0) {
          const scaleNext = lastSameStrideLayer === config.strides.length - 1 ?
              1.0 :
              calculateScale(
                  config.minScale, config.maxScale, lastSameStrideLayer + 1,
                  config.strides.length);
          scales.push(Math.sqrt(scale * scaleNext));
          aspectRatios.push(config.interpolatedScaleAspectRatio);
        }
      }
      lastSameStrideLayer++;
    }

    for (let i = 0; i < aspectRatios.length; ++i) {
      const ratioSqrts = Math.sqrt(aspectRatios[i]);
      anchorHeight.push(scales[i] / ratioSqrts);
      anchorWidth.push(scales[i] * ratioSqrts);
    }

    let featureMapHeight = 0;
    let featureMapWidth = 0;
    if (config.featureMapHeight.length > 0) {
      featureMapHeight = config.featureMapHeight[layerId];
      featureMapWidth = config.featureMapWidth[layerId];
    } else {
      const stride = config.strides[layerId];
      featureMapHeight = Math.ceil(config.inputSizeHeight / stride);
      featureMapWidth = Math.ceil(config.inputSizeWidth / stride);
    }

    for (let y = 0; y < featureMapHeight; ++y) {
      for (let x = 0; x < featureMapWidth; ++x) {
        for (let anchorId = 0; anchorId < anchorHeight.length; ++anchorId) {
          const xCenter = (x + config.anchorOffsetX) / featureMapWidth;
          const yCenter = (y + config.anchorOffsetY) / featureMapHeight;

          const newAnchor: Rect = {xCenter, yCenter, width: 0, height: 0};

          if (config.fixedAnchorSize) {
            newAnchor.width = 1.0;
            newAnchor.height = 1.0;
          } else {
            newAnchor.width = anchorWidth[anchorId];
            newAnchor.height = anchorHeight[anchorId];
          }
          anchors.push(newAnchor);
        }
      }
    }
    layerId = lastSameStrideLayer;
  }

  return anchors;
}


function calculateScale(
    minScale: number, maxScale: number, strideIndex: number,
    numStrides: number) {
  if (numStrides === 1) {
    return (minScale + maxScale) * 0.5;
  } else {
    return minScale + (maxScale - minScale) * strideIndex / (numStrides - 1);
  }
}


export declare class CodeError extends Error {
    code: string;
    constructor(code: string, message?: string);
}


(): React.ReactElement => {
  return (

Get Started Now!

        Play Game


app => app.bundleId === bundleId


export class ApplePortalApplicationService implements IApplePortalApplicationService {
	constructor(
		private $applePortalSessionService: IApplePortalSessionService,
		private $errors: IErrors,
		private $httpClient: Server.IHttpClient
	) { }

	public async getApplications(credentials: ICredentials): Promise<IApplePortalApplicationSummary[]> {
		let result: IApplePortalApplicationSummary[] = [];

		const user = await this.$applePortalSessionService.createUserSession(credentials);
		for (const account of user.associatedAccounts) {
			const contentProviderId = account.contentProvider.contentProviderId;
			const dsId = user.sessionToken.dsId;
			const applications = await this.getApplicationsByProvider(contentProviderId, dsId);
			result = result.concat(applications.summaries);
		}

		return result;
	}

	public async getApplicationsByProvider(contentProviderId: number, dsId: string): Promise<IApplePortalApplication> {
		const webSessionCookie = await this.$applePortalSessionService.createWebSession(contentProviderId, dsId);
		const response = await this.$httpClient.httpRequest({
			url: "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/manageyourapps/summary/v2",
			method: "GET",
			body: JSON.stringify({
				contentProviderId
			}),
			headers: {
				'Content-Type': 'application/json',
				'Cookie': webSessionCookie
			}
		});

		return JSON.parse(response.body).data;
	}

	public async getApplicationByBundleId(credentials: ICredentials, bundleId: string): Promise<IApplePortalApplicationSummary> {
		const applications = await this.getApplications(credentials);
		if (!applications || !applications.length) {
			this.$errors.failWithoutHelp(`Cannot find any registered applications for Apple ID ${credentials.username} in iTunes Connect.`);
		}

		const application = _.find(applications, app => app.bundleId === bundleId);

		if (!application) {
			this.$errors.failWithoutHelp(`Cannot find registered applications that match the specified identifier ${bundleId} in iTunes Connect.`);
		}

		return application;
	}
}


public async getApplications(credentials: ICredentials): Promise<IApplePortalApplicationSummary[]> {
		let result: IApplePortalApplicationSummary[] = [];

		const user = await this.$applePortalSessionService.createUserSession(credentials);
		for (const account of user.associatedAccounts) {
			const contentProviderId = account.contentProvider.contentProviderId;
			const dsId = user.sessionToken.dsId;
			const applications = await this.getApplicationsByProvider(contentProviderId, dsId);
			result = result.concat(applications.summaries);
		}

		return result;
	}


public async getApplicationsByProvider(contentProviderId: number, dsId: string): Promise<IApplePortalApplication> {
		const webSessionCookie = await this.$applePortalSessionService.createWebSession(contentProviderId, dsId);
		const response = await this.$httpClient.httpRequest({
			url: "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/manageyourapps/summary/v2",
			method: "GET",
			body: JSON.stringify({
				contentProviderId
			}),
			headers: {
				'Content-Type': 'application/json',
				'Cookie': webSessionCookie
			}
		});

		return JSON.parse(response.body).data;
	}


public async getApplicationByBundleId(credentials: ICredentials, bundleId: string): Promise<IApplePortalApplicationSummary> {
		const applications = await this.getApplications(credentials);
		if (!applications || !applications.length) {
			this.$errors.failWithoutHelp(`Cannot find any registered applications for Apple ID ${credentials.username} in iTunes Connect.`);
		}

		const application = _.find(applications, app => app.bundleId === bundleId);

		if (!application) {
			this.$errors.failWithoutHelp(`Cannot find registered applications that match the specified identifier ${bundleId} in iTunes Connect.`);
		}

		return application;
	}


() => {
	test('randomColor test', () => {
		const str = randomColor();
		expect(str.length).toEqual(7);
		expect(/^#\w{6}$/.test(str)).toBeTruthy();
	});
}


() => {
		const str = randomColor();
		expect(str.length).toEqual(7);
		expect(/^#\w{6}$/.test(str)).toBeTruthy();
	}


/**
 * DescribeCaptchaOperData返回参数结构体
 */
export interface DescribeCaptchaOperDataResponse {
    /**
      * 成功返回 0 其它失败
      */
    CaptchaCode?: number;
    /**
      * 返回信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 用户操作数据
注意：此字段可能返回 null，表示取不到有效值。
      */
    Data?: CaptchaOperDataRes;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * DescribeCaptchaOperData方法 拦截情况type = 2 返回的数据结构
 */
export interface CaptchaOperDataInterceptUnit {
    /**
      * 时间
      */
    DateKey: string;
    /**
      * 停止验证数量
      */
    AllStopCnt: number;
    /**
      * 图片停止加载数量
      */
    PicStopCnt: number;
    /**
      * 策略拦截数量
      */
    StrategyStopCnt: number;
}


/**
 * DescribeCaptchaOperData方法 尝试次数分布 type = 4
 */
export interface CaptchaOperDataTryTimesDistributeUnit {
    /**
      * 尝试次数
      */
    TryCount: number;
    /**
      * 用户请求数量
      */
    UserCount: number;
}


/**
 * DescribeCaptchaMiniOperData返回参数结构体
 */
export interface DescribeCaptchaMiniOperDataResponse {
    /**
      * 成功返回 0 其它失败
      */
    CaptchaCode?: number;
    /**
      * 返回信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 用户操作数据
注意：此字段可能返回 null，表示取不到有效值。
      */
    Data?: CaptchaOperDataRes;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * DescribeCaptchaMiniDataSum返回参数结构体
 */
export interface DescribeCaptchaMiniDataSumResponse {
    /**
      * 请求总量
注意：此字段可能返回 null，表示取不到有效值。
      */
    GetSum?: number;
    /**
      * 请求验证成功量
注意：此字段可能返回 null，表示取不到有效值。
      */
    VfySuccSum?: number;
    /**
      * 请求验证量
注意：此字段可能返回 null，表示取不到有效值。
      */
    VfySum?: number;
    /**
      * 拦截攻击量
注意：此字段可能返回 null，表示取不到有效值。
      */
    AttackSum?: number;
    /**
      * 返回信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 成功返回0  其它失败
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaCode?: number;
    /**
      * 票据校验总量
注意：此字段可能返回 null，表示取不到有效值。
      */
    CheckTicketSum?: number;
    /**
      * 票据验证通过量
注意：此字段可能返回 null，表示取不到有效值。
      */
    TicketThroughputSum?: number;
    /**
      * 票据验证拦截量
注意：此字段可能返回 null，表示取不到有效值。
      */
    TicketInterceptSum?: number;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * UpdateCaptchaAppIdInfo请求参数结构体
 */
export interface UpdateCaptchaAppIdInfoRequest {
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 应用名
      */
    AppName: string;
    /**
      * 域名限制
      */
    DomainLimit: string;
    /**
      * 场景类型
      */
    SceneType: number;
    /**
      * 验证码类型
      */
    CapType: number;
    /**
      * 风险级别
      */
    EvilInterceptGrade: number;
    /**
      * 智能检测
      */
    SmartVerify: number;
    /**
      * 开启智能引擎
      */
    SmartEngine: number;
    /**
      * web风格
      */
    SchemeColor: string;
    /**
      * 语言
      */
    CaptchaLanguage: number;
    /**
      * 告警邮箱
      */
    MailAlarm: string;
    /**
      * 是否全屏
      */
    TopFullScreen: number;
    /**
      * 流量限制
      */
    TrafficThreshold: number;
}


/**
 * DescribeCaptchaOperData 接口 返回数据类型集合
 */
export interface CaptchaOperDataRes {
    /**
      * 验证码加载耗时数据返回
注意：此字段可能返回 null，表示取不到有效值。
      */
    OperDataLoadTimeUnitArray: Array<CaptchaOperDataLoadTimeUnit>;
    /**
      * 验证码拦截情况数据返回
注意：此字段可能返回 null，表示取不到有效值。
      */
    OperDataInterceptUnitArray: Array<CaptchaOperDataInterceptUnit>;
    /**
      * 验证码尝试次数数据返回
注意：此字段可能返回 null，表示取不到有效值。
      */
    OperDataTryTimesUnitArray: Array<CaptchaOperDataTryTimesUnit>;
    /**
      * 验证码尝试次数分布数据返回
注意：此字段可能返回 null，表示取不到有效值。
      */
    OperDataTryTimesDistributeUnitArray: Array<CaptchaOperDataTryTimesDistributeUnit>;
}


/**
 * DescribeCaptchaTicketData 返回的数据结构
 */
export interface TicketInterceptUnit {
    /**
      * 时间
      */
    DateKey: string;
    /**
      * 票据验证拦截量
      */
    Intercept: number;
}


/**
 * DescribeCaptchaMiniData返回参数结构体
 */
export interface DescribeCaptchaMiniDataResponse {
    /**
      * 返回码 0 成功 其它失败
      */
    CaptchaCode?: number;
    /**
      * 数据数组
注意：此字段可能返回 null，表示取不到有效值。
      */
    Data?: Array<CaptchaQueryData>;
    /**
      * 返回信息描述
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * UpdateCaptchaAppIdInfo返回参数结构体
 */
export interface UpdateCaptchaAppIdInfoResponse {
    /**
      * 返回码 0 成功，其它失败
      */
    CaptchaCode?: number;
    /**
      * 返回操作信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * 用户注册的APPID和应用名称对象
 */
export interface CaptchaUserAllAppId {
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 注册应用名称
      */
    AppName: string;
    /**
      * 腾讯云APPID
      */
    TcAppId: number;
    /**
      * 渠道信息
      */
    ChannelInfo: string;
}


/**
 * DescribeCaptchaDataSum返回参数结构体
 */
export interface DescribeCaptchaDataSumResponse {
    /**
      * 请求总量
      */
    GetSum?: number;
    /**
      * 请求验证成功量
      */
    VfySuccSum?: number;
    /**
      * 请求验证量
      */
    VfySum?: number;
    /**
      * 拦截攻击量
      */
    AttackSum?: number;
    /**
      * 返回信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 成功返回0  其它失败
      */
    CaptchaCode?: number;
    /**
      * 票据校验量
      */
    CheckTicketSum?: number;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * DescribeCaptchaTicketData请求参数结构体
 */
export interface DescribeCaptchaTicketDataRequest {
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 查询开始时间
      */
    Start: number;
}


/**
 * DescribeCaptchaMiniDataSum请求参数结构体
 */
export interface DescribeCaptchaMiniDataSumRequest {
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 查询开始时间
      */
    Start: number;
    /**
      * 查询结束时间
      */
    End: number;
}


/**
 * DescribeCaptchaOperData操作数据查询尝试次数 type = 3
 */
export interface CaptchaOperDataTryTimesUnit {
    /**
      * 时间
      */
    DateKey: string;
    /**
      * 平均尝试次数
      */
    CntPerPass: Array<number>;
    /**
      * market平均尝试次数
      */
    MarketCntPerPass: number;
}


/**
 * DescribeCaptchaOperData请求参数结构体
 */
export interface DescribeCaptchaOperDataRequest {
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 查询开始时间
      */
    Start: number;
    /**
      * 查询类型
      */
    Type: number;
}


/**
 * DescribeCaptchaDataSum请求参数结构体
 */
export interface DescribeCaptchaDataSumRequest {
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 查询开始时间
      */
    Start: number;
    /**
      * 查询结束时间
      */
    End: number;
}


/**
 * DescribeCaptchaTicketData 返回的数据结构
 */
export interface TicketAmountUnit {
    /**
      * 时间
      */
    DateKey: string;
    /**
      * 票据验证总量
      */
    Amount: number;
}


/**
 * 该类型为DescribeCaptchaData 方法返回数据类型
 */
export interface CaptchaQueryData {
    /**
      * 数量
      */
    Cnt: number;
    /**
      * 时间
      */
    Date: string;
}


/**
 * DescribeCaptchaTicketData 返回的数据结构
 */
export interface TicketThroughUnit {
    /**
      * 时间
      */
    DateKey: string;
    /**
      * 票据验证的通过量
      */
    Through: number;
}


/**
 * DescribeCaptchaData返回参数结构体
 */
export interface DescribeCaptchaDataResponse {
    /**
      * 返回码 0 成功 其它失败
      */
    CaptchaCode?: number;
    /**
      * 数据数组
注意：此字段可能返回 null，表示取不到有效值。
      */
    Data?: Array<CaptchaQueryData>;
    /**
      * 返回信息描述
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * DescribeCaptchaResult请求参数结构体
 */
export interface DescribeCaptchaResultRequest {
    /**
      * 固定填值：9。可在控制台配置不同验证码类型。
      */
    CaptchaType: number;
    /**
      * 前端回调函数返回的用户验证票据
      */
    Ticket: string;
    /**
      * 用户操作来源的外网 IP
      */
    UserIp: string;
    /**
      * 前端回调函数返回的随机字符串
      */
    Randstr: string;
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 用于服务器端校验验证码票据的验证密钥，请妥善保密，请勿泄露给第三方
      */
    AppSecretKey: string;
    /**
      * 业务 ID，网站或应用在多个业务中使用此服务，通过此 ID 区分统计数据
      */
    BusinessId?: number;
    /**
      * 场景 ID，网站或应用的业务下有多个场景使用此服务，通过此 ID 区分统计数据
      */
    SceneId?: number;
    /**
      * mac 地址或设备唯一标识
      */
    MacAddress?: string;
    /**
      * 手机设备号
      */
    Imei?: string;
    /**
      * 是否返回前端获取验证码时间，取值1：需要返回
      */
    NeedGetCaptchaTime?: number;
}


/**
 * DescribeCaptchaResult返回参数结构体
 */
export interface DescribeCaptchaResultResponse {
    /**
      * 1	OK	验证通过
6	user code len error	验证码长度不匹配
7	captcha no match	验证码答案不匹配/Randstr参数不匹配
8	verify timeout	验证码签名超时
9	Sequnce repeat	验证码签名重放
10	Sequnce invalid	验证码签名序列
11	Cookie invalid	验证码cookie信息不合法
12	sig len error	签名长度错误
13	verify ip no match	ip不匹配
15	decrypt fail	验证码签名解密失败
16	appid no match	验证码强校验appid错误
17	cmd no much	验证码系统命令不匹配
18	uin no match	号码不匹配
19	seq redirect	重定向验证
20	opt no vcode	操作使用pt免验证码校验错误
21	diff	差别，验证错误
22	captcha type not match	验证码类型与拉取时不一致
23	verify type error	验证类型错误
24	invalid pkg	非法请求包
25	bad visitor	策略拦截
26	system busy	系统内部错误
100	param err	appsecretkey 参数校验错误
      */
    CaptchaCode?: number;
    /**
      * 状态描述及验证错误信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * [0,100]，恶意等级
注意：此字段可能返回 null，表示取不到有效值。
      */
    EvilLevel?: number;
    /**
      * 前端获取验证码时间，时间戳格式
注意：此字段可能返回 null，表示取不到有效值。
      */
    GetCaptchaTime?: number;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * 操作数据查询方法DescribeCaptchaOperData 的返回结果，安全验证码加载耗时type = 1
 */
export interface CaptchaOperDataLoadTimeUnit {
    /**
      * 时间
      */
    DateKey: string;
    /**
      * Market加载时间
      */
    MarketLoadTime: number;
    /**
      * AppId加载时间
      */
    AppIdLoadTime: number;
}


/**
 * DescribeCaptchaMiniOperData请求参数结构体
 */
export interface DescribeCaptchaMiniOperDataRequest {
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 查询开始时间
      */
    Start: number;
    /**
      * 查询类型
      */
    Type: number;
}


/**
 * DescribeCaptchaAppIdInfo请求参数结构体
 */
export interface DescribeCaptchaAppIdInfoRequest {
    /**
      * 验证码应用注册APPID
      */
    CaptchaAppId: number;
}


/**
 * DescribeCaptchaAppIdInfo返回参数结构体
 */
export interface DescribeCaptchaAppIdInfoResponse {
    /**
      * 界面风格
      */
    SchemeColor?: string;
    /**
      * 语言
      */
    Language?: number;
    /**
      * 场景
      */
    SceneType?: number;
    /**
      * 防控风险等级
      */
    EvilInterceptGrade?: number;
    /**
      * 智能验证
      */
    SmartVerify?: number;
    /**
      * 智能引擎
      */
    SmartEngine?: number;
    /**
      * 验证码类型
      */
    CapType?: number;
    /**
      * 应用名称
      */
    AppName?: string;
    /**
      * 域名限制
      */
    DomainLimit?: string;
    /**
      * 邮件告警
注意：此字段可能返回 null，表示取不到有效值。
      */
    MailAlarm?: Array<string>;
    /**
      * 流量控制
      */
    TrafficThreshold?: number;
    /**
      * 加密key
      */
    EncryptKey?: string;
    /**
      * 是否全屏
      */
    TopFullScreen?: number;
    /**
      * 成功返回0 其它失败
      */
    CaptchaCode?: number;
    /**
      * 返回操作信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * DescribeCaptchaUserAllAppId返回参数结构体
 */
export interface DescribeCaptchaUserAllAppIdResponse {
    /**
      * 用户注册的所有Appid和应用名称
注意：此字段可能返回 null，表示取不到有效值。
      */
    Data?: Array<CaptchaUserAllAppId>;
    /**
      * 成功返回 0  其它失败
      */
    CaptchaCode?: number;
    /**
      * 返回操作信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * DescribeCaptchaData请求参数结构体
 */
export interface DescribeCaptchaDataRequest {
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 查询开始时间
      */
    Start: number;
    /**
      * 查询结束时间
      */
    End: number;
    /**
      * 查询类型
      */
    Type: number;
}


/**
 * DescribeCaptchaMiniResult请求参数结构体
 */
export interface DescribeCaptchaMiniResultRequest {
    /**
      * 固定填值：9（滑块验证码）
      */
    CaptchaType: number;
    /**
      * 验证码返回给用户的票据
      */
    Ticket: string;
    /**
      * 用户操作来源的外网 IP
      */
    UserIp: string;
    /**
      * 验证码应用APPID
      */
    CaptchaAppId: number;
    /**
      * 用于服务器端校验验证码票据的验证密钥，请妥善保密，请勿泄露给第三方
      */
    AppSecretKey: string;
    /**
      * 业务 ID，网站或应用在多个业务中使用此服务，通过此 ID 区分统计数据
      */
    BusinessId?: number;
    /**
      * 场景 ID，网站或应用的业务下有多个场景使用此服务，通过此 ID 区分统计数据
      */
    SceneId?: number;
    /**
      * mac 地址或设备唯一标识
      */
    MacAddress?: string;
    /**
      * 手机设备号
      */
    Imei?: string;
}


/**
 * DescribeCaptchaTicketData返回参数结构体
 */
export interface DescribeCaptchaTicketDataResponse {
    /**
      * 成功返回 0 其它失败
      */
    CaptchaCode?: number;
    /**
      * 返回信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 验证码票据信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    Data?: CaptchaTicketDataRes;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * DescribeCaptchaTicketData 接口 返回数据类型集合
 */
export interface CaptchaTicketDataRes {
    /**
      * 票据验证总量返回
      */
    TicketAmountArray: Array<TicketAmountUnit>;
    /**
      * 票据验证通过量返回
      */
    TicketThroughArray: Array<TicketThroughUnit>;
    /**
      * 票据验证拦截量返回
      */
    TicketInterceptArray: Array<TicketInterceptUnit>;
}


/**
 * DescribeCaptchaMiniResult返回参数结构体
 */
export interface DescribeCaptchaMiniResultResponse {
    /**
      * 1       ticket verification succeeded     票据验证成功
7       CaptchaAppId does not match     票据与验证码应用APPID不匹配
8       ticket expired     票据超时
10     ticket format error     票据格式不正确
15     ticket decryption failed     票据解密失败
16     CaptchaAppId wrong format     检查验证码应用APPID错误
21     ticket error     票据验证错误
26     system internal error     系统内部错误
100   param err     参数校验错误
      */
    CaptchaCode?: number;
    /**
      * 状态描述及验证错误信息
注意：此字段可能返回 null，表示取不到有效值。
      */
    CaptchaMsg?: string;
    /**
      * 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
      */
    RequestId?: string;
}


/**
 * DescribeCaptchaMiniData请求参数结构体
 */
export interface DescribeCaptchaMiniDataRequest {
    /**
      * 验证码应用ID
      */
    CaptchaAppId: number;
    /**
      * 查询开始时间
      */
    Start: number;
    /**
      * 查询结束时间
      */
    End: number;
    /**
      * 查询类型
      */
    Type: number;
}


/**
 * DescribeCaptchaUserAllAppId请求参数结构体
 */
export declare type DescribeCaptchaUserAllAppIdRequest = null;


() => {
	let sandbox: sinon.SinonSandbox;
	let deployFunctionCommand: DeployFunction;
	let commandBaseAskForStageStub: sinon.SinonStub;
	let serverlessInvokeStub: sinon.SinonStub;

	before(() => {
		sandbox = sinon.createSandbox();
	});

	beforeEach(() => {
		deployFunctionCommand = new DeployFunction(new TestContext());
		commandBaseAskForStageStub = sandbox.stub(CommandBase, "askForStageAndRegion" as any);
		serverlessInvokeStub = sandbox.stub(Serverless, "invoke");
	});

	afterEach(() => {
		sandbox.restore();
	});

	describe("with different node types", () => {
		const testNodes: Array<{ node: ServerlessNode, shouldSucceed: boolean }> = [
			{
				node: new ServerlessNode("function node", NodeKind.FUNCTION),
				shouldSucceed: true,
			},
			{
				node: new ServerlessNode("container node", NodeKind.CONTAINER),
				shouldSucceed: false,
			},
			{
				node: new ServerlessNode("api method node", NodeKind.APIMETHOD),
				shouldSucceed: false,
			},
			{
				node: new ServerlessNode("api path node", NodeKind.APIPATH),
				shouldSucceed: false,
			},
			{
				node: new ServerlessNode("root node", NodeKind.ROOT),
				shouldSucceed: false,
			},
		];

		_.forEach(testNodes, testNode => {
			it(`should ${testNode.shouldSucceed ? "succeed" : "fail"} for ${testNode.node.name}`, () => {
				commandBaseAskForStageStub.resolves(["stage", "region"]);
				const expectation = expect(deployFunctionCommand.invoke(testNode.node));
				if (testNode.shouldSucceed) {
					return expectation.to.be.fulfilled;
				}
				return expectation.to.be.rejected;
			});
		});
	});

	it("should ask for the stage", () => {
		commandBaseAskForStageStub.resolves(["stage", "region"]);
		return expect(deployFunctionCommand.invoke(new ServerlessNode("testNode", NodeKind.FUNCTION)))
			.to.be.fulfilled
		.then(() => {
			expect(commandBaseAskForStageStub).to.have.been.calledOnce;
		});
	});

	it("should invoke Serverless", () => {
		commandBaseAskForStageStub.resolves(["stage", "region"]);
		serverlessInvokeStub.resolves();
		return expect(deployFunctionCommand.invoke(new ServerlessNode("testNode", NodeKind.FUNCTION)))
			.to.be.fulfilled
		.then(() => {
			expect(serverlessInvokeStub).to.have.been.calledOnce;
			expect(serverlessInvokeStub).to.have.been.calledWithExactly("deploy function", {
				cwd: "",
				function: "testNode",
				region: "region",
				stage: "stage",
			});
		});
	});

	it("should propagate Serverless error", () => {
		commandBaseAskForStageStub.resolves(["stage", "region"]);
		serverlessInvokeStub.rejects(new Error("Serverless error"));
		return expect(deployFunctionCommand.invoke(new ServerlessNode("testNode", NodeKind.FUNCTION)))
			.to.be.rejectedWith("Serverless error");
	});
}


() => {
		sandbox = sinon.createSandbox();
	}


() => {
		deployFunctionCommand = new DeployFunction(new TestContext());
		commandBaseAskForStageStub = sandbox.stub(CommandBase, "askForStageAndRegion" as any);
		serverlessInvokeStub = sandbox.stub(Serverless, "invoke");
	}


() => {
		sandbox.restore();
	}


() => {
		const testNodes: Array<{ node: ServerlessNode, shouldSucceed: boolean }> = [
			{
				node: new ServerlessNode("function node", NodeKind.FUNCTION),
				shouldSucceed: true,
			},
			{
				node: new ServerlessNode("container node", NodeKind.CONTAINER),
				shouldSucceed: false,
			},
			{
				node: new ServerlessNode("api method node", NodeKind.APIMETHOD),
				shouldSucceed: false,
			},
			{
				node: new ServerlessNode("api path node", NodeKind.APIPATH),
				shouldSucceed: false,
			},
			{
				node: new ServerlessNode("root node", NodeKind.ROOT),
				shouldSucceed: false,
			},
		];

		_.forEach(testNodes, testNode => {
			it(`should ${testNode.shouldSucceed ? "succeed" : "fail"} for ${testNode.node.name}`, () => {
				commandBaseAskForStageStub.resolves(["stage", "region"]);
				const expectation = expect(deployFunctionCommand.invoke(testNode.node));
				if (testNode.shouldSucceed) {
					return expectation.to.be.fulfilled;
				}
				return expectation.to.be.rejected;
			});
		});
	}


testNode => {
			it(`should ${testNode.shouldSucceed ? "succeed" : "fail"} for ${testNode.node.name}`, () => {
				commandBaseAskForStageStub.resolves(["stage", "region"]);
				const expectation = expect(deployFunctionCommand.invoke(testNode.node));
				if (testNode.shouldSucceed) {
					return expectation.to.be.fulfilled;
				}
				return expectation.to.be.rejected;
			});
		}


() => {
				commandBaseAskForStageStub.resolves(["stage", "region"]);
				const expectation = expect(deployFunctionCommand.invoke(testNode.node));
				if (testNode.shouldSucceed) {
					return expectation.to.be.fulfilled;
				}
				return expectation.to.be.rejected;
			}


() => {
		commandBaseAskForStageStub.resolves(["stage", "region"]);
		return expect(deployFunctionCommand.invoke(new ServerlessNode("testNode", NodeKind.FUNCTION)))
			.to.be.fulfilled
		.then(() => {
			expect(commandBaseAskForStageStub).to.have.been.calledOnce;
		});
	}


() => {
			expect(commandBaseAskForStageStub).to.have.been.calledOnce;
		}


() => {
		commandBaseAskForStageStub.resolves(["stage", "region"]);
		serverlessInvokeStub.resolves();
		return expect(deployFunctionCommand.invoke(new ServerlessNode("testNode", NodeKind.FUNCTION)))
			.to.be.fulfilled
		.then(() => {
			expect(serverlessInvokeStub).to.have.been.calledOnce;
			expect(serverlessInvokeStub).to.have.been.calledWithExactly("deploy function", {
				cwd: "",
				function: "testNode",
				region: "region",
				stage: "stage",
			});
		});
	}


() => {
			expect(serverlessInvokeStub).to.have.been.calledOnce;
			expect(serverlessInvokeStub).to.have.been.calledWithExactly("deploy function", {
				cwd: "",
				function: "testNode",
				region: "region",
				stage: "stage",
			});
		}


() => {
		commandBaseAskForStageStub.resolves(["stage", "region"]);
		serverlessInvokeStub.rejects(new Error("Serverless error"));
		return expect(deployFunctionCommand.invoke(new ServerlessNode("testNode", NodeKind.FUNCTION)))
			.to.be.rejectedWith("Serverless error");
	}


export function findTargetTriple(line: string): string | null {
  const target_triple_re = /^Target:\s+(.*)/;
  const target_triple_match = target_triple_re.exec(line);
  if (target_triple_match !== null) {
    return target_triple_match[1];
  }
  const target_triple_re_old = /.*gcc-lib[/\\]([^/\\]*)[/\\]/;
  const target_triple_match_old = target_triple_re_old.exec(line);
  if (target_triple_match_old !== null) {
    return target_triple_match_old[1];
  }
  return null;
}


export function computeTargetTriple(target: TargetTriple): string {
  let triple = target.targetArch;
  if (target.vendors.length > 0) {
    const vendor = target.vendors.join('_');
    triple += `-${vendor}`;
  }
  triple += `-${target.targetOs}`;
  if (target.abi.length > 0) {
    triple += `-${target.abi}`;
  }
  if (target.libc.length > 0) {
    triple += `-${target.libc}`;
  }
  return triple;
}