text:
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

$PLACEHOLDER = "PLACEHOLDER1@";

<#
.SYNOPSIS
Tests Create-AzureVM with valid information.
#>
function Test-GetAzureVM
{
    # Setup
    $location = Get-DefaultLocation
    $imgName = Get-DefaultImage $location

    $storageName = getAssetName
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location

    Set-CurrentStorageAccountName $storageName

    $vmName = "vm1"
    $svcName = Get-CloudServiceName

    # Test
    New-AzureService -ServiceName $svcName -Location $location
    New-AzureQuickVM -Windows -ImageName $imgName -Name $vmName -ServiceName $svcName -AdminUsername "pstestuser" -Password $PLACEHOLDER

    Get-AzureVM -ServiceName $svcName -Name $vmName

    # Cleanup
    Cleanup-CloudService $svcName
}

<#
.SYNOPSIS
Test Get-AzureLocation
#>
function Test-GetAzureLocation
{
    $locations = Get-AzureLocation;

    foreach ($loc in $locations)
    {
        $svcName = getAssetName;
        $st = New-AzureService -ServiceName $svcName -Location $loc.Name;

        # Cleanup
        Cleanup-CloudService $svcName
    }
}

# Test Service Management Cloud Exception
function Run-ServiceManagementCloudExceptionTests
{
    $compare = "*OperationID : `'*`'";
    Assert-ThrowsLike { $st = Get-AzureService -ServiceName '*' } $compare;
    Assert-ThrowsLike { $st = Get-AzureVM -ServiceName '*' } $compare;
    Assert-ThrowsLike { $st = Get-AzureAffinityGroup -Name '*' } $compare;
}

# Test Start/Stop-AzureVM for Multiple VMs
function Run-StartAndStopMultipleVirtualMachinesTest
{
    # Virtual Machine cmdlets are now showing a non-terminating error message for ResourceNotFound
    # To continue script, $ErrorActionPreference should be set to 'SilentlyContinue'.
    $tempErrorActionPreference = $ErrorActionPreference;
    $ErrorActionPreference='SilentlyContinue';

    # Setup
    $location = Get-DefaultLocation;
    $imgName = Get-DefaultImage $location;

    $storageName = 'pstest' + (getAssetName);
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;

    # Associate the new storage account with the current subscription
    Set-CurrentStorageAccountName $storageName;

    $vmNameList = @("vm01", "vm02", "test04");
    $svcName = 'pstest' + (Get-CloudServiceName);
    $userName = "pstestuser";
    $password = $PLACEHOLDER;

    # Test
    New-AzureService -ServiceName $svcName -Location $location;

    try
    {
        foreach ($vmName in $vmNameList)
        {
            New-AzureQuickVM -Windows -ImageName $imgName -Name $vmName -ServiceName $svcName -AdminUsername $userName -Password $password;
        }

        # Get VM List
        $vmList = Get-AzureVM -ServiceName $svcName;

        # Test Stop
        Stop-AzureVM -Force -ServiceName $svcName -Name $vmNameList[0];
        Stop-AzureVM -Force -ServiceName $svcName -Name $vmNameList[0],$vmNameList[1];
        Stop-AzureVM -Force -ServiceName $svcName -Name $vmNameList;
        Stop-AzureVM -Force -ServiceName $svcName -Name '*';
        Stop-AzureVM -Force -ServiceName $svcName -Name 'vm*';
        Stop-AzureVM -Force -ServiceName $svcName -Name 'vm*','test*';
        Stop-AzureVM -Force -ServiceName $svcName -VM $vmList[0];
        Stop-AzureVM -Force -ServiceName $svcName -VM $vmList[0],$vmList[1];
        Stop-AzureVM -Force -ServiceName $svcName -VM $vmList;

        # Test Start
        Start-AzureVM -ServiceName $svcName -Name $vmNameList[0];
        Start-AzureVM -ServiceName $svcName -Name $vmNameList[0],$vmNameList[1];
        Start-AzureVM -ServiceName $svcName -Name $vmNameList;
        Start-AzureVM -ServiceName $svcName -Name '*';
        Start-AzureVM -ServiceName $svcName -Name 'vm*';
        Start-AzureVM -ServiceName $svcName -Name 'vm*','test*';
        Start-AzureVM -ServiceName $svcName -VM $vmList[0];
        Start-AzureVM -ServiceName $svcName -VM $vmList[0],$vmList[1];
        Start-AzureVM -ServiceName $svcName -VM $vmList;
    }
    finally
    {
        # Cleanup
        Cleanup-CloudService $svcName;
        $ErrorActionPreference = $tempErrorActionPreference;
    }
}

# Run Auto-Generated Hosted Service Cmdlet Tests
function Run-AutoGeneratedHostedServiceCmdletTests
{
    # Setup
    $location = Get-DefaultLocation;
    $imgName = Get-DefaultImage $location;

    $storageName = 'pstest' + (getAssetName);
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;

    # Associate the new storage account with the current subscription
    Set-CurrentStorageAccountName $storageName;

    $vmNameList = @("vm01", "vm02", "test04");
    $svcName = 'pstest' + (Get-CloudServiceName);
    $userName = "pstestuser";
    $password = $PLACEHOLDER;

    try
    {
        # Create Parameters
        $svcCreateParams = New-AzureComputeParameterObject -FriendlyName 'HostedServiceCreateParameters';
        $svcCreateParams.ServiceName = $svcName;
        $svcCreateParams.Location = $location;
        $svcCreateParams.Description = $svcName;
        $svcCreateParams.Label = $svcName;

        # Invoke Create
        $st = Invoke-AzureComputeMethod -MethodName 'HostedServiceCreate' -HostedServiceCreateParameters $svcCreateParams;

        Assert-AreEqual $st.StatusCode 'Created';
        Assert-NotNull $st.RequestId;

        # Invoke Get
        $svcGetResult = Invoke-AzureComputeMethod -MethodName 'HostedServiceGet' -ServiceName $svcName;
        Assert-AreEqual $svcGetResult.ServiceName $svcName;
        Assert-AreEqual $svcGetResult.Properties.Description $svcName;
        Assert-AreEqual $svcGetResult.Properties.Label $svcName;

        # Update Parameters
        $svcUpdateParams = New-AzureComputeParameterObject -FriendlyName 'HostedServiceUpdateParameters';
        $svcUpdateParams.Description = 'update1';
        $svcUpdateParams.Label = 'update2';

        # Invoke Update
        $svcGetResult2 = Invoke-AzureComputeMethod -MethodName 'HostedServiceUpdate' -ServiceName $svcName -HostedServiceUpdateParameters $svcUpdateParams;

        # Invoke Get
        $svcGetResult2 = Invoke-AzureComputeMethod -MethodName 'HostedServiceGet' -ServiceName $svcName;
        Assert-AreEqual $svcGetResult2.ServiceName $svcName;
        Assert-AreEqual $svcGetResult2.Properties.Description $svcUpdateParams.Description;
        Assert-AreEqual $svcGetResult2.Properties.Label $svcUpdateParams.Label;

        # Invoke List
        $svcListResult = Invoke-AzureComputeMethod -MethodName 'HostedServiceList';
        Assert-True { ($svcListResult | where { $_.ServiceName -eq $svcName }).Count -gt 0 };

        # Invoke Delete
        $st = Invoke-AzureComputeMethod -MethodName 'HostedServiceDelete' -ServiceName $svcName;
        Assert-AreEqual $st.StatusCode 'OK';
        Assert-NotNull $st.RequestId;
    }
    finally
    {
        # Cleanup
        Cleanup-CloudService $svcName;
    }
}

# Run Auto-Generated Virtual Machine Cmdlet Tests
function Run-AutoGeneratedVirtualMachineCmdletTests
{
    # Setup
    $location = Get-DefaultLocation;

    $storageName = 'pstest' + (getAssetName);
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;

    # Associate the new storage account with the current subscription
    Set-CurrentStorageAccountName $storageName;

    $svcName = 'pstest' + (Get-CloudServiceName);
    $userName = "pstestuser";
    $password = $PLACEHOLDER;

    try
    {
        # Create Hosted Service Parameters
        $svcCreateParams = New-AzureComputeParameterObject -FriendlyName 'HostedServiceCreateParameters';
        $svcCreateParams.ServiceName = $svcName;
        $svcCreateParams.Location = $location;
        $svcCreateParams.Description = $svcName;
        $svcCreateParams.Label = $svcName;

        # Invoke Hosted Service Create
        $st = Invoke-AzureComputeMethod -MethodName 'HostedServiceCreate' -ArgumentList $svcCreateParams;
        Assert-AreEqual $st.StatusCode 'Created';
        Assert-NotNull $st.RequestId;

        # Invoke Hosted Service Get
        $svcGetResult = Invoke-AzureComputeMethod -MethodName 'HostedServiceGet' -ArgumentList $svcName;
        Assert-AreEqual $svcGetResult.ServiceName $svcName;
        Assert-AreEqual $svcGetResult.Properties.Description $svcName;
        Assert-AreEqual $svcGetResult.Properties.Label $svcName;

        # Invoke Virtual Machine OS Image List
        $images = (Invoke-AzureComputeMethod -MethodName 'VirtualMachineOSImageList').Images;
        $image = $images | where { $_.OperatingSystemType -eq 'Windows' -and $_.LogicalSizeInGB -le 100 } | select -First 1;

        # Create Virtual Machine Deployment Create Parameters
        $vmDeployment = New-AzureComputeParameterObject -FriendlyName 'VirtualMachineCreateDeploymentParameters';
        $vmDeployment.Name = $svcName;
        $vmDeployment.Label = $svcName;
        $vmDeployment.DeploymentSlot = 'Production';
        $vmDeployment.Roles = New-AzureComputeParameterObject -FriendlyName 'VirtualMachineRoleList';
        $vmDeployment.Roles.Add((New-AzureComputeParameterObject -FriendlyName 'VirtualMachineRole'));
        $vmDeployment.Roles[0].RoleName = $svcName;
        $vmDeployment.Roles[0].RoleSize = 'Large';
        $vmDeployment.Roles[0].RoleType = 'PersistentVMRole';
        $vmDeployment.Roles[0].ProvisionGuestAgent = $false;
        $vmDeployment.Roles[0].ResourceExtensionReferences = $null;
        $vmDeployment.Roles[0].DataVirtualHardDisks = $null;
        $vmDeployment.Roles[0].OSVirtualHardDisk = New-AzureComputeParameterObject -FriendlyName 'VirtualMachineOSVirtualHardDisk';
        $vmDeployment.Roles[0].OSVirtualHardDisk.SourceImageName = $image.Name;
        $vmDeployment.Roles[0].OSVirtualHardDisk.MediaLink = "http://${storageName}.blob.core.windows.net/myvhds/${svcName}.vhd";
        $vmDeployment.Roles[0].OSVirtualHardDisk.ResizedSizeInGB = 128;
        $vmDeployment.Roles[0].OSVirtualHardDisk.HostCaching = 'ReadWrite';
        $vmDeployment.Roles[0].ConfigurationSets = New-AzureComputeParameterObject -FriendlyName 'VirtualMachineConfigurationSetList';
        $vmDeployment.Roles[0].ConfigurationSets.Add((New-AzureComputeParameterObject -FriendlyName 'VirtualMachineConfigurationSet'));
        $vmDeployment.Roles[0].ConfigurationSets[0].ConfigurationSetType = "WindowsProvisioningConfiguration";
        $vmDeployment.Roles[0].ConfigurationSets[0].AdminUserName = $userName;
        $vmDeployment.Roles[0].ConfigurationSets[0].AdminPassword = $password;
        $vmDeployment.Roles[0].ConfigurationSets[0].ComputerName = 'test';
        $vmDeployment.Roles[0].ConfigurationSets[0].HostName = "${svcName}.cloudapp.net";
        $vmDeployment.Roles[0].ConfigurationSets[0].EnableAutomaticUpdates = $false;
        $vmDeployment.Roles[0].ConfigurationSets[0].TimeZone = "Pacific Standard Time";

        # Invoke Virtual Machine Create Deployment
        $st = Invoke-AzureComputeMethod -MethodName 'VirtualMachineCreateDeployment' -ArgumentList $svcName,$vmDeployment;
        Assert-AreEqual $st.StatusCode 'OK';
        Assert-NotNull $st.RequestId;

        # Invoke Virtual Machine Get
        $st = Invoke-AzureComputeMethod -MethodName 'VirtualMachineGet' -ArgumentList $svcName,$svcName,$svcName;
        Assert-AreEqual $st.RoleName $svcName;

        # Invoke Hosted Service Delete
        $st = Invoke-AzureComputeMethod -MethodName 'HostedServiceDeleteAll' -ArgumentList $svcName;
        Assert-AreEqual $st.StatusCode 'OK';
        Assert-NotNull $st.RequestId;
    }
    finally
    {
        # Cleanup
        Cleanup-CloudService $svcName;
    }
}

# Run New-AzureComputeArgumentList Cmdlet Tests Using Method Names
function Run-NewAzureComputeArgumentListTests
{
    $command = Get-Command -Name 'New-AzureComputeArgumentList';
    $all_methods = $command.Parameters['MethodName'].Attributes.ValidValues;

    foreach ($method in $all_methods)
    {
        $args = New-AzureComputeArgumentList -MethodName $method;
        foreach ($arg in $args)
        {
            Assert-NotNull $arg;
        }

        Write-Verbose "Invoke-AzureComputeMethod -MethodName $method -ArgumentList $args;";

        if ($args.Count -gt 0)
        {
            # If the method requires any inputs, empty/null input call would fail
            Assert-Throws { Invoke-AzureComputeMethod -MethodName $method -ArgumentList $args; }
        }
        else
        {
            # If the method doesn't requires any inputs, it shall succeed.
            $st = Invoke-AzureComputeMethod -MethodName $method;
        }
    }
}

# Run New-AzureComputeParameterObject Cmdlet Tests
function Run-NewAzureComputeParameterObjectTests
{
    $command = Get-Command -Name 'New-AzureComputeParameterObject';

    $all_friendly_names = $command.Parameters['FriendlyName'].Attributes.ValidValues;
    foreach ($friendly_name in $all_friendly_names)
    {
        $param = New-AzureComputeParameterObject -FriendlyName $friendly_name;
        Assert-NotNull $param;
    }

    $all_full_names = $command.Parameters['FullName'].Attributes.ValidValues;
    foreach ($full_name in $all_full_names)
    {
        $param = New-AzureComputeParameterObject -FullName $full_name;
        Assert-NotNull $param;

        $param_type_name = $param.GetType().ToString().Replace('+', '.');
        $full_name_query = $full_name.Replace('+', '.').Replace('<', '*').Replace('>', '*');
        Assert-True { $param_type_name -like $full_name_query } "`'$param_type_name`' & `'$full_name`'";
    }
}

# Run Set-AzurePlatformVMImage Cmdlet Negative Tests
function Run-AzurePlatformVMImageNegativeTest
{
    $location = Get-DefaultLocation;
    $imgName = Get-DefaultImage $location;
    $replicate_locations = (Get-AzureLocation | where { $_.Name -like '*US*' } | select -ExpandProperty Name);

    $c1 = New-AzurePlatformComputeImageConfig -Offer test -Sku test -Version test;
    $c2 = New-AzurePlatformMarketplaceImageConfig -PlanName test -Product test -Publisher test -PublisherId test;

    Assert-ThrowsContains `
        { Set-AzurePlatformVMImage -ImageName $imgName -ReplicaLocations $replicate_locations -ComputeImageConfig $c1 -MarketplaceImageConfig $c2 } `
        "ForbiddenError: This operation is not allowed for this subscription.";

    foreach ($mode in @("MSDN", "Private", "Public"))
    {
        Assert-ThrowsContains `
            { Set-AzurePlatformVMImage -ImageName $imgName -Permission $mode } `
            "ForbiddenError: This operation is not allowed for this subscription.";
    }
}

# Run Auto-Generated Service Extension Cmdlet Tests
function Run-AutoGeneratedServiceExtensionCmdletTests
{
    # Setup
    $location = Get-DefaultLocation;

    $storageName = 'pstest' + (getAssetName);
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;

    # Associate the new storage account with the current subscription
    Set-CurrentStorageAccountName $storageName;

    $svcName = 'pstest' + (Get-CloudServiceName);

    try
    {
        # Create Hosted Service Parameters
        $svcCreateParams = New-AzureComputeParameterObject -FriendlyName 'HostedServiceCreateParameters';
        $svcCreateParams.ServiceName = $svcName;
        $svcCreateParams.Location = $location;
        $svcCreateParams.Description = $svcName;
        $svcCreateParams.Label = $svcName;

        # Invoke Hosted Service Create
        $st = Invoke-AzureComputeMethod -MethodName 'HostedServiceCreate' -ArgumentList $svcCreateParams;
        Assert-AreEqual $st.StatusCode 'Created';
        Assert-NotNull $st.RequestId;

        # New-AzureDeployment (in Azure.psd1)
        $testMode = Get-ComputeTestMode;
        if ($testMode.ToLower() -ne 'playback')
        {
            $cspkg = '.\Resources\ServiceManagement\Files\OneWebOneWorker.cspkg';
        }
        else
        {
            $cspkg = "https://${storageName}.blob.azure.windows.net/blob/OneWebOneWorker.cspkg";
        }
        $cscfg = "$TestOutputRoot\Resources\ServiceManagement\Files\OneWebOneWorker.cscfg";

        $st = New-AzureDeployment -ServiceName $svcName -Package $cspkg -Configuration $cscfg -Label $svcName -Slot Production;

        $deployment = Get-AzureDeployment -ServiceName $svcName -Slot Production;
        $config = $deployment.Configuration;

        # Invoke Hosted Service Add Extension
        $p1 = New-AzureComputeArgumentList -MethodName HostedServiceAddExtension;
        $p1[0].Value = $svcName;
        $p1[1].Value.Id = 'test';
        $p1[1].Value.PublicConfiguration =
@"
<?xml version="1.0" encoding="UTF-8"?>
<PublicConfig>
  <UserName>pstestuser</UserName>
  <Expiration></Expiration>
</PublicConfig>
"@;
        $p1[1].Value.PrivateConfiguration =
@"
<?xml version="1.0" encoding="UTF-8"?>
<PrivateConfig>
  <Password>pstestuser</Password>
</PrivateConfig>
"@;
        $p1[1].Value.ProviderNamespace = 'Microsoft.Windows.Azure.Extensions';
        $p1[1].Value.Type = 'RDP';
        $p1[1].Value.Version = '1.*';
        $d1 = ($p1 | select -ExpandProperty Value);
        $st = Invoke-AzureComputeMethod -MethodName HostedServiceAddExtension -ArgumentList $d1;

        # Invoke Deployment Change Configuration
        $p2 = New-AzureComputeArgumentList -MethodName DeploymentChangeConfigurationBySlot;
        $p2[0].Value = $svcName;
        $p2[1].Value = [Microsoft.WindowsAzure.Management.Compute.Models.DeploymentSlot]::Production;
        $p2[2].Value = New-Object -TypeName Microsoft.WindowsAzure.Management.Compute.Models.DeploymentChangeConfigurationParameters;
        $p2[2].Value.Configuration = $deployment.Configuration;
        $p2[2].Value.ExtensionConfiguration = New-Object -TypeName Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration;
        $p2[2].Value.ExtensionConfiguration.AllRoles.Add('test');
        $d2 = ($p2 | select -ExpandProperty Value);
        $st = Invoke-AzureComputeMethod -MethodName DeploymentChangeConfigurationBySlot -ArgumentList $d2;

        # Invoke Hosted Service Delete
        $st = Invoke-AzureComputeMethod -MethodName 'HostedServiceDeleteAll' -ArgumentList $svcName;
        Assert-AreEqual $st.StatusCode 'OK';
        Assert-NotNull $st.RequestId;
    }
    finally
    {
        # Cleanup
        Cleanup-CloudService $svcName;
    }
}

# Run Service Extension Set Cmdlet Tests
function Run-ServiceExtensionSetCmdletTests
{
    # Setup
    $location = Get-DefaultLocation;
    $imgName = Get-DefaultImage $location;

    $storageName = 'pstest' + (getAssetName);
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;

    # Associate the new storage account with the current subscription
    Set-CurrentStorageAccountName $storageName;

    $svcName = 'pstest' + (Get-CloudServiceName);
    $userName = "pstestuser";
    $password = $PLACEHOLDER;
    $sPassword = ConvertTo-SecureString $password -AsPlainText -Force;
    $credential = New-Object System.Management.Automation.PSCredential ($userName, $sPassword);

    # Test
    New-AzureService -ServiceName $svcName -Location $location;

    try
    {
        # New-AzureDeployment (in Azure.psd1)
        $testMode = Get-ComputeTestMode;
        if ($testMode.ToLower() -ne 'playback')
        {
            $cspkg = '.\Resources\ServiceManagement\Files\OneWebOneWorker.cspkg';
        }
        else
        {
            $cspkg = "https://${storageName}.blob.azure.windows.net/blob/OneWebOneWorker.cspkg";
        }
        $cscfg = "$TestOutputRoot\Resources\ServiceManagement\Files\OneWebOneWorker.cscfg";

        # Staging 1st
        $st = New-AzureDeployment -ServiceName $svcName -Package $cspkg -Configuration $cscfg -Label $svcName -Slot Staging;
        $st = Set-AzureServiceRemoteDesktopExtension -ServiceName $svcName -Slot Staging -Credential $credential;
        $ex = Get-AzureServiceExtension -ServiceName $svcName -Slot Staging;
        $st = Move-AzureDeployment -ServiceName $svcName;
        $ex = Get-AzureServiceExtension -ServiceName $svcName -Slot Production;

        # Staging 2nd
        $st = New-AzureDeployment -ServiceName $svcName -Package $cspkg -Configuration $cscfg -Label $svcName -Slot Staging;
        $st = Set-AzureServiceRemoteDesktopExtension -ServiceName $svcName -Slot Staging -Credential $credential;
        $ex = Get-AzureServiceExtension -ServiceName $svcName -Slot Staging;
        $st = Move-AzureDeployment -ServiceName $svcName;
        $ex = Get-AzureServiceExtension -ServiceName $svcName -Slot Production;

        # Set Extensions
        $st = Set-AzureServiceRemoteDesktopExtension -ServiceName $svcName -Slot Production -Credential $credential;
        $st = Set-AzureServiceRemoteDesktopExtension -ServiceName $svcName -Slot Staging -Credential $credential;
    }
    finally
    {
        # Cleanup
        Cleanup-CloudService $svcName;
    }
}

# Run Service Deployment Extension Cmdlet Tests
function Run-ServiceDeploymentExtensionCmdletTests
{
    # Setup
    $location = Get-DefaultLocation;
    $imgName = Get-DefaultImage $location;

    $storageName = 'pstest' + (getAssetName);
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;

    # Associate the new storage account with the current subscription
    Set-CurrentStorageAccountName $storageName;

    $svcName = 'pstest' + (Get-CloudServiceName);
    $userName = "pstestuser";
    $password = $PLACEHOLDER;
    $sPassword = ConvertTo-SecureString $password -AsPlainText -Force;
    $credential = New-Object System.Management.Automation.PSCredential ($userName, $sPassword);

    # Test
    New-AzureService -ServiceName $svcName -Location $location;

    try
    {
        # New-AzureDeployment (in Azure.psd1)
        $testMode = Get-ComputeTestMode;
        if ($testMode.ToLower() -ne 'playback')
        {
            $cspkg = "$TestOutputRoot\Resources\ServiceManagement\Files\LongRoleName.Cloud.cspkg";
        }
        else
        {
            $cspkg = "https://${storageName}.blob.azure.windows.net/blob/LongRoleName.Cloud.cspkg";
        }
        $cscfg = "$TestOutputRoot\Resources\ServiceManagement\Files\LongRoleName.Cloud.cscfg";

        $webRoleNameWithSpaces = "WebRole1 With Spaces In Name";
        $workerRoleLongName = "Microsoft.Contoso.Department.ProjectCodeName.Worker";
        $rdpCfg1 = New-AzureServiceRemoteDesktopExtensionConfig -Credential $credential -Role $webRoleNameWithSpaces
        $rdpCfg2 = New-AzureServiceRemoteDesktopExtensionConfig -Credential $credential -Role $workerRoleLongName;
        $adCfg1 = New-AzureServiceADDomainExtensionConfig -Role $webRoleNameWithSpaces -WorkgroupName 'test1';
        $adCfg2 = New-AzureServiceADDomainExtensionConfig -Role $workerRoleLongName -WorkgroupName 'test2';

        $st = New-AzureDeployment -ServiceName $svcName -Package $cspkg -Configuration $cscfg -Label $svcName -Slot Production -ExtensionConfiguration $rdpCfg1,$adCfg1;
        $exts = Get-AzureServiceExtension -ServiceName $svcName -Slot Production;
        Assert-True { $exts.Count -eq 2 };

        $st = New-AzureDeployment -ServiceName $svcName -Package $cspkg -Configuration $cscfg -Label $svcName -Slot Staging -ExtensionConfiguration $rdpCfg2,$adCfg2;
        $exts = Get-AzureServiceExtension -ServiceName $svcName -Slot Staging;
        Assert-True { $exts.Count -eq 2 };

        $st = Set-AzureDeployment -Config -ServiceName $svcName -Configuration $cscfg -Slot Production -ExtensionConfiguration $rdpCfg2;
        $exts = Get-AzureServiceExtension -ServiceName $svcName -Slot Production;
        Assert-True { $exts.Count -eq 1 };

        $st = Set-AzureDeployment -Config -ServiceName $svcName -Configuration $cscfg -Slot Staging -ExtensionConfiguration $rdpCfg1,$adCfg1;
        $exts = Get-AzureServiceExtension -ServiceName $svcName -Slot Staging;
        Assert-True { $exts.Count -eq 2 };
    }
    finally
    {
        # Cleanup
        Cleanup-CloudService $svcName;
    }
}

# Run Data Collection Cmdlet Tests
function Run-EnableAndDisableDataCollectionTests
{
    $st = Enable-AzureDataCollection;

    $locations = Get-AzureLocation;
    foreach ($loc in $locations)
    {
        $svcName = getAssetName;
        $st = New-AzureService -ServiceName $svcName -Location $loc.Name;

        # Cleanup
        Cleanup-CloudService $svcName
    }

    $st = Disable-AzureDataCollection;
}

<#
.SYNOPSIS
Tests Move-AzureService
#>
function Test-MigrateAzureDeployment
{
    # Setup
    $location = Get-DefaultLocation;
    $imgName = Get-DefaultImage $location;

    $storageName = getAssetName;
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;
    Set-CurrentStorageAccountName $storageName;

    $vmName = "vm1";
    $svcName = Get-CloudServiceName;

    # Test
    New-AzureService -ServiceName $svcName -Location $location;
    New-AzureQuickVM -Windows -ImageName $imgName -Name $vmName -ServiceName $svcName -AdminUsername "pstestuser" -Password $PLACEHOLDER;
    Get-AzureVM -ServiceName $svcName -Name $vmName;

    Move-AzureService -Prepare -ServiceName $svcName -DeploymentName $svcName -CreateNewVirtualNetwork;
    $vm = Get-AzureVM -ServiceName $svcName -Name $vmName;
    Assert-AreEqual "Prepared" $vm.VM.MigrationState;

    try
    {
        Move-AzureService -Commit -ServiceName $svcName -DeploymentName $svcName -ErrorAction Stop;
    }
    catch
    {}
    $vm = Get-AzureVM -ServiceName $svcName -Name $vmName;
    Assert-AreEqual "CommitFailed" $vm.VM.MigrationState;

    # Cleanup failed because the service is being migrated.
    #Cleanup-CloudService $svcName
}

<#
.SYNOPSIS
Tests Move-AzureService with Abort
#>
function Test-MigrationAbortAzureDeployment
{
    # Setup
    $location = Get-DefaultLocation;
    $imgName = Get-DefaultImage $location;

    $storageName = getAssetName;
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;
    Set-CurrentStorageAccountName $storageName;

    $vmName = "vm1";
    $svcName = Get-CloudServiceName;

    # Test
    New-AzureService -ServiceName $svcName -Location $location;
    New-AzureQuickVM -Windows -ImageName $imgName -Name $vmName -ServiceName $svcName -AdminUsername "pstestuser" -Password $PLACEHOLDER -WaitForBoot;
    Get-AzureVM -ServiceName $svcName -Name $vmName;

    $result = Move-AzureService -Validate -ServiceName $svcName -DeploymentName $svcName -CreateNewVirtualNetwork;
    Assert-True {$result.Result.Contains("Validation Passed.")}
    $vm = Get-AzureVM -ServiceName $svcName -Name $vmName;

    Move-AzureService -Prepare -ServiceName $svcName -DeploymentName $svcName -CreateNewVirtualNetwork;
    $vm = Get-AzureVM -ServiceName $svcName -Name $vmName;
    Assert-AreEqual "Prepared" $vm.VM.MigrationState;

    Move-AzureService -Abort -ServiceName $svcName -DeploymentName $svcName;
    $vm = Get-AzureVM -ServiceName $svcName -Name $vmName;
    Assert-Null $vm.VM.MigrationState;

    # Cleanup
    Cleanup-CloudService $svcName;
}

<#
.SYNOPSIS
Tests Move-AzureService with Abort
#>
function Test-MigrationValidateAzureDeployment
{
    # Setup
    $location = Get-DefaultLocation;
    $imgName = Get-DefaultImage $location;

    $storageName = getAssetName;
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;
    Set-CurrentStorageAccountName $storageName;

    $vmName = "vm1";
    $svcName = Get-CloudServiceName;

    # Test
    New-AzureService -ServiceName $svcName -Location $location;
    New-AzureQuickVM -Windows -ImageName $imgName -Name $vmName -ServiceName $svcName -AdminUsername "pstestuser" -Password $PLACEHOLDER;
    Get-AzureVM -ServiceName $svcName -Name $vmName;

    $result = Move-AzureService -Validate -ServiceName $svcName -DeploymentName $svcName -CreateNewVirtualNetwork;
    Assert-True {$result.Result.Contains("Validation Failed.")}
    Assert-AreNotEqual 0 $result.ValidationMessages.Count;
}

<#
.SYNOPSIS
Tests Move-AzureVirtualNetwork with Prepare and Commit
#>
function Test-MigrateAzureVNet
{
    # Setup
    $TestOutputRoot = [System.AppDomain]::CurrentDomain.BaseDirectory;
    $location = Get-DefaultLocation
    $affName = "WestUsAffinityGroup";
    $vnetConfigPath = "$TestOutputRoot\Resources\ServiceManagement\Files\vnetconfig.netcfg";
    $vnetName = "NewVNet1";

    # Test

    Set-AzureVNetConfig -ConfigurationPath $vnetConfigPath;

    Get-AzureVNetSite;

    Move-AzureVirtualNetwork -Prepare -VirtualNetworkName $vnetName;

    Get-AzureVNetSite;

    Move-AzureVirtualNetwork -Commit -VirtualNetworkName $vnetName;

    Get-AzureVNetSite;

    # Cleanup
    Remove-AzureVNetConfig
}

<#
.SYNOPSIS
Tests Move-AzureVirtualNetwork with Prepare and Abort
#>
function Test-MigrationAbortAzureVNet
{
    # Setup
    $TestOutputRoot = [System.AppDomain]::CurrentDomain.BaseDirectory;
    $location = Get-DefaultLocation
    $affName = "WestUsAffinityGroup";
    $vnetConfigPath = "$TestOutputRoot\Resources\ServiceManagement\Files\vnetconfig.netcfg";
    $vnetName = "NewVNet1";

    # Test

    Set-AzureVNetConfig -ConfigurationPath $vnetConfigPath;
    Get-AzureVNetSite;

    $result = Move-AzureVirtualNetwork -Validate -VirtualNetworkName $vnetName;
    Assert-True {$result.Result.Contains("Validation Passed.")}
    Get-AzureVNetSite;

    Move-AzureVirtualNetwork -Prepare -VirtualNetworkName $vnetName;
    Get-AzureVNetSite;

    Move-AzureVirtualNetwork -Abort -VirtualNetworkName $vnetName;
    Get-AzureVNetSite;

    # Cleanup
    Remove-AzureVNetConfig
}

<#
.SYNOPSIS
Tests Move-AzureStorageAccount with Prepare and Commit
#>
function Test-MigrateAzureStorageAccount
{
    # Setup
    $location = "Central US";
    $storageName = getAssetName;
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;
    Get-AzureStorageAccount -StorageAccountName $storageName;

    # Test
    Move-AzureStorageAccount -Prepare -StorageAccountName $storageName;
    Get-AzureStorageAccount -StorageAccountName $storageName;

    Move-AzureStorageAccount -Commit -StorageAccountName $storageName;
    Assert-ThrowsContains { Get-AzureStorageAccount -StorageAccountName $storageName; } "ResourceNotFound";
}

<#
.SYNOPSIS
Tests Move-AzureStorageAccount with Prepare and Abort
#>
function Test-MigrationAbortAzureStorageAccount
{
    # Setup
    $location = "Central US";
    $storageName = getAssetName;
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;
    Get-AzureStorageAccount -StorageAccountName $storageName;

    # Test
    $result = Move-AzureStorageAccount -Validate -StorageAccountName $storageName;
    Assert-True {$result.Result.Contains("Validation Passed.")}
    Get-AzureStorageAccount -StorageAccountName $storageName;

    Move-AzureStorageAccount -Prepare -StorageAccountName $storageName;
    $result = Get-AzureStorageAccount -StorageAccountName $storageName;
    Assert-AreEqual "Prepared" $result.MigrationState;
    $resultOut = $result | Out-String;

    Move-AzureStorageAccount -Abort -StorageAccountName $storageName;
    $result = Get-AzureStorageAccount -StorageAccountName $storageName;
    Assert-Null $result.MigrationState;
    $resultOut = $result | Out-String;

    # Cleanup
    Remove-AzureStorageAccount -StorageAccountName $storageName;
}

<#
.SYNOPSIS
Tests Move-AzureNetworkSecurityGroup
#>
function Test-MigrationNetworkSecurityGroup
{
    # Setup
    $securityGroupName = getAssetName
    $location = Get-DefaultLocation
    New-AzureNetworkSecurityGroup -Name $securityGroupName -location $location

    # Validate move
    $status = Move-AzureNetworkSecurityGroup -NetworkSecurityGroupName $securityGroupName -Validate
    Assert-NotNull $status
    Assert-Null $status.ValidationMessages

    # Prepare move
    Move-AzureNetworkSecurityGroup -NetworkSecurityGroupName $securityGroupName -Prepare

    # Abort Move
    Move-AzureNetworkSecurityGroup -NetworkSecurityGroupName $securityGroupName -Abort

    # Remove
    $isDeleted = Remove-AzureNetworkSecurityGroup -Name $securityGroupName -Force -PassThru
}

<#
.SYNOPSIS
Tests Move-AzureRouteTable
#>
function Test-MigrationRouteTable
{
    # Setup
    $routeTableName = getAssetName
    $location = Get-DefaultLocation
    New-AzureRouteTable -Name $routeTableName -location $location

    # Validate move
    $status = Move-AzureRouteTable -RouteTableName $routeTableName -Validate
    Assert-NotNull $status
    Assert-Null $status.ValidationMessages

    # Prepare move
    Move-AzureRouteTable -RouteTableName $routeTableName -Prepare

    # Abort Move
    Move-AzureRouteTable -RouteTableName $routeTableName -Abort

    # Remove
    $isDeleted = Remove-AzureRouteTable -Name $routeTableName -Force -PassThru
}

<#
.SYNOPSIS
Tests Move-AzureReservedIP
#>
function Test-MigrationAzureReservedIP
{
    # Setup
    $name = getAssetName
    $location = Get-DefaultLocation

    # Test Create Reserved IP
    New-AzureReservedIP -ReservedIPName $name -Location $location
    $reservedIP = Get-AzureReservedIP -ReservedIPName $name

    # Assert
    Assert-NotNull($reservedIP)
    Assert-AreEqual $reservedIP.Location $location

    # Validate move
    $status = Move-AzureReservedIP -ReservedIPName $name -Validate
    Assert-NotNull $status
    Assert-Null $status.ValidationMessages

    # Prepare move
    Move-AzureReservedIP -ReservedIPName $name -Prepare

    # Abort Move
    Move-AzureReservedIP -ReservedIPName $name -Abort

    #Test Remove reserved IP
    $removeReservedIP = Remove-AzureReservedIP -ReservedIPName $name -Force
    Assert-AreEqual $removeReservedIP.OperationStatus "Succeeded"
}

<#
.SYNOPSIS
Tests New-AzureReservedIPWithTags
#>
function Test-AzureReservedIPWithIPTags
{
    # Setu
    $name = getAssetName
    $location = "West Central US"
    $iptag  = New-AzureIPTag -IPTagType "FirstPartyUsage" -Value "/tagTypes/SystemService/operators/Microsoft/platforms/Azure/services/Microsoft.AzureAD"
    # Test Create Reserved IP
    New-AzureReservedIP -ReservedIPName $name -Location $location -IPTagList $iptag
    $reservedIP = Get-AzureReservedIP -ReservedIPName $name
    #-IPTags $iptag
    # Assert
    Assert-NotNull($reservedIP)
    Assert-AreEqual $reservedIP.Location $location
    Assert-NotNull($reservedIP.IPTags)

    #Test Remove reserved IP
    $removeReservedIP = Remove-AzureReservedIP -ReservedIPName $name -Force
    Assert-AreEqual $removeReservedIP.OperationStatus "Succeeded"
}

function Test-NewAzureVMWithBYOL
{
    # Setup
    $location = "Central US";
    $storageName = "mybyolosimagerdfe";

    $vm1Name = "vm1";
    $vm2Name = "vm2";
    $svcName = Get-CloudServiceName;

    $vmSize = "Small";
    $licenseType = "Windows_Server";
    $imgName = getAssetName;
    $userName = "User" + $svcName;
    $pass = $PLACEHOLDER;

    $media1 = "http://mybyolosimagerdfe.blob.core.windows.net/myvhd/" + $svcName + "0.vhd";
    $media2 = "http://mybyolosimagerdfe.blob.core.windows.net/myvhd/" + $svcName + "1.vhd";

    Set-CurrentStorageAccountName $storageName;

    Add-AzureVMImage -ImageName $imgName `
        -MediaLocation "https://mybyolosimagerdfe.blob.core.windows.net/vhdsrc/win2012-tag0.vhd" `
        -OS "Windows" `
        -Label "BYOL Image" `
        -RecommendedVMSize $vmSize `
        -IconUri "http://www.bing.com" `
        -SmallIconUri "http://www.bing.com" `
        -ShowInGui;

    # Test
    New-AzureService -ServiceName $svcName -Location $location;

    $vm1 = New-AzureVMConfig -Name $vm1Name -ImageName $imgName -InstanceSize $vmSize `
         -LicenseType $licenseType -HostCaching ReadWrite -MediaLocation $media1;

    $vm1 = Add-AzureProvisioningConfig -VM $vm1 -Windows -Password $pass -AdminUsername $userName;

    $vm2 = New-AzureVMConfig -Name $vm2Name -ImageName $imgName -InstanceSize $vmSize `
         -LicenseType $licenseType -HostCaching ReadWrite -MediaLocation $media2;

    $vm2 = Add-AzureProvisioningConfig -VM $vm2 -Windows -Password $pass -AdminUsername $userName;

    New-AzureVM -ServiceName $svcName -VMs $vm1,$vm2

    $vm1result = Get-AzureVM -ServiceName $svcName -Name $vm1Name;
    $vm2result = Get-AzureVM -ServiceName $svcName -Name $vm2Name;

    Update-AzureVM -ServiceName $svcName -Name $vm1Name -VM $vm1result.VM;

    $vm1result = Get-AzureVM -ServiceName $svcName -Name $vm1Name;
    $vm2result = Get-AzureVM -ServiceName $svcName -Name $vm2Name;

    # Cleanup
    Cleanup-CloudService $svcName
}

# Test Redeploy VM
function Run-RedeployVirtualMachineTest
{
    # Setup
    $location = Get-DefaultLocation;
    $imgName = Get-DefaultImage $location;

    $storageName = 'pstest' + (getAssetName);
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;

    # Associate the new storage account with the current subscription
    Set-CurrentStorageAccountName $storageName;

    $vmName = "vm01";
    $svcName = 'pstest' + (Get-CloudServiceName);
    $userName = "pstestuser";
    $password = $PLACEHOLDER;

    # Test
    New-AzureService -ServiceName $svcName -Location $location;

    try
    {
        New-AzureQuickVM -Windows -ImageName $imgName -Name $vmName -ServiceName $svcName -AdminUsername $userName -Password $password;
        # Get VM
        $vm = Get-AzureVM -ServiceName $svcName -Name $vmName;

        # Test Redeploy
        $vm | Restart-AzureVM -Redeploy;

        $vm = Get-AzureVM -ServiceName $svcName -Name $vmName;
    }
    finally
    {
        # Cleanup
        Cleanup-CloudService $svcName;
    }
}

# Test Initiate Maintenance VM
function Run-InitiateMaintenanceTest
{
    # Depending on the environment, the initiate maintenance operation may return 200
    # or 400 with error message like "User initiated maintenance on the virtual machine was
    # successfully completed". Both are expected reponses.
    # To continue script, $ErrorActionPreference should be set to 'SilentlyContinue'.
    $tempErrorActionPreference = $ErrorActionPreference;
    $ErrorActionPreference = 'SilentlyContinue';

    # Setup
    $location = "Central US EUAP";
    $imgName = Get-DefaultImage $location;

    $storageName = 'pstest' + (getAssetName);
    New-AzureStorageAccount -StorageAccountName $storageName -Location $location;

    # Associate the new storage account with the current subscription
    Set-CurrentStorageAccountName $storageName;

    $vmName = "psvm01";
    $svcName = 'pstest' + (Get-CloudServiceName);
    $userName = "pstestuser";
    $password = $PLACEHOLDER;

    # Test
    New-AzureService -ServiceName $svcName -Location $location;

    try
    {
        New-AzureQuickVM -Windows -ImageName $imgName -Name $vmName -ServiceName $svcName -AdminUsername $userName -Password $password;
        #Start-Sleep -s 300; #Uncomment this line for record mode testing.

        # Get VM
        $vm = Get-AzureVM -ServiceName $svcName -Name $vmName;
        Assert-NotNull $vm;
        Assert-NotNull $vm.MaintenanceStatus;

        # Test Initiate Maintenance
        $result = Restart-AzureVM -InitiateMaintenance -ServiceName $svcName -Name $vmName;

        $vm = Get-AzureVM -ServiceName $svcName -Name $vmName
        Assert-NotNull $vm.MaintenanceStatus;
    }
    catch
    {
        Assert-True {$result.Result.Contains("User initiated maintenance on the Virtual Machine was successfully completed.")};
        $vm = Get-AzureVM -ServiceName $svcName -Name $vmName
        Assert-NotNull $vm.MaintenanceStatus;
    }
    finally
    {
        # Cleanup
        Cleanup-CloudService $srcName;
        $ErrorActionPreference = $tempErrorActionPreference;
    }
}


text:
import Offcanvas from '../../src/offcanvas'
import EventHandler from '../../src/dom/event-handler'
import { clearBodyAndDocument, clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture'
import { isVisible } from '../../src/util/index'
import ScrollBarHelper from '../../src/util/scrollbar'

describe('Offcanvas', () => {
  let fixtureEl

  beforeAll(() => {
    fixtureEl = getFixture()
  })

  afterEach(() => {
    clearFixture()
    document.body.classList.remove('offcanvas-open')
    clearBodyAndDocument()
  })

  beforeEach(() => {
    clearBodyAndDocument()
  })

  describe('VERSION', () => {
    it('should return plugin version', () => {
      expect(Offcanvas.VERSION).toEqual(jasmine.any(String))
    })
  })

  describe('Default', () => {
    it('should return plugin default config', () => {
      expect(Offcanvas.Default).toEqual(jasmine.any(Object))
    })
  })

  describe('DATA_KEY', () => {
    it('should return plugin data key', () => {
      expect(Offcanvas.DATA_KEY).toEqual('bs.offcanvas')
    })
  })

  describe('constructor', () => {
    it('should call hide when a element with data-bs-dismiss="offcanvas" is clicked', () => {
      fixtureEl.innerHTML = [
        '
',
        '  Close',
        '
'
      ].join('')

      const offCanvasEl = fixtureEl.querySelector('.offcanvas')
      const closeEl = fixtureEl.querySelector('a')
      const offCanvas = new Offcanvas(offCanvasEl)

      const spy = spyOn(offCanvas, 'hide')

      closeEl.click()

      expect(offCanvas._config.keyboard).toBeTrue()
      expect(spy).toHaveBeenCalled()
    })

    it('should hide if esc is pressed', () => {
      fixtureEl.innerHTML = '

'

      const offCanvasEl = fixtureEl.querySelector('.offcanvas')
      const offCanvas = new Offcanvas(offCanvasEl)
      const keyDownEsc = createEvent('keydown')
      keyDownEsc.key = 'Escape'

      const spy = spyOn(offCanvas, 'hide')

      offCanvasEl.dispatchEvent(keyDownEsc)

      expect(spy).toHaveBeenCalled()
    })

    it('should hide if esc is pressed and backdrop is static', () => {
      fixtureEl.innerHTML = '

'

      const offCanvasEl = fixtureEl.querySelector('.offcanvas')
      const offCanvas = new Offcanvas(offCanvasEl, { backdrop: 'static' })
      const keyDownEsc = createEvent('keydown')
      keyDownEsc.key = 'Escape'

      const spy = spyOn(offCanvas, 'hide')

      offCanvasEl.dispatchEvent(keyDownEsc)

      expect(spy).toHaveBeenCalled()
    })

    it('should not hide if esc is not pressed', () => {
      fixtureEl.innerHTML = '

'

      const offCanvasEl = fixtureEl.querySelector('.offcanvas')
      const offCanvas = new Offcanvas(offCanvasEl)
      const keydownTab = createEvent('keydown')
      keydownTab.key = 'Tab'

      const spy = spyOn(offCanvas, 'hide')

      offCanvasEl.dispatchEvent(keydownTab)

      expect(spy).not.toHaveBeenCalled()
    })

    it('should not hide if esc is pressed but with keyboard = false', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('.offcanvas')
        const offCanvas = new Offcanvas(offCanvasEl, { keyboard: false })
        const keyDownEsc = createEvent('keydown')
        keyDownEsc.key = 'Escape'

        const spy = spyOn(offCanvas, 'hide')
        const hidePreventedSpy = jasmine.createSpy('hidePrevented')
        offCanvasEl.addEventListener('hidePrevented.bs.offcanvas', hidePreventedSpy)

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(offCanvas._config.keyboard).toBeFalse()
          offCanvasEl.dispatchEvent(keyDownEsc)

          expect(hidePreventedSpy).toHaveBeenCalled()
          expect(spy).not.toHaveBeenCalled()
          resolve()
        })

        offCanvas.show()
      })
    })

    it('should not hide if user clicks on static backdrop', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('div')
        const offCanvas = new Offcanvas(offCanvasEl, { backdrop: 'static' })

        const clickEvent = new Event('mousedown', { bubbles: true, cancelable: true })
        const spyClick = spyOn(offCanvas._backdrop._config, 'clickCallback').and.callThrough()
        const spyHide = spyOn(offCanvas._backdrop, 'hide').and.callThrough()
        const hidePreventedSpy = jasmine.createSpy('hidePrevented')
        offCanvasEl.addEventListener('hidePrevented.bs.offcanvas', hidePreventedSpy)

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(spyClick).toEqual(jasmine.any(Function))

          offCanvas._backdrop._getElement().dispatchEvent(clickEvent)
          expect(hidePreventedSpy).toHaveBeenCalled()
          expect(spyHide).not.toHaveBeenCalled()
          resolve()
        })

        offCanvas.show()
      })
    })

    it('should call `hide` on resize, if element\'s position is not fixed any more', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('div')
        const offCanvas = new Offcanvas(offCanvasEl)

        const spy = spyOn(offCanvas, 'hide').and.callThrough()

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          const resizeEvent = createEvent('resize')
          offCanvasEl.style.removeProperty('position')

          window.dispatchEvent(resizeEvent)
          expect(spy).toHaveBeenCalled()
          resolve()
        })

        offCanvas.show()
      })
    })
  })

  describe('config', () => {
    it('should have default values', () => {
      fixtureEl.innerHTML = '

'

      const offCanvasEl = fixtureEl.querySelector('.offcanvas')
      const offCanvas = new Offcanvas(offCanvasEl)

      expect(offCanvas._config.backdrop).toBeTrue()
      expect(offCanvas._backdrop._config.isVisible).toBeTrue()
      expect(offCanvas._config.keyboard).toBeTrue()
      expect(offCanvas._config.scroll).toBeFalse()
    })

    it('should read data attributes and override default config', () => {
      fixtureEl.innerHTML = '

'

      const offCanvasEl = fixtureEl.querySelector('.offcanvas')
      const offCanvas = new Offcanvas(offCanvasEl)

      expect(offCanvas._config.backdrop).toBeFalse()
      expect(offCanvas._backdrop._config.isVisible).toBeFalse()
      expect(offCanvas._config.keyboard).toBeFalse()
      expect(offCanvas._config.scroll).toBeTrue()
    })

    it('given a config object must override data attributes', () => {
      fixtureEl.innerHTML = '

'

      const offCanvasEl = fixtureEl.querySelector('.offcanvas')
      const offCanvas = new Offcanvas(offCanvasEl, {
        backdrop: true,
        keyboard: true,
        scroll: false
      })
      expect(offCanvas._config.backdrop).toBeTrue()
      expect(offCanvas._config.keyboard).toBeTrue()
      expect(offCanvas._config.scroll).toBeFalse()
    })
  })

  describe('options', () => {
    it('if scroll is enabled, should allow body to scroll while offcanvas is open', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const spyHide = spyOn(ScrollBarHelper.prototype, 'hide').and.callThrough()
        const spyReset = spyOn(ScrollBarHelper.prototype, 'reset').and.callThrough()
        const offCanvasEl = fixtureEl.querySelector('.offcanvas')
        const offCanvas = new Offcanvas(offCanvasEl, { scroll: true })

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(spyHide).not.toHaveBeenCalled()
          offCanvas.hide()
        })
        offCanvasEl.addEventListener('hidden.bs.offcanvas', () => {
          expect(spyReset).not.toHaveBeenCalled()
          resolve()
        })
        offCanvas.show()
      })
    })

    it('if scroll is disabled, should call ScrollBarHelper to handle scrollBar on body', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const spyHide = spyOn(ScrollBarHelper.prototype, 'hide').and.callThrough()
        const spyReset = spyOn(ScrollBarHelper.prototype, 'reset').and.callThrough()
        const offCanvasEl = fixtureEl.querySelector('.offcanvas')
        const offCanvas = new Offcanvas(offCanvasEl, { scroll: false })

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(spyHide).toHaveBeenCalled()
          offCanvas.hide()
        })
        offCanvasEl.addEventListener('hidden.bs.offcanvas', () => {
          expect(spyReset).toHaveBeenCalled()
          resolve()
        })
        offCanvas.show()
      })
    })

    it('should hide a shown element if user click on backdrop', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('div')
        const offCanvas = new Offcanvas(offCanvasEl, { backdrop: true })

        const clickEvent = new Event('mousedown', { bubbles: true, cancelable: true })
        const spy = spyOn(offCanvas._backdrop._config, 'clickCallback').and.callThrough()

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(offCanvas._backdrop._config.clickCallback).toEqual(jasmine.any(Function))

          offCanvas._backdrop._getElement().dispatchEvent(clickEvent)
        })

        offCanvasEl.addEventListener('hidden.bs.offcanvas', () => {
          expect(spy).toHaveBeenCalled()
          resolve()
        })

        offCanvas.show()
      })
    })

    it('should not trap focus if scroll is allowed', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('.offcanvas')
        const offCanvas = new Offcanvas(offCanvasEl, {
          scroll: true,
          backdrop: false
        })

        const spy = spyOn(offCanvas._focustrap, 'activate').and.callThrough()

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(spy).not.toHaveBeenCalled()
          resolve()
        })

        offCanvas.show()
      })
    })

    it('should trap focus if scroll is allowed OR backdrop is enabled', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('.offcanvas')
        const offCanvas = new Offcanvas(offCanvasEl, {
          scroll: true,
          backdrop: true
        })

        const spy = spyOn(offCanvas._focustrap, 'activate').and.callThrough()

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(spy).toHaveBeenCalled()
          resolve()
        })

        offCanvas.show()
      })
    })
  })

  describe('toggle', () => {
    it('should call show method if show class is not present', () => {
      fixtureEl.innerHTML = '

'

      const offCanvasEl = fixtureEl.querySelector('.offcanvas')
      const offCanvas = new Offcanvas(offCanvasEl)

      const spy = spyOn(offCanvas, 'show')

      offCanvas.toggle()

      expect(spy).toHaveBeenCalled()
    })

    it('should call hide method if show class is present', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('.offcanvas')
        const offCanvas = new Offcanvas(offCanvasEl)

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(offCanvasEl).toHaveClass('show')
          const spy = spyOn(offCanvas, 'hide')

          offCanvas.toggle()

          expect(spy).toHaveBeenCalled()
          resolve()
        })

        offCanvas.show()
      })
    })
  })

  describe('show', () => {
    it('should add `showing` class during opening and `show` class on end', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'
        const offCanvasEl = fixtureEl.querySelector('.offcanvas')
        const offCanvas = new Offcanvas(offCanvasEl)

        offCanvasEl.addEventListener('show.bs.offcanvas', () => {
          expect(offCanvasEl).not.toHaveClass('show')
        })

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(offCanvasEl).not.toHaveClass('showing')
          expect(offCanvasEl).toHaveClass('show')
          resolve()
        })

        offCanvas.show()
        expect(offCanvasEl).toHaveClass('showing')
      })
    })

    it('should do nothing if already shown', () => {
      fixtureEl.innerHTML = '

'

      const offCanvasEl = fixtureEl.querySelector('div')
      const offCanvas = new Offcanvas(offCanvasEl)
      offCanvas.show()

      expect(offCanvasEl).toHaveClass('show')

      const spyShow = spyOn(offCanvas._backdrop, 'show').and.callThrough()
      const spyTrigger = spyOn(EventHandler, 'trigger').and.callThrough()
      offCanvas.show()

      expect(spyTrigger).not.toHaveBeenCalled()
      expect(spyShow).not.toHaveBeenCalled()
    })

    it('should show a hidden element', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('div')
        const offCanvas = new Offcanvas(offCanvasEl)
        const spy = spyOn(offCanvas._backdrop, 'show').and.callThrough()

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(offCanvasEl).toHaveClass('show')
          expect(spy).toHaveBeenCalled()
          resolve()
        })

        offCanvas.show()
      })
    })

    it('should not fire shown when show is prevented', () => {
      return new Promise((resolve, reject) => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('div')
        const offCanvas = new Offcanvas(offCanvasEl)
        const spy = spyOn(offCanvas._backdrop, 'show').and.callThrough()

        const expectEnd = () => {
          setTimeout(() => {
            expect(spy).not.toHaveBeenCalled()
            resolve()
          }, 10)
        }

        offCanvasEl.addEventListener('show.bs.offcanvas', event => {
          event.preventDefault()
          expectEnd()
        })

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          reject(new Error('should not fire shown event'))
        })

        offCanvas.show()
      })
    })

    it('on window load, should make visible an offcanvas element, if its markup contains class "show"', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('div')
        const spy = spyOn(Offcanvas.prototype, 'show').and.callThrough()

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          resolve()
        })

        window.dispatchEvent(createEvent('load'))

        const instance = Offcanvas.getInstance(offCanvasEl)
        expect(instance).not.toBeNull()
        expect(spy).toHaveBeenCalled()
      })
    })

    it('should trap focus', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('.offcanvas')
        const offCanvas = new Offcanvas(offCanvasEl)

        const spy = spyOn(offCanvas._focustrap, 'activate').and.callThrough()

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(spy).toHaveBeenCalled()
          resolve()
        })

        offCanvas.show()
      })
    })
  })

  describe('hide', () => {
    it('should add `hiding` class during closing and remover `show` & `hiding` classes on end', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'
        const offCanvasEl = fixtureEl.querySelector('.offcanvas')
        const offCanvas = new Offcanvas(offCanvasEl)

        offCanvasEl.addEventListener('hide.bs.offcanvas', () => {
          expect(offCanvasEl).not.toHaveClass('showing')
          expect(offCanvasEl).toHaveClass('show')
        })

        offCanvasEl.addEventListener('hidden.bs.offcanvas', () => {
          expect(offCanvasEl).not.toHaveClass('hiding')
          expect(offCanvasEl).not.toHaveClass('show')
          resolve()
        })

        offCanvas.show()
        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          offCanvas.hide()
          expect(offCanvasEl).not.toHaveClass('showing')
          expect(offCanvasEl).toHaveClass('hiding')
        })
      })
    })

    it('should do nothing if already shown', () => {
      fixtureEl.innerHTML = '

'

      const spyTrigger = spyOn(EventHandler, 'trigger').and.callThrough()

      const offCanvasEl = fixtureEl.querySelector('div')
      const offCanvas = new Offcanvas(offCanvasEl)
      const spyHide = spyOn(offCanvas._backdrop, 'hide').and.callThrough()

      offCanvas.hide()
      expect(spyHide).not.toHaveBeenCalled()
      expect(spyTrigger).not.toHaveBeenCalled()
    })

    it('should hide a shown element', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('div')
        const offCanvas = new Offcanvas(offCanvasEl)
        const spy = spyOn(offCanvas._backdrop, 'hide').and.callThrough()
        offCanvas.show()

        offCanvasEl.addEventListener('hidden.bs.offcanvas', () => {
          expect(offCanvasEl).not.toHaveClass('show')
          expect(spy).toHaveBeenCalled()
          resolve()
        })

        offCanvas.hide()
      })
    })

    it('should not fire hidden when hide is prevented', () => {
      return new Promise((resolve, reject) => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('div')
        const offCanvas = new Offcanvas(offCanvasEl)
        const spy = spyOn(offCanvas._backdrop, 'hide').and.callThrough()

        offCanvas.show()

        const expectEnd = () => {
          setTimeout(() => {
            expect(spy).not.toHaveBeenCalled()
            resolve()
          }, 10)
        }

        offCanvasEl.addEventListener('hide.bs.offcanvas', event => {
          event.preventDefault()
          expectEnd()
        })

        offCanvasEl.addEventListener('hidden.bs.offcanvas', () => {
          reject(new Error('should not fire hidden event'))
        })

        offCanvas.hide()
      })
    })

    it('should release focus trap', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = '

'

        const offCanvasEl = fixtureEl.querySelector('div')
        const offCanvas = new Offcanvas(offCanvasEl)
        const spy = spyOn(offCanvas._focustrap, 'deactivate').and.callThrough()
        offCanvas.show()

        offCanvasEl.addEventListener('hidden.bs.offcanvas', () => {
          expect(spy).toHaveBeenCalled()
          resolve()
        })

        offCanvas.hide()
      })
    })
  })

  describe('dispose', () => {
    it('should dispose an offcanvas', () => {
      fixtureEl.innerHTML = '

'

      const offCanvasEl = fixtureEl.querySelector('div')
      const offCanvas = new Offcanvas(offCanvasEl)
      const backdrop = offCanvas._backdrop
      const spyDispose = spyOn(backdrop, 'dispose').and.callThrough()
      const focustrap = offCanvas._focustrap
      const spyDeactivate = spyOn(focustrap, 'deactivate').and.callThrough()

      expect(Offcanvas.getInstance(offCanvasEl)).toEqual(offCanvas)

      offCanvas.dispose()

      expect(spyDispose).toHaveBeenCalled()
      expect(offCanvas._backdrop).toBeNull()
      expect(spyDeactivate).toHaveBeenCalled()
      expect(offCanvas._focustrap).toBeNull()
      expect(Offcanvas.getInstance(offCanvasEl)).toBeNull()
    })
  })

  describe('data-api', () => {
    it('should not prevent event for input', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = [
          '<input type="checkbox" data-bs-toggle="offcanvas" data-bs-target="#offcanvasdiv1">',
          '

'
        ].join('')

        const target = fixtureEl.querySelector('input')
        const offCanvasEl = fixtureEl.querySelector('#offcanvasdiv1')

        offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
          expect(offCanvasEl).toHaveClass('show')
          expect(target.checked).toBeTrue()
          resolve()
        })

        target.click()
      })
    })

    it('should not call toggle on disabled elements', () => {
      fixtureEl.innerHTML = [
        '',
        '

'
      ].join('')

      const target = fixtureEl.querySelector('a')

      const spy = spyOn(Offcanvas.prototype, 'toggle')

      target.click()

      expect(spy).not.toHaveBeenCalled()
    })

    it('should call hide first, if another offcanvas is open', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = [
          '<button id="btn2" data-bs-toggle="offcanvas" data-bs-target="#offcanvas2"></button>',
          '

',
          '

'
        ].join('')

        const trigger2 = fixtureEl.querySelector('#btn2')
        const offcanvasEl1 = document.querySelector('#offcanvas1')
        const offcanvasEl2 = document.querySelector('#offcanvas2')
        const offcanvas1 = new Offcanvas(offcanvasEl1)

        offcanvasEl1.addEventListener('shown.bs.offcanvas', () => {
          trigger2.click()
        })
        offcanvasEl1.addEventListener('hidden.bs.offcanvas', () => {
          expect(Offcanvas.getInstance(offcanvasEl2)).not.toBeNull()
          resolve()
        })
        offcanvas1.show()
      })
    })

    it('should focus on trigger element after closing offcanvas', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = [
          '<button id="btn" data-bs-toggle="offcanvas" data-bs-target="#offcanvas"></button>',
          '

'
        ].join('')

        const trigger = fixtureEl.querySelector('#btn')
        const offcanvasEl = fixtureEl.querySelector('#offcanvas')
        const offcanvas = new Offcanvas(offcanvasEl)
        const spy = spyOn(trigger, 'focus')

        offcanvasEl.addEventListener('shown.bs.offcanvas', () => {
          offcanvas.hide()
        })
        offcanvasEl.addEventListener('hidden.bs.offcanvas', () => {
          setTimeout(() => {
            expect(spy).toHaveBeenCalled()
            resolve()
          }, 5)
        })

        trigger.click()
      })
    })

    it('should not focus on trigger element after closing offcanvas, if it is not visible', () => {
      return new Promise(resolve => {
        fixtureEl.innerHTML = [
          '<button id="btn" data-bs-toggle="offcanvas" data-bs-target="#offcanvas"></button>',
          '

'
        ].join('')

        const trigger = fixtureEl.querySelector('#btn')
        const offcanvasEl = fixtureEl.querySelector('#offcanvas')
        const offcanvas = new Offcanvas(offcanvasEl)
        const spy = spyOn(trigger, 'focus')

        offcanvasEl.addEventListener('shown.bs.offcanvas', () => {
          trigger.style.display = 'none'
          offcanvas.hide()
        })
        offcanvasEl.addEventListener('hidden.bs.offcanvas', () => {
          setTimeout(() => {
            expect(isVisible(trigger)).toBeFalse()
            expect(spy).not.toHaveBeenCalled()
            resolve()
          }, 5)
        })

        trigger.click()
      })
    })
  })

  describe('jQueryInterface', () => {
    it('should create an offcanvas', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')

      jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface
      jQueryMock.elements = [div]

      jQueryMock.fn.offcanvas.call(jQueryMock)

      expect(Offcanvas.getInstance(div)).not.toBeNull()
    })

    it('should not re create an offcanvas', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')
      const offCanvas = new Offcanvas(div)

      jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface
      jQueryMock.elements = [div]

      jQueryMock.fn.offcanvas.call(jQueryMock)

      expect(Offcanvas.getInstance(div)).toEqual(offCanvas)
    })

    it('should throw error on undefined method', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')
      const action = 'undefinedMethod'

      jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface
      jQueryMock.elements = [div]

      expect(() => {
        jQueryMock.fn.offcanvas.call(jQueryMock, action)
      }).toThrowError(TypeError, `No method named "${action}"`)
    })

    it('should throw error on protected method', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')
      const action = '_getConfig'

      jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface
      jQueryMock.elements = [div]

      expect(() => {
        jQueryMock.fn.offcanvas.call(jQueryMock, action)
      }).toThrowError(TypeError, `No method named "${action}"`)
    })

    it('should throw error if method "constructor" is being called', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')
      const action = 'constructor'

      jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface
      jQueryMock.elements = [div]

      expect(() => {
        jQueryMock.fn.offcanvas.call(jQueryMock, action)
      }).toThrowError(TypeError, `No method named "${action}"`)
    })

    it('should call offcanvas method', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')

      const spy = spyOn(Offcanvas.prototype, 'show')

      jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface
      jQueryMock.elements = [div]

      jQueryMock.fn.offcanvas.call(jQueryMock, 'show')
      expect(spy).toHaveBeenCalled()
    })

    it('should create a offcanvas with given config', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')

      jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface
      jQueryMock.elements = [div]

      jQueryMock.fn.offcanvas.call(jQueryMock, { scroll: true })

      const offcanvas = Offcanvas.getInstance(div)
      expect(offcanvas).not.toBeNull()
      expect(offcanvas._config.scroll).toBeTrue()
    })
  })

  describe('getInstance', () => {
    it('should return offcanvas instance', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')
      const offCanvas = new Offcanvas(div)

      expect(Offcanvas.getInstance(div)).toEqual(offCanvas)
      expect(Offcanvas.getInstance(div)).toBeInstanceOf(Offcanvas)
    })

    it('should return null when there is no offcanvas instance', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')

      expect(Offcanvas.getInstance(div)).toBeNull()
    })
  })

  describe('getOrCreateInstance', () => {
    it('should return offcanvas instance', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')
      const offcanvas = new Offcanvas(div)

      expect(Offcanvas.getOrCreateInstance(div)).toEqual(offcanvas)
      expect(Offcanvas.getInstance(div)).toEqual(Offcanvas.getOrCreateInstance(div, {}))
      expect(Offcanvas.getOrCreateInstance(div)).toBeInstanceOf(Offcanvas)
    })

    it('should return new instance when there is no Offcanvas instance', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')

      expect(Offcanvas.getInstance(div)).toBeNull()
      expect(Offcanvas.getOrCreateInstance(div)).toBeInstanceOf(Offcanvas)
    })

    it('should return new instance when there is no offcanvas instance with given configuration', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')

      expect(Offcanvas.getInstance(div)).toBeNull()
      const offcanvas = Offcanvas.getOrCreateInstance(div, {
        scroll: true
      })
      expect(offcanvas).toBeInstanceOf(Offcanvas)

      expect(offcanvas._config.scroll).toBeTrue()
    })

    it('should return the instance when exists without given configuration', () => {
      fixtureEl.innerHTML = '

'

      const div = fixtureEl.querySelector('div')
      const offcanvas = new Offcanvas(div, {
        scroll: true
      })
      expect(Offcanvas.getInstance(div)).toEqual(offcanvas)

      const offcanvas2 = Offcanvas.getOrCreateInstance(div, {
        scroll: false
      })
      expect(offcanvas).toBeInstanceOf(Offcanvas)
      expect(offcanvas2).toEqual(offcanvas)

      expect(offcanvas2._config.scroll).toBeTrue()
    })
  })
})

redpajama_set_name: RedPajamaGithub


text:
package io.atomix.protocols.raft.storage.log.entry;

import io.atomix.primitive.operation.PrimitiveOperation;

/**
 * Represents a state machine query.
 * <p>
 * The {@code QueryEntry} is a special entry that is typically not ever written to the Raft log.
 * Query entries are simply used to represent the context within which a query is applied to the
 * state machine. Query entry {@link #sequenceNumber() sequence} numbers and indexes
 * are used to sequence queries as they're applied to the user state machine.
 */
public class QueryEntry extends OperationEntry {
  public QueryEntry(long term, long timestamp, long session, long sequence, PrimitiveOperation operation) {
    super(term, timestamp, session, sequence, operation);
  }
}


text:
//----------------------------------------------------------------
//
//  Copyright (c) Microsoft Corporation. All rights reserved.
//
//----------------------------------------------------------------

#import "MSBConstants.h"

@protocol MSBNotificationManagerProtocol <NSObject>

/**
 Sent a customized vibration to Band.
 @vibrationType     see MSBVibrationType
 */
- (void)vibrateWithType:(MSBVibrationType)vibrationType completionHandler:(void (^) (NSError *error))completionHandler;

/**
 Show a pop up Dialog Notification to Band. This dialog will disappear either timeout or user dismiss it.
 @tileID        identifier of the Tile which app has added.
 @title         title of the dialog. see MSBNotificationDialogTitleLengthMax
 @body          body of the dialog. see MSBNotificationDialogBodyLengthMax
 */
- (void)showDialogWithTileID:(NSUUID *)tileID title:(NSString *)title body:(NSString *)body completionHandler:(void (^)(NSError *error))completionHandler;

/**
 Send a Message Notification to a Tile on the Band, with the options to include Pop up Dialog.
 @tileID        identifier of the Tile which app has added.
 @title         title of the message. see MSBNotificationMessageTitleLengthMax
 @body          body of the message. see MSBNotificationMessageBodyLengthMax
 @timeStamp     optional timeStamp of the message. Default to [NSDate date]
 @flags         options of the message. see MSBNotificationMessageFlags
 */
- (void)sendMessageWithTileID:(NSUUID *)tileID title:(NSString *)title body:(NSString *)body timeStamp:(NSDate *)timeStamp flags:(MSBNotificationMessageFlags)flags completionHandler:(void (^)(NSError *error))completionHandler;

/**
 register Push Notifications of the current App to Band, Notifications will be sent to specified Tile
 @tileID        identifier of the Tile which app has added.
 */
- (void)registerNotificationWithTileID:(NSUUID *)tileID completionHandler:(void (^)(NSError *error))completionHandler NS_AVAILABLE_IOS(7_0);

/**
 register Push Notifications of the current App to Band, Notifications will be sent to the Tile created by the app.
 @discussion    use this method is the current App only has one Tile on Band. If the app has added more than one Tile, use -registerNotificationWithTileID:completionHandler:.
 */
- (void)registerNotificationWithCompletionHandler:(void (^)(NSError *error))completionHandler NS_AVAILABLE_IOS(7_0);

/**
 Unregister Push Notifications of the current App from the Band.
 */
- (void)unregisterNotificationWithCompletionHandler:(void (^)(NSError *error))completionHandler NS_AVAILABLE_IOS(7_0);

@end


text:
require 'net/http'

module Net # :nodoc:
  class HTTPS < Net::HTTP
    def initialize(address, port = 443)
      super(address, port)
      self.use_ssl = true
      @ssl_context = OpenSSL::SSL::SSLContext.new
      @ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
  end
end


text:
package com.yidejia.app.mall.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.util.Log;

public class Md5 {
	/**
     * MD5 ¼ÓÃÜ
     */
    public String getMD5Str(String str) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("MD5");

            messageDigest.reset();

            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            Log.e("MainPageAddress", "NoSuchAlgorithmException caught!");
            e.printStackTrace();
//            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.e("MainPageAddress", "UnsupportedEncodingException caught!");
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }

        return md5StrBuff.toString();
    }
}


text:
package logparser

import (
	"io/ioutil"
	"os"
	"runtime"
	"strings"
	"testing"

	"github.com/influxdata/telegraf/testutil"

	"github.com/influxdata/telegraf/plugins/inputs/logparser/grok"

	"github.com/stretchr/testify/assert"
)

func TestStartNoParsers(t *testing.T) {
	logparser := &LogParserPlugin{
		FromBeginning: true,
		Files:         []string{"grok/testdata/*.log"},
	}

	acc := testutil.Accumulator{}
	assert.Error(t, logparser.Start(&acc))
}

func TestGrokParseLogFilesNonExistPattern(t *testing.T) {
	thisdir := getCurrentDir()
	p := &grok.Parser{
		Patterns:           []string{"%{FOOBAR}"},
		CustomPatternFiles: []string{thisdir + "grok/testdata/test-patterns"},
	}

	logparser := &LogParserPlugin{
		FromBeginning: true,
		Files:         []string{thisdir + "grok/testdata/*.log"},
		GrokParser:    p,
	}

	acc := testutil.Accumulator{}
	assert.Error(t, logparser.Start(&acc))

	logparser.Stop()
}

func TestGrokParseLogFiles(t *testing.T) {
	thisdir := getCurrentDir()
	p := &grok.Parser{
		Patterns:           []string{"%{TEST_LOG_A}", "%{TEST_LOG_B}"},
		CustomPatternFiles: []string{thisdir + "grok/testdata/test-patterns"},
	}

	logparser := &LogParserPlugin{
		FromBeginning: true,
		Files:         []string{thisdir + "grok/testdata/*.log"},
		GrokParser:    p,
	}

	acc := testutil.Accumulator{}
	assert.NoError(t, logparser.Start(&acc))

	acc.Wait(2)

	logparser.Stop()

	acc.AssertContainsTaggedFields(t, "logparser_grok",
		map[string]interface{}{
			"clientip":      "192.168.1.1",
			"myfloat":       float64(1.25),
			"response_time": int64(5432),
			"myint":         int64(101),
		},
		map[string]string{"response_code": "200"})

	acc.AssertContainsTaggedFields(t, "logparser_grok",
		map[string]interface{}{
			"myfloat":    1.25,
			"mystring":   "mystring",
			"nomodifier": "nomodifier",
		},
		map[string]string{})
}

func TestGrokParseLogFilesAppearLater(t *testing.T) {
	emptydir, err := ioutil.TempDir("", "TestGrokParseLogFilesAppearLater")
	defer os.RemoveAll(emptydir)
	assert.NoError(t, err)

	thisdir := getCurrentDir()
	p := &grok.Parser{
		Patterns:           []string{"%{TEST_LOG_A}", "%{TEST_LOG_B}"},
		CustomPatternFiles: []string{thisdir + "grok/testdata/test-patterns"},
	}

	logparser := &LogParserPlugin{
		FromBeginning: true,
		Files:         []string{emptydir + "/*.log"},
		GrokParser:    p,
	}

	acc := testutil.Accumulator{}
	assert.NoError(t, logparser.Start(&acc))

	assert.Equal(t, acc.NFields(), 0)

	os.Symlink(
		thisdir+"grok/testdata/test_a.log",
		emptydir+"/test_a.log")
	assert.NoError(t, logparser.Gather(&acc))
	acc.Wait(1)

	logparser.Stop()

	acc.AssertContainsTaggedFields(t, "logparser_grok",
		map[string]interface{}{
			"clientip":      "192.168.1.1",
			"myfloat":       float64(1.25),
			"response_time": int64(5432),
			"myint":         int64(101),
		},
		map[string]string{"response_code": "200"})
}

// Test that test_a.log line gets parsed even though we don't have the correct
// pattern available for test_b.log
func TestGrokParseLogFilesOneBad(t *testing.T) {
	thisdir := getCurrentDir()
	p := &grok.Parser{
		Patterns:           []string{"%{TEST_LOG_A}", "%{TEST_LOG_BAD}"},
		CustomPatternFiles: []string{thisdir + "grok/testdata/test-patterns"},
	}
	assert.NoError(t, p.Compile())

	logparser := &LogParserPlugin{
		FromBeginning: true,
		Files:         []string{thisdir + "grok/testdata/test_a.log"},
		GrokParser:    p,
	}

	acc := testutil.Accumulator{}
	acc.SetDebug(true)
	assert.NoError(t, logparser.Start(&acc))

	acc.Wait(1)
	logparser.Stop()

	acc.AssertContainsTaggedFields(t, "logparser_grok",
		map[string]interface{}{
			"clientip":      "192.168.1.1",
			"myfloat":       float64(1.25),
			"response_time": int64(5432),
			"myint":         int64(101),
		},
		map[string]string{"response_code": "200"})
}

func getCurrentDir() string {
	_, filename, _, _ := runtime.Caller(1)
	return strings.Replace(filename, "logparser_test.go", "", 1)
}


text:
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

internal static partial class Interop
{
    internal static partial class Sys
    {
        [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat", SetLastError = true)]
        internal static extern int FStat(SafePipeHandle fd, out FileStatus output);
    }
}


text:
jsPsych can show a progress bar at the top of the experiment page indicating the subject's overall completion progress. The progress bar is rendered outside the jsPsych display element, and it requires the `jspsych.css` file to be loaded on the page. As of version 6.0, the progress bar looks like this:

![Progressbar Screenshot](/img/progress_bar.png)

To show the progress bar, set the `show_progress_bar` option in `jsPsych.init` to `true`:

```javascript
jsPsych.init({
	timeline: exp,
	show_progress_bar: true
});
```

The progress bar updates after every node on the top-level timeline updates. This avoids distracting updates in the middle of trials that are composed of multiple plugins, or confusing updates due to looping or conditional structures that may or may not execute depending on the actions of the subject. This also allows some flexibility for the programmer; by nesting timelines in a deliberate manner, the timing of progress bar updates can be controlled.

## Manual Control

The progress bar can also be manually controlled using the function `jsPsych.setProgressBar()`. This function takes a numeric value between 0 and 1, representing the proportion of the progress bar to fill.

```js
var trial = {
	type: 'html-keyboard-response',
	stimulus: 'Almost done...',
	on_finish: function(){
		jsPsych.setProgressBar(0.85); // set progress bar to 85% full.
	}
}
```

You can also get the current value of the progress bar with `jsPsych.getProgressBarCompleted()`

```js
var proportion_complete = jsPsych.getProgressBarCompleted();
```

If you are going to use manual progress bar control, you may want to disable the automatic progress bar updates by setting the `auto_update_progress_bar` property in `jsPsych.init()` to `false`.

```js
jsPsych.init({
	timeline: exp,
	show_progress_bar: true,
	auto_update_progress_bar: false
});
```


text:
// DROP - AREA . COMPONENT . TS

import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnInit} from '@angular/core';
import { filter } from 'rxjs/operators';

import { FamilyMember } from '../family-member.interface';
import { Cell } from '../cell.class';
import { CellModel } from '../cell-model.class';
import { SelectableWidget } from '../selectable-widget.class';

import { CellActivatedEvent } from '../events/cell-activated.event';
import { CellDeactivatedEvent } from '../events/cell-deactivated.event';
import { CellDropEvent } from '../events/cell-drop.event';
import { CellModelActivatedEvent } from '../events/cell-model-activated.event';
import { CellModelDeactivatedEvent } from '../events/cell-model-deactivated.event';
import { CellSelectionClearEvent } from '../events/cell-selection-clear.event';
import { DropAreaSelectEvent } from '../events/drop-area-select.event';
import { InfoModeEvent } from '../events/info-mode.event';
import { EventService } from '../services/event.service';
import { UXEvent } from '../events/ux.event';

@Component({
	selector: 'drop-area',
	//changeDetection: ChangeDetectionStrategy.OnPush,
	template: `

			{{position}}

					[active][inactive], selected={{selected}}]

		`,
	styles:[`
				.drop-area {
					padding-top: 2px;
					padding-bottom: 2px;
				}
				.drop-area-active {
					padding-top: 0px;
					padding-bottom: 0px;
					border: 2px dotted #080;
					border-radius: 5px;
					opacity: 0.8;
				}
				.drop-area-inactive {
					opacity: 0.01;
				}
				.drop-area-selected {
					padding-top: 0px;
					padding-bottom: 0px;
					border: 2px dashed #00f;
					border-radius: 5px;
				}
				.drop-area-info {
					padding-top: 2px;
					padding-bottom: 2px;
					background-color: #eaeaea;
					opacity: 0.8;
				}
			`]
})

export class DropAreaComponent extends SelectableWidget implements OnInit {

@Input() parent: FamilyMember;
@Input() position: number;

active = false;
selected = false;			// are we selected?
info = false;

constructor(eventService: EventService, private cdr: ChangeDetectorRef) {
	super(eventService);
}

ngOnInit() {

	//console.debug("DropAreaComponent::ngOnInit()");

	// we check for null of parent as we're not getting the binding set at the beginning for some reason
	// IDEA: we could use the function of the drop enabled (gets cell as input) though it's less interactive
	this.register(this.events.service.of<CellDeactivatedEvent>(CellDeactivatedEvent)
			.pipe(filter(deactivated => this.matchesCell(deactivated.cell)))
			.subscribe(() => this.becomeInactive())
					//console.log("-> drop-area comp gets cell deactivated event for '"+deactivated.cell.name+"'");

	);

	this.register(this.events.service.of<CellActivatedEvent>(CellActivatedEvent)
			.pipe(filter(activated => this.parent && this.parent.canAdopt(activated.cell, this.position)))
			.subscribe(() => this.becomeActive())
					// console.log("-> drop-area component '"+this.parent.getAdoptionName()+"' gets cell activated event for '"+activated.cell.name+"'");
	);

	this.register(this.events.service.of<CellModelDeactivatedEvent>(CellModelDeactivatedEvent)
			.subscribe(d => {
				if (this.matchesCellmodel(d.cellModel)) {
					//console.log("-> drop comp gets cellmodel deactivated event for '"+d.cellModel.name+"'");
					this.becomeInactive();
				}
			})
	);

	// TODO: the matches cell model does not take the position into account
	this.register(this.events.service.of<CellModelActivatedEvent>(CellModelActivatedEvent)
			.pipe(filter(activated => activated.cellModel && this.matchesCellmodel(activated.cellModel)))
			.subscribe(() => this.becomeActive())
	);

	this.register(this.events.service.of<CellDropEvent>(CellDropEvent)
			.pipe(filter(cd => this.selected && cd.newParent==undefined))
			.subscribe( cd => {
				console.log("-> drop comp gets cell drop event from '"+cd.cell.name+"'");
				this.performDropHere(cd.cell, this.parent, this.position);
			})
	);

	this.register(this.events.service.of<InfoModeEvent>(InfoModeEvent).subscribe( mode => this.info = mode.active));

}

select(position:number) {

	if (this.active && position==this.position) {

		console.log("[UI] DropAreaComponent::select("+this.parent.getURI()+"["+this.position+"])");
		this.selected = true;
		this.unsubscribeFromSelection();

		// We temporarily unsubscribe from clear, send a clear event and re-subscribe
		// This means we are the only ones selected now (previous parent will be unselected, for instance)
		this.unsubscribeFromSelectionClear();
		this.events.service.publish(new CellSelectionClearEvent());
		this.subscribeToSelectionClear();

	} else if (this.parent && position>=this.parent.childrenCount()) {
		console.log("[UI] DropAreaComponent::select(out of bounds)");
	} else {
		this.clearSelection();	// out of bounds, sorry, clear
	}

	this.cdr.markForCheck();

}

subscribeToSelection() {

	this.selectionSubscription = this.register(this.events.service.of<DropAreaSelectEvent>(DropAreaSelectEvent)
			.subscribe(das => this.select(das.position))
	);
	this.subscribeToSelectionClear();  // if we are selectable we are also clearable

}

becomeInactive() {
	this.active = false;
	//this.cdr.markForCheck();
}

becomeActive() {
	this.active = true;
	//this.cdr.markForCheck();

}

matchesCell(cell: Cell): boolean {
	return this.parent && this.parent.canAdopt(cell);
}

matchesCellmodel(cellModel: CellModel): boolean {
	//console.debug("matching with %s, this.parent="+(this.parent&& true)+",canAdopt="+this.parent && this.parent.canAdopt(cellModel), cellModel.getAdoptionName());
	return this.parent && this.parent.canAdopt(cellModel);
}

/** we drop here as we are only droppeable if we are active, and that's model validated */
dropSuccess($event: any) {
	this.performDropHere($event.dragData, this.parent, this.position);
}

performDropHere(cell:Cell, newParent: FamilyMember, newPosition: number) {

	if (!cell || !newParent || newPosition===undefined) {
		console.error('DropAreaComponent::performDropHere parameter issue ',cell, newParent, newPosition);
	}

	console.log("[UI] DropAreaComponent::dropSuccess("+cell.URI+")");
	this.events.service.publish(new CellDropEvent(cell, this.parent, this.position));
	// the document is now dirty
	this.events.service.publish(new UXEvent(UXEvent.DOCUMENT_DIRTY));

	//this.cdr.markForCheck();

}

}

/*
 *	  Copyright 2019 Daniel Giribet
 *
 *	 Licensed under the Apache License, Version 2.0 (the "License");
 *	 you may not use this file except in compliance with the License.
 *	 You may obtain a copy of the License at
 *
 *		 http://www.apache.org/licenses/LICENSE-2.0
 *
 *	 Unless required by applicable law or agreed to in writing, software
 *	 distributed under the License is distributed on an "AS IS" BASIS,
 *	 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *	 See the License for the specific language governing permissions and
 *	 limitations under the License.
 */


text:
import { Component } from 'react';
declare type Props = {
    className?: string;
    onDelete: () => void;
};
declare class DeleteButton extends Component<Props> {
    static defaultProps: {
        className: string;
    };
    get className(): string;
    confirmAndDelete: () => void;
    render: () => JSX.Element;
}
export default DeleteButton;


text:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _

class DemoUser(AbstractUser):
	"""DemoUser Model Class."""
	userfullname = models.CharField(u'お名前',blank=False,null=False,max_length=50)
	url = models.URLField(u'URL',blank=True,null=True)
	birth = models.DateField(u'生年月',blank=True,null=True)

	USERNAME_FIELD = 'username'
	REQUIRED_FIELDS = ['email', 'password']

	def __unicode__(self):
		return self.userfullname

	class Meta:
		db_table = 'user'
		swappable = 'AUTH_USER_MODEL'


text:
using System;
using System.Linq.Expressions;

namespace LinqToDB.Linq.Builder
{
	using LinqToDB.Expressions;
	using SqlQuery;

	class CountBuilder : MethodCallBuilder
	{
		public static readonly string[] MethodNames = { "Count", "LongCount" };

		protected override bool CanBuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo)
		{
			return methodCall.IsQueryable(MethodNames);
		}

		protected override IBuildContext BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo)
		{
			var returnType = methodCall.Method.ReturnType;
			var sequence   = builder.BuildSequence(new BuildInfo(buildInfo, methodCall.Arguments[0]) { CreateSubQuery = true });

			if (sequence.SelectQuery != buildInfo.SelectQuery)
			{
				if (sequence is JoinBuilder.GroupJoinSubQueryContext)
				{
					var ctx = new CountContext(buildInfo.Parent, sequence, returnType)
					{
						SelectQuery =
							sequence.SelectQuery
							//((JoinBuilder.GroupJoinSubQueryContext)sequence).GetCounter(methodCall)
					};

					ctx.Sql        = ctx.SelectQuery;
					ctx.FieldIndex = ctx.SelectQuery.Select.Add(SqlFunction.CreateCount(returnType, ctx.SelectQuery), "cnt");

					return ctx;
				}

				if (sequence is GroupByBuilder.GroupByContext)
				{
//					var ctx = new CountContext(buildInfo.Parent, sequence, returnType);
//
//					ctx.Sql        = ctx.SelectQuery;
//					ctx.FieldIndex = ctx.SelectQuery.Select.Add(SqlFunction.CreateCount(returnType, ctx.SelectQuery), "cnt");
//
//					return ctx;

//					return new CountContext(buildInfo.Parent, sequence, returnType)
//					{
//						Sql        = SqlFunction.CreateCount(returnType, sequence.SelectQuery),
//						FieldIndex = -1
//					};
				}
			}

			if (sequence.SelectQuery.Select.IsDistinct        ||
			    sequence.SelectQuery.Select.TakeValue != null ||
			    sequence.SelectQuery.Select.SkipValue != null)
			{
				sequence.ConvertToIndex(null, 0, ConvertFlags.Key);
				sequence = new SubQueryContext(sequence);
			}
			else if (!sequence.SelectQuery.GroupBy.IsEmpty)
			{
				if (!builder.DataContext.SqlProviderFlags.IsSybaseBuggyGroupBy)
					sequence.SelectQuery.Select.Add(new SqlValue(0));
				else
					foreach (var item in sequence.SelectQuery.GroupBy.Items)
						sequence.SelectQuery.Select.Add(item);

				sequence = new SubQueryContext(sequence);
			}

			if (sequence.SelectQuery.OrderBy.Items.Count > 0)
			{
				if (sequence.SelectQuery.Select.TakeValue == null && sequence.SelectQuery.Select.SkipValue == null)
					sequence.SelectQuery.OrderBy.Items.Clear();
				else
					sequence = new SubQueryContext(sequence);
			}

			var context = new CountContext(buildInfo.Parent, sequence, returnType);

			context.Sql        = context.SelectQuery;
			context.FieldIndex = context.SelectQuery.Select.Add(SqlFunction.CreateCount(returnType, context.SelectQuery), "cnt");

			return context;
		}

		protected override SequenceConvertInfo Convert(
			ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo, ParameterExpression param)
		{
			return null;
		}

		internal class CountContext : SequenceContextBase
		{
			public CountContext(IBuildContext parent, IBuildContext sequence, Type returnType)
				: base(parent, sequence, null)
			{
				_returnType = returnType;
			}

			readonly Type      _returnType;
			private  SqlInfo[] _index;

			public int            FieldIndex;
			public ISqlExpression Sql;

			public override void BuildQuery<T>(Query<T> query, ParameterExpression queryParameter)
			{
				var expr   = Builder.BuildSql(_returnType, FieldIndex);
				var mapper = Builder.BuildMapper<object>(expr);

				QueryRunner.SetRunQuery(query, mapper);
			}

			public override Expression BuildExpression(Expression expression, int level, bool enforceServerSide)
			{
				var index = ConvertToIndex(expression, level, ConvertFlags.Field)[0].Index;
				if (Parent != null)
					ConvertToParentIndex(index, Parent);
				return Builder.BuildSql(_returnType, index);
			}

			public override SqlInfo[] ConvertToSql(Expression expression, int level, ConvertFlags flags)
			{
				switch (flags)
				{
					case ConvertFlags.Field : return new[] { new SqlInfo { Query = Parent.SelectQuery, Sql = Sql } };
				}

				throw new NotImplementedException();
			}

			public override SqlInfo[] ConvertToIndex(Expression expression, int level, ConvertFlags flags)
			{
				switch (flags)
				{
					case ConvertFlags.Field :
						return _index ?? (_index = new[]
						{
							new SqlInfo { Query = Parent.SelectQuery, Index = Parent.SelectQuery.Select.Add(Sql), Sql = Sql, }
						});
				}

				throw new NotImplementedException();
			}

			public override IsExpressionResult IsExpression(Expression expression, int level, RequestFor requestFlag)
			{
				switch (requestFlag)
				{
					case RequestFor.Expression : return IsExpressionResult.True;
				}

				return IsExpressionResult.False;
			}

			public override IBuildContext GetContext(Expression expression, int level, BuildInfo buildInfo)
			{
				return Sequence.GetContext(expression, level, buildInfo);
			}

			public override ISqlExpression GetSubQuery(IBuildContext context)
			{
				var query = context.SelectQuery;

				if (query == SelectQuery)
				{
					var col = query.Select.Columns[query.Select.Columns.Count - 1];

					query.Select.Columns.RemoveAt(query.Select.Columns.Count - 1);

					return col.Expression;
				}

				return null;
			}
		}
	}
}


text:
package org.sablecc.objectmacro.codegeneration.java;

import java.util.*;

import org.sablecc.objectmacro.codegeneration.java.structure.*;
import org.sablecc.objectmacro.intermediate.syntax3.analysis.*;
import org.sablecc.objectmacro.intermediate.syntax3.node.*;

class ChildrenCollector
        extends DepthFirstAdapter {

    private final Map<String, SMacro> macros;

    private SMacro currentMacro;

    ChildrenCollector(
            Map<String, SMacro> macros) {

        this.macros = macros;
    }

    @Override
    public void caseAIntermediateRepresentation(
            AIntermediateRepresentation node) {

        if (node.getVersions() != null) {
            for (PMacro macro : node.getMacros()) {
                macro.apply(this);

                for (PMacro child : node.getMacros()) {
                    child.apply(this);
                }

                this.currentMacro = null;
            }
        }
    }

    @Override
    public void caseAMacro(
            AMacro node) {

        String macro_name = GenerationUtils.buildNameCamelCase(node.getNames());
        if (this.currentMacro == null) {
            this.currentMacro = this.macros.get(macro_name);
        }

        if (node.getParent() != null) {
            String parent
                    = GenerationUtils.buildNameCamelCase(node.getParent());
            if (parent.equals(this.currentMacro.getName())) {

                for (TString version : node.getVersions()) {
                    String version_name
                            = GenerationUtils.string(version).toUpperCase();
                    this.currentMacro.addChild(version_name, macro_name);
                    this.macros.get(macro_name).setParent(this.currentMacro);
                }
            }
        }
    }
}


text:
from flask import Flask, url_for, request
from pykwalify.core import Core
from replications.replications import *

class Config():
    def __init__(self):
        config = self.validate_config()
        self.configs = {}
        if config:
            for item in config:
                for k, v in item.iteritems():
                    self.configs[k] = v

            api = self.configs.get('api')
        else:
            raise Exception('Unable to load config files')
    @staticmethod
    def get_config():
        return
    def get_api(self):
        if self.api_connect:
            return self.api_connect
        else:
            self.api_connect = ApiConnect(
                api.get('host'),
                api.get('port'),
                api.get('version'),
                (api.get('user'), api.get('pass')))

    def get_cluster(self):
        if self.cluster:
            return self.cluster
        self.cluster = OmniaCluster(
            self.configs.get('cluster').get('name'),
            self.get_api)

    def validate_config(self):
        try:
            c = Core(source_file="/Users/JohnS5/dev/replication_manager/src/webapp/bdr_app.yml",
                schema_files=['/Users/JohnS5/dev/replication_manager/src/webapp/schema.yml'])
            return c.validate(raise_exception=True)
        except Exception as e:
            print "LOG: ERROR: config file is not valid"
            print e
            return None


text:
#ifndef TYPES_STATUSRECEIVER_H_
#define TYPES_STATUSRECEIVER_H_

#include <prim/prim.h>

class StatusReceiver {
 public:
  StatusReceiver();
  virtual ~StatusReceiver();
  virtual void receiveStatus(u32 _clientId, f64 _percentComplete) = 0;
};

#endif  // TYPES_STATUSRECEIVER_H_


text:
#ifndef __ATS__
#define __ATS__

#ifndef __CORESERVICES__
#include <CoreServices.h>
#endif

#ifndef __ATSLAYOUTTYPES__
#include <ATSLayoutTypes.h>
#endif

#ifndef __ATSFONT__
#include <ATSFont.h>
#endif

#ifndef __ATSTYPES__
#include <ATSTypes.h>
#endif

#ifndef __SCALERSTREAMTYPES__
#include <ScalerStreamTypes.h>
#endif

#ifndef __SFNTLAYOUTTYPES__
#include <SFNTLayoutTypes.h>
#endif

#ifndef __SFNTTYPES__
#include <SFNTTypes.h>
#endif

#endif /* __ATS__ */


text:
class NetworkImplMPI;

// Hackery to get around mpi's unhappiness with threads.  This thread
// simply polls MPI continuously for any kind of update and adds it to
// a local queue.
class NetworkThread{
public:
	bool active() const;
	size_t pending_pkgs() const;
	int64_t pending_bytes() const;
	size_t unpicked_pkgs() const{
		return receive_buffer.size();
	}
	int64_t unpicked_bytes() const;

	// Blocking read for the given source and message type.
	void readAny(std::string& data, int *sourcsrcRete=nullptr, int *typeRet=nullptr);
	// Unblocked read for the given source and message type.
	bool tryReadAny(std::string& data, int *sosrcReturce=nullptr, int *typeRet=nullptr);

	// Enqueue the given request to pending buffer for transmission.
	template <class T>
	int send(int dst, int tag, const T& msg) {
		std::string s = serialize(msg);
		return send(new Task(dst, tag, move(s)));
	}
	// Directly send the request bypassing the pending buffer.
	template <class T>
	int sendDirect(int dst, int tag, const T& msg) {
		std::string s = serialize(msg);
		return sendDirect(new Task(dst, tag, move(s)));
	}

	template <class T>
	int broadcast(int tag, const T& msg) {
		std::string s = serialize(msg);
		return broadcast(new Task(Task::ANY_DST, tag, move(s)));
	}

	void flush();

	int id() const;
	int size() const;

	static NetworkThread *GetInstance();
	static void Init(int argc, char* argv[]);
	// finish current tasks and terminate
	static void Shutdown();
	// abandon ongoing tasks and terminate all network related functions
	static void Terminate();

	bool pause_=false;

	uint64_t stat_send_pkg, stat_recv_pkg;
	uint64_t stat_send_byte, stat_recv_byte;

private:
	bool running;
	bool done;
	NetworkImplMPI* net;
	mutable std::thread t_;

	//buffer for request to be sent, double buffer design for performance
	std::vector<Task*> ps_buffer_[2];
	std::vector<Task*>* pending_sends_=&ps_buffer_[0];
	unsigned ps_idx_=0;
	mutable std::recursive_mutex ps_lock;

	std::deque<std::pair<std::string,TaskBase> > receive_buffer;
	mutable std::recursive_mutex rec_lock;

	// Enqueue the given request to pending buffer for transmission.
	int send(Task *req);
	// Directly (Physically) send the request.
	int sendDirect(Task *req);
	int broadcast(Task *req);

	bool checkReceiveQueue(std::string& data, TaskBase& info);

	void Run();

	static NetworkThread* self;
	NetworkThread();
};


text:
from board import Board
from controler import Controler

if __name__ == "__main__":
    c1 = Controler()
    c1.header()
    while not c1.exit:
        c1.menu()