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.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Tests that we get an "ATP is not ON" error for all vulnerability assessment cmdlets
#>
function Test-VulnerabilityAssessmentWithAtpOffTest
{
	# Setup
	$testSuffix = getAssetName
	Create-VulnerabilityAssessmentTestEnvironment $testSuffix
	$params = Get-SqlVulnerabilityAssessmentTestEnvironmentParameters $testSuffix

	try
	{
		$atpOffErrorMessage = "Server Advanced Threat Protection is not defined. Please run Enable-AzureRmSqlServerAdvancedThreatProtection first."
		$ruleId = "VA2031"
		$scanId = "myCustomScanId"
		$baselineResults = @(@("userA", "SELECT"),@("userB", "SELECT"))

		# Settings related cmdlets
		Assert-ThrowsContains -script { Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -StorageAccountName $params.storageAccount } -message $atpOffErrorMessage

		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName } -message $atpOffErrorMessage

		Assert-ThrowsContains -script { Clear-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName } -message $atpOffErrorMessage

		# Baseline related cmdlets
		Assert-ThrowsContains -script { Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId -BaselineResult $baselineResults } -message $atpOffErrorMessage

		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId } -message $atpOffErrorMessage

		Assert-ThrowsContains -script { Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId } -message $atpOffErrorMessage

		# Scan related cmdlets
		Assert-ThrowsContains -script { Convert-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -ScanId $scanId } -message $atpOffErrorMessage

		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName } -message $atpOffErrorMessage

		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -ScanId $scanId } -message $atpOffErrorMessage

		Assert-ThrowsContains -script { Start-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -ScanId $scanId } -message $atpOffErrorMessage
	}
	finally
	{
		# Cleanup
		Remove-VulnerabilityAssessmentTestEnvironment $testSuffix
	}
}

<#
.SYNOPSIS
Tests that we get a "Vulnerability Assessment settings not defined" error for all vulnerability assessment cmdlets
#>
function Test-VulnerabilityAssessmentWithSettingsNotDefinedTest
{
	# Setup
	$testSuffix = getAssetName
	Create-VulnerabilityAssessmentTestEnvironment $testSuffix
	$params = Get-SqlVulnerabilityAssessmentTestEnvironmentParameters $testSuffix

	try
	{
		$vaSettingsAreOffErrorMessage = "Vulnerability assessment settings are not defined. Please run Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings first."
		$ruleId = "VA2031"
		$scanId = "myCustomScanId"
		$baselineResults = @(@("userA", "SELECT"),@("userB", "SELECT"))

		# Turn on ATP
		Enable-AzureRmSqlServerAdvancedThreatProtection -ResourceGroupName $params.rgname -ServerName $params.serverName

		# Baseline related cmdlets
		Assert-ThrowsContains -script { Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId -BaselineResult $baselineResults } -message $vaSettingsAreOffErrorMessage

		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId } -message $vaSettingsAreOffErrorMessage

		Assert-ThrowsContains -script { Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId } -message $vaSettingsAreOffErrorMessage

		# Scan related cmdlets
		Assert-ThrowsContains -script { Convert-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -ScanId $scanId } -message $vaSettingsAreOffErrorMessage

		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName } -message $vaSettingsAreOffErrorMessage

		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -ScanId $scanId } -message $vaSettingsAreOffErrorMessage

		Assert-ThrowsContains -script { Start-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -ScanId $scanId } -message $vaSettingsAreOffErrorMessage
	}
	finally
	{
		# Cleanup
		Remove-VulnerabilityAssessmentTestEnvironment $testSuffix
	}
}

<#
.SYNOPSIS
Tests for vulnerability assessment settings scenarios
#>
function Test-VulnerabilityAssessmentSettingsTest
{
	# Setup
	$testSuffix = getAssetName
	Create-VulnerabilityAssessmentTestEnvironment $testSuffix
	$params = Get-SqlVulnerabilityAssessmentTestEnvironmentParameters $testSuffix

	try
	{
		# Turn on ATP
		Enable-AzureRmSqlServerAdvancedThreatProtection -ResourceGroupName $params.rgname -ServerName $params.serverName

		# Set Vulnerability Assessment settings (SetSettingsWithStorageAccountNameParameterSet parameter set) with a client errors
		Assert-ThrowsContains -script { Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		 -StorageAccountName $params.storageAccount -EmailAdmins $false -NotificationEmail @() -RecurringScansInterval Weekly } `
		 -message "You need to provide at least one email address or set EmailAdmins to True."

		Assert-ThrowsContains -script { Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		 -StorageAccountName $params.storageAccount -EmailAdmins $true -NotificationEmail @("invalidMail") -RecurringScansInterval Weekly } `
		 -message "One or more of the email addresses you entered are not valid.."

		Assert-ThrowsContains -script { Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		 -BlobStorageSasUri "https://invalid.blob.core.windows.netXXXXXXXXXXXXXXX"} `
		 -message "Invalid BlobStorageSasUri parameter value. The value should be in format of https://mystorage.blob.core.windows.net/vulnerability-assessment?st=XXXXXX."

		# Update Vulnerability Assessment settings (UpdateSettingsWithStorageAccountNameParameterSet parameter set)
		try
		{
			Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
			 -StorageAccountName $params.storageAccount
		}
		catch
		{
			if ((Get-SqlTestMode) -eq 'Playback')
			{
				# This command fails in Playback mode because the recorder do not record storage container creation command
				# Issue #6600 (https://github.com/Azure/azure-powershell/issues/6600)
			}
			else
			{
				throw;
			}
		}

		# Get Vulnerability Assessment settings
		$settings = Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName

		# Validate the settings
		Assert-AreEqual $params.rgname $settings.ResourceGroupName
		Assert-AreEqual $params.serverName $settings.ServerName
		Assert-AreEqual $params.databaseName $settings.DatabaseName
		Assert-AreEqual "vulnerability-assessment" $settings.ScanResultsContainerName
		Assert-AreEqual $params.storageAccount $settings.StorageAccountName
		Assert-AreEqual None $settings.RecurringScansInterval
		Assert-AreEqual $false $settings.EmailAdmins
		Assert-AreEqualArray @() $settings.NotificationEmail

		# Set Vulnerability Assessment settings with all optional values (SetSettingsWithStorageAccountNameParameterSet parameter set)
		$testScanResultsContainerName = "test-scan-results-container-name"
		$testEmailAdmins = $true
		$testNotificationEmail = @("test1@mailTest.com", "test2@mailTest.com")
		$testRecurringScansInterval = [Microsoft.Azure.Commands.Sql.VulnerabilityAssessment.Model.RecurringScansInterval]::Weekly

		# Update Vulnerability Assessment settings (UpdateSettingsWithStorageAccountNameParameterSet parameter set)
		try
		{
			Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
			  -RecurringScansInterval $testRecurringScansInterval -EmailAdmins $testEmailAdmins `
			  -NotificationEmail $testNotificationEmail
		}
		catch
		{
			if ((Get-SqlTestMode) -eq 'Playback')
			{
				# This command fails in Playback mode because the recorder do not record storage container creation command
				# Issue #6600 (https://github.com/Azure/azure-powershell/issues/6600)
			}
			else
			{
				throw;
			}
		}

		# Get Vulnerability Assessment settings
		$settings = Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName

		# Validate the settings
		Assert-AreEqual $params.rgname $settings.ResourceGroupName
		Assert-AreEqual $params.serverName $settings.ServerName
		Assert-AreEqual $params.databaseName $settings.DatabaseName
		Assert-AreEqual $testScanResultsContainerName $settings.ScanResultsContainerName
		Assert-AreEqual $params.storageAccount $settings.StorageAccountName
		Assert-AreEqual $testRecurringScansInterval $settings.RecurringScansInterval
		Assert-AreEqual $testEmailAdmins $settings.EmailAdmins
		Assert-AreEqualArray $testNotificationEmail $settings.NotificationEmail

		# Clear the settings
		Clear-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName

		# Test Get and Clear end expect an error
		$vaSettingsAreOffErrorMessage = "Vulnerability assessment settings is not defined. Please run Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings first."

		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName } -message $vaSettingsAreOffErrorMessage

		Assert-ThrowsContains -script { Clear-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName } -message $vaSettingsAreOffErrorMessage

		# Update Vulnerability Assessment settings with all optional values (UpdateSettingsWithBlobStorageSasUri parameter set)
		$testScanResultsContainerName = "custom-container"
		$testStorageName = "storage1"
		$testBlobStorageSasUri = "https://" + $testStorageName +".blob.core.windows.net/" + $testScanResultsContainerName + "?st=XXXXXXXXXXXXXXX"
		$testRecurringScansInterval = [Microsoft.Azure.Commands.Sql.VulnerabilityAssessment.Model.RecurringScansInterval]::None

		Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		 -BlobStorageSasUri $testBlobStorageSasUri -RecurringScansInterval $testRecurringScansInterval -EmailAdmins $testEmailAdmins `
		 -NotificationEmail $testNotificationEmail

		# Test piping of set settings from resource object
		$newDatabaseName = "newDatabaseName";
		$testNewNotificationEmail = @("test3@mailTest.com", "test4@mailTest.com")
		$testStorageName = $params.storageAccount
		$testBlobStorageSasUri = "https://" + $testStorageName +".blob.core.windows.net/" + $testScanResultsContainerName + "?st=XXXXXXXXXXXXXXX"
		$testRecurringScansInterval = [Microsoft.Azure.Commands.Sql.VulnerabilityAssessment.Model.RecurringScansInterval]::None

		New-AzureRmSqlDatabase -DatabaseName $newDatabaseName -ResourceGroupName $params.rgname -ServerName $params.serverName -Edition Basic

		Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $newDatabaseName `
		 -BlobStorageSasUri $testBlobStorageSasUri -RecurringScansInterval $testRecurringScansInterval -EmailAdmins $testEmailAdmins `
		 -NotificationEmail $testNewNotificationEmail

		try
		{
			 Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $newDatabaseName | Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings `
			 -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName
		}
		catch
		{
			if ((Get-SqlTestMode) -eq 'Playback')
			{
				# This command fails in Playback mode because the recorder do not record storage container creation command
				# Issue #6600 (https://github.com/Azure/azure-powershell/issues/6600)
			}
			else
			{
				throw;
			}
		}

		$settings = Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName

		Assert-AreEqual $params.rgname $settings.ResourceGroupName
		Assert-AreEqual $params.serverName $settings.ServerName
		Assert-AreEqual $params.databaseName $settings.DatabaseName
		Assert-AreEqual $testScanResultsContainerName $settings.ScanResultsContainerName
		Assert-AreEqual $testStorageName $settings.StorageAccountName
		Assert-AreEqual $testRecurringScansInterval $settings.RecurringScansInterval
		Assert-AreEqual $testEmailAdmins $settings.EmailAdmins
		Assert-AreEqualArray $testNewNotificationEmail $settings.NotificationEmail

		# Test piping of get settings from parent object
		$settings = Get-AzureRmSqlDatabase -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName | Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings

		# Validate the settings
		Assert-AreEqual $params.rgname $settings.ResourceGroupName
		Assert-AreEqual $params.serverName $settings.ServerName
		Assert-AreEqual $params.databaseName $settings.DatabaseName
		Assert-AreEqual $testScanResultsContainerName $settings.ScanResultsContainerName
		Assert-AreEqual $testStorageName $settings.StorageAccountName
		Assert-AreEqual $testRecurringScansInterval $settings.RecurringScansInterval
		Assert-AreEqual $testEmailAdmins $settings.EmailAdmins
		Assert-AreEqualArray $testNewNotificationEmail $settings.NotificationEmail

		# Test piping of clear settings from resource object
		Get-AzureRmSqlDatabase -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName | Clear-AzureRmSqlDatabaseVulnerabilityAssessmentSettings

		 Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName } -message $vaSettingsAreOffErrorMessage

		# Test WhatIf parameter of Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings
		Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		  -StorageAccountName $params.storageAccount -WhatIf

		# See that exception is thrown because set settings was run with WhatIf
		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName } -message $vaSettingsAreOffErrorMessage

		# Test WhatIf parameter of Clear-AzureRmSqlDatabaseVulnerabilityAssessmentSettings
		Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		 -BlobStorageSasUri $testBlobStorageSasUri

		Clear-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-WhatIf

		# See no exception is thrown because clear was run with WhatIf
		Get-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName
	}
	finally
	{
		# Cleanup
		Remove-VulnerabilityAssessmentTestEnvironment $testSuffix
	}
}

<#
.SYNOPSIS
Tests for vulnerability assessment baseline scenarios
#>
function Test-VulnerabilityAssessmentBaselineTest
{
	# Setup
	$testSuffix = getAssetName
	Create-VulnerabilityAssessmentTestEnvironment $testSuffix
	$params = Get-SqlVulnerabilityAssessmentTestEnvironmentParameters $testSuffix

	try
	{
		# Turn on ATP
		Enable-AzureRmSqlServerAdvancedThreatProtection -ResourceGroupName $params.rgname -ServerName $params.serverName

		# Set Vulnerability Assessment settings (SetSettingsWithStorageAccountNameParameterSet parameter set)
		try
		{
			Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
			 -StorageAccountName $params.storageAccount
		}
		catch
		{
			if ((Get-SqlTestMode) -eq 'Playback')
			{
				# This command fails in Playback mode because the recorder do not record storage container creation command
				# Issue #6600 (https://github.com/Azure/azure-powershell/issues/6600)
			}
			else
			{
				throw;
			}
		}

		$ruleId = "VA2108"

		# Get and remove baseline for non existing baseline
		$baselineDoesntExistsErrorMessage = "Baseline does not exist for rule 'VA2108'."
		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId } -message $baselineDoesntExistsErrorMessage

		Assert-ThrowsContains -script { Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId } -message $baselineDoesntExistsErrorMessage

		# Set baseline
		$baselineToSet = @( 'Principal1', 'db_ddladmin', 'SQL_USER', 'None'), @( 'Principal2', 'db_ddladmin', 'SQL_USER', 'None')
		Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId -BaselineResult $baselineToSet

		# Get baseline and compare with what we sent
		$baseline = Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId

		Assert-AreEqual $params.rgname $baseline.ResourceGroupName
		Assert-AreEqual $params.serverName $baseline.ServerName
		Assert-AreEqual $params.databaseName $baseline.DatabaseName
		Assert-AreEqual $ruleId $baseline.RuleId
		Assert-AreEqual $false $baseline.RuleAppliesToMaster
		Assert-AreEqualArray $baselineToSet[0] $baseline.BaselineResult[0].Result
		Assert-AreEqualArray $baselineToSet[1] $baseline.BaselineResult[1].Result

		# Set baseline
		$baselineToSet = @( 'Principal3', 'db_ddladmin', 'SQL_USER', 'None'), @( 'Principal4', 'db_ddladmin', 'SQL_USER', 'None')
		Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId -BaselineResult $baselineToSet

		# Get baseline and compare with what we sent
		$baseline = Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId

		Assert-AreEqual $params.rgname $baseline.ResourceGroupName
		Assert-AreEqual $params.serverName $baseline.ServerName
		Assert-AreEqual $params.databaseName $baseline.DatabaseName
		Assert-AreEqual $ruleId $baseline.RuleId
		Assert-AreEqual $false $baseline.RuleAppliesToMaster
		Assert-AreEqualArray $baselineToSet[0] $baseline.BaselineResult[0].Result
		Assert-AreEqualArray $baselineToSet[1] $baseline.BaselineResult[1].Result

		# Clear baseline
		Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId

		# Get and remove baseline for non existing baseline
		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId } -message $baselineDoesntExistsErrorMessage

		Assert-ThrowsContains -script { Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId } -message $baselineDoesntExistsErrorMessage

		# Test RuleAppliesToMaster parameter
		Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId -BaselineResult $baselineToSet

		# We expect no baseline to be found on the master
		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId -RuleAppliesToMaster } -message $baselineDoesntExistsErrorMessage

		Assert-ThrowsContains -script { Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId -RuleAppliesToMaster} -message $baselineDoesntExistsErrorMessage

		Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId -RuleAppliesToMaster -BaselineResult $baselineToSet

		$baseline = Get-AzureRmSqlDatabase -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName`
		| Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -RuleId $ruleId -RuleAppliesToMaster
		Assert-AreEqual $params.rgname $baseline.ResourceGroupName
		Assert-AreEqual $params.serverName $baseline.ServerName
		Assert-AreEqual $params.databaseName $baseline.DatabaseName
		Assert-AreEqual $ruleId $baseline.RuleId
		Assert-AreEqual $true $baseline.RuleAppliesToMaster
		Assert-AreEqualArray $baselineToSet[0] $baseline.BaselineResult[0].Result
		Assert-AreEqualArray $baselineToSet[1] $baseline.BaselineResult[1].Result

		Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId -RuleAppliesToMaster

		# piping scenario
		Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId -BaselineResult $baselineToSet

		Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId | Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline

		$baseline = Get-AzureRmSqlDatabase -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName | Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline `
		-RuleId $ruleId
		Assert-AreEqual $params.rgname $baseline.ResourceGroupName
		Assert-AreEqual $params.serverName $baseline.ServerName
		Assert-AreEqual $params.databaseName $baseline.DatabaseName
		Assert-AreEqual $ruleId $baseline.RuleId
		Assert-AreEqual $false $baseline.RuleAppliesToMaster
		Assert-AreEqualArray $baselineToSet[0] $baseline.BaselineResult[0].Result
		Assert-AreEqualArray $baselineToSet[1] $baseline.BaselineResult[1].Result

		Get-AzureRmSqlDatabase -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName | Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline `
		-RuleId $ruleId
		Assert-ThrowsContains -script { Get-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId } -message $baselineDoesntExistsErrorMessage

		# Test WhatIf parameter of Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline
		Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId -BaselineResult $baselineToSet -WhatIf

		# See that exception is thrown because set settings was run with WhatIf
		Assert-ThrowsContains -script { Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId } -message $baselineDoesntExistsErrorMessage

		# Test WhatIf parameter of Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline
		Set-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId -BaselineResult $baselineToSet

		Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -RuleId $ruleId -WhatIf

		# See no exception is thrown because clear was run with WhatIf
		Clear-AzureRmSqlDatabaseVulnerabilityAssessmentRuleBaseline -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-RuleId $ruleId
	}
	finally
	{
		# Cleanup
		Remove-VulnerabilityAssessmentTestEnvironment $testSuffix
	}
}

<#
.SYNOPSIS
Tests for vulnerability assessment scan , scan record get and list scenarios
#>
function Test-VulnerabilityAssessmentScanRecordGetListTest
{
	# Setup
	$testSuffix = getAssetName
	Create-VulnerabilityAssessmentTestEnvironment $testSuffix
	$params = Get-SqlVulnerabilityAssessmentTestEnvironmentParameters $testSuffix

	try
	{
		# Turn on ATP
		Enable-AzureRmSqlServerAdvancedThreatProtection -ResourceGroupName $params.rgname -ServerName $params.serverName

		# Set Vulnerability Assessment settings (SetSettingsWithStorageAccountNameParameterSet parameter set)
		try
		{
			Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
			 -StorageAccountName $params.storageAccount
		}
		catch
		{
			if ((Get-SqlTestMode) -eq 'Playback')
			{
				# This command fails in Playback mode because the recorder do not record storage container creation command
				# Issue #6600 (https://github.com/Azure/azure-powershell/issues/6600)
			}
			else
			{
				throw;
			}
		}

		# Trigger scan without scan ID
		try
		{
			Start-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName
		}
		catch
		{
			if ((Get-SqlTestMode) -eq 'Playback')
			{
				# This command generated a scanId of DateTime.UtcNow.ToString("yyyyMMdd_HHmmss")
				# So the recording will always fail
			}
			else
			{
				throw;
			}
		}

		# Trigger scan  as a Job with scan ID
		$scanId1 = "cmdletGetListScan"
		$scanJob = Start-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName -ScanId $scanId1 -AsJob
		$scanJob | Wait-Job
		$scanRecord1 = $scanJob | Receive-Job

		# Validate the scan record that we got from the scan
		Assert-AreEqual $params.rgname $scanRecord1.ResourceGroupName
		Assert-AreEqual $params.serverName $scanRecord1.ServerName
		Assert-AreEqual $params.databaseName $scanRecord1.DatabaseName
		Assert-AreEqual $scanId1 $scanRecord1.ScanId
		Assert-AreEqual "OnDemand" $scanRecord1.TriggerType

		# Validate the scan record that we got from the get scan record cmdlet
		$scanRecord1FromGet = Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName -ScanId $scanId1

		Assert-AreEqual $scanRecord1FromGet.ResourceGroupName $scanRecord1.ResourceGroupName
		Assert-AreEqual $scanRecord1FromGet.ServerName $scanRecord1.ServerName
		Assert-AreEqual $scanRecord1FromGet.DatabaseName $scanRecord1.DatabaseName
		Assert-AreEqual $scanRecord1FromGet.ScanId $scanRecord1.ScanId
		Assert-AreEqual $scanRecord1FromGet.TriggerType $scanRecord1.TriggerType
		Assert-AreEqual $scanRecord1FromGet.State $scanRecord1.State
		Assert-AreEqual $scanRecord1FromGet.StartTime $scanRecord1.StartTime
		Assert-AreEqual $scanRecord1FromGet.EndTime $scanRecord1.EndTime
		Assert-AreEqual $scanRecord1FromGet.Errors $scanRecord1.Errors
		Assert-AreEqual $scanRecord1FromGet.ScanResultsLocationPath $scanRecord1.ScanResultsLocationPath
		Assert-AreEqual $scanRecord1FromGet.NumberOfFailedSecurityChecks $scanRecord1.NumberOfFailedSecurityChecks

		# Validate the scan record that we got from the get scan record cmdlet with piping
		$scanRecord1FromGet = Get-AzureRmSqlDatabase -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName | Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord `
		-ScanId $scanId1

		Assert-AreEqual $scanRecord1FromGet.ResourceGroupName $scanRecord1.ResourceGroupName
		Assert-AreEqual $scanRecord1FromGet.ServerName $scanRecord1.ServerName
		Assert-AreEqual $scanRecord1FromGet.DatabaseName $scanRecord1.DatabaseName
		Assert-AreEqual $scanRecord1FromGet.ScanId $scanRecord1.ScanId
		Assert-AreEqual $scanRecord1FromGet.TriggerType $scanRecord1.TriggerType
		Assert-AreEqual $scanRecord1FromGet.State $scanRecord1.State
		Assert-AreEqual $scanRecord1FromGet.StartTime $scanRecord1.StartTime
		Assert-AreEqual $scanRecord1FromGet.EndTime $scanRecord1.EndTime
		Assert-AreEqual $scanRecord1FromGet.Errors $scanRecord1.Errors
		Assert-AreEqual $scanRecord1FromGet.ScanResultsLocationPath $scanRecord1.ScanResultsLocationPath
		Assert-AreEqual $scanRecord1FromGet.NumberOfFailedSecurityChecks $scanRecord1.NumberOfFailedSecurityChecks

		# Verify list scans
		$excpectedScanCount = 2
		$scanRecordList = Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName
		Assert-AreEqual $excpectedScanCount $scanRecordList.Count

		$scanRecord1FromListCmdlet = $scanRecordList[$excpectedScanCount-1]
		Assert-AreEqual $scanRecord1FromListCmdlet.ResourceGroupName $scanRecord1.ResourceGroupName
		Assert-AreEqual $scanRecord1FromListCmdlet.ServerName $scanRecord1.ServerName
		Assert-AreEqual $scanRecord1FromListCmdlet.DatabaseName $scanRecord1.DatabaseName
		Assert-AreEqual $scanRecord1FromListCmdlet.ScanId $scanRecord1.ScanId
		Assert-AreEqual $scanRecord1FromListCmdlet.TriggerType $scanRecord1.TriggerType
		Assert-AreEqual $scanRecord1FromListCmdlet.State $scanRecord1.State
		Assert-AreEqual $scanRecord1FromListCmdlet.StartTime $scanRecord1.StartTime
		Assert-AreEqual $scanRecord1FromListCmdlet.EndTime $scanRecord1.EndTime
		Assert-AreEqual $scanRecord1FromListCmdlet.Errors $scanRecord1.Errors
		Assert-AreEqual $scanRecord1FromListCmdlet.ScanResultsLocationPath $scanRecord1.ScanResultsLocationPath
		Assert-AreEqual $scanRecord1FromListCmdlet.NumberOfFailedSecurityChecks $scanRecord1.NumberOfFailedSecurityChecks

		# Run scan with piping
		$excpectedScanCount = $excpectedScanCount + 1
		Get-AzureRmSqlDatabase -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		| Start-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ScanId $scanId1

		# Verify list scans with piping
		$scanRecordList = Get-AzureRmSqlDatabase -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName | Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord
		Assert-AreEqual $excpectedScanCount $scanRecordList.Count

		$scanRecord1FromListCmdlet = $scanRecordList[$excpectedScanCount-1]
		Assert-AreEqual $scanRecord1FromListCmdlet.ResourceGroupName $scanRecord1.ResourceGroupName
		Assert-AreEqual $scanRecord1FromListCmdlet.ServerName $scanRecord1.ServerName
		Assert-AreEqual $scanRecord1FromListCmdlet.DatabaseName $scanRecord1.DatabaseName
		Assert-AreEqual $scanRecord1FromListCmdlet.ScanId $scanRecord1.ScanId
		Assert-AreEqual $scanRecord1FromListCmdlet.TriggerType $scanRecord1.TriggerType
		Assert-AreEqual $scanRecord1FromListCmdlet.State $scanRecord1.State

		# Test WhatIf parameter of Start-AzureRmSqlDatabaseVulnerabilityAssessmentScan
		$scanRecordList = Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName
		$scansCount = $scanRecordList.Count

		Start-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-WhatIf

		# Verify no new scan was made
		$scanRecordList = Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName
		Assert-AreEqual $scansCount $scanRecordList.Count
	}
	finally
	{
		# Cleanup
		Remove-VulnerabilityAssessmentTestEnvironment $testSuffix
	}
}

<#
.SYNOPSIS
Tests for vulnerability assessment scan Convert scenarios
#>
function Test-VulnerabilityAssessmentScanConvertTest
{
	# Setup
	$testSuffix = getAssetName
	Create-VulnerabilityAssessmentTestEnvironment $testSuffix
	$params = Get-SqlVulnerabilityAssessmentTestEnvironmentParameters $testSuffix

	try
	{
		# Turn on ATP
		Enable-AzureRmSqlServerAdvancedThreatProtection -ResourceGroupName $params.rgname -ServerName $params.serverName

		# Set Vulnerability Assessment settings (SetSettingsWithStorageAccountNameParameterSet parameter set)
		try
		{
			Update-AzureRmSqlDatabaseVulnerabilityAssessmentSettings -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
			 -StorageAccountName $params.storageAccount
		}
		catch
		{
			if ((Get-SqlTestMode) -eq 'Playback')
			{
				# This command fails in Playback mode because the recorder do not record storage container creation command
				# Issue #6600 (https://github.com/Azure/azure-powershell/issues/6600)
			}
			else
			{
				throw;
			}
		}

		# Convert scan without providing scan ID
		Assert-ThrowsContains -script { Convert-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName `
		-DatabaseName $params.databaseName } -message "ScanId is a required parameter for this cmdlet. Please explicitly provide it or pass the Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord output via pipe."

		# Trigger a new scan
		$scanId = "cmdletConvertScan"
		Start-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName -ScanId $scanId

		# Convert the scan
		$convertScanObject = Convert-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-ScanId $scanId

		Assert-AreEqual $params.rgname $convertScanObject.ResourceGroupName
		Assert-AreEqual $params.serverName $convertScanObject.ServerName
		Assert-AreEqual $params.databaseName $convertScanObject.DatabaseName
		Assert-True -script  { $convertScanObject.ExportedReportLocation.Contains($scanId) }
		Assert-True -script  { $convertScanObject.ExportedReportLocation.Contains($params.storageAccount) }

		# Convert the scan (piping scenario)
		$scanId = "cmdletConvertScan1"
		Start-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName -ScanId $scanId

		$convertScanObject =  Get-AzureRmSqlDatabaseVulnerabilityAssessmentScanRecord -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-ScanId $scanId | Convert-AzureRmSqlDatabaseVulnerabilityAssessmentScan

		Assert-AreEqual $params.rgname $convertScanObject.ResourceGroupName
		Assert-AreEqual $params.serverName $convertScanObject.ServerName
		Assert-AreEqual $params.databaseName $convertScanObject.DatabaseName
		Assert-True -script  { $convertScanObject.ExportedReportLocation.Contains($scanId) }
		Assert-True -script  { $convertScanObject.ExportedReportLocation.Contains($params.storageAccount) }

		# Test WhatIf parameter of Convert-AzureRmSqlDatabaseVulnerabilityAssessmentScan
		$convertScanObject = Convert-AzureRmSqlDatabaseVulnerabilityAssessmentScan -ResourceGroupName $params.rgname -ServerName $params.serverName -DatabaseName $params.databaseName `
		-ScanId $scanId -WhatIf
		Assert-Null $convertScanObject.ExportedReportLocation
	}
	finally
	{
		# Cleanup
		Remove-VulnerabilityAssessmentTestEnvironment $testSuffix
	}
}

<#
.SYNOPSIS
Creates the test environment needed to perform the tests
#>
function Create-VulnerabilityAssessmentTestEnvironment ($testSuffix, $location = "West Central US", $serverVersion = "12.0")
{
	$params = Get-SqlVulnerabilityAssessmentTestEnvironmentParameters $testSuffix
	Create-TestEnvironmentWithParams $params $location $serverVersion
}

<#
.SYNOPSIS
Gets the values of the parameters used at the tests
#>
function Get-SqlVulnerabilityAssessmentTestEnvironmentParameters ($testSuffix)
{
	return @{ rgname = "sql-va-cmdlet-test-rg" +$testSuffix;
			  serverName = "sql-va-cmdlet-server" +$testSuffix;
			  databaseName = "sql-va-cmdlet-db" + $testSuffix;
			  storageAccount = "sqlvacmdlets" +$testSuffix
		}
}

<#
.SYNOPSIS
Removes the test environment that was needed to perform the tests
#>
function Remove-VulnerabilityAssessmentTestEnvironment ($testSuffix)
{
	$params = Get-SqlVulnerabilityAssessmentTestEnvironmentParameters $testSuffix
	Remove-AzureRmResourceGroup -Name $params.rgname -Force
}


text:
<!DOCTYPE html>

        <title>About Me</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700" rel="stylesheet">
        <link rel="stylesheet" href="styles.css">

Front-End Apprentice

My name is...

Calvin

I want to be...

a front-end master

I live in...

Kamloops

My favorite way to work is...

with a timer and some music

In my free time, I like to...

read about history and statistics; hike and cook

redpajama_set_name: RedPajamaGithub


text:
title:      Les spammeurs, vils flatteurs
lang:       fr
tags:       [SPIP, spam]
---

Je ne sais pas chez vous, mais sur ce blog la plupart des spams récents sont rédigés sous forme de flatteries sans finesse, sans doute une nouvelle tendance dans la course sans fin entre spammeurs et systèmes anti spam. Le fait est que [le plugin NoSpam pour SPIP](http://plugins.spip.net/nospam.html) n'arrive pas — pour l'instant ? — à éviter ceux-ci. Voici un petit florilège.

J'ai visiblement de nombreuses admiratrices qui travaillent dans le domaine bancaire :

> J'ai manqué le bus par la faute de votre article, j'explorais ce website, forcément je suis sorti en retard ! Emmanuelle du site abordant la meilleur banque en ligne

> Ça fait déjà le troisième post que je lis à ce propos, bravo pour la cohérence de votre discours ! Serena du site abordant la meilleur banque en ligne

> J'ai parfaitement compris ce que vous dîtes, d'ailleurs nos analyses se rejoignent. Corinne de ce site web traitant de : comparatif banque

> Vraiment content d'avoir déniché ce billet, je prends la plume comme vous de temps à autre et je sais reconnaître la qualité ! Stephanie du site banque truc

> Style agréable et propos rationnels, j'adhère totalement à votre page ! Magalie du site banque machin

> Ce website, très ergonomique, me pousse à faire pareil, sans imitation bien entendu ! Elena du site abordant la meilleur banque en ligne

La crise pousse en tout cas à communiquer sur les jeux d'argent ou les économies à réaliser, plus que sur les viagra et autres psychotropes habituels :

> J'ai déjà déniché différents post qui causaient de ça, celui-ci me paraît vraiment très fiable ! Julien de jeu de roulette

> J'ai lu à l'instant votre point de vue là-dessus, c'est extrêmement intéressant ! Malika du portail de proteine pas cher

C'est Michel Audiard qui a dit « dans la flatterie, aucune précaution à prendre, aucune limite à respecter. On ne va jamais trop loin. ». Les spammeurs ont dû le lire.

Je constate qu'aucun spammeur n'essaie jamais de se faire passer pour une personne qui a déjà posté un message légitime sur ce blog. Je pense que le plugin NoSpam devrait permettre — optionnellement — de mettre en modération tout message posté par un nouveau commenteur. Une modération à priori sélective, mais ne nécessitant pas l'authentification préalable pour les légitimes.


text:
var numInterpolations = 4; //numInterpolations containing 32 notes

// generates an array where indices correspond to midi notes
var everyNote = 'C,C#,D,D#,E,F,F#,G,G#,A,A#,B,'.repeat(20).split(',').map( function(x,i) {
    return x + '' + Math.floor(i/12);
});

//returns the midi pitch value for the given note.
//returns -1 if not found
function toMidi(note) {
    return everyNote.indexOf(note);
}

//If you want to try out other melodies copy and paste any of these in https://github.....
var MELODY1 = { notes: [
    {pitch: toMidi('A3'), quantizedStartStep: 0, quantizedEndStep: 4},
    {pitch: toMidi('D4'), quantizedStartStep: 4, quantizedEndStep: 6},
    {pitch: toMidi('E4'), quantizedStartStep: 6, quantizedEndStep: 8},
    {pitch: toMidi('F4'), quantizedStartStep: 8, quantizedEndStep: 10},
    {pitch: toMidi('D4'), quantizedStartStep: 10, quantizedEndStep: 12},
    {pitch: toMidi('E4'), quantizedStartStep: 12, quantizedEndStep: 16},
    {pitch: toMidi('C4'), quantizedStartStep: 16, quantizedEndStep: 20},
    {pitch: toMidi('D4'), quantizedStartStep: 20, quantizedEndStep: 26},
    {pitch: toMidi('A3'), quantizedStartStep: 26, quantizedEndStep: 28},
    {pitch: toMidi('A3'), quantizedStartStep: 28, quantizedEndStep: 32}
]};

//you can also just put in the midi pitch note if you know it
var MELODY2 = { notes: [
    {pitch: 50, quantizedStartStep: 0, quantizedEndStep: 1},
    {pitch: 53, quantizedStartStep: 1, quantizedEndStep: 2},
    {pitch: 58, quantizedStartStep: 2, quantizedEndStep: 3},
    {pitch: 58, quantizedStartStep: 3, quantizedEndStep: 4},
    {pitch: 58, quantizedStartStep: 4, quantizedEndStep: 5},
    {pitch: 53, quantizedStartStep: 5, quantizedEndStep: 6},
    {pitch: 53, quantizedStartStep: 6, quantizedEndStep: 7},
    {pitch: 53, quantizedStartStep: 7, quantizedEndStep: 8},
    {pitch: 52, quantizedStartStep: 8, quantizedEndStep: 9},
    {pitch: 55, quantizedStartStep: 9, quantizedEndStep: 10},
    {pitch: 60, quantizedStartStep: 10, quantizedEndStep: 11},
    {pitch: 60, quantizedStartStep: 11, quantizedEndStep: 12},
    {pitch: 60, quantizedStartStep: 12, quantizedEndStep: 13},
    {pitch: 60, quantizedStartStep: 13, quantizedEndStep: 14},
    {pitch: 60, quantizedStartStep: 14, quantizedEndStep: 15},
    {pitch: 52, quantizedStartStep: 15, quantizedEndStep: 16},
    {pitch: 57, quantizedStartStep: 16, quantizedEndStep: 17},
    {pitch: 57, quantizedStartStep: 17, quantizedEndStep: 18},
    {pitch: 57, quantizedStartStep: 18, quantizedEndStep: 19},
    {pitch: 65, quantizedStartStep: 19, quantizedEndStep: 20},
    {pitch: 65, quantizedStartStep: 20, quantizedEndStep: 21},
    {pitch: 65, quantizedStartStep: 21, quantizedEndStep: 22},
    {pitch: 57, quantizedStartStep: 22, quantizedEndStep: 23},
    {pitch: 57, quantizedStartStep: 23, quantizedEndStep: 24},
    {pitch: 57, quantizedStartStep: 24, quantizedEndStep: 25},
    {pitch: 57, quantizedStartStep: 25, quantizedEndStep: 26},
    {pitch: 62, quantizedStartStep: 26, quantizedEndStep: 27},
    {pitch: 62, quantizedStartStep: 27, quantizedEndStep: 28},
    {pitch: 65, quantizedStartStep: 28, quantizedEndStep: 29},
    {pitch: 65, quantizedStartStep: 29, quantizedEndStep: 30},
    {pitch: 69, quantizedStartStep: 30, quantizedEndStep: 31},
    {pitch: 69, quantizedStartStep: 31, quantizedEndStep: 32}
]};

// go to https://http://goo.gl/magenta/musicvae-checkpoints to see more checkpoint urls
// var melodiesModelCheckPoint = 'https://storage.googleapis.com/download.magenta.tensorflow.org/models/music_vae/dljs/mel_small';
var melodiesModelCheckPoint = './data/mel_small';

//Uses promises to chain together asynchronous operations.
//Check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises for info on promises
new musicvae.MusicVAE(melodiesModelCheckPoint)
    .initialize()
    .then(function(musicVAE) {
        //blends between the given two melodies and returns numInterpolations note sequences
        var noteSequences = musicVAE.interpolate([MELODY1, MELODY2], numInterpolations);
        noteSequences.forEach(function(noteSequence, index) {
            displayMelodies(noteSequence.notes, index);
        });
    });

// takes the given array of notes and index. updates the output <spans>
function displayMelodies(notes, index) {
    var output = 'Melody ' + index + '
';
    output += JSON.stringify(notes, null, '  ') + '

';
    document.querySelector('.output' + index).innerHTML = output;
}


text:
<?
	/** esta plantilla funcionara con los datos aqui recogidos */
	$kernel  =  $this->oDataTemplate->getKeyData('kernel');
	$datos   =  $this->oDataTemplate->getKeyData('proyectos');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

		<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"/>

Proyecto    Nº: <?=$datos[fproyecto]?>    Fecha: <?=$datos[falta]?>    Estado: <?=$datos[estado]?>

			<img title="Crea un acceso directo en el escritorio de la vista actual" src="<?=OS_WEB_PATH?>/applications/_commons/_images/shortcut.png" />
			Link

			<img title="Imprimir estos datos" src="<?=OS_WEB_PATH?>/applications/_commons/_images/print.png" />
			PDF

	<form name="fapplication" id="fapplication">

Proyecto

Pedido

Observaciones

Control

					Cliente:
					<input type="hidden" name="id_cliente" id="id_cliente" value="<?=$datos[id_cliente]?>"/><input class="roField" type="text" name="cliente" id="cliente" value="<?=$datos[cliente]?>" disabled/><button class="fields" id="btBuscadorClientes" title="Abrir una ventana para buscar el cliente de este proyecto"><img src="<?=OS_WEB_PATH?>/applications/_commons/_images/find.png" /></button>

					Contactos:
					<textarea id="contactos" name="contactos"><?=$datos[contactos]?></textarea>

				<? if ($this->oUser->getRol()>2){ ?>

						Fecha registro:
						<?=$datos[falta]?>

						Fecha modificación:
						<?=$datos[fmodificacion]?>   (<?=$datos[usuario]?>)

				<?} else echo "Información de auditoría"; ?>

				<input id="btCancelar" type="button" value="Cancelar" />
				<input id="btAceptar" type="button" value="Aceptar" />

		<input type="hidden" name="proyecto" id="proyecto" value="<?=$datos[proyecto]?>"/>
		<input type="hidden" name="do" id="do" value=""/>
		<input type="hidden" name="details" id="details" value=""/>
		<input type="hidden" name="sessionclass" id="sessionclass" value="<?=$this->getOrderActionClass()->getClassSession()?>"/>
		<input type="hidden" name="class" id="class" value="<?=$this->getOrderActionClass()->getClass()?>"/>
		<input type="hidden" name="channel" id="channel" value="html"/>
	</form>


text:
$(document).ready(function() {

  // User clicked on an edit button
  $(".editButton").click(function () {
    console.log("is this thing firing?");
    window.location.href = '/form/' + $(this)[0].id;
  });

  // User clicked on a delete button
  $(".deleteButton").click(function () {
    var batchItemId = $(this)[0].id;
    console.log(batchItemId);

    $.ajax({
      url: "/form",
      method: "DELETE",
      data: {
        _id: batchItemId
      },
      success: function (response) {
        $("#panel_" + batchItemId).remove();  // Remove the DOM element on success
      }
    });
  });
});


text:
require 'rails_helper'

describe 'Filter merge requests', feature: true do
  include FilteredSearchHelpers
  include MergeRequestHelpers

  let!(:project)   { create(:project) }
  let!(:group)     { create(:group) }
  let!(:user)      { create(:user) }
  let!(:milestone) { create(:milestone, project: project) }
  let!(:label)     { create(:label, project: project) }
  let!(:wontfix)   { create(:label, project: project, title: "Won't fix") }

  before do
    project.team << [user, :master]
    group.add_developer(user)
    login_as(user)
    create(:merge_request, source_project: project, target_project: project)

    visit namespace_project_merge_requests_path(project.namespace, project)
  end

  describe 'for assignee from mr#index' do
    let(:search_query) { "assignee:@#{user.username}" }

    def expect_assignee_visual_tokens
      expect_tokens([{ name: 'assignee', value: "@#{user.username}" }])
      expect_filtered_search_input_empty
    end

    before do
      input_filtered_search(search_query)

      expect_mr_list_count(0)
    end

    context 'assignee', js: true do
      it 'updates to current user' do
        expect_assignee_visual_tokens()
      end

      it 'does not change when closed link is clicked' do
        find('.issues-state-filters a', text: "Closed").click

        expect_assignee_visual_tokens()
      end

      it 'does not change when all link is clicked' do
        find('.issues-state-filters a', text: "All").click

        expect_assignee_visual_tokens()
      end
    end
  end

  describe 'for milestone from mr#index' do
    let(:search_query) { "milestone:%\"#{milestone.title}\"" }

    def expect_milestone_visual_tokens
      expect_tokens([{ name: 'milestone', value: "%\"#{milestone.title}\"" }])
      expect_filtered_search_input_empty
    end

    before do
      input_filtered_search(search_query)

      expect_mr_list_count(0)
    end

    context 'milestone', js: true do
      it 'updates to current milestone' do
        expect_milestone_visual_tokens()
      end

      it 'does not change when closed link is clicked' do
        find('.issues-state-filters a', text: "Closed").click

        expect_milestone_visual_tokens()
      end

      it 'does not change when all link is clicked' do
        find('.issues-state-filters a', text: "All").click

        expect_milestone_visual_tokens()
      end
    end
  end

  describe 'for label from mr#index', js: true do
    it 'filters by no label' do
      input_filtered_search('label:none')

      expect_mr_list_count(1)
      expect_tokens([{ name: 'label', value: 'none' }])
      expect_filtered_search_input_empty
    end

    it 'filters by a label' do
      input_filtered_search("label:~#{label.title}")

      expect_mr_list_count(0)
      expect_tokens([{ name: 'label', value: "~#{label.title}" }])
      expect_filtered_search_input_empty
    end

    it "filters by `won't fix` and another label" do
      input_filtered_search("label:~\"#{wontfix.title}\" label:~#{label.title}")

      expect_mr_list_count(0)
      expect_tokens([
        { name: 'label', value: "~\"#{wontfix.title}\"" },
        { name: 'label', value: "~#{label.title}" }
      ])
      expect_filtered_search_input_empty
    end

    it "filters by `won't fix` label followed by another label after page load" do
      input_filtered_search("label:~\"#{wontfix.title}\"")

      expect_mr_list_count(0)
      expect_tokens([{ name: 'label', value: "~\"#{wontfix.title}\"" }])
      expect_filtered_search_input_empty

      input_filtered_search_keys("label:~#{label.title}")

      expect_mr_list_count(0)
      expect_tokens([
        { name: 'label', value: "~\"#{wontfix.title}\"" },
        { name: 'label', value: "~#{label.title}" }
      ])
      expect_filtered_search_input_empty
    end
  end

  describe 'for assignee and label from issues#index' do
    let(:search_query) { "assignee:@#{user.username} label:~#{label.title}" }

    before do
      input_filtered_search("assignee:@#{user.username}")

      expect_mr_list_count(1)
      expect_tokens([{ name: 'assignee', value: "@#{user.username}" }])
      expect_filtered_search_input_empty

      input_filtered_search_keys("label:~#{label.title} ")

      expect_mr_list_count(1)

      find("#state-opened[href=\"#{URI.parse(current_url).path}?assignee_username=#{user.username}&label_name%5B%5D=#{label.title}&scope=all&state=opened\"]")
    end

    context 'assignee and label', js: true do
      def expect_assignee_label_visual_tokens
        expect_tokens([
          { name: 'assignee', value: "@#{user.username}" },
          { name: 'label', value: "~#{label.title}" }
        ])
        expect_filtered_search_input_empty
      end

      it 'updates to current assignee and label' do
        expect_assignee_label_visual_tokens()
      end

      it 'does not change when closed link is clicked' do
        find('.issues-state-filters a', text: "Closed").click

        expect_assignee_label_visual_tokens()
      end

      it 'does not change when all link is clicked' do
        find('.issues-state-filters a', text: "All").click

        expect_assignee_label_visual_tokens()
      end
    end
  end

  describe 'filter merge requests by text' do
    before do
      create(:merge_request, title: "Bug", source_project: project, target_project: project, source_branch: "bug")

      bug_label = create(:label, project: project, title: 'bug')
      milestone = create(:milestone, title: "8", project: project)

      mr = create(:merge_request,
        title: "Bug 2",
        source_project: project,
        target_project: project,
        source_branch: "bug2",
        milestone: milestone,
        author: user,
        assignee: user)
      mr.labels << bug_label

      visit namespace_project_merge_requests_path(project.namespace, project)
    end

    context 'only text', js: true do
      it 'filters merge requests by searched text' do
        input_filtered_search('bug')

        expect_mr_list_count(2)
      end

      it 'does not show any merge requests' do
        input_filtered_search('testing')

        page.within '.mr-list' do
          expect(page).not_to have_selector('.merge-request')
        end
      end
    end

    context 'filters and searches', js: true do
      it 'filters by text and label' do
        input_filtered_search('Bug')

        expect_mr_list_count(2)
        expect_filtered_search_input('Bug')

        input_filtered_search_keys(' label:~bug')

        expect_mr_list_count(1)
        expect_tokens([{ name: 'label', value: '~bug' }])
        expect_filtered_search_input('Bug')
      end

      it 'filters by text and milestone' do
        input_filtered_search('Bug')

        expect_mr_list_count(2)
        expect_filtered_search_input('Bug')

        input_filtered_search_keys(' milestone:%8')

        expect_mr_list_count(1)
        expect_tokens([{ name: 'milestone', value: '%8' }])
        expect_filtered_search_input('Bug')
      end

      it 'filters by text and assignee' do
        input_filtered_search('Bug')

        expect_mr_list_count(2)
        expect_filtered_search_input('Bug')

        input_filtered_search_keys(" assignee:@#{user.username}")

        expect_mr_list_count(1)
        expect_tokens([{ name: 'assignee', value: "@#{user.username}" }])
        expect_filtered_search_input('Bug')
      end

      it 'filters by text and author' do
        input_filtered_search('Bug')

        expect_mr_list_count(2)
        expect_filtered_search_input('Bug')

        input_filtered_search_keys(" author:@#{user.username}")

        expect_mr_list_count(1)
        expect_tokens([{ name: 'author', value: "@#{user.username}" }])
        expect_filtered_search_input('Bug')
      end
    end
  end

  describe 'filter merge requests and sort', js: true do
    before do
      bug_label = create(:label, project: project, title: 'bug')

      mr1 = create(:merge_request, title: "Frontend", source_project: project, target_project: project, source_branch: "Frontend")
      mr2 = create(:merge_request, title: "Bug 2", source_project: project, target_project: project, source_branch: "bug2")

      mr1.labels << bug_label
      mr2.labels << bug_label

      visit namespace_project_merge_requests_path(project.namespace, project)
    end

    it 'is able to filter and sort merge requests' do
      input_filtered_search('label:~bug')

      expect_mr_list_count(2)

      click_button 'Last created'
      page.within '.dropdown-menu-sort' do
        click_link 'Oldest created'
      end
      wait_for_ajax

      page.within '.mr-list' do
        expect(page).to have_content('Frontend')
      end
    end
  end

  describe 'filter by assignee id', js: true do
    it 'filter by current user' do
      visit namespace_project_merge_requests_path(project.namespace, project, assignee_id: user.id)

      expect_tokens([{ name: 'assignee', value: "@#{user.username}" }])
      expect_filtered_search_input_empty
    end

    it 'filter by new user' do
      new_user = create(:user)
      project.add_developer(new_user)

      visit namespace_project_merge_requests_path(project.namespace, project, assignee_id: new_user.id)

      expect_tokens([{ name: 'assignee', value: "@#{new_user.username}" }])
      expect_filtered_search_input_empty
    end
  end

  describe 'filter by author id', js: true do
    it 'filter by current user' do
      visit namespace_project_merge_requests_path(project.namespace, project, author_id: user.id)

      expect_tokens([{ name: 'author', value: "@#{user.username}" }])
      expect_filtered_search_input_empty
    end

    it 'filter by new user' do
      new_user = create(:user)
      project.add_developer(new_user)

      visit namespace_project_merge_requests_path(project.namespace, project, author_id: new_user.id)

      expect_tokens([{ name: 'author', value: "@#{new_user.username}" }])
      expect_filtered_search_input_empty
    end
  end
end


text:
package metadslx.core;

public interface MetaPropertyInitializer
{
    metadslx.core.MetaConstructor getConstructor();
    void setConstructor(metadslx.core.MetaConstructor value);
    String getPropertyName();
    void setPropertyName(String value);
    metadslx.core.MetaClass getPropertyContext();
    void setPropertyContext(metadslx.core.MetaClass value);
    metadslx.core.MetaProperty getProperty();
    void setProperty(metadslx.core.MetaProperty value);
    metadslx.core.MetaExpression getValue();
    void setValue(metadslx.core.MetaExpression value);

}


text:
'use strict'

/**
 * This will be removed in next versions as it is not handled in the babel-loader
 * See: https://github.com/geowarin/friendly-errors-webpack-plugin/issues/2
 */
function cleanStackTrace (message) {
  return message
    .replace(/^\s*at\s.*:\d+:\d+[\s)]*\n/gm, '') // at ... ...:x:y
}

function cleanMessage (message) {
  return message
  // match until the last semicolon followed by a space
  // this should match
  // linux => "(SyntaxError: )Unexpected token (5:11)"
  // windows => "(SyntaxError: C:/projects/index.js: )Unexpected token (5:11)"
    .replace(/^Module build failed.*:(\sSyntaxError:(.*:)?)?\s/, 'Syntax Error: ')
}

function isBabelSyntaxError (e) {
  return e.name === 'ModuleBuildError' &&
    e.message.indexOf('SyntaxError') >= 0
}

function transform (error) {
  if (isBabelSyntaxError(error)) {
    return Object.assign({}, error, {
      message: cleanStackTrace(cleanMessage(error.message) + '\n'),
      severity: 1000,
      name: 'Syntax Error'
    })
  }

  return error
}

module.exports = transform


text:
"""
Sensor to indicate whether the current day is a workday.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.workday/
"""
import asyncio
import logging
import datetime

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, WEEKDAYS
import homeassistant.util.dt as dt_util
from homeassistant.components.binary_sensor import BinarySensorDevice
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

REQUIREMENTS = ['holidays==0.8.1']

# List of all countries currently supported by holidays
# There seems to be no way to get the list out at runtime
ALL_COUNTRIES = ['Australia', 'AU', 'Austria', 'AT', 'Canada', 'CA',
                 'Colombia', 'CO', 'Czech', 'CZ', 'Denmark', 'DK', 'England',
                 'EuropeanCentralBank', 'ECB', 'TAR', 'Germany', 'DE',
                 'Ireland', 'Isle of Man', 'Mexico', 'MX', 'Netherlands', 'NL',
                 'NewZealand', 'NZ', 'Northern Ireland', 'Norway', 'NO',
                 'Portugal', 'PT', 'PortugalExt', 'PTE', 'Scotland', 'Spain',
                 'ES', 'UnitedKingdom', 'UK', 'UnitedStates', 'US', 'Wales']
CONF_COUNTRY = 'country'
CONF_PROVINCE = 'province'
CONF_WORKDAYS = 'workdays'
# By default, Monday - Friday are workdays
DEFAULT_WORKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri']
CONF_EXCLUDES = 'excludes'
# By default, public holidays, Saturdays and Sundays are excluded from workdays
DEFAULT_EXCLUDES = ['sat', 'sun', 'holiday']
DEFAULT_NAME = 'Workday Sensor'
ALLOWED_DAYS = WEEKDAYS + ['holiday']

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_COUNTRY): vol.In(ALL_COUNTRIES),
    vol.Optional(CONF_PROVINCE, default=None): cv.string,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Optional(CONF_WORKDAYS, default=DEFAULT_WORKDAYS):
        vol.All(cv.ensure_list, [vol.In(ALLOWED_DAYS)]),
    vol.Optional(CONF_EXCLUDES, default=DEFAULT_EXCLUDES):
        vol.All(cv.ensure_list, [vol.In(ALLOWED_DAYS)]),
})

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Workday sensor."""
    import holidays

    sensor_name = config.get(CONF_NAME)
    country = config.get(CONF_COUNTRY)
    province = config.get(CONF_PROVINCE)
    workdays = config.get(CONF_WORKDAYS)
    excludes = config.get(CONF_EXCLUDES)

    year = datetime.datetime.now().year
    obj_holidays = getattr(holidays, country)(years=year)

    if province:
        # 'state' and 'prov' are not interchangeable, so need to make
        # sure we use the right one
        if (hasattr(obj_holidays, "PROVINCES") and
                province in obj_holidays.PROVINCES):
            obj_holidays = getattr(holidays, country)(prov=province,
                                                      years=year)
        elif (hasattr(obj_holidays, "STATES") and
              province in obj_holidays.STATES):
            obj_holidays = getattr(holidays, country)(state=province,
                                                      years=year)
        else:
            _LOGGER.error("There is no province/state %s in country %s",
                          province, country)
            return False

    _LOGGER.debug("Found the following holidays for your configuration:")
    for date, name in sorted(obj_holidays.items()):
        _LOGGER.debug("%s %s", date, name)

    add_devices([IsWorkdaySensor(
        obj_holidays, workdays, excludes, sensor_name)], True)

def day_to_string(day):
    """Convert day index 0 - 7 to string."""
    try:
        return ALLOWED_DAYS[day]
    except IndexError:
        return None

class IsWorkdaySensor(BinarySensorDevice):
    """Implementation of a Workday sensor."""

    def __init__(self, obj_holidays, workdays, excludes, name):
        """Initialize the Workday sensor."""
        self._name = name
        self._obj_holidays = obj_holidays
        self._workdays = workdays
        self._excludes = excludes
        self._state = None

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def is_on(self):
        """Return the state of the device."""
        return self._state

    def is_include(self, day, now):
        """Check if given day is in the includes list."""
        if day in self._workdays:
            return True
        elif 'holiday' in self._workdays and now in self._obj_holidays:
            return True

        return False

    def is_exclude(self, day, now):
        """Check if given day is in the excludes list."""
        if day in self._excludes:
            return True
        elif 'holiday' in self._excludes and now in self._obj_holidays:
            return True

        return False

    @asyncio.coroutine
    def async_update(self):
        """Get date and look whether it is a holiday."""
        # Default is no workday
        self._state = False

        # Get iso day of the week (1 = Monday, 7 = Sunday)
        day = datetime.datetime.today().isoweekday() - 1
        day_of_week = day_to_string(day)

        if self.is_include(day_of_week, dt_util.now()):
            self._state = True

        if self.is_exclude(day_of_week, dt_util.now()):
            self._state = False


text:
FROM golang:1.9.0

RUN go get github.com/Masterminds/glide
RUN go get -u github.com/pressly/goose/cmd/goose

WORKDIR $GOPATH/src/github.com/Masterminds/glide

RUN make build
RUN glide -v


text:
from lib import *
import time

from lib.internal_py_lib.utils import setup_logging

import logging
log = logging.getLogger()

version = "1.4"

def main(cmd_options):
   options = ConfigOptions(cmd_options)
   options.add_setup_detail('Version',version)

   setup_logging(enable_debug=options.get_setup('debug'))

   #input
   pickle = options.get_setup('pickle')
   kdf_files_csv = options.get_setup('kdf_files')

   allow_missing_bin = options.get_setup('allow_missing_bin')
   if allow_missing_bin is None: allow_missing_bin=False

   kdf_files = []
   kdfdata = None
   if pickle is not None and os.path.exists(pickle):
      read_data = loadKdfDataPickle(pickle)

      if read_data is None or ('data' not in read_data or 'files' not in read_data):
         log.warn("%s exists, but failed to get data. Parsing KDFs again." % pickle)
         kdf_files = getKdfFiles(kdf_files_csv)
         read_data = getKdfData(kdf_files,allow_missing_bin=allow_missing_bin,pickle_file=pickle)

      kdfdata = read_data['data']
      kdf_files = read_data['files']

   elif kdf_files_csv is not None:
      kdf_files = getKdfFiles(kdf_files_csv)
      parsed_data = getKdfData(kdf_files,allow_missing_bin=allow_missing_bin,pickle_file=pickle)
      kdfdata = parsed_data['data']


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class com.google.flightmap.common.data.LatLngRect (Flight Map common)
</TITLE>

<META NAME="date" CONTENT="2011-02-02">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.google.flightmap.common.data.LatLngRect

Packages that use LatLngRect

com.google.flightmap.common.data

com.google.flightmap.common.db

com.google.flightmap.common.geo

Uses of LatLngRect in com.google.flightmap.common.data

Fields in com.google.flightmap.common.data declared as LatLngRect

 LatLngRect
AirspaceArc.boundingBox

          Bounding box of circle from which this arc is drawn.

Methods in com.google.flightmap.common.data that return LatLngRect

static LatLngRect
LatLngRect.getBoundingBox(LatLng center,
               int radius)

private static LatLngRect
LatLngRect.getRectOrNullIfEmpty(int lat1,
                     int lng1,
                     int lat2,
                     int lng2)

 LatLngRect
LatLngRect.intersect(LatLngRect that)

          Returns intersection of this and that.

Methods in com.google.flightmap.common.data that return types with arguments of type LatLngRect

 LinkedList<LatLngRect>
LatLngRect.remove(LatLngRect that)

          Returns relative complement of that in this.

Methods in com.google.flightmap.common.data with parameters of type LatLngRect

 void
LatLngRect.add(LatLngRect area)

          Grow rectangle to include this area.

 boolean
LatLngRect.contains(LatLngRect area)

 LatLngRect
LatLngRect.intersect(LatLngRect that)

          Returns intersection of this and that.

 LinkedList<LatLngRect>
LatLngRect.remove(LatLngRect that)

          Returns relative complement of that in this.

Constructors in com.google.flightmap.common.data with parameters of type LatLngRect

AirspaceArc(LatLngRect boundingBox,
            float startAngle,
            float sweepAngle)

Uses of LatLngRect in com.google.flightmap.common.db

Fields in com.google.flightmap.common.db declared as LatLngRect

private  LatLngRect
CachedAirportDirectory.cachedArea

          Latest cached area.

private  LatLngRect
CachedAviationDbAdapter.cachedArea

          Latest cached area.

private  LatLngRect
CachedAirportDirectory.inProgressArea

private  LatLngRect
CachedAviationDbAdapter.inProgressArea

Methods in com.google.flightmap.common.db with parameters of type LatLngRect

 Collection<Airport>
CachedAirportDirectory.getAirportsInRectangle(LatLngRect area,
                       int minRank)

 Collection<Airport>
CustomGridAirportDirectory.getAirportsInRectangle(LatLngRect area,
                       int minRank)

 Collection<Airport>
AirportDirectory.getAirportsInRectangle(LatLngRect area,
                       int minRank)

          Returns airports in area.

 Collection<Airspace>
CachedAviationDbAdapter.getAirspacesInRectangle(LatLngRect area)

 Collection<Airspace>
AviationDbAdapter.getAirspacesInRectangle(LatLngRect rect)

          Returns airspaces overlapping the given area.

(package private) static LinkedList<int[]>
CustomGridUtil.getCellsInRectangle(LatLngRect area)

          Returns set of cells that cover at least the given area.

 boolean
CachedAviationDbAdapter.isCacheMatch(LatLngRect area)

          Returns true if area will either 1) hit the
 cache, or 2) give the same results as the query that's in progress by
 CachedAviationDbAdapter.getAirspacesInRectangle(com.google.flightmap.common.data.LatLngRect).

 boolean
CachedAirportDirectory.isCacheMatch(LatLngRect area,
             int minRank)

          Returns true if area and minRank will either 1) hit the
 cache, or 2) give the same results as the query that's in progress by
 CachedAirportDirectory.getAirportsInRectangle(LatLngRect, int).

Uses of LatLngRect in com.google.flightmap.common.geo

Methods in com.google.flightmap.common.geo with parameters of type LatLngRect

static void
MercatorProjection.toRect(double zoom,
       LatLngRect rect,
       int[] points)

          Converts rect to a rectangle in Mercator pixel space.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>

#include <numeric>

#include "base/memory/ref_counted_memory.h"
#include "build/build_config.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/api/device_permissions_prompt.h"
#include "extensions/browser/api/usb/usb_api.h"
#include "extensions/shell/browser/shell_extensions_api_client.h"
#include "extensions/shell/test/shell_apitest.h"
#include "extensions/test/extension_test_message_listener.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "services/device/public/cpp/test/fake_usb_device_info.h"
#include "services/device/public/cpp/test/fake_usb_device_manager.h"
#include "services/device/public/cpp/test/mock_usb_mojo_device.h"
#include "services/device/public/mojom/usb_device.mojom.h"

using device::mojom::UsbControlTransferParams;
using device::mojom::UsbControlTransferRecipient;
using device::mojom::UsbControlTransferType;
using device::mojom::UsbIsochronousPacket;
using device::mojom::UsbOpenDeviceError;
using device::mojom::UsbTransferDirection;
using device::mojom::UsbTransferStatus;

using testing::_;
using testing::AnyNumber;
using testing::Invoke;
using testing::Return;
using testing::SaveArg;

namespace extensions {

namespace {
ACTION_TEMPLATE(InvokeCallback,
                HAS_1_TEMPLATE_PARAMS(int, k),
                AND_1_VALUE_PARAMS(p1)) {
  std::move(*std::get<k>(args)).Run(p1);
}

ACTION_TEMPLATE(BuildIsochronousTransferReturnValue,
                HAS_1_TEMPLATE_PARAMS(int, k),
                AND_2_VALUE_PARAMS(transferred_length, success_packets)) {
  const std::vector<uint32_t>& packet_lengths = std::get<k>(args);
  std::vector<UsbIsochronousPacket> packets(packet_lengths.size());
  for (size_t i = 0; i < packets.size(); ++i) {
    packets[i].length = packet_lengths[i];
    if (i < success_packets) {
      packets[i].transferred_length = transferred_length;
      packets[i].status = UsbTransferStatus::COMPLETED;
    } else {
      packets[i].transferred_length = 0;
      packets[i].status = UsbTransferStatus::TRANSFER_ERROR;
    }
  }
  return packets;
}

ACTION_P(SetConfiguration, fake_device) {
  fake_device->SetActiveConfig(arg0);
  std::move(*arg1).Run(true);
}

ACTION(InvokeClosureCallback) {
  std::move(*arg0).Run();
}

MATCHER_P(BufferSizeIs, size, "") {
  return arg.size() == size;
}

MATCHER_P(UsbControlTransferParamsEquals, expected, "") {
  return arg.Equals(expected);
}

class TestDevicePermissionsPrompt
    : public DevicePermissionsPrompt,
      public DevicePermissionsPrompt::Prompt::Observer {
 public:
  explicit TestDevicePermissionsPrompt(content::WebContents* web_contents)
      : DevicePermissionsPrompt(web_contents) {}

  void ShowDialog() override { prompt()->SetObserver(this); }

  void OnDevicesInitialized() override {
    for (size_t i = 0; i < prompt()->GetDeviceCount(); ++i) {
      prompt()->GrantDevicePermission(i);
      if (!prompt()->multiple()) {
        break;
      }
    }

    prompt()->Dismissed();
  }

  void OnDeviceAdded(size_t index, const std::u16string& device_name) override {
  }

  void OnDeviceRemoved(size_t index,
                       const std::u16string& device_name) override {}
};

class TestExtensionsAPIClient : public ShellExtensionsAPIClient {
 public:
  TestExtensionsAPIClient() : ShellExtensionsAPIClient() {}

  std::unique_ptr<DevicePermissionsPrompt> CreateDevicePermissionsPrompt(
      content::WebContents* web_contents) const override {
    return std::make_unique<TestDevicePermissionsPrompt>(web_contents);
  }

#if defined(OS_CHROMEOS)
  bool ShouldAllowDetachingUsb(int vid, int pid) const override {
    return vid == 1 && pid == 2;
  }
#endif  // defined(OS_CHROMEOS)
};

class UsbApiTest : public ShellApiTest {
 public:
  void SetUpOnMainThread() override {
    ShellApiTest::SetUpOnMainThread();

    // Set fake USB device manager for extensions::UsbDeviceManager.
    mojo::PendingRemote<device::mojom::UsbDeviceManager> usb_manager;
    fake_usb_manager_.AddReceiver(usb_manager.InitWithNewPipeAndPassReceiver());
    UsbDeviceManager::Get(browser_context())
        ->SetDeviceManagerForTesting(std::move(usb_manager));
    base::RunLoop().RunUntilIdle();

    std::vector<device::mojom::UsbConfigurationInfoPtr> configs;
    configs.push_back(
        device::FakeUsbDeviceInfo::CreateConfiguration(0xff, 0x00, 0x00, 1));
    configs.push_back(
        device::FakeUsbDeviceInfo::CreateConfiguration(0xff, 0x00, 0x00, 2));

    fake_device_ = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
        0, 0, "Test Manufacturer", "Test Device", "ABC123", std::move(configs));
    fake_usb_manager_.AddDevice(fake_device_);
    fake_usb_manager_.SetMockForDevice(fake_device_->guid(), &mock_device_);
    base::RunLoop().RunUntilIdle();
  }

 protected:
  void SetActiveConfigForFakeDevice(uint8_t config_value) {
    fake_device_->SetActiveConfig(config_value);
    UsbDeviceManager::Get(browser_context())
        ->UpdateActiveConfig(fake_device_->guid(), config_value);
  }

  device::FakeUsbDeviceManager fake_usb_manager_;
  scoped_refptr<device::FakeUsbDeviceInfo> fake_device_;
  device::MockUsbMojoDevice mock_device_;
};

}  // namespace

IN_PROC_BROWSER_TEST_F(UsbApiTest, DeviceHandling) {
  SetActiveConfigForFakeDevice(1);
  EXPECT_CALL(mock_device_, OpenInternal(_))
      .WillOnce(InvokeCallback<0>(UsbOpenDeviceError::OK))
      .WillOnce(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_, CloseInternal(_))
      .WillOnce(InvokeClosureCallback())
      .WillOnce(InvokeClosureCallback());
  ASSERT_TRUE(RunAppTest("api_test/usb/device_handling"));
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, ResetDevice) {
  EXPECT_CALL(mock_device_, OpenInternal(_))
      .WillOnce(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_, CloseInternal(_)).WillOnce(InvokeClosureCallback());

  EXPECT_CALL(mock_device_, ResetInternal(_))
      .WillOnce(InvokeCallback<0>(true))
      .WillOnce(InvokeCallback<0>(false));
  EXPECT_CALL(mock_device_,
              GenericTransferOutInternal(2, BufferSizeIs(1u), _, _))
      .WillOnce(InvokeCallback<3>(UsbTransferStatus::COMPLETED));
  ASSERT_TRUE(RunAppTest("api_test/usb/reset_device"));
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, SetConfiguration) {
  EXPECT_CALL(mock_device_, OpenInternal(_))
      .WillOnce(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_, CloseInternal(_)).WillOnce(InvokeClosureCallback());

  EXPECT_CALL(mock_device_, SetConfigurationInternal(1, _))
      .WillOnce(SetConfiguration(fake_device_.get()));

  ASSERT_TRUE(RunAppTest("api_test/usb/set_configuration"));
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, ListInterfaces) {
  SetActiveConfigForFakeDevice(1);
  EXPECT_CALL(mock_device_, OpenInternal(_))
      .WillOnce(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_, CloseInternal(_)).WillOnce(InvokeClosureCallback());
  ASSERT_TRUE(RunAppTest("api_test/usb/list_interfaces"));
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, TransferEvent) {
  auto expectedParams = UsbControlTransferParams::New();
  expectedParams->type = UsbControlTransferType::STANDARD;
  expectedParams->recipient = UsbControlTransferRecipient::DEVICE;
  expectedParams->request = 1;
  expectedParams->value = 2;
  expectedParams->index = 3;

  EXPECT_CALL(mock_device_, OpenInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_, ControlTransferOutInternal(
                                UsbControlTransferParamsEquals(*expectedParams),
                                BufferSizeIs(1u), _, _))
      .WillOnce(InvokeCallback<3>(UsbTransferStatus::COMPLETED));
  EXPECT_CALL(mock_device_,
              GenericTransferOutInternal(1, BufferSizeIs(1u), _, _))
      .WillOnce(InvokeCallback<3>(UsbTransferStatus::COMPLETED));
  EXPECT_CALL(mock_device_,
              GenericTransferOutInternal(2, BufferSizeIs(1u), _, _))
      .WillOnce(InvokeCallback<3>(UsbTransferStatus::COMPLETED));
  EXPECT_CALL(mock_device_, IsochronousTransferOutInternal(3, _, _, _))
      .WillOnce(BuildIsochronousTransferReturnValue<2>(1, 1u));
  EXPECT_CALL(mock_device_, CloseInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeClosureCallback());
  ASSERT_TRUE(RunAppTest("api_test/usb/transfer_event"));
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, ZeroLengthTransfer) {
  EXPECT_CALL(mock_device_, OpenInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_,
              GenericTransferOutInternal(_, BufferSizeIs(0u), _, _))
      .WillOnce(InvokeCallback<3>(UsbTransferStatus::COMPLETED));
  EXPECT_CALL(mock_device_, CloseInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeClosureCallback());
  ASSERT_TRUE(RunAppTest("api_test/usb/zero_length_transfer"));
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, TransferFailure) {
  EXPECT_CALL(mock_device_, OpenInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_, GenericTransferOutInternal(1, _, _, _))
      .WillOnce(InvokeCallback<3>(UsbTransferStatus::COMPLETED))
      .WillOnce(InvokeCallback<3>(UsbTransferStatus::TRANSFER_ERROR))
      .WillOnce(InvokeCallback<3>(UsbTransferStatus::TIMEOUT));
  EXPECT_CALL(mock_device_, IsochronousTransferInInternal(2, _, _))
      .WillOnce(BuildIsochronousTransferReturnValue<1>(8, 10u))
      .WillOnce(BuildIsochronousTransferReturnValue<1>(8, 5u));
  EXPECT_CALL(mock_device_, CloseInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeClosureCallback());
  ASSERT_TRUE(RunAppTest("api_test/usb/transfer_failure"));
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, InvalidLengthTransfer) {
  EXPECT_CALL(mock_device_, OpenInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_, CloseInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeClosureCallback());
  ASSERT_TRUE(RunAppTest("api_test/usb/invalid_length_transfer"));
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, InvalidTimeout) {
  EXPECT_CALL(mock_device_, OpenInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_, CloseInternal(_))
      .Times(AnyNumber())
      .WillRepeatedly(InvokeClosureCallback());
  ASSERT_TRUE(RunAppTest("api_test/usb/invalid_timeout"));
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, CallsAfterDisconnect) {
  ExtensionTestMessageListener ready_listener("ready", false);
  ExtensionTestMessageListener result_listener("success", false);
  result_listener.set_failure_message("failure");

  EXPECT_CALL(mock_device_, OpenInternal(_))
      .WillOnce(InvokeCallback<0>(UsbOpenDeviceError::OK));

  ASSERT_TRUE(LoadApp("api_test/usb/calls_after_disconnect"));
  ASSERT_TRUE(ready_listener.WaitUntilSatisfied());

  fake_usb_manager_.RemoveDevice(fake_device_);
  ASSERT_TRUE(result_listener.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, TransferFailureOnDisconnect) {
  ExtensionTestMessageListener ready_listener("ready", false);
  ExtensionTestMessageListener result_listener("success", false);
  result_listener.set_failure_message("failure");

  EXPECT_CALL(mock_device_, OpenInternal(_))
      .WillOnce(InvokeCallback<0>(UsbOpenDeviceError::OK));

  device::mojom::UsbDevice::GenericTransferInCallback saved_callback;
  EXPECT_CALL(mock_device_, GenericTransferInInternal(_, _, _, _))
      .WillOnce(
          [&saved_callback](
              uint8_t endpoint_number, uint32_t length, uint32_t timeout,
              device::MockUsbMojoDevice::GenericTransferInCallback* callback) {
            saved_callback = std::move(*callback);
          });

  ASSERT_TRUE(LoadApp("api_test/usb/transfer_failure_on_disconnect"));
  ASSERT_TRUE(ready_listener.WaitUntilSatisfied());

  fake_usb_manager_.RemoveDevice(fake_device_);
  ASSERT_TRUE(result_listener.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, OnDeviceAdded) {
  ExtensionTestMessageListener load_listener("loaded", false);
  ExtensionTestMessageListener result_listener("success", false);
  result_listener.set_failure_message("failure");

  ASSERT_TRUE(LoadApp("api_test/usb/add_event"));
  ASSERT_TRUE(load_listener.WaitUntilSatisfied());

  fake_usb_manager_.CreateAndAddDevice(0x18D1, 0x58F0);
  fake_usb_manager_.CreateAndAddDevice(0x18D1, 0x58F1);

  ASSERT_TRUE(result_listener.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, OnDeviceRemoved) {
  ExtensionTestMessageListener load_listener("loaded", false);
  ExtensionTestMessageListener result_listener("success", false);
  result_listener.set_failure_message("failure");

  ASSERT_TRUE(LoadApp("api_test/usb/remove_event"));
  ASSERT_TRUE(load_listener.WaitUntilSatisfied());

  fake_usb_manager_.RemoveDevice(fake_device_);
  ASSERT_TRUE(result_listener.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(UsbApiTest, GetUserSelectedDevices) {
  ExtensionTestMessageListener ready_listener("opened_device", false);
  ExtensionTestMessageListener result_listener("success", false);
  result_listener.set_failure_message("failure");

  EXPECT_CALL(mock_device_, OpenInternal(_))
      .WillOnce(InvokeCallback<0>(UsbOpenDeviceError::OK));
  EXPECT_CALL(mock_device_, CloseInternal(_)).WillOnce(InvokeClosureCallback());

  TestExtensionsAPIClient test_api_client;
  ASSERT_TRUE(LoadApp("api_test/usb/get_user_selected_devices"));
  ASSERT_TRUE(ready_listener.WaitUntilSatisfied());

  fake_usb_manager_.RemoveDevice(fake_device_);
  ASSERT_TRUE(result_listener.WaitUntilSatisfied());
}

#if defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(UsbApiTest, MassStorage) {
  ExtensionTestMessageListener ready_listener("ready", false);
  ready_listener.set_failure_message("failure");
  ExtensionTestMessageListener result_listener("success", false);
  result_listener.set_failure_message("failure");

  // Mass storage devices should be hidden unless allowed in policy.
  // The TestExtensionsAPIClient allows only vid=1, pid=2.
  TestExtensionsAPIClient test_api_client;
  std::vector<device::mojom::UsbConfigurationInfoPtr> storage_configs;
  auto storage_config = device::FakeUsbDeviceInfo::CreateConfiguration(
      /* mass storage */ 0x08, 0x06, 0x50);
  storage_configs.push_back(storage_config->Clone());
  device::mojom::UsbDeviceInfoPtr device_1 =
      fake_usb_manager_.CreateAndAddDevice(0x1, 0x2, 0x00,
                                           std::move(storage_configs));

  storage_configs.clear();
  storage_configs.push_back(storage_config->Clone());
  device::mojom::UsbDeviceInfoPtr device_2 =
      fake_usb_manager_.CreateAndAddDevice(0x5, 0x6, 0x00,
                                           std::move(storage_configs));

  ASSERT_TRUE(LoadApp("api_test/usb/mass_storage"));
  ASSERT_TRUE(ready_listener.WaitUntilSatisfied());

  fake_usb_manager_.RemoveDevice(device_2->guid);
  fake_usb_manager_.RemoveDevice(device_1->guid);

  ASSERT_TRUE(result_listener.WaitUntilSatisfied());
}
#endif  // defined(OS_CHROMEOS)

}  // namespace extensions


text:
% poolType = 'mean' or 'max'
% poolLayer = integer layer number after which we do the pooling
function layer = genNetworkTemporalConv2(para)
if isfield(para, 'LastActivation4MSE')==0
    para.LastActivation4MSE = 'linear';
end
inputDim = double(para.inputDim);

layer{1}.name = 'Input';        % this is an input layer
layer{end}.inputIdx = 1;    % specifies the index of GCC in Visible_tr
layer{end}.dim = [1 1]*inputDim;             % [input dim; output dim];

nFilter = para.nFilter;
for i=1:length(nFilter)
    layer{end+1}.name = 'tconv';
    layer{end}.prev = -1;
    layer{end}.W = []; % to be initialized randomly or by pretraining
    layer{end}.b = [];
    if i==1
        layer{end}.dim = [nFilter(i) inputDim*para.filterLen(i)];
    else
        layer{end}.dim = [nFilter(i) nFilter(i-1)*para.filterLen(i)];
    end
    layer{end}.update = 1;

    layer{end+1}.name = 'tmaxpool';
    layer{end}.context = para.poolingLen(i);
    layer{end}.stride = para.poolingStride(i);
    layer{end}.prev = -1;
    layer{end}.dim = [1 1]*nFilter(i);

    layer{end+1}.name = 'sigmoid';
    layer{end}.prev = -1;
    layer{end}.dim = [1 1]*nFilter(i);
end

layer2 = genNetworkFeedForward_v2(nFilter(end), para.hiddenLayerSizeFF, para.outputDim, para.costFn, para.LastActivation4MSE);

layer = [layer layer2(2:end)];

% automatically derive the list of layers that the output of the current layer goes.
for i=1:length(layer); layer{i}.next = []; end
for i=length(layer):-1:1
    if isfield(layer{i}, 'prev')
        for j=1:length(layer{i}.prev)
            layer{i+layer{i}.prev(j)}.next(end+1) = -layer{i}.prev(j);
        end
    end
end

end


text:
[![Build status](https://ci.appveyor.com/api/projects/status/c77k9ubitc25v2gv/branch/master?svg=true)](https://ci.appveyor.com/project/SimonWahlin/internetsettings/branch/master)

# InternetSettings

The **InternetSettings** module contains the **ZoneSite** resource, which adds or removes sites from zones for the current user in Internet Exporer Internet Settings.

## Installation

To install **InternetSettings** module

*   Unzip the content under $env:ProgramFiles\WindowsPowerShell\Modules folder

To confirm installation:

*   Run **Get-DSCResource** to see that **InternetSettings** is among the DSC Resources listed.

## Requirements

This module requires the latest version of PowerShell (v4.0, which ships in Windows 8.1 or Windows Server 2012R2).
To easily use PowerShell 4.0 on older operating systems, [install WMF 4.0](http://www.microsoft.com/en-us/download/details.aspx?id=40855).
Please read the installation instructions that are present on both the download page and the release notes for WMF 4.0.

## Description

The **InternetSettings** module contains the **ZoneSite** resource, which adds or removes sites from zones for the current user in Internet Exporer Internet Settings.

Adding the FQDN of a computer to the LocalIntranet Zone will allow running programs from a share on that computer using Start-Process even if the Execution Policy is set to RemoteSigned. This is useful when installing software using DSC resources.

## Details

**ZoneSite** resource has following properties:

* **Uri:** URI to be part of the Zone.

* **Ensure** Set if Uri is present or absent.
	Valid values are:

	* Present
	* Absent

* **Type** Set type of Uri.
	Valid values are:

	* *
	* file
	* ftp
	* http
	* https
	* knownfolder
	* ldap
	* news
	* nntp
	* oecmd
	* shell
	* snews

* **Zone**: Name of zone.
	Valid values are:

	* MyComputer
	* LocalIntranet
	* TrustedSite
	* Internet
	* Restricted

* **Platform**: Add Uri for 32-bit, 64-bit or All platforms.
	Valid values are:

	* x86
	* x64
	* All

## Versions

### 1.0.0.0

*   Initial release with the following resources
    * ZoneSite

## Examples

Add server.contoso.com to LocalIntranet to be able to install a software from the share \\server01.contoso.com\share when Execution Policy is set to RemoteSigned.

```powershell
Configuration TrustServer01
{
    Import-DscResource -Module InternetSettings
    ZoneSite Source
    {
        Ensure = 'Present'
        Uri = 'server01.contoso.com'
        Type = '*'
        Zone = 'LocalIntranet'
        Platform = 'All'
    }
}
```


text:
   #include <boost/assert.hpp>
   #define BOOST_INTRUSIVE_INVARIANT_ASSERT BOOST_ASSERT
#elif defined(BOOST_INTRUSIVE_INVARIANT_ASSERT_INCLUDE)
   #include BOOST_INTRUSIVE_INVARIANT_ASSERT_INCLUDE
#endif

#if !defined(BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT)
   #include <boost/assert.hpp>
   #define BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT BOOST_ASSERT
#elif defined(BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT_INCLUDE)
   #include BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT_INCLUDE
#endif

#if !defined(BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT)
   #include <boost/assert.hpp>
   #define BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT BOOST_ASSERT
#elif defined(BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT_INCLUDE)
   #include BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT_INCLUDE
#endif

#endif //BOOST_INTRUSIVE_DETAIL_ASSERT_HPP


text:
#ifndef __ASM_SIBYTE_TRACE_PROF_H
#define __ASM_SIBYTE_TRACE_PROF_H

#undef DBG
#if SBPROF_TB_DEBUG
#define DBG(a) a
#else
#define DBG(a)
#endif

#define SBPROF_TB_MAJOR 240
#define DEVNAME "bcm1250_tbprof"

typedef u_int64_t tb_sample_t[6*256];

struct sbprof_tb {
	int          open;
	tb_sample_t *sbprof_tbbuf;
	int          next_tb_sample;

	volatile int tb_enable;
	volatile int tb_armed;

	wait_queue_head_t tb_sync;
	wait_queue_head_t tb_read;
};

#define MAX_SAMPLE_BYTES (24*1024*1024)
#define MAX_TBSAMPLE_BYTES (12*1024*1024)

#define MAX_SAMPLES (MAX_SAMPLE_BYTES/sizeof(u_int32_t))
#define TB_SAMPLE_SIZE (sizeof(tb_sample_t))
#define MAX_TB_SAMPLES (MAX_TBSAMPLE_BYTES/TB_SAMPLE_SIZE)

/* IOCTLs */
#define SBPROF_ZBSTART		_IOW('s', 0, int)
#define SBPROF_ZBSTOP		_IOW('s', 1, int)
#define SBPROF_ZBWAITFULL	_IOW('s', 2, int)

/***************************************************************************
 * Routines for gathering ZBbus profiles using trace buffer
 ***************************************************************************/

/* Requires: Already called zclk_timer_init with a value that won't
	     saturate 40 bits.  No subsequent use of SCD performance counters
	     or trace buffer.
   Effect:   Starts gathering random ZBbus profiles using trace buffer. */
extern int sbprof_zbprof_start(struct file *filp);

/* Effect: Stops collection of ZBbus profiles */
extern int sbprof_zbprof_stop(void);

/***************************************************************************
 * Routines for using 40-bit SCD cycle counter
 *
 * Client responsible for either handling interrupts or making sure
 * the cycles counter never saturates, e.g., by doing
 * zclk_timer_init(0) at least every 2^40 - 1 ZCLKs.
 ***************************************************************************/

/* Configures SCD counter 0 to count ZCLKs starting from val;
   Configures SCD counters1,2,3 to count nothing.
   Must not be called while gathering ZBbus profiles.

unsigned long long val; */
#define zclk_timer_init(val) \
  __asm__ __volatile__ (".set push;" \
			".set mips64;" \
			"la   $8, 0xb00204c0;" /* SCD perf_cnt_cfg */ \
			"sd   %0, 0x10($8);"   /* write val to counter0 */ \
			"sd   %1, 0($8);"      /* config counter0 for zclks*/ \
			".set pop" \
			: /* no outputs */ \
						     /* enable, counter0 */ \
			: /* inputs */ "r"(val), "r" ((1ULL << 33) | 1ULL) \
			: /* modifies */ "$8" )

/* Reads SCD counter 0 and puts result in value
   unsigned long long val; */
#define zclk_get(val) \
  __asm__ __volatile__ (".set push;" \
			".set mips64;" \
			"la   $8, 0xb00204c0;" /* SCD perf_cnt_cfg */ \
			"ld   %0, 0x10($8);"   /* write val to counter0 */ \
			".set pop" \
			: /* outputs */ "=r"(val) \
			: /* inputs */ \
			: /* modifies */ "$8" )

#endif /* __ASM_SIBYTE_TRACE_PROF_H */


text:
**TBD**

## Build
*Requires CMake*
### Release
Run

    mkdir build
    cd build
    cmake ..
    make

to build release version of shared library.

### Debug
Replace

    cmake ..

with

    cmake -DCMAKE_BUILD_TYPE=Debug

to build debug version.

### Documentation
*Requires Doxygen and Graphviz (dot util)*.
Replace

    make

with

    make doc-libcppmisc

to build html documentation inside build directory.

## Usage
Please refer to `examples` directory to find some use-cases.

### Build
Add `-DBUILD_EXAMPLES=1` to `cmake` command to build examples also.

## License
Licensed under the terms of BSD New License. Copy of license
may be found in LICENSE file.

© Ilya Arefiev <arefiev.id@gmail.com>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>firesimulator Class Hierarchy</title>
<meta name="date" content="2013-12-16">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package firesimulator

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

rescuecore2.components.AbstractComponent<T> (implements rescuecore2.components.Component)

rescuecore2.components.AbstractSimulator<T> (implements rescuecore2.components.Simulator)

rescuecore2.standard.components.StandardSimulator

firesimulator.FireSimulatorWrapper

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes