text:
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using FluentAssertions;
using Microsoft.Build.Construction;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SonarScanner.MSBuild.Common;
using TestUtilities;

namespace SonarScanner.MSBuild.Tasks.IntegrationTests.TargetsTests
{
    [TestClass]
    public class RoslynTargetsTests
    {
        private const string RoslynAnalysisResultsSettingName = "sonar.cs.roslyn.reportFilePath";
        private const string AnalyzerWorkDirectoryResultsSettingName = "sonar.cs.analyzer.projectOutPath";
        private const string ErrorLogFilePattern = "{0}.RoslynCA.json";

        public TestContext TestContext { get; set; }

        #region SetRoslynSettingsTarget tests

        [TestMethod]
        [Description("Checks the happy path i.e. settings exist in config, no reason to exclude the project")]
        public void Roslyn_Settings_ValidSetup()
        {
            // Arrange

            // Set the config directory so the targets know where to look for the analysis config file
            var confDir = TestUtils.CreateTestSpecificFolder(TestContext, "config");

            // Create a valid config file containing analyzer settings
            var expectedAssemblies = new string[] { "c:\\data\\config.analyzer1.dll", "c:\\config2.dll" };
            var analyzerAdditionalFiles = new string[] { "c:\\config.1.txt", "c:\\config.2.txt" };

            var config = new AnalysisConfig();

            var analyzerSettings = new AnalyzerSettings
            {
                Language = "cs",
                RuleSetFilePath = "d:\\my.ruleset",
                AnalyzerAssemblyPaths = expectedAssemblies.ToList(),
                AdditionalFilePaths = analyzerAdditionalFiles.ToList()
            };
            config.AnalyzersSettings = new List<AnalyzerSettings>
            {
                analyzerSettings
            };

            var configFilePath = Path.Combine(confDir, FileConstants.ConfigFileName);
            config.Save(configFilePath);

            // Create the project
            var properties = new WellKnownProjectProperties
            {
                SonarQubeConfigPath = confDir,
                ResolvedCodeAnalysisRuleset = "c:\\should.be.overridden.ruleset"
            };

            var projectRoot = CreateValidProjectSetup(properties);

            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "should.be.removed.analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\should.be.removed.analyzer2.dll");

            var notRemovedAdditionalFiles = new string[] { "should.not.be.removed.additional1.txt", "should.not.be.removed.additional2.txt" };

            foreach (var notRemovedAdditionalFile in notRemovedAdditionalFiles)
            {
                projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, notRemovedAdditionalFile);
            }

            projectRoot.Save(); // re-save the modified project

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                TargetConstants.OverrideRoslynAnalysisTarget);

            var projectSpecificConfFilePath = result.GetCapturedPropertyValue(TargetProperties.ProjectConfFilePath);
            var expectedRoslynAdditionalFiles = new string[] { projectSpecificConfFilePath }
                .Concat(analyzerAdditionalFiles)
                .Concat(notRemovedAdditionalFiles)
                .ToArray();

            // Assert
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertExpectedResolvedRuleset(result, "d:\\my.ruleset");
            AssertExpectedItemValuesExists(result, TargetProperties.AdditionalFilesItemType, expectedRoslynAdditionalFiles);
            AssertExpectedItemValuesExists(result, TargetProperties.AnalyzerItemType, expectedAssemblies);

            AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }

        [TestMethod]
        [Description("Checks the happy path i.e. settings exist in config, no reason to exclude the project")]
        public void Roslyn_Settings_ValidSetup_Override_AdditionalFiles()
        {
            // Arrange

            // Set the config directory so the targets know where to look for the analysis config file
            var confDir = TestUtils.CreateTestSpecificFolder(TestContext, "config");

            // Create a valid config file containing analyzer settings
            var expectedAssemblies = new string[] { "c:\\data\\config.analyzer1.dll", "c:\\config2.dll" };
            var analyzer1ExpectedFileName = "config.1.txt";
            var analyzerAdditionalFiles = new string[] { "c:\\" + analyzer1ExpectedFileName, "c:\\config.2.txt" };

            var config = new AnalysisConfig();

            var analyzerSettings = new AnalyzerSettings
            {
                Language = "cs",
                RuleSetFilePath = "d:\\my.ruleset",
                AnalyzerAssemblyPaths = expectedAssemblies.ToList(),
                AdditionalFilePaths = analyzerAdditionalFiles.ToList()
            };
            config.AnalyzersSettings = new List<AnalyzerSettings>
            {
                analyzerSettings
            };

            var configFilePath = Path.Combine(confDir, FileConstants.ConfigFileName);
            config.Save(configFilePath);

            // Create the project
            var properties = new WellKnownProjectProperties
            {
                SonarQubeConfigPath = confDir,
                ResolvedCodeAnalysisRuleset = "c:\\should.be.overridden.ruleset"
            };

            var projectRoot = CreateValidProjectSetup(properties);

            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "should.be.removed.analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\should.be.removed.analyzer2.dll");

            var notRemovedAdditionalFiles = new string[] { "should.not.be.removed.additional1.txt", "should.not.be.removed.additional2.txt" };

            foreach (var notRemovedAdditionalFile in notRemovedAdditionalFiles)
            {
                projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, notRemovedAdditionalFile);
            }

            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, "DummyPath\\" + analyzer1ExpectedFileName.ToUpperInvariant());

            projectRoot.Save(); // re-save the modified file

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath, TargetConstants.OverrideRoslynAnalysisTarget);

            var projectSpecificConfFilePath = result.GetCapturedPropertyValue(TargetProperties.ProjectConfFilePath);
            var expectedRoslynAdditionalFiles = new string[] { projectSpecificConfFilePath }
                .Concat(analyzerAdditionalFiles)
                .Concat(notRemovedAdditionalFiles)
                .ToArray();

            // Assert
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertExpectedResolvedRuleset(result, "d:\\my.ruleset");
            AssertExpectedItemValuesExists(result, TargetProperties.AdditionalFilesItemType, expectedRoslynAdditionalFiles);
            AssertExpectedItemValuesExists(result, TargetProperties.AnalyzerItemType, expectedAssemblies);

            AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }

        [TestMethod]
        [Description("Checks that a config file with no analyzer settings does not cause an issue")]
        public void Roslyn_Settings_SettingsMissing_NoError()
        {
            // Arrange

            // Set the config directory so the targets know where to look for the analysis config file
            var confDir = TestUtils.CreateTestSpecificFolder(TestContext, "config");

            // Create a valid config file that does not contain analyzer settings
            var config = new AnalysisConfig();
            var configFilePath = Path.Combine(confDir, FileConstants.ConfigFileName);
            config.Save(configFilePath);

            // Create the project
            var properties = new WellKnownProjectProperties
            {
                SonarQubeConfigPath = confDir,
                ResolvedCodeAnalysisRuleset = "c:\\should.be.overridden.ruleset"
            };

            var projectRoot = CreateValidProjectSetup(properties);

            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "should.be.removed.analyzer1.dll");
            const string additionalFileName = "should.not.be.removed.additional1.txt";
            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, additionalFileName);

            projectRoot.Save(); // re-save the modified project

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath, TargetConstants.OverrideRoslynAnalysisTarget);

            var projectSpecificConfFilePath = result.GetCapturedPropertyValue(TargetProperties.ProjectConfFilePath);

            var expectedRoslynAdditionalFiles = new string[] {
                projectSpecificConfFilePath,
                additionalFileName /* additional files are not removed any longer */
            };

            // Assert
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertExpectedResolvedRuleset(result, string.Empty);
            result.AssertExpectedItemGroupCount(TargetProperties.AnalyzerItemType, 0);
            AssertExpectedItemValuesExists(result, TargetProperties.AdditionalFilesItemType, expectedRoslynAdditionalFiles);
        }

        [TestMethod]
        [Description("Checks the target is not executed if the temp folder is not set")]
        public void Roslyn_Settings_TempFolderIsNotSet()
        {
            // Arrange

            var properties = new WellKnownProjectProperties
            {
                ErrorLog = "pre-existing.log",
                ResolvedCodeAnalysisRuleset = "pre-existing.ruleset",
                WarningsAsErrors = "CS101",
                TreatWarningsAsErrors = "true"
            };

            var projectRoot = CreateValidProjectSetup(properties);
            projectRoot.AddProperty(TargetProperties.SonarQubeTempPath, string.Empty); // needs to overwritten once the valid project has been created

            projectRoot.Save(); // re-save the modified project

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            result.AssertTargetNotExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetNotExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);

            // Existing properties should not be changed
            AssertExpectedErrorLog(result, "pre-existing.log");
            AssertExpectedResolvedRuleset(result, "pre-existing.ruleset");
            result.AssertExpectedItemGroupCount(TargetProperties.AnalyzerItemType, 0);
            result.AssertExpectedItemGroupCount(TargetProperties.AdditionalFilesItemType, 0);

            result.AssertExpectedCapturedPropertyValue(TargetProperties.TreatWarningsAsErrors, "true");
            result.AssertExpectedCapturedPropertyValue(TargetProperties.WarningsAsErrors, "CS101");
        }

        [TestMethod]
        [Description("Checks an existing errorLog value is used if set")]
        public void Roslyn_Settings_ErrorLogAlreadySet()
        {
            // Arrange
            var properties = new WellKnownProjectProperties
            {
                [TargetProperties.ErrorLog] = "already.set.txt"
            };

            var projectRoot = CreateValidProjectSetup(properties);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            result.AssertExpectedCapturedPropertyValue(TargetProperties.ErrorLog, "already.set.txt");
        }

        [TestMethod]
        [Description("Checks the code analysis properties are cleared for test projects")]
        public void Roslyn_Settings_NotRunForTestProject()
        {
            // Arrange
            var properties = new WellKnownProjectProperties
            {
                ProjectTypeGuids = TargetConstants.MsTestProjectTypeGuid // mark the project as a test project
            };

            var projectRoot = CreateValidProjectSetup(properties);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetNotExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            AssertCodeAnalysisIsDisabled(result, string.Empty);
        }

        [TestMethod]
        [Description("Checks the code analysis properties are cleared for excludedprojects")]
        public void Roslyn_Settings_NotRunForExcludedProject()
        {
            // Arrange
            var properties = new WellKnownProjectProperties
            {
                SonarQubeExclude = "TRUE", // mark the project as excluded
                ResolvedCodeAnalysisRuleset = "Dummy value"
            };

            var projectRoot = CreateValidProjectSetup(properties);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetNotExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            AssertCodeAnalysisIsDisabled(result, properties.ResolvedCodeAnalysisRuleset);
        }

        #endregion SetRoslynSettingsTarget tests

        #region AddAnalysisResults tests

        [TestMethod]
        [Description("Checks the target is not executed if the temp folder is not set")]
        public void Roslyn_SetResults_TempFolderIsNotSet()
        {
            // Arrange
            var rootInputFolder = TestUtils.CreateTestSpecificFolder(TestContext, "Inputs");

            var properties = new WellKnownProjectProperties
            {
                SonarQubeTempPath = ""
            };

            var projectRoot = BuildUtilities.CreateValidProjectRoot(TestContext, rootInputFolder, properties);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                TargetConstants.SetRoslynResultsTarget);

            // Assert
            result.AssertTargetNotExecuted(TargetConstants.SetRoslynResultsTarget);
        }

        [TestMethod]
        [Description("Checks the analysis setting is not set if the results file does not exist")]
        public void Roslyn_SetResults_ResultsFileDoesNotExist()
        {
            // Arrange
            var rootInputFolder = TestUtils.CreateTestSpecificFolder(TestContext, "Inputs");

            var properties = new WellKnownProjectProperties
            {
                SonarQubeTempPath = rootInputFolder
            };

            var projectRoot = BuildUtilities.CreateValidProjectRoot(TestContext, rootInputFolder, properties);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath, TargetConstants.SetRoslynResultsTarget);

            // Assert
            result.AssertTargetExecuted(TargetConstants.SetRoslynResultsTarget);
            AssertAnalysisSettingDoesNotExist(result, RoslynAnalysisResultsSettingName);
        }

        [TestMethod]
        [Description("Checks the analysis setting is set if the result file exists")]
        public void Roslyn_SetResults_ResultsFileExists()
        {
            // Arrange
            var rootInputFolder = TestUtils.CreateTestSpecificFolder(TestContext, "Inputs");

            var resultsFile = TestUtils.CreateTextFile(rootInputFolder, "error.report.txt", "dummy report content");

            var properties = new WellKnownProjectProperties
            {
                SonarQubeTempPath = rootInputFolder
            };
            properties[TargetProperties.ErrorLog] = resultsFile;

            var projectRoot = BuildUtilities.CreateValidProjectRoot(TestContext, rootInputFolder, properties);
            AddCaptureTargetsImport(rootInputFolder, projectRoot);
            projectRoot.Save();

            // Act
            var result = BuildRunner.BuildTargets(TestContext,
                projectRoot.FullPath,
                TargetConstants.CreateProjectSpecificDirs, TargetConstants.SetRoslynResultsTarget);

            var projectSpecificOutDir = result.GetCapturedPropertyValue(TargetProperties.ProjectSpecificOutDir);

            // Assert
            result.AssertTargetExecuted(TargetConstants.CreateProjectSpecificDirs);
            result.AssertTargetExecuted(TargetConstants.SetRoslynResultsTarget);
            AssertExpectedAnalysisSetting(result, RoslynAnalysisResultsSettingName, resultsFile);
            AssertExpectedAnalysisSetting(result, AnalyzerWorkDirectoryResultsSettingName, projectSpecificOutDir);
        }

        #endregion AddAnalysisResults tests

        #region Combined tests

        [TestMethod]
        [Description("Checks the targets are executed in the expected order")]
        public void Roslyn_TargetExecutionOrder()
        {
            // Arrange
            var rootInputFolder = TestUtils.CreateTestSpecificFolder(TestContext, "Inputs");
            var rootOutputFolder = TestUtils.CreateTestSpecificFolder(TestContext, "Outputs");

            var properties = new WellKnownProjectProperties
            {
                SonarQubeTempPath = rootInputFolder,
                SonarQubeOutputPath = rootInputFolder,
                SonarQubeConfigPath = rootOutputFolder
            };

            var projectRoot = BuildUtilities.CreateValidProjectRoot(TestContext, rootInputFolder, properties);

            // Add some settings we expect to be ignored
            AddAnalysisSetting("sonar.other.setting", "other value", projectRoot);
            projectRoot.Save();

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath, TargetConstants.DefaultBuildTarget);

            // Assert
            // Checks that should succeed irrespective of the MSBuild version
            result.AssertTargetSucceeded(TargetConstants.DefaultBuildTarget);
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);

            result.AssertExpectedTargetOrdering(
                TargetConstants.ResolveCodeAnalysisRuleSet,
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.OverrideRoslynAnalysisTarget,
                TargetConstants.SetRoslynAnalysisPropertiesTarget,
                TargetConstants.CoreCompile,
                TargetConstants.DefaultBuildTarget,
                TargetConstants.SetRoslynResultsTarget,
                TargetConstants.WriteProjectDataTarget);
        }

        #endregion Combined tests

        #region Private methods

        private static void AddAnalysisSetting(string name, string value, ProjectRootElement project)
        {
            var element = project.AddItem(BuildTaskConstants.SettingItemName, name);
            element.AddMetadata(BuildTaskConstants.SettingValueMetadataName, value);
        }

        #endregion Private methods

        #region Checks

        private static void AssertCodeAnalysisIsDisabled(BuildLog result, string expectedResolvedCodeAnalysisRuleset)
        {
            // Check the ruleset and error log are not set
            AssertExpectedErrorLog(result, string.Empty);
            AssertExpectedResolvedRuleset(result, expectedResolvedCodeAnalysisRuleset);
        }

        /// <summary>
        /// Checks the error log property has been set to the value supplied in the targets file
        /// </summary>
        private static void AssertErrorLogIsSetBySonarQubeTargets(BuildLog result)
        {
            var targetDir = result.GetCapturedPropertyValue(TargetProperties.TargetDir);
            var targetFileName = result.GetCapturedPropertyValue(TargetProperties.TargetFileName);

            var expectedErrorLog = Path.Combine(targetDir, string.Format(CultureInfo.InvariantCulture, ErrorLogFilePattern, targetFileName));

            AssertExpectedErrorLog(result, expectedErrorLog);
        }

        private static void AssertExpectedErrorLog(BuildLog result, string expectedErrorLog)
        {
            result.AssertExpectedCapturedPropertyValue(TargetProperties.ErrorLog, expectedErrorLog);
        }

        private static void AssertExpectedResolvedRuleset(BuildLog result, string expectedResolvedRuleset)
        {
            result.AssertExpectedCapturedPropertyValue(TargetProperties.ResolvedCodeAnalysisRuleset, expectedResolvedRuleset);
        }

        private void AssertExpectedItemValuesExists(BuildLog result, string itemType, params string[] expectedValues)
        {
            DumpLists(result, itemType, expectedValues);
            foreach (var expectedValue in expectedValues)
            {
                result.AssertSingleItemExists(itemType, expectedValue);
            }
            result.AssertExpectedItemGroupCount(itemType, expectedValues.Length);
        }

        private void DumpLists(BuildLog actualResult, string itemType, string[] expected)
        {
            TestContext.WriteLine("");
            TestContext.WriteLine("Dumping <" + itemType + "> list: expected");
            foreach (var item in expected)
            {
                TestContext.WriteLine("\t{0}", item);
            }
            TestContext.WriteLine("");

            TestContext.WriteLine("");
            TestContext.WriteLine("Dumping <" + itemType + "> list: actual");
            foreach (var item in actualResult.GetCapturedItemValues(itemType))
            {
                TestContext.WriteLine("\t{0}", item);
            }
            TestContext.WriteLine("");
        }

        /// <summary>
        /// Checks that no analysis warnings will be treated as errors nor will they be ignored
        /// </summary>
        private static void AssertWarningsAreNotTreatedAsErrorsNorIgnored(BuildLog actualResult)
        {
            actualResult.AssertExpectedCapturedPropertyValue(TargetProperties.TreatWarningsAsErrors, "false");
            actualResult.AssertExpectedCapturedPropertyValue(TargetProperties.WarningsAsErrors, "");
            actualResult.AssertExpectedCapturedPropertyValue(TargetProperties.WarningLevel, "4");
        }

        /// <summary>
        /// Checks that a SonarQubeSetting does not exist
        /// </summary>
        private static void AssertAnalysisSettingDoesNotExist(BuildLog actualResult, string settingName)
        {
            var matches = actualResult.GetCapturedItemValues(BuildTaskConstants.SettingItemName);

            matches.Should().BeEmpty("Not expected SonarQubeSetting with include value of '{0}' to exist. Actual occurrences: {1}", settingName, matches.Count());
        }

        /// <summary>
        /// Checks whether there is a single "SonarQubeSetting" item with the expected name and setting value
        /// </summary>
        private static void AssertExpectedAnalysisSetting(BuildLog actualResult, string settingName, string expectedValue)
        {
            /* The equivalent XML would look like this:
            <ItemGroup>
              <SonarQubeSetting Include="settingName">
                <Value>expectedValue</Value
              </SonarQubeSetting>
            </ItemGroup>
            */

            var settings = actualResult.GetCapturedItemValues(BuildTaskConstants.SettingItemName);
            settings.Any().Should().BeTrue();

            var matches = settings.Where(v => v.Value.Equals(settingName, System.StringComparison.Ordinal)).ToList();
            matches.Should().HaveCount(1, $"Only one and only expecting one SonarQubeSetting with include value of '{0}' to exist. Count: {matches.Count}", settingName);

            var item = matches[0];
            var value = item.Metadata.SingleOrDefault(v => v.Name.Equals(BuildTaskConstants.SettingValueMetadataName));

            value.Should().NotBeNull();
            value.Value.Should().Be(expectedValue, "SonarQubeSetting with include value '{0}' does not have the expected value", settingName);
        }

        #endregion Checks

        #region Setup

        /// <summary>
        /// Creates a valid project with the necessary ruleset and assembly files on disc
        /// to successfully run the "OverrideRoslynCodeAnalysisProperties" target
        /// </summary>
        private ProjectRootElement CreateValidProjectSetup(WellKnownProjectProperties properties)
        {
            var sqTempFolder = TestUtils.EnsureTestSpecificFolder(TestContext);

            var projectProperties = properties ?? new WellKnownProjectProperties();
            var projectFolder = TestUtils.CreateTestSpecificFolder(TestContext, "Project");

            projectProperties.SonarQubeTempPath = sqTempFolder;
            projectProperties[TargetProperties.Language] = "C#";

            var projectRoot = BuildUtilities.CreateValidProjectRoot(TestContext, projectFolder, projectProperties);

            AddCaptureTargetsImport(projectFolder, projectRoot);

            var projectFilePath = Path.Combine(projectFolder, "valid.project.proj");
            projectRoot.Save(projectFilePath);
            return projectRoot;
        }

        private void AddCaptureTargetsImport(string projectFolder, ProjectRootElement projectRoot)
        {
            // Add an additional import that will dump data we are interested in to the build log
            var captureTargetsFilePath = CreateCaptureDataTargetsFile(projectFolder);
            projectRoot.AddImport(captureTargetsFilePath);

            var projectFilePath = Path.Combine(projectFolder, "valid.project.proj");
            projectRoot.Save(projectFilePath);
        }

        private string CreateCaptureDataTargetsFile(string directory)
        {
            // Most of the tests above want to check the value of build property
            // or item group after a target has been executed. However, this
            // information is not available through the buildlogger interface.
            // So, we'll add a special target that writes the properties/items
            // we are interested in to the message log.
            // The SimpleXmlLogger has special handling to extract the data
            // from the message and add it to the BuildLog.

            // Make sure that the target is run after all of the targets
            // used by the any of the tests.
            string afterTargets = string.Join(";",
                TargetConstants.SetRoslynResultsTarget,
                TargetConstants.OverrideRoslynAnalysisTarget,
                TargetConstants.SetRoslynAnalysisPropertiesTarget
                );

            string xml = $@"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='15.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <Target Name='CaptureValues' AfterTargets='{afterTargets}'>
    <Message Importance='high' Text='CAPTURE::PROPERTY::TargetDir::$(TargetDir)' />
    <Message Importance='high' Text='CAPTURE::PROPERTY::TargetFileName::$(TargetFileName)' />
    <Message Importance='high' Text='CAPTURE::PROPERTY::ErrorLog::$(ErrorLog)' />
    <Message Importance='high' Text='CAPTURE::PROPERTY::ProjectConfFilePath::$(ProjectConfFilePath)' />
    <Message Importance='high' Text='CAPTURE::PROPERTY::ResolvedCodeAnalysisRuleSet::$(ResolvedCodeAnalysisRuleSet)' />
    <Message Importance='high' Text='CAPTURE::PROPERTY::TreatWarningsAsErrors::$(TreatWarningsAsErrors)' />
    <Message Importance='high' Text='CAPTURE::PROPERTY::WarningsAsErrors::$(WarningsAsErrors)' />
    <Message Importance='high' Text='CAPTURE::PROPERTY::WarningLevel::$(WarningLevel)' />
    <Message Importance='high' Text='CAPTURE::PROPERTY::ProjectSpecificOutDir::$(ProjectSpecificOutDir)' />

    <!-- Item group values will be written out one per line -->
    <Message Importance='high' Text='CAPTURE::ITEM::AdditionalFiles::%(AdditionalFiles.Identity)' Condition="" @(AdditionalFiles) != '' ""/>
    <Message Importance='high' Text='CAPTURE::ITEM::Analyzer::%(Analyzer.Identity)'  Condition="" @(Analyzer) != '' "" />

    <!-- For the SonarQubeSetting items, we also want to capture the Value metadata item -->
    <Message Importance='high' Text='CAPTURE::ITEM::SonarQubeSetting::%(SonarQubeSetting.Identity)::Value::%(SonarQubeSetting.Value)'  Condition="" @(SonarQubeSetting) != '' "" />
  </Target>
</Project>";

            // We're using :: as a separator here: replace it with whatever
            // whatever the logger is using as a separator
            xml = xml.Replace("::", SimpleXmlLogger.CapturedDataSeparator);

            var filePath = Path.Combine(directory, "Capture.targets");
            File.WriteAllText(filePath, xml);
            TestContext.AddResultFile(filePath);
            return filePath;
        }

        #endregion Setup
    }
}


text:
require File.expand_path('test_helper', File.dirname(__FILE__))

class TestParamProtection < ActionController::TestCase

  class BaseController < ActionController::Base
    class << self
      attr_accessor :last_parameters
    end

    def index
      self.class.last_parameters = request.params.except(:controller, :action)
      render :nothing => true
    end
  end

  class ParamsProtectedController < BaseController
    params_protected :framework
  end

  test "should remove protected parameter" do
    params = {:user => 'slawosz',:framework => 'rails',:lang => 'ruby'}

    result = _process(ParamsProtectedController, params)

    assert_equal ({:user => 'slawosz',:lang => 'ruby'}), result
  end

  class ParamsAccessibleController < BaseController
    params_accessible :framework
  end

  test "should preserve allowed parameter" do
    params = {:user => 'slawosz',:framework => 'rails',:lang => 'ruby'}

    result = _process(ParamsAccessibleController, params)

    assert_equal ({:framework => 'rails'}), result
  end

  class FooAllowedController < BaseController
    params_accessible :framework
  end

  class BarAllowedController < FooAllowedController
    params_accessible :user
  end

  test "remember accessible parameters from superclass" do
    params = {:user => 'slawosz',:framework => 'rails',:lang => 'ruby'}

    result = _process(BarAllowedController, params)

    assert_equal ({:framework => 'rails', :user => 'slawosz'}), result
  end

  class MultipleAllowedParamsDefinitionsController < BaseController
    params_accessible :framework
    params_accessible :user
  end

  test "use parameters from each declaration" do
    params = {:user => 'slawosz',:framework => 'rails',:lang => 'ruby'}

    result = _process(MultipleAllowedParamsDefinitionsController, params)

    assert_equal ({:framework => 'rails', :user => 'slawosz'}), result
  end

  class FooProtectedController < BaseController
    params_protected :framework
  end

  class BarProtectedController < FooProtectedController
    params_protected :user
  end

  test "remember protected parameters from superclass" do
    params = {:user => 'slawosz',:framework => 'rails',:lang => 'ruby'}

    result = _process(BarProtectedController, params)

    assert_equal ({:lang => 'ruby'}), result
  end

  class MultipleProtectedParamsDefinitionsController < BaseController
    params_protected :framework
    params_protected :user
  end

  test "protect parameters from each declaration" do
    params = {:user => 'slawosz',:framework => 'rails',:lang => 'ruby'}

    result = _process(MultipleProtectedParamsDefinitionsController, params)

    assert_equal ({:lang => 'ruby'}), result
  end

  class TwoAllowedParamsController < BaseController
    params_accessible ({:user => {:type => {:admin => [:login, :email]}}}), :url
  end

  test "should allow two params" do
    params = {:user => {:type => {:admin => {:login => 'slawosz',:email => 'slawosz@gmail.com',:password => 'secret'}},:photo => 'slawosz.jpg',:job => 'developer'},:url => 'slawosz.github.com',:language => 'ruby'}

    result = _process(TwoAllowedParamsController, params)

    assert_equal ({:user => {:type => {:admin => {:login => 'slawosz',:email => 'slawosz@gmail.com'}}}, :url => 'slawosz.github.com'}), result
  end

  class TwoProtectedParamsController < BaseController
    params_protected ({:user => {:type => {:admin => [:login, :email]}}}), :url
  end

  test "should protect two params" do
    params = {:user => {:type => {:admin => {:login => 'slawosz',:email => 'slawosz@gmail.com',:password => 'secret'}},:photo => 'slawosz.jpg',:job => 'developer'},:url => 'slawosz.github.com',:language => 'ruby'}

    result = _process(TwoProtectedParamsController, params)

    assert_equal ({:user => {:type => {:admin => {:password => 'secret'}},:photo => 'slawosz.jpg',:job => 'developer'},:language => 'ruby'}), result
  end

  class OneComplexAllowedParamsController < BaseController
    params_accessible :user => {:type => {:admin => [:login, :email]}}
  end

  test "should allow one param using complex definition" do
    params = {:user => {:type => {:admin => {:login => 'slawosz',:email => 'slawosz@gmail.com',:password => 'secret'}},:photo => 'slawosz.jpg',:job => 'developer'},:url => 'slawosz.github.com',:language => 'ruby'}

    result = _process(OneComplexAllowedParamsController, params)

    assert_equal ({:user => {:type => {:admin => {:login => 'slawosz',:email => 'slawosz@gmail.com'}}}}), result
  end

  class OneComplexProtectedParamsController < BaseController
    params_protected :user => {:type => {:admin => [:login, :email]}}
  end

  test "should protect one param using complex definition" do
    params = {:user => {:type => {:admin => {:login => 'slawosz',:email => 'slawosz@gmail.com',:password => 'secret'}},:photo => 'slawosz.jpg',:job => 'developer'},:url => 'slawosz.github.com',:language => 'ruby'}

    result = _process(OneComplexProtectedParamsController, params)

    assert_equal ({:user => {:type => {:admin => {:password => 'secret'}},:photo => 'slawosz.jpg',:job => 'developer'},:url => 'slawosz.github.com',:language => 'ruby'}), result
  end

  class WrongParamsFilteringDefinition < BaseController
    params_protected :foo
    params_accessible :bar
  end

  test "should raise error when both filtering exists in controller" do
    params = {:user => {:type => {:admin => {:login => 'slawosz',:email => 'slawosz@gmail.com',:password => 'secret'}},:photo => 'slawosz.jpg',:job => 'developer'},:url => 'slawosz.github.com',:language => 'ruby'}

    assert_raise RailsParamProtection::ParamsFilteringDefinitionMismatch do
      _process(WrongParamsFilteringDefinition, params)
    end

  end

  class BaseWrongParamsFilteringDefinition < BaseController
    params_protected :foo
  end

  class SubWrongParamsFilteringDefinition < BaseWrongParamsFilteringDefinition
    params_accessible :bar
  end

  test "should raise error when both filtering exists in controller inheritance hierarchy" do
    params = {:user => {:type => {:admin => {:login => 'slawosz',:email => 'slawosz@gmail.com',:password => 'secret'}},:photo => 'slawosz.jpg',:job => 'developer'},:url => 'slawosz.github.com',:language => 'ruby'}

    assert_raise RailsParamProtection::ParamsFilteringDefinitionMismatch do
      _process(SubWrongParamsFilteringDefinition, params)
    end

  end

  test "should work without params" do
    result = _process(OneComplexProtectedParamsController, nil)
    assert result.blank?

    result = _process(OneComplexAllowedParamsController, nil)
    assert result.blank?

    result = _process(OneComplexProtectedParamsController, {})
    assert result.blank?

    result = _process(OneComplexAllowedParamsController, {})
    assert result.blank?
  end

  private
  def _process(controller, params)
    @controller = controller.is_a?(Class) ? controller.new : controller

    get :index, params
    @controller.class.last_parameters.symbolize_keys
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.rekognition.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetPersonTrackingRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The identifier for a job that tracks persons in a video. You get the JobId from a call to
     * StartPersonTracking.
     *

     */
    private String jobId;
    /**
     *

     * Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you specify
     * a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     *

     */
    private Integer maxResults;
    /**
     *

     * If the previous response was incomplete (because there are more persons to retrieve), Amazon Rekognition Video
     * returns a pagination token in the response. You can use this pagination token to retrieve the next set of
     * persons.
     *

     */
    private String nextToken;
    /**
     *

     * Sort to use for elements in the Persons array. Use TIMESTAMP to sort array elements by
     * the time persons are detected. Use INDEX to sort by the tracked persons. If you sort by
     * INDEX, the array elements for each person are sorted by detection confidence. The default sort is by
     * TIMESTAMP.
     *

     */
    private String sortBy;

    /**
     *

     * The identifier for a job that tracks persons in a video. You get the JobId from a call to
     * StartPersonTracking.
     *

     *
     * @param jobId
     *        The identifier for a job that tracks persons in a video. You get the JobId from a call to
     *        StartPersonTracking.
     */

    public void setJobId(String jobId) {
        this.jobId = jobId;
    }

    /**
     *

     * The identifier for a job that tracks persons in a video. You get the JobId from a call to
     * StartPersonTracking.
     *

     *
     * @return The identifier for a job that tracks persons in a video. You get the JobId from a call to
     *         StartPersonTracking.
     */

    public String getJobId() {
        return this.jobId;
    }

    /**
     *

     * The identifier for a job that tracks persons in a video. You get the JobId from a call to
     * StartPersonTracking.
     *

     *
     * @param jobId
     *        The identifier for a job that tracks persons in a video. You get the JobId from a call to
     *        StartPersonTracking.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetPersonTrackingRequest withJobId(String jobId) {
        setJobId(jobId);
        return this;
    }

    /**
     *

     * Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you specify
     * a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     *

     *
     * @param maxResults
     *        Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you
     *        specify a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you specify
     * a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     *

     *
     * @return Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you
     *         specify a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you specify
     * a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     *

     *
     * @param maxResults
     *        Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you
     *        specify a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetPersonTrackingRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     *

     * If the previous response was incomplete (because there are more persons to retrieve), Amazon Rekognition Video
     * returns a pagination token in the response. You can use this pagination token to retrieve the next set of
     * persons.
     *

     *
     * @param nextToken
     *        If the previous response was incomplete (because there are more persons to retrieve), Amazon Rekognition
     *        Video returns a pagination token in the response. You can use this pagination token to retrieve the next
     *        set of persons.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * If the previous response was incomplete (because there are more persons to retrieve), Amazon Rekognition Video
     * returns a pagination token in the response. You can use this pagination token to retrieve the next set of
     * persons.
     *

     *
     * @return If the previous response was incomplete (because there are more persons to retrieve), Amazon Rekognition
     *         Video returns a pagination token in the response. You can use this pagination token to retrieve the next
     *         set of persons.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * If the previous response was incomplete (because there are more persons to retrieve), Amazon Rekognition Video
     * returns a pagination token in the response. You can use this pagination token to retrieve the next set of
     * persons.
     *

     *
     * @param nextToken
     *        If the previous response was incomplete (because there are more persons to retrieve), Amazon Rekognition
     *        Video returns a pagination token in the response. You can use this pagination token to retrieve the next
     *        set of persons.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetPersonTrackingRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     *

     * Sort to use for elements in the Persons array. Use TIMESTAMP to sort array elements by
     * the time persons are detected. Use INDEX to sort by the tracked persons. If you sort by
     * INDEX, the array elements for each person are sorted by detection confidence. The default sort is by
     * TIMESTAMP.
     *

     *
     * @param sortBy
     *        Sort to use for elements in the Persons array. Use TIMESTAMP to sort array
     *        elements by the time persons are detected. Use INDEX to sort by the tracked persons. If you
     *        sort by INDEX, the array elements for each person are sorted by detection confidence. The
     *        default sort is by TIMESTAMP.
     * @see PersonTrackingSortBy
     */

    public void setSortBy(String sortBy) {
        this.sortBy = sortBy;
    }

    /**
     *

     * Sort to use for elements in the Persons array. Use TIMESTAMP to sort array elements by
     * the time persons are detected. Use INDEX to sort by the tracked persons. If you sort by
     * INDEX, the array elements for each person are sorted by detection confidence. The default sort is by
     * TIMESTAMP.
     *

     *
     * @return Sort to use for elements in the Persons array. Use TIMESTAMP to sort array
     *         elements by the time persons are detected. Use INDEX to sort by the tracked persons. If you
     *         sort by INDEX, the array elements for each person are sorted by detection confidence. The
     *         default sort is by TIMESTAMP.
     * @see PersonTrackingSortBy
     */

    public String getSortBy() {
        return this.sortBy;
    }

    /**
     *

     * Sort to use for elements in the Persons array. Use TIMESTAMP to sort array elements by
     * the time persons are detected. Use INDEX to sort by the tracked persons. If you sort by
     * INDEX, the array elements for each person are sorted by detection confidence. The default sort is by
     * TIMESTAMP.
     *

     *
     * @param sortBy
     *        Sort to use for elements in the Persons array. Use TIMESTAMP to sort array
     *        elements by the time persons are detected. Use INDEX to sort by the tracked persons. If you
     *        sort by INDEX, the array elements for each person are sorted by detection confidence. The
     *        default sort is by TIMESTAMP.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see PersonTrackingSortBy
     */

    public GetPersonTrackingRequest withSortBy(String sortBy) {
        setSortBy(sortBy);
        return this;
    }

    /**
     *

     * Sort to use for elements in the Persons array. Use TIMESTAMP to sort array elements by
     * the time persons are detected. Use INDEX to sort by the tracked persons. If you sort by
     * INDEX, the array elements for each person are sorted by detection confidence. The default sort is by
     * TIMESTAMP.
     *

     *
     * @param sortBy
     *        Sort to use for elements in the Persons array. Use TIMESTAMP to sort array
     *        elements by the time persons are detected. Use INDEX to sort by the tracked persons. If you
     *        sort by INDEX, the array elements for each person are sorted by detection confidence. The
     *        default sort is by TIMESTAMP.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see PersonTrackingSortBy
     */

    public GetPersonTrackingRequest withSortBy(PersonTrackingSortBy sortBy) {
        this.sortBy = sortBy.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getJobId() != null)
            sb.append("JobId: ").append(getJobId()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken()).append(",");
        if (getSortBy() != null)
            sb.append("SortBy: ").append(getSortBy());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetPersonTrackingRequest == false)
            return false;
        GetPersonTrackingRequest other = (GetPersonTrackingRequest) obj;
        if (other.getJobId() == null ^ this.getJobId() == null)
            return false;
        if (other.getJobId() != null && other.getJobId().equals(this.getJobId()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getSortBy() == null ^ this.getSortBy() == null)
            return false;
        if (other.getSortBy() != null && other.getSortBy().equals(this.getSortBy()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getJobId() == null) ? 0 : getJobId().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode + ((getSortBy() == null) ? 0 : getSortBy().hashCode());
        return hashCode;
    }

    @Override
    public GetPersonTrackingRequest clone() {
        return (GetPersonTrackingRequest) super.clone();
    }

}


text:
package config

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"
	"time"

	squashkubeutils "github.com/solo-io/squash/pkg/utils/kubeutils"

	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"

	"github.com/solo-io/solo-kit/pkg/api/v1/resources/core"
	squashv1 "github.com/solo-io/squash/pkg/api/v1"
	"github.com/solo-io/squash/pkg/debuggers/local"
	sqOpts "github.com/solo-io/squash/pkg/options"
	squashkube "github.com/solo-io/squash/pkg/platforms/kubernetes"
	"github.com/solo-io/squash/pkg/utils"
	v1 "k8s.io/api/core/v1"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

type Squash struct {
	ChooseDebugger        bool
	NoClean               bool
	ChoosePod             bool
	TimeoutSeconds        int
	DebugContainerVersion string
	DebugContainerRepo    string
	LocalPort             int

	Debugger           string
	Namespace          string
	Pod                string
	Container          string
	Machine            bool
	DebugServerAddress string
	ProcessName        string

	CRISock string

	clientset kubernetes.Interface

	SquashNamespace string
}

func NewSquashConfig() Squash {
	return Squash{}
}

type DebugTarget struct {
	Pod       *v1.Pod
	Container *v1.Container
}

func StartDebugContainer(s Squash, dbt DebugTarget) (*v1.Pod, error) {
	dbgpod, err := s.debugPodFor()
	if err != nil {
		return nil, err
	}

	cs, err := s.getClientSet()
	if err != nil {
		return nil, err
	}

	// create namespace. ignore errors as it most likely exists and will error
	cs.CoreV1().Namespaces().Create(&v1.Namespace{ObjectMeta: meta_v1.ObjectMeta{Name: s.SquashNamespace}})

	// create debugger pod
	createdPod, err := cs.CoreV1().Pods(s.SquashNamespace).Create(dbgpod)
	if err != nil {
		return nil, fmt.Errorf("Could not create pod: %v", err)
	}

	if !s.Machine && !s.NoClean {
		// do not remove the pod on a debug server as it is waiting for a
		// connection
		// TODO: handle returned error
		defer s.deletePod(createdPod)
	}

	// wait for running state
	ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
	err = <-s.waitForPod(ctx, createdPod)
	cancel()
	if err != nil {
		// s.printError(createdPodName)
		return nil, fmt.Errorf("Waiting for pod: %v", err)
	}

	if err := s.ReportOrConnectToCreatedDebuggerPod(); err != nil {
		return nil, err
	}

	return createdPod, nil
}

// for the debug controller, this function finds the debug target
// from the squash spec that it receives
// If it is able to find a unique target, it applies the target
// values to the DebugTarget argument. Otherwise it errors.
func (s *Squash) ExpectToGetUniqueDebugTargetFromSpec(dbt *DebugTarget) error {
	if err := s.GetDebugTargetPodFromSpec(dbt); err != nil {
		return err
	}
	if err := s.GetDebugTargetContainerFromSpec(dbt); err != nil {
		return err
	}
	return nil
}

func (s *Squash) GetDebugTargetPodFromSpec(dbt *DebugTarget) error {
	cs, err := s.getClientSet()
	if err != nil {
		return err
	}
	dbt.Pod, err = cs.CoreV1().Pods(s.Namespace).Get(s.Pod, meta_v1.GetOptions{})
	if err != nil {
		return errors.Wrap(err, "fetching pod")
	}
	return nil
}

func (s *Squash) GetDebugTargetContainerFromSpec(dbt *DebugTarget) error {
	for _, podContainer := range dbt.Pod.Spec.Containers {
		log.Debug(podContainer.Image)
		log.Info(podContainer.Image)
		if strings.HasPrefix(podContainer.Name, s.Container) {
			dbt.Container = &podContainer
			break
		}
	}
	if dbt.Container == nil {
		return errors.New(fmt.Sprintf("no such container name: %v", s.Container))
	}
	return nil
}

func (s *Squash) getDebuggerPodNamespace() string {
	return s.Namespace
}

func (s *Squash) ReportOrConnectToCreatedDebuggerPod() error {
	da, err := s.getDebugAttachment()
	if err != nil {
		return err
	}
	remoteDbgPort, err := local.GetDebugPortFromCrd(da.Metadata.Name, s.Namespace)
	if err != nil {
		return err
	}
	if s.Machine {
		return s.printEditorExtensionData(remoteDbgPort)
	}
	return s.connectUser(da, remoteDbgPort)
}

type EditorData struct {
	PortForwardCmd string
}

func (s *Squash) connectUser(da *squashv1.DebugAttachment, remoteDbgPort int) error {
	if s.Machine {
		return nil
	}
	debugger := local.GetParticularDebugger(s.Debugger)
	kubectlCmd := debugger.GetRemoteConnectionCmd(
		da.PlankName,
		s.SquashNamespace,
		s.Pod,
		s.Namespace,
		s.LocalPort,
		remoteDbgPort,
	)
	// Starting port forward in background.
	if err := kubectlCmd.Start(); err != nil {
		// s.printError(createdPodName)
		return err
	}
	// kill the kubectl port-forward process on exit to free the port
	// this defer must be called after Start() initializes Process
	defer kubectlCmd.Process.Kill()

	// Delaying to allow port forwarding to complete.
	time.Sleep(5 * time.Second)
	if os.Getenv("DEBUG_SELF") != "" {
		fmt.Println("FOR DEBUGGING SQUASH'S DEBUGGER CONTAINER:")
		fmt.Println("TODO")
		// s.printError(createdPod)
	}

	dbgCmd := debugger.GetDebugCmd(s.LocalPort)
	return dbgCmd.Run()
}

func (s *Squash) printEditorExtensionData(remoteDbgPort int) error {
	da, err := s.getDebugAttachment()
	if err != nil {
		return err
	}

	debugger := local.GetParticularDebugger(s.Debugger)
	kubectlCmd := debugger.GetEditorRemoteConnectionCmd(
		da.PlankName,
		s.SquashNamespace,
		s.Pod,
		s.Namespace,
		remoteDbgPort,
	)
	ed := EditorData{
		PortForwardCmd: kubectlCmd,
	}
	json, err := json.Marshal(ed)
	if err != nil {
		return err
	}
	fmt.Println(string(json))
	return nil
}

// TODO - remove this when V2 api is ready
func (s *Squash) GetIntent() squashv1.Intent {
	return squashv1.Intent{
		Debugger: s.Debugger,
		Pod: &core.ResourceRef{
			Name:      s.Pod,
			Namespace: s.Namespace,
		},
		ContainerName: s.Container,
	}
}

func (s *Squash) getDebugAttachment() (*squashv1.DebugAttachment, error) {
	// Refactor - eventually Intent will be created during config/user entry
	intent := s.GetIntent()
	daClient, err := utils.GetBasicDebugAttachmentClient(context.Background())
	if err != nil {
		return &squashv1.DebugAttachment{}, err
	}
	return intent.GetDebugAttachment(daClient)
}

func (s *Squash) deletePod(createdPod *v1.Pod) error {
	var options meta_v1.DeleteOptions
	cs, err := s.getClientSet()
	if err != nil {
		return err
	}
	return cs.CoreV1().Pods(s.Namespace).Delete(createdPod.ObjectMeta.Name, &options)
}

func (s *Squash) waitForPod(ctx context.Context, createdPod *v1.Pod) <-chan error {
	errchan := make(chan error, 1)
	go func() {
		defer close(errchan)
		name := createdPod.ObjectMeta.Name

		for {
			select {
			case <-ctx.Done():
				errchan <- ctx.Err()
				return
			case <-time.After(time.Second):

				var options meta_v1.GetOptions
				options.ResourceVersion = createdPod.ResourceVersion

				cs, err := s.getClientSet()
				if err != nil {
					errchan <- err
					return
				}
				createdPod, err = cs.CoreV1().Pods(s.SquashNamespace).Get(name, options)

				if createdPod.Status.Phase == v1.PodPending {
					if !s.Machine {
						fmt.Println("Pod creating")
					}
					continue
				}
				if err != nil {
					errchan <- errors.Wrap(err, "Error during read")
					return
				}
				// TODO - consider refactor such that GetParticularDebugger is only ever called once per session
				if !local.GetParticularDebugger(s.Debugger).ExpectRunningPlank() {
					return
				}
				if createdPod.Status.Phase == v1.PodRunning {
					return
				}
				if createdPod.Status.Phase != v1.PodPending {
					// err := s.printError(createdPod)
					if err != nil {
						errchan <- errors.Wrapf(err, "pod is not running and not pending, status: %v", createdPod.Status.Phase)
					} else {
						errchan <- errors.New(fmt.Sprintf("pod is not running and not pending, status: %v", createdPod.Status.Phase))
					}
					return
				}
			}
		}
	}()
	return errchan
}

func (s *Squash) printError(podName string) error {
	cs, err := s.getClientSet()
	if err != nil {
		return err
	}

	var options v1.PodLogOptions

	req := cs.CoreV1().Pods(s.Namespace).GetLogs(podName, &options)

	readCloser, err := req.Stream()
	if err != nil {
		return err
	}
	defer readCloser.Close()

	_, err = io.Copy(os.Stderr, readCloser)
	if err != nil {
		return err
	}
	return nil
}

// Containers have a common name, suffixed by the particular debugger that they have installed
// TODO(mitchdraft) - implement more specific debug containers (for example, bare containers for debuggers that don't need a specific process)
// for now, default to the gdb variant
func containerNameFromSpec(debugger string) string {
	containerVariant := "gdb"
	if debugger == "dlv" {
		containerVariant = "dlv"
	}
	return fmt.Sprintf("%v-%v", sqOpts.ParticularContainerRootName, containerVariant)
}

func (s *Squash) debugPodFor() (*v1.Pod, error) {
	it := s.GetIntent()
	const crisockvolume = "crisock"
	cs, err := s.getClientSet()
	if err != nil {
		return nil, err
	}
	targetPod, err := cs.CoreV1().Pods(it.Pod.Namespace).Get(it.Pod.Name, meta_v1.GetOptions{})
	if err != nil {
		return nil, err
	}

	// get debugAttachment name so Plank knows where to find it
	daClient, err := utils.GetBasicDebugAttachmentClient(context.Background())
	if err != nil {
		return nil, err
	}
	da, err := it.GetDebugAttachment(daClient)
	if err != nil {
		return nil, err
	}

	// this is our convention for naming the container images that contain specific debuggers
	fullParticularContainerName := containerNameFromSpec(it.Debugger)
	// repoRoot/containerName:tag
	targetImage := fmt.Sprintf("%v/%v:%v", s.DebugContainerRepo, fullParticularContainerName, s.DebugContainerVersion)
	templatePod := &v1.Pod{
		TypeMeta: meta_v1.TypeMeta{
			Kind:       "Pod",
			APIVersion: "v1",
		},
		ObjectMeta: meta_v1.ObjectMeta{
			GenerateName: sqOpts.PlankContainerName,
			Labels:       sqOpts.GeneratePlankLabels(it.Pod),
		},
		Spec: v1.PodSpec{
			ServiceAccountName: sqOpts.PlankServiceAccountName,
			HostPID:            true,
			RestartPolicy:      v1.RestartPolicyNever,
			NodeName:           targetPod.Spec.NodeName,
			ImagePullSecrets: []v1.LocalObjectReference{{
				Name: sqOpts.SquashServiceAccountImagePullSecretName,
			}},
			Containers: []v1.Container{{
				Name:      sqOpts.PlankContainerName,
				Image:     targetImage,
				Stdin:     true,
				StdinOnce: true,
				TTY:       true,
				VolumeMounts: []v1.VolumeMount{{
					Name:      crisockvolume,
					MountPath: squashkube.CriRuntime,
				}},
				SecurityContext: &v1.SecurityContext{
					Capabilities: &v1.Capabilities{
						Add: []v1.Capability{
							"SYS_PTRACE",
						},
					},
				},
				Env: []v1.EnvVar{{
					Name:  sqOpts.PlankEnvDebugAttachmentNamespace,
					Value: it.Pod.Namespace,
				}, {
					Name:  sqOpts.PlankEnvDebugAttachmentName,
					Value: da.Metadata.Name,
				}, {
					Name:  sqOpts.PlankEnvDebugSquashNamespace,
					Value: s.SquashNamespace,
				},
				}},
			},
			Volumes: []v1.Volume{{
				Name: crisockvolume,
				VolumeSource: v1.VolumeSource{
					HostPath: &v1.HostPathVolumeSource{
						Path: s.CRISock,
					},
				},
			}},
		}}

	return templatePod, nil
}

func (s *Squash) getClientSet() (kubernetes.Interface, error) {
	if s.clientset == nil {
		cs, err := squashkubeutils.GetKubeClient()
		if err != nil {
			return nil, err
		}
		s.clientset = cs
	}

	return s.clientset, nil
}

// DeletePlankPod deletes the plank pod that was created for the debug session
// represented by the Squash object. This should be called when a debugging session
// is terminated.
func (s *Squash) DeletePlankPod() error {
	intent := s.GetIntent()
	daClient, err := utils.GetBasicDebugAttachmentClient(context.Background())
	if err != nil {
		return err
	}

	da, err := intent.GetDebugAttachment(daClient)
	if err != nil {
		return err
	}

	cs, err := s.getClientSet()
	if err != nil {
		return err
	}

	return cs.CoreV1().Pods(s.SquashNamespace).Delete(da.PlankName, &meta_v1.DeleteOptions{})
}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

		<link rel="shortcut icon" type="image/png" href="apple-touch-icon-black.png" />
		<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
		<link rel="stylesheet" href="fonts/font.css">
        <link rel="stylesheet" href="ionicons/css/ionicons.css">
        <link rel="stylesheet" href="css/reset.css">
        <link rel="stylesheet" href="css/bootstrap.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/checkbox.css">

		<link href="css/jquery.bxslider.css" rel="stylesheet" />

這美好的生活,可以由喝一杯茶開始。

This is all the better, can be start from a cup of tea.

		<?php /*

 */?>

			<?php /*

				<h7 style="display: block;font-weight: bold;color:#000">it's time to have tea !</h7>

	*/?>

what is this

donate tea

			<?php /*
慢
活
。
 */?>

start from
 a cup of tea.

真正慢生活不但指減慢生活速度,是需要停下關注人與環境關系。
所以我們提倡全面慢生活方式,由喝茶作慢生活的第一步,然後廷續一杯茶的可能性。

我們了解有98%的人喝茶後,直接拋棄茶渣,而不知道剩茶渣在生活環境上的貢獻。
我們希望由一個人喝茶,然後重用,回收並再重用剩下的茶渣。
利用天然材料增加人與人,與環境的互動,將理念附加在產品上,打造全面慢生活的方式!

我們總希望更好,更好的健康,更好的生活環境,更美好的社會。
這美好的生活,可以由喝一杯茶開始。

					Drink herbal tea is good natural media. It is a great way to slow down and keep our mind healthy. From drinking a cup of tea, to extend the community and life attitude, it can be one of leading role of our life.

I found out that 98% people throw away the used tea-leaf after they drank tea. It is waste because leftover tea-leaf have many contribution in our daily life.Therefore, this project is a sustainable concept which from choosing a cup of tea, recycle and reuse the natural material, leftover tea leaves, we not focus on the branding visual only, let the slow lifestyle concept add-in product and create "a cup of good life"!

We want to be better and better health, better lifestyle, better living environment, better community.
This is all the better, can be start from a cup of tea.

捐贈茶渣

donate tea-leave

不論你是個人,或商企,只有你有剩茶渣,我們都願意接收,並轉化成有用小幫手,幫助有需要人士,包括幫助農場施肥,替露宿者製作洗頭水等。如果你可有興趣了解更多,請留下電郵地址,我們會盡快聯絡你,謝謝

					 Whether you are an individual, or business company, if you have leftover tea leaves, we are willing to receive, and tranforming into useful little helper to help those in need, including helping farm fertilizer, making shampoo for homeless. If you may be interested, please leave your email address, we will contact you as soon as possible, thank you

			  		  	<input type="text" class="form-control" id="form-name" placeholder="your email">
			  		 	<input type="submit" class="btn btn-info" value="提交" style="width: 50%;margin-bottom: 30px" id="donate-submit">

選擇花草茶

start from a cup of tea.

	<?php $json = file_get_contents('result.json');
		  $obj = json_decode($json);
		  $results = $obj->flowers;
	?>
			<?php $x = 1 ?>

			<?php foreach ($results as $result): ?>
			<?php  $x++ ?>
			<?php if ($x < 11):?>

					<div class="box-wrapper" style="background-image: url(img/ss1/flower<?php echo $result->flowerpPosition ?>.svg)">

			  		  	<form style="display:inline;">
			  		  	  <input type="checkbox" id="mobile-checkbox-<?php echo $x ?>" class="regular-checkbox "  /><label for="mobile-checkbox-<?php echo $x ?>">
						</form>

<?php echo $result->flowerChinese; ?>

<?php echo $result->flowerName; ?>

			<?php else: endif ;?>

			<?php endforeach; ?>

選擇花草茶 start from a cup of tea.

如欲訂購或想參與我們計劃,你可先選擇你想要的花茶,並留下姓名和電郵地址,我們會盡快確認有關訂單,以及告知付款方式,謝謝。If order or join our project, you can choose what you want to tea firstly, and leave your name and e-mail address and we will confirm the order as soon as possible, and inform payment, thank you.

			  		  	<input type="text" class="form-control" id="form-name" placeholder="your name">
			  		  	<input type="text" class="form-control" id="form-name" placeholder="your email">
			  		 	<input type="submit" class="btn btn-info" value="提交">


text:
namespace Google.Cloud.Eventarc.V1.Snippets
{
    // [START eventarc_v1_generated_Eventarc_DeleteChannel_async_flattened]
    using Google.Cloud.Eventarc.V1;
    using Google.LongRunning;
    using System.Threading.Tasks;

    public sealed partial class GeneratedEventarcClientSnippets
    {
        /// <summary>Snippet for DeleteChannelAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task DeleteChannelAsync()
        {
            // Create client
            EventarcClient eventarcClient = await EventarcClient.CreateAsync();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/locations/[LOCATION]/channels/[CHANNEL]";
            // Make the request
            Operation<Channel, OperationMetadata> response = await eventarcClient.DeleteChannelAsync(name);

            // Poll until the returned long-running operation is complete
            Operation<Channel, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Channel result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<Channel, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceDeleteChannelAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Channel retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END eventarc_v1_generated_Eventarc_DeleteChannel_async_flattened]
}


text:
package org.opensplice.cm;

/**
 * Represents a waitset in SPLICE-DDS.
 *
 * @date Oct 28, 2004
 */
public interface Waitset extends Entity {
    public void attach(Entity entity) throws CMException;

    public void detach(Entity entity) throws CMException;

    public Entity[] _wait() throws CMException;

    public Entity[] timedWait(Time time) throws CMException;

    public int getEventMask() throws CMException;

    public void setEventMask(int mask) throws CMException;
}


text:
package drx.graph

//import java.lang.ref.Cleaner

import drx.{Name, internals, withInstant}

import scala.util.{Success, Try}

object Var {
//  private val cleaner = Cleaner.create()

  def apply[X](buffer: X)(implicit n: Name): Var[X] =
    new Var(Success(buffer))(n)

  def mkEmptyVar[X](implicit n: Name): Var[X] =
    new Var[X](internals.emptyValExc())(n)
}

// Distributed Programming: Building Functional Refuges inside Imperative Chaos

sealed class Var[X] private[drx](protected var buffer: Try[X])(implicit n: Name)
  extends RxDynamic[X](true, n.toString, buffer) with Rx[X] {
  // TODO watch that ad-hoc classes do not capture this of outer,
  //      bc Proxys finalize would no longer work

  override protected[this] val formula: Try[X] => X = _ => buffer.get

  forceObserved = true

  def set(newValue: X): Unit = if (newValue != buffer) {
    buffer = Success(newValue)
    withInstant(_.markSource(this))
  }

  // using the above definitions

  def transform(transformer: X => X): Unit = set(transformer(getIt.get))

//  // make observers and sources declarative by collecting them if unreachable
//  // turn all Sources & Sinks (Folds+Observers)
//  // into proxies/wrappers that only weakref the real Rx.
//  // Then we can kill/stop them in the finalizer.
//  override def finalize(): Unit = { rxit.freeze() }
}

// TODO parallel
// each change may start its own transaction. globally lock write levels.
// next transactions may begin running on levels that are lower than still
// running past transactions.

// TODO time travel
// save serializable list of transactions

//  // TODO async call value
//object FutureWork {
//  def async[X,Y](rx: Rx[X], init: Y, f: (X)=>Y): Rx[Y] = {
//    val input = rx.underlying.value
//    val result = new Var[Y](init)
//    runInThread { () =>
//      val value = f(input)
//      result.set(value)
//    }
//    result
//  }
//}


text:
#import "GPUImageFilterGroup.h"
#import "GPUImagePicture.h"

@implementation GPUImageFilterGroup

@synthesize terminalFilter = _terminalFilter;
@synthesize initialFilters = _initialFilters;
@synthesize inputFilterToIgnoreForUpdates = _inputFilterToIgnoreForUpdates;

- (id)init;
{
    if (!(self = [super init]))
    {
		return nil;
    }

    filters = [[NSMutableArray alloc] init];

    return self;
}

#pragma mark -
#pragma mark Filter management

- (void)addFilter:(GPUImageOutput<GPUImageInput> *)newFilter;
{
    [filters addObject:newFilter];
}

- (GPUImageOutput<GPUImageInput> *)filterAtIndex:(NSUInteger)filterIndex;
{
    return [filters objectAtIndex:filterIndex];
}

- (NSUInteger)filterCount;
{
    return [filters count];
}

#pragma mark -
#pragma mark Still image processing

- (void)useNextFrameForImageCapture;
{
    [self.terminalFilter useNextFrameForImageCapture];
}

- (CGImageRef)newCGImageFromCurrentlyProcessedOutput;
{
    return [self.terminalFilter newCGImageFromCurrentlyProcessedOutput];
}

#pragma mark -
#pragma mark GPUImageOutput overrides

- (void)setTargetToIgnoreForUpdates:(id<GPUImageInput>)targetToIgnoreForUpdates;
{
    [_terminalFilter setTargetToIgnoreForUpdates:targetToIgnoreForUpdates];
}

- (void)addTarget:(id<GPUImageInput>)newTarget atTextureLocation:(NSInteger)textureLocation;
{
    [_terminalFilter addTarget:newTarget atTextureLocation:textureLocation];
}

- (void)removeTarget:(id<GPUImageInput>)targetToRemove;
{
    [_terminalFilter removeTarget:targetToRemove];
}

- (void)removeAllTargets;
{
    [_terminalFilter removeAllTargets];
}

- (void)setFrameProcessingCompletionBlock:(void (^)(GPUImageOutput *, CMTime))frameProcessingCompletionBlock;
{
    [_terminalFilter setFrameProcessingCompletionBlock:frameProcessingCompletionBlock];
}

- (void (^)(GPUImageOutput *, CMTime))frameProcessingCompletionBlock;
{
    return [_terminalFilter frameProcessingCompletionBlock];
}

#pragma mark -
#pragma mark GPUImageInput protocol

- (void)newFrameReadyAtTime:(CMTime)frameTime atIndex:(NSInteger)textureIndex;
{
    for (GPUImageOutput<GPUImageInput> *currentFilter in _initialFilters)
    {
        if (currentFilter != self.inputFilterToIgnoreForUpdates)
        {
            [currentFilter newFrameReadyAtTime:frameTime atIndex:textureIndex];
        }
    }
}

- (void)setInputFramebuffer:(GPUImageFramebuffer *)newInputFramebuffer atIndex:(NSInteger)textureIndex;
{
    for (GPUImageOutput<GPUImageInput> *currentFilter in _initialFilters)
    {
        [currentFilter setInputFramebuffer:newInputFramebuffer atIndex:textureIndex];
    }
}

- (NSInteger)nextAvailableTextureIndex;
{
//    if ([_initialFilters count] > 0)
//    {
//        return [[_initialFilters objectAtIndex:0] nextAvailableTextureIndex];
//    }

    return 0;
}

- (void)setInputSize:(CGSize)newSize atIndex:(NSInteger)textureIndex;
{
    for (GPUImageOutput<GPUImageInput> *currentFilter in _initialFilters)
    {
        [currentFilter setInputSize:newSize atIndex:textureIndex];
    }
}

- (void)setInputRotation:(GPUImageRotationMode)newInputRotation atIndex:(NSInteger)textureIndex;
{
    for (GPUImageOutput<GPUImageInput> *currentFilter in _initialFilters)
    {
        [currentFilter setInputRotation:newInputRotation  atIndex:(NSInteger)textureIndex];
    }
}

- (void)forceProcessingAtSize:(CGSize)frameSize;
{
    for (GPUImageOutput<GPUImageInput> *currentFilter in filters)
    {
        [currentFilter forceProcessingAtSize:frameSize];
    }
}

- (void)forceProcessingAtSizeRespectingAspectRatio:(CGSize)frameSize;
{
    for (GPUImageOutput<GPUImageInput> *currentFilter in filters)
    {
        [currentFilter forceProcessingAtSizeRespectingAspectRatio:frameSize];
    }
}

- (CGSize)maximumOutputSize;
{
    // I'm temporarily disabling adjustments for smaller output sizes until I figure out how to make this work better
    return CGSizeZero;

    /*
    if (CGSizeEqualToSize(cachedMaximumOutputSize, CGSizeZero))
    {
        for (id<GPUImageInput> currentTarget in _initialFilters)
        {
            if ([currentTarget maximumOutputSize].width > cachedMaximumOutputSize.width)
            {
                cachedMaximumOutputSize = [currentTarget maximumOutputSize];
            }
        }
    }

    return cachedMaximumOutputSize;
     */
}

- (void)endProcessing;
{
//    if (!isEndProcessing)  // Repeat apply a same filter. Johnny xu,2014/8/13
    {
        isEndProcessing = YES;

        for (id<GPUImageInput> currentTarget in _initialFilters)
        {
            [currentTarget endProcessing];
        }
    }
}

- (BOOL)wantsMonochromeInput;
{
    BOOL allInputsWantMonochromeInput = YES;
    for (GPUImageOutput<GPUImageInput> *currentFilter in _initialFilters)
    {
        allInputsWantMonochromeInput = allInputsWantMonochromeInput && [currentFilter wantsMonochromeInput];
    }

    return allInputsWantMonochromeInput;
}

- (void)setCurrentlyReceivingMonochromeInput:(BOOL)newValue;
{
    for (GPUImageOutput<GPUImageInput> *currentFilter in _initialFilters)
    {
        [currentFilter setCurrentlyReceivingMonochromeInput:newValue];
    }
}

@end


text:
Puppet::Type.newtype(:postgresql_psql) do

  newparam(:name) do
    desc "An arbitrary tag for your own reference; the name of the message."
    isnamevar
  end

  newproperty(:command) do
    desc 'The SQL command to execute via psql.'

    defaultto { @resource[:name] }

    def sync(refreshing = false)
      # We're overriding 'sync' here in order to do some magic
      # in support of providing a 'refreshonly' parameter.  This
      # is kind of hacky because the logic for 'refreshonly' is
      # spread between the type and the provider, but this is
      # the least horrible way that I could determine to accomplish
      # it.
      #
      # Note that our overridden version of 'sync' takes a parameter,
      # 'refreshing', which the parent version doesn't take.  This
      # allows us to call the sync method directly from the 'refresh'
      # method, and then inside of the body of 'sync' we can tell
      # whether or not we're refreshing.

      if ((@resource[:refreshonly] == :false) || refreshing)
        # If we're not in 'refreshonly' mode, or we're not currently
        # refreshing, then we just call the parent method.
        super()
      else
        # If we get here, it means we're in 'refreshonly' mode and
        # we're not being called by the 'refresh' method, so we
        # just no-op.  We'll be called again by the 'refresh'
        # method momentarily.
        nil
      end
    end
  end

  newparam(:unless) do
    desc "An optional SQL command to execute prior to the main :command; " +
        "this is generally intended to be used for idempotency, to check " +
        "for the existence of an object in the database to determine whether " +
        "or not the main SQL command needs to be executed at all."
  end

  newparam(:db) do
    desc "The name of the database to execute the SQL command against."
  end

  newparam(:psql_path) do
    desc "The path to psql executable."
    defaultto("psql")
  end

  newparam(:psql_user) do
    desc "The system user account under which the psql command should be executed."
    defaultto("postgres")
  end

  newparam(:psql_group) do
    desc "The system user group account under which the psql command should be executed."
    defaultto("postgres")
  end

  newparam(:cwd, :parent => Puppet::Parameter::Path) do
    desc "The working directory under which the psql command should be executed."
    defaultto("/tmp")
  end

  newparam(:refreshonly) do
    desc "If 'true', then the SQL will only be executed via a notify/subscribe event."

    defaultto(:false)
  end

  def refresh()
    # All of the magic for this type is attached to the ':command' property, so
    # we just need to sync it to accomplish a 'refresh'.
    self.property(:command).sync(true)
  end

end


text:
namespace mozc {
struct Point {
  int x;
  int y;
  Point(int newx = 0, int newy = 0) : x(newx), y(newy) {}
  Point(const Point &point) : x(point.x), y(point.y) {}
};

struct Size {
  int width;
  int height;
  Size(int newwidth = 0, int newheight = 0)
      : width(newwidth), height(newheight) {}
  Size(const Size &size) : width(size.width), height(size.height) {}
};

struct Rect {
  Point origin;
  Size size;
  Rect(int newx, int newy, int newwidth, int newheight)
      : origin(newx, newy), size(newwidth, newheight) {}
  Rect(const Point &o, const Size &s) : origin(o), size(s) {}
  Rect(const Rect &rect) : origin(rect.origin), size(rect.size) {}
  Rect() {}

  // Accessors
  inline int Width() const { return size.width; }
  inline int Height() const { return size.height; }
  inline int Left() const { return origin.x; }
  inline int Top() const { return origin.y; }
  inline int Right() const { return origin.x + size.width; }
  inline int Bottom() const { return origin.y + size.height; }

  // Other methods
  inline void DeflateRect(int l, int t, int r, int b) {
    origin.x += l;
    origin.y += t;
    size.width -= l + r;
    size.height -= t + b;
  }
  inline void DeflateRect(int x, int y) {
    DeflateRect(x, y, x, y);
  }
  inline void DeflateRect(const Size &s) { DeflateRect(s.width, s.height); }
  // Returns true if the right side is less than or equal to the coordinate
  // of the left side, or the coordinate of the bottom side is less than or
  // equal to the coordinate of the top side.
  // This behaviour is compatible to the IsRectEmpty API
  // http://msdn.microsoft.com/en-us/library/dd145017.aspx
  inline bool IsRectEmpty() const {
    return size.width <= 0 || size.height <= 0;
  }
  inline bool PtrInRect(const Point &p) const {
    return p.x >= origin.x && p.x <= origin.x + size.width &&
        p.y >= origin.y && p.y <= origin.y + size.height;
  }
};
}  // namespace mozc
#endif  // MOZC_BASE_COORDINATES_H_


text:
import React, { PropTypes } from "react";
import ReactDOM from "react-dom"
import TransitionGroup from "react-addons-css-transition-group";
import Router, { Route, DefaultRoute, NotFoundRoute, Redirect } from "react-router";

import Navbar from "./components/navbar";
import { Authenticated as Layout, Anonymous as AnonymousLayout } from "./layouts";

import Application from "./application";

import IndexPage from "./pages/index";
import NotFoundPage from "./pages/notfound";
import NullPage from "./pages/null";
import Profile from "./pages/profile";
import World from "./pages/world";
import SignInPage from "./pages/signin";
import SignUpPage from "./pages/signup";
import SignOut from "./pages/signout";

const container = document.getElementById("content");

const routes = (
  <Route handler={Application}>
    <Route name="anonymous" path="/auth" handler={AnonymousLayout}>
      <Route name="sign-in" path="signin" handler={SignInPage} />
      <Route name="sign-up" path="signup" handler={SignUpPage} />
      <Route name="sign-out" path="signout" handler={SignOut} />
      <NotFoundRoute handler={NotFoundPage} />
    </Route>
    <Route name="home" path="/" handler={Layout}>
      <DefaultRoute name="index" handler={Profile} />
      <Route name="null-page" path="null" handler={NullPage} />
      <Route name="profile" path="profile" handler={Profile} />
      <Route name="world" path="world" handler={World} />
      <NotFoundRoute handler={NotFoundPage} />
    </Route>
  </Route>
);

Router.run(routes, Router.HashLocation, (Handler) => {
  ReactDOM.render(<Handler/>, container);
});