text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using Gallio.Common.Collections;
using Gallio.Model.Schema;
using Gallio.Runner.Extensions;
using Gallio.Runner.Projects;
using Gallio.Runner.Reports.Schema;
using Gallio.Runtime.Logging;
using Gallio.Runtime.ProgressMonitoring;
using Gallio.Runtime;
using Gallio.Model;
using Gallio.Runner.Reports;
using System.Threading;

namespace Gallio.Runner
{
    /// <summary>
    /// The test launcher encapsulated the entire test execution lifecycle from
    /// start to finish and provides a simplified pattern for running tests.
    /// </summary>
    /// <remarks>
    /// <para>
    /// The basic usage pattern is as follows:
    /// <list type="numbered">
    /// <item>Create the launcher.</item>
    /// <item>Set properties to specify the inputs and outputs of the test run.</item>
    /// <item>Run the tests all in one go.</item>
    /// <item>Optionally do something with the contents of the final report.</item>
    /// </list>
    /// </para>
    /// <para>
    /// By default, the launcher assumes that a runtime environment has already been
    /// established and is accessible via the <see cref="RuntimeAccessor" />.  If there
    /// is no runtime yet, then you can cause one to be configured automatically for the
    /// duration of the test run by setting the <see cref="RuntimeSetup"/> property accordingly.
    /// </para>
    /// </remarks>
    public class TestLauncher
    {
        private readonly List<string> filePatterns;
        private TestProject testProject;
        private TestRunnerOptions testRunnerOptions;
        private TestExplorationOptions testExplorationOptions;
        private TestExecutionOptions testExecutionOptions;
        private readonly List<string> reportFormats;
        private ReportFormatterOptions reportFormatterOptions;
        private IProgressMonitorProvider progressMonitorProvider;
        private ILogger logger;
        private readonly object cancelationSyncRoot = new object();
        private bool isCanceled;
        private IProgressMonitor cancelableProgressMonitor;

        /// <summary>
        /// Creates a launcher with default options and no test assemblies specified.
        /// </summary>
        public TestLauncher()
        {
            filePatterns = new List<string>();
            testProject = new TestProject();
            testRunnerOptions = new TestRunnerOptions();
            testExplorationOptions = new TestExplorationOptions();
            testExecutionOptions = new TestExecutionOptions();
            reportFormats = new List<string>();
            reportFormatterOptions = new ReportFormatterOptions();
            progressMonitorProvider = NullProgressMonitorProvider.Instance;
            logger = NullLogger.Instance;
        }

        /// <summary>
        /// Gets or sets the progress monitor provider to use.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The default provider is <see cref="NullProgressMonitorProvider.Instance" />.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
        public IProgressMonitorProvider ProgressMonitorProvider
        {
            get
            {
                return progressMonitorProvider;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException(@"value");

                progressMonitorProvider = value;
            }
        }

        /// <summary>
        /// Gets or sets the logger to use.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The default logger is <see cref="NullLogger.Instance" />.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
        public ILogger Logger
        {
            get
            {
                return logger;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException(@"value");

                logger = value;
            }
        }

        /// <summary>
        /// Gets or sets the <see cref="RuntimeSetup" /> to use for automatically initializing
        /// the runtime during test execution or <c>null</c> if the runtime is already initialized.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If this value if not <c>null</c> then the launcher will initialize the runtime
        /// using this <see cref="RuntimeSetup" /> (unless already initialized) just prior to
        /// test execution and will automatically shut down the runtime just afterwards.
        /// </para>
        /// <para>
        /// The default value is <c>null</c> which assumes that the runtime is already initialized.
        /// </para>
        /// </remarks>
        public RuntimeSetup RuntimeSetup
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the test runner options.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
        public TestRunnerOptions TestRunnerOptions
        {
            get
            {
                return testRunnerOptions;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");

                testRunnerOptions = value;
            }
        }

        /// <summary>
        /// Gets a read-only list of test file patterns (with wildcards) or test project files
        /// that are to be resolved and included in the test package prior to execution.
        /// </summary>
        public IList<string> FilePatterns
        {
            get
            {
                return new ReadOnlyCollection<string>(filePatterns);
            }
        }

        /// <summary>
        /// Gets or sets the test project.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
        public TestProject TestProject
        {
            get
            {
                return testProject;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException(@"value");

                testProject = value;
            }
        }

        /// <summary>
        /// Gets or sets the test exploration options.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
        public TestExplorationOptions TestExplorationOptions
        {
            get
            {
                return testExplorationOptions;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException(@"value");

                testExplorationOptions = value;
            }
        }

        /// <summary>
        /// Gets or sets the test execution options.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
        public TestExecutionOptions TestExecutionOptions
        {
            get
            {
                return testExecutionOptions;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException(@"value");

                testExecutionOptions = value;
            }
        }

        /// <summary>
        /// Controls whether the test runner will echo result to the <see cref="Logger" />
        /// as each test finishes.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The default value is <c>false</c>.
        /// </para>
        /// </remarks>
        public bool EchoResults
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets whether to skip test execution.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This option may be used to produce a report that contains test
        /// metadata for consumption by other tools.
        /// </para>
        /// <para>
        /// The default value is <c>false</c>.
        /// </para>
        /// </remarks>
        public bool DoNotRun
        {
            get;
            set;
        }

        /// <summary>
        /// Gets a read-only list of report formats to generate.
        /// </summary>
        public IList<string> ReportFormats
        {
            get
            {
                return new ReadOnlyCollection<string>(reportFormats);
            }
        }

        /// <summary>
        /// Gets or sets the report formatter options.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
        public ReportFormatterOptions ReportFormatterOptions
        {
            get
            {
                return reportFormatterOptions;
            }

            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");

                reportFormatterOptions = value;
            }
        }

        /// <summary>
        /// Gets or sets whether to show the reports after the test run finishes.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The default value is <c>false</c>.
        /// </para>
        /// </remarks>
        public bool ShowReports
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets whether to ignore annotations when determining the result code.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If false, then error annotations, usually indicative of broken tests, will cause
        /// a failure result to be generated.
        /// </para>
        /// <para>
        /// The default value is <c>false</c>.
        /// </para>
        /// </remarks>
        public bool IgnoreAnnotations
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the maximum amount of time the tests can run before they are canceled.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The default value is <c>null</c>, meaning an infinite time.
        /// </para>
        /// </remarks>
        public TimeSpan? RunTimeLimit
        {
            get;
            set;
        }

        /// <summary>
        /// Clears the list of file patterns.
        /// </summary>
        public void ClearFilePatterns()
        {
            filePatterns.Clear();
        }

        /// <summary>
        /// Adds a file pattern if not already added to the launcher.
        /// </summary>
        /// <param name="filePattern">The file path or a wildcard pattern to add.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="filePattern"/> is null.</exception>
        public void AddFilePattern(string filePattern)
        {
            if (filePattern == null)
                throw new ArgumentNullException("filePattern");

            if (!filePatterns.Contains(filePattern))
                filePatterns.Add(filePattern);
        }

        /// <summary>
        /// Removes a file pattern.
        /// </summary>
        /// <param name="filePattern">The file pattern to remove.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="filePattern"/> is null.</exception>
        public void RemoveFilePattern(string filePattern)
        {
            if (filePattern == null)
                throw new ArgumentNullException("filePattern");

            filePatterns.Remove(filePattern);
        }

        /// <summary>
        /// Clears the list of report formats.
        /// </summary>
        public void ClearReportFormats()
        {
            reportFormats.Clear();
        }

        /// <summary>
        /// Adds a report format if not already added to the launcher.
        /// </summary>
        /// <param name="reportFormat">The report format to add.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="reportFormat"/> is null.</exception>
        public void AddReportFormat(string reportFormat)
        {
            if (reportFormat == null)
                throw new ArgumentNullException("reportFormat");

            if (!reportFormats.Contains(reportFormat))
                reportFormats.Add(reportFormat);
        }

        /// <summary>
        /// Removes a report format.
        /// </summary>
        /// <param name="reportFormat">The report format to remove.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="reportFormat"/> is null.</exception>
        public void RemoveReportFormat(string reportFormat)
        {
            if (reportFormat == null)
                throw new ArgumentNullException("reportFormat");

            reportFormats.Remove(reportFormat);
        }

        /// <summary>
        /// Cancels the test run and prevents a new one from starting.
        /// </summary>
        public void Cancel()
        {
            lock (cancelationSyncRoot)
            {
                isCanceled = true;

                if (cancelableProgressMonitor != null)
                    cancelableProgressMonitor.Cancel();
            }
        }

        /// <summary>
        /// Runs the test package as configured.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If <see cref="RuntimeSetup" /> is non-<c>null</c>,
        /// initializes the runtime for the duration of this method then shuts it down automatically
        /// before returning.  Otherwise assumes the runtime has already been initialized and
        /// accesses it using <see cref="RuntimeAccessor" />.
        /// </para>
        /// <para>
        /// Runtimes cannot be nested.  So if the launcher is asked to initialize the runtime and
        /// it has already been initialized, then it will not be initialized again.
        /// </para>
        /// </remarks>
        /// <returns>A result object.</returns>
        public TestLauncherResult Run()
        {
            Canonicalize(null);
            DisplayConfiguration();

            Timer runTimeTimer = null;
            if (RunTimeLimit != null)
            {
                runTimeTimer = new Timer(delegate
                {
                    Cancel();
                    logger.Log(LogSeverity.Warning, "Run time limit reached!  Canceled test run.");
                }, null, (int)RunTimeLimit.Value.TotalMilliseconds, Timeout.Infinite);
            }

            Stopwatch stopWatch = Stopwatch.StartNew();
            logger.Log(LogSeverity.Important, String.Format("Start time: {0}", DateTime.Now.ToShortTimeString()));
            bool wasCanceled = false;
            try
            {
                using (InitializeRuntimeIfNeeded(ref wasCanceled))
                {
                    if (wasCanceled)
                        return CreateResult(ResultCode.Canceled, testProject);

                    return RunWithRuntime();
                }
            }
            finally
            {
                logger.Log(LogSeverity.Important,
                    String.Format("Stop time: {0} (Total execution time: {1:#0.000} seconds)",
                        DateTime.Now.ToShortTimeString(),
                        stopWatch.Elapsed.TotalSeconds));

                if (runTimeTimer != null)
                    runTimeTimer.Dispose();
            }
        }

        private IDisposable InitializeRuntimeIfNeeded(ref bool canceled)
        {
            IDisposable result = null;

            if (RuntimeSetup != null && !RuntimeAccessor.IsInitialized)
            {
                RunWithProgress(progressMonitor =>
                {
                    progressMonitor.BeginTask("Initializing the runtime and loading plugins.", 1);
                    result = RuntimeBootstrap.Initialize(RuntimeSetup, logger);
                }, ref canceled);
            }

            return result;
        }

        private TestLauncherResult RunWithRuntime()
        {
            bool wasCanceled = false;

            ITestProjectManager testProjectManager = RuntimeAccessor.ServiceLocator.Resolve<ITestProjectManager>();

            TestProject consolidatedTestProject = ConsolidateTestProject(testProjectManager, ref wasCanceled);
            if (wasCanceled)
                return CreateResult(ResultCode.Canceled, testProject);
            if (consolidatedTestProject == null)
                return CreateResult(ResultCode.InvalidArguments, testProject);

            if (consolidatedTestProject.TestPackage.Files.Count == 0)
            {
                logger.Log(LogSeverity.Warning, "No test files to execute!");
                return CreateResult(ResultCode.NoTests, consolidatedTestProject);
            }

            IReportManager reportManager = RuntimeAccessor.ServiceLocator.Resolve<IReportManager>();
            if (!ValidateReportFormats(reportManager, consolidatedTestProject))
                return CreateResult(ResultCode.InvalidArguments, consolidatedTestProject);

            ITestRunnerManager testRunnerManager = RuntimeAccessor.ServiceLocator.Resolve<ITestRunnerManager>();
            ITestRunnerFactory testRunnerFactory = testRunnerManager.GetFactory(consolidatedTestProject.TestRunnerFactoryName);
            if (testRunnerFactory == null)
            {
                logger.Log(LogSeverity.Error, String.Format("Unrecognized test runner factory name: '{0}'.", consolidatedTestProject.TestRunnerFactoryName));
                return CreateResult(ResultCode.InvalidArguments, consolidatedTestProject);
            }

            ITestRunner runner = testRunnerFactory.CreateTestRunner();
            var result = new TestLauncherResult(new Report { TestPackage = new TestPackageData(TestProject.TestPackage) });
            try
            {
                DoRegisterExtensions(runner, consolidatedTestProject);
                DoInitialize(runner, ref wasCanceled);

                if (!wasCanceled)
                {
                    result = RunWithInitializedRunner(runner, consolidatedTestProject, reportManager);
                }
            }
            finally
            {
                DoDispose(runner, ref wasCanceled);
            }

            if (wasCanceled)
                result.SetResultCode(ResultCode.Canceled);

            return result;
        }

        private TestLauncherResult RunWithInitializedRunner(ITestRunner runner, TestProject consolidatedTestProject, IReportManager reportManager)
        {
            bool wasCanceled = false;

            // Explore or Run tests.
            Report report = DoExploreOrRun(runner, consolidatedTestProject.TestPackage, ref wasCanceled);

            if (report == null)
                report = new Report();
            var result = new TestLauncherResult(report);

            // Generate reports even if the test run is canceled, unless this step
            // also gets canceled.
            if (result.Report.TestPackageRun != null || DoNotRun)
                GenerateReports(result, reportManager, consolidatedTestProject, ref wasCanceled);

            // Done.
            if (ShowReports)
                ShowReportDocuments(result);

            // Produce the final result code.
            if (wasCanceled)
            {
                result.SetResultCode(ResultCode.Canceled);
            }
            else
            {
                if (! IgnoreAnnotations
                    && result.Report.TestModel != null
                    && result.Report.TestModel.GetErrorAnnotationCount() != 0)
                    result.SetResultCode(ResultCode.Failure);
                else if (result.Report.TestPackageRun != null
                    && result.Statistics.FailedCount > 0)
                    result.SetResultCode(ResultCode.Failure);
                else if (result.Report.TestPackageRun != null
                    && result.Statistics.TestCount == 0)
                    result.SetResultCode(ResultCode.NoTests);
            }

            return result;
        }

        private void GenerateReports(TestLauncherResult result, IReportManager reportManager,
            TestProject consolidatedTestProject, ref bool canceled)
        {
            if (reportFormats.Count == 0)
                return;

            RunWithProgress(progressMonitor => result.GenerateReports(consolidatedTestProject.ReportDirectory,
                result.Report.FormatReportName(consolidatedTestProject.ReportNameFormat), consolidatedTestProject.ReportArchive,
                reportFormats, reportFormatterOptions, reportManager, progressMonitor), ref canceled);
        }

        private void ShowReportDocuments(TestLauncherResult result)
        {
            if (result.ReportDocumentPaths.Count == 0)
                return;

            logger.Log(LogSeverity.Important, "Displaying reports.");

            if (!result.ShowReportDocuments())
                logger.Log(LogSeverity.Important, "There was an error opening the report documents.");
        }

        private bool ValidateReportFormats(IReportManager reportManager, TestProject consolidatedTestProject)
        {
            foreach (string reportFormat in reportFormats)
            {
                IReportFormatter formatter = reportManager.GetReportFormatter(reportFormat);

                if (formatter != null)
                    continue;

                logger.Log(LogSeverity.Error, String.Format("Unrecognized report format: '{0}'.", reportFormat));
                return false;
            }

            if (consolidatedTestProject.ReportNameFormat.Length == 0)
            {
                logger.Log(LogSeverity.Error, "Report name format must not be empty.");
                return false;
            }

            return true;
        }

        private void DoRegisterExtensions(ITestRunner runner, TestProject consolidatedTestProject)
        {
            if (EchoResults)
                runner.RegisterExtension(new LogExtension());

            foreach (ITestRunnerExtension extension in consolidatedTestProject.TestRunnerExtensions)
                runner.RegisterExtension(extension);

            // de-dupe extension specs
            List<string> uniqueExtensionSpecifications = new List<string>();
            GenericCollectionUtils.AddAllIfNotAlreadyPresent(consolidatedTestProject.TestRunnerExtensionSpecifications,
                uniqueExtensionSpecifications);

            foreach (string extensionSpecification in uniqueExtensionSpecifications)
            {
                var testRunnerExtension =
                    TestRunnerExtensionUtils.CreateExtensionFromSpecification(extensionSpecification);
                runner.RegisterExtension(testRunnerExtension);
            }
        }

        private void DisplayConfiguration()
        {
            DisplayPaths(testProject.TestPackage.Files, "Test Files:");
            DisplayPaths(testProject.TestPackage.HintDirectories, "Hint Directories:");

            if (RuntimeSetup != null)
                DisplayPaths(RuntimeSetup.PluginDirectories, "Plugin Directories:");
        }

        private void DisplayPaths<T>(ICollection<T> paths, string name)
            where T : FileSystemInfo
        {
            DisplayPaths(GenericCollectionUtils.ConvertAllToArray(paths, path => path.ToString()), name);
        }

        private void DisplayPaths(ICollection<string> paths, string name)
        {
            if (paths == null || paths.Count <= 0)
                return;

            var message = new StringBuilder();
            message.Append(name);

            foreach (string path in paths)
                message.Append("\n\t").Append(path);
            message.AppendLine();

            logger.Log(LogSeverity.Info, message.ToString());
        }

        private void Canonicalize(string baseDirectory)
        {
            if (RuntimeSetup != null)
                RuntimeSetup.Canonicalize(baseDirectory);
        }

        /// <summary>
        /// Processes test file patterns and generates a consolidated test project.
        /// </summary>
        private TestProject ConsolidateTestProject(ITestProjectManager testProjectManager, ref bool canceled)
        {
            TestProject consolidatedTestProject = null;

            RunWithProgress(delegate(IProgressMonitor progressMonitor)
            {
                List<string> allFilePatterns = new List<string>(filePatterns);
                GenericCollectionUtils.ConvertAndAddAll(testProject.TestPackage.Files, allFilePatterns, x => x.ToString());

                TestProject overlayTestProject = testProject.Copy();
                overlayTestProject.TestPackage.ClearFiles();
                TestProject baseTestProject = null;

                bool haveProject = false;
                using (progressMonitor.BeginTask("Verifying test files.", Math.Max(allFilePatterns.Count, 1)))
                {
                    foreach (string filePattern in allFilePatterns)
                    {
                        IList<FileInfo> files = ExpandFilePattern(filePattern);
                        if (files == null)
                            return;

                        foreach (FileInfo file in files)
                        {
                            bool isProject = file.Extension == TestProject.Extension;
                            if (isProject && overlayTestProject.TestPackage.Files.Count != 0 || haveProject)
                            {
                                logger.Log(LogSeverity.Error, "At most one test project can be specified at a time and it cannot be combined with other test files.");
                                return;
                            }

                            if (isProject)
                            {
                                haveProject = true;

                                try
                                {
                                    baseTestProject = testProjectManager.LoadProject(file);
                                }
                                catch (Exception ex)
                                {
                                    logger.Log(LogSeverity.Error, string.Format("Could not load test project '{0}'.", file.FullName), ex);
                                }
                            }
                            else
                            {
                                overlayTestProject.TestPackage.AddFile(file);
                            }
                        }

                        progressMonitor.Worked(1);
                    }

                    if (baseTestProject != null)
                    {
                        baseTestProject.ApplyOverlay(overlayTestProject);
                        consolidatedTestProject = baseTestProject;
                    }
                    else
                    {
                        consolidatedTestProject = overlayTestProject;
                    }
                }
            }, ref canceled);

            return consolidatedTestProject;
        }

        private IList<FileInfo> ExpandFilePattern(string filePattern)
        {
            if (filePattern.Contains("?") || filePattern.Contains("*"))
            {
                string directory = Path.GetDirectoryName(filePattern);
                if (string.IsNullOrEmpty(directory))
                    directory = Environment.CurrentDirectory;
                else
                    directory = Path.GetFullPath(directory);

                if (! Directory.Exists(directory))
                {
                    logger.Log(LogSeverity.Error,
                        String.Format("Cannot find directory containing file pattern '{0}'.", filePattern));
                    return null;
                }

                var files = new List<FileInfo>();

                string searchPattern = Path.GetFileName(filePattern);

                foreach (string file in Directory.GetFiles(directory, searchPattern))
                    files.Add(new FileInfo(Path.Combine(directory, file)));

                return files;
            }

            if (! File.Exists(filePattern))
            {
                logger.Log(LogSeverity.Error, String.Format("Cannot find file '{0}'.", filePattern));
                return null;
            }

            return new[] { new FileInfo(Path.GetFullPath(filePattern)) };
        }

        private void DoInitialize(ITestRunner runner, ref bool canceled)
        {
            RunWithProgress(progressMonitor => runner.Initialize(testRunnerOptions,
                logger, progressMonitor), ref canceled);
        }

        private Report DoExploreOrRun(ITestRunner runner, TestPackage testPackage, ref bool canceled)
        {
            Report report = null;
            RunWithProgress(delegate(IProgressMonitor progressMonitor)
            {
                report = DoNotRun ? runner.Explore(testPackage, testExplorationOptions, progressMonitor) :
                    runner.Run(testPackage, testExplorationOptions, testExecutionOptions, progressMonitor);
            }, ref canceled);

            return report;
        }

        private void DoDispose(ITestRunner runner, ref bool canceled)
        {
            RunWithProgress(runner.Dispose, ref canceled);
        }

        private TestLauncherResult CreateResult(int resultCode, TestProject consolidatedTestProject)
        {
            Report report = new Report();
            report.TestPackage = new TestPackageData(consolidatedTestProject.TestPackage);
            var result = new TestLauncherResult(report);
            result.SetResultCode(resultCode);
            return result;
        }

        private void RunWithProgress(TaskWithProgress task, ref bool canceled)
        {
            try
            {
                progressMonitorProvider.Run(progressMonitor =>
                {
                    try
                    {
                        bool wasCanceled;
                        lock (cancelationSyncRoot)
                        {
                            wasCanceled = isCanceled;
                            cancelableProgressMonitor = progressMonitor;
                        }

                        if (wasCanceled)
                        {
                            progressMonitor.Cancel();
                        }
                        else
                        {
                            task(progressMonitor);
                        }
                    }
                    finally
                    {
                        lock (cancelationSyncRoot)
                            cancelableProgressMonitor = null;
                    }
                });
            }
            catch (OperationCanceledException)
            {
                canceled = true;
            }
        }
    }
}


text:
  class Exp_Cuda_GFC : public CudaExperiment {
  public:
    Exp_Cuda_GFC();
    ~Exp_Cuda_GFC();
    unsigned int GetMinCu();
    unsigned int GetMax();
    void Init(std::vector<cuda::CudaDevice> &devices);
    void Shutdown();

  private:
    void Start(unsigned int num_runs, const std::vector<int> options);
  };

redpajama_set_name: RedPajamaGithub


text:
package org.optaplanner.persistence.jackson.api.score;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.persistence.jackson.api.OptaPlannerJacksonModule;

/**
 * Jackson binding support for a {@link Score} subtype.
 * For a {@link Score} field, use {@link PolymorphicScoreJacksonJsonSerializer} instead,
 * so the score type is recorded too and it can be deserialized.
 *

 * For example: use {@code @JsonSerialize(using = HardSoftScoreJacksonJsonSerializer.class) @JsonDeserialize(using = HardSoftScoreJacksonJsonDeserializer.class)}
 * on a {@code HardSoftScore score} field and it will marshalled to JSON as {@code "score":"-999hard/-999soft"}.
 * Or better yet, use {@link OptaPlannerJacksonModule} instead.
 *

 * Do not use ScoreJacksonJsonSerializer directly: in 8.0 this will become an abstract class and renamed to AbstractScoreJacksonJsonSerializer.
 * @see Score
 * @param <Score_> the actual score type
 */
public class ScoreJacksonJsonSerializer<Score_ extends Score<Score_>> extends JsonSerializer<Score_>
        implements ContextualSerializer {

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
            throws JsonMappingException {
        JavaType propertyType = property.getType();
        if (Score.class.equals(propertyType.getRawClass())) {
            // If the property type is Score (not HardSoftScore for example),
            // delegate to PolymorphicScoreJacksonJsonSerializer instead to write the score type too
            // This presumes that OptaPlannerJacksonModule is registered
            return provider.findValueSerializer(propertyType);
        }
        return this;
    }

    @Override
    public void serialize(Score_ score, JsonGenerator generator, SerializerProvider serializers) throws IOException {
        generator.writeString(score.toString());
    }

}


text:
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require_self
 *= require_tree .
 */

/* Settings for the browser window */
html, body {
  height: 100%;
  width: 100%;
  overflow: hidden;
  font-family: Verdana, Arial, Helvetica, sans-serif;
  font-size: small;
  color: black;
  background: white;
}

/* The main application window */
#main {
  height: 96%;
  width: 98%;
  border: 2px solid black;
}

/* The application menu on the left */
#menu {
  width: 350px;
  height: 98%;
}

/* Sections of content within the menu */
.menuContent {
  overflow: auto;
}

/* The content window on the right */
#content {
  padding: 10px;
  height: 95%;
  overflow: auto;
}

#content h3 {
  padding-top: 5px;
}

.letter {
  font-family: Times New Roman, serif;
  padding: 0px;
  margin: 0px 0px -5px 0px;
}

/* A section of information in the content window (i.e. Address) */
.section {
  margin-left: 30px;
  width: 525px;
  border: 1px solid black;
  padding: 5px;
  background: #e1ebfb;
  -moz-border-radius: 7px;
  -webkit-border-radius: 7px;
}

/* A table column in the section */
.section td {
  padding-right: 10px;
}

.addressOption {
  padding-left: 30px;
}

#spinner {
  position: absolute;
  margin-left: 365px;
  margin-top: 10px;
  padding: 5px;
  background: white;
  z-index: 10;
}

/* BEGIN - Styles for addresses */
.addressContacts th {
  padding: 10px;
}

.addressContacts td {
  text-align: center;
}
/* END - Styles for addresses */

/* BEGIN - Styles for group maintenance */
.selectGroupAddresses {
  width: 235px;
  height: 455px;
}

#maintainGroupTable td {
  border: none;
}

#maintainGroupControls {
  text-align: center;
  width: 55px;
}

.groupListAddresses {
  border: 1px solid black;
  background: #e1ebfb;
  width: 235px;
}

.groupListAddresses ul {
  padding: 0px;
  margin: 0px;
}

.groupListAddresses li {
  cursor: -moz-grab;
}
/* END - styles for group maintenance */

/* The notice to the user, when we send them a message */
#notice {
  border: 2px solid red;
  padding: 1em;
  margin-bottom: 2em;
  background-color: #f0f0f0;
  font: bold smaller sans-serif;
}

/* START:error styles */
.fieldWithErrors {
  padding: 2px;
  background-color: red;
  display: table;
}

#errorExplanation {
  width: 400px;
  border: 2px solid red;
  padding: 7px;
  padding-bottom: 12px;
  margin-bottom: 20px;
  background-color: #f0f0f0;
}

#errorExplanation h2 {
  text-align: left;
  font-weight: bold;
  padding: 5px 5px 5px 15px;
  font-size: 12px;
  margin: -7px;
  background-color: #c00;
  color: #fff;
}

#errorExplanation p {
  color: #333;
  margin-bottom: 0;
  padding: 5px;
}

#errorExplanation ul li {
  font-size: 12px;
  list-style: square;
}
/* END:error styles */

/* START:link styles */
a, a:visited {
  color: blue;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

#menu a {
  color: black;
  text-decoration: none;
}

#menu a:hover {
  text-decoration: underline;
}
/* END:link styles */

#multipleAddressConfirmation {
  width: 400px;
  height: 250px;
  margin-top: auto;
  margin-bottom: auto;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

/* START: button styles */

.buttons a, .buttons button, .buttons input[type="submit"] {
  display:table-cell;
  float:left;
  margin:0 7px 0 0;
  background-color:#f5f5f5;
  border:1px solid #dedede;
  border-top:1px solid #eee;
  border-left:1px solid #eee;

  font-family:"Lucida Grande", Tahoma, Arial, Verdana, sans-serif;
  font-size:12px;
  line-height:130%;
  text-decoration:none;
  font-weight:bold;
  color:#565656;
  cursor:pointer;
  padding:5px 10px 6px 7px; /* Links */
}

.buttons button, .buttons input[type="submit"] {
  width:auto;
  overflow:visible;
  padding:4px 10px 3px 7px; /* IE6 */
}

.buttons button[type], .buttons input[type="submit"] {
  padding:5px 10px 5px 7px; /* Firefox */
  line-height:17px; /* Safari */
}

*:first-child+html button[type], *:first-child+html input[type="submit"] {
  padding:4px 10px 3px 7px; /* IE7 */
}

.buttons button img, .buttons a img, .buttons input[type="submit"] img {
  margin:0 3px -3px 0 !important;
  padding:0;
  border:none;
  width:16px;
  height:16px;
}

/* STANDARD */

button:hover, .buttons a:hover, input[type="submit"]:hover {
  background-color:#dff4ff;
  border:1px solid #c2e1ef;
  color:#336699;
}

.buttons a:active {
  background-color:#6299c5;
  border:1px solid #6299c5;
  color:#fff;
}

/* POSITIVE */

button.positive, .buttons a.positive, input[type="submit"].positive {
  color:#529214;
}

.buttons a.positive:hover, button.positive:hover, input[type="submit"].positive:hover {
  background-color:#E6EFC2;
  border:1px solid #C6D880;
  color:#529214;
}

.buttons a.positive:active {
  background-color:#529214;
  border:1px solid #529214;
  color:#fff;
}

/* NEGATIVE */

.buttons a.negative, button.negative, input[type="submit"].negative {
  color:#d12f19;
}

.buttons a.negative:hover, button.negative:hover, input[type="submit"].negative:hover {
  background:#fbe3e4;
  border:1px solid #fbc2c4;
  color:#d12f19;
}

.buttons a.negative:active {
  background-color:#d12f19;
  border:1px solid #d12f19;
  color:#fff;
}

/* REGULAR */

button.regular, .buttons a.regular, input[type="submit"].regular {
  color:#336699;
}

.buttons a.regular:hover, button.regular:hover, input[type="submit"].regular:hover {
  background-color:#dff4ff;
  border:1px solid #c2e1ef;
  color:#336699;
}

.buttons a.regular:active {
  background-color:#6299c5;
  border:1px solid #6299c5;
  color:#fff;
}
/* END: button styles */


text:
namespace Microsoft.Azure.Management.WebSites.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// The configuration settings of the app registration for providers that
    /// have app ids and app secrets
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class AppRegistration : ProxyOnlyResource
    {
        /// <summary>
        /// Initializes a new instance of the AppRegistration class.
        /// </summary>
        public AppRegistration()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the AppRegistration class.
        /// </summary>
        /// <param name="id">Resource Id.</param>
        /// <param name="name">Resource Name.</param>
        /// <param name="kind">Kind of resource.</param>
        /// <param name="type">Resource type.</param>
        /// <param name="appId">The App ID of the app used for login.</param>
        /// <param name="appSecretSettingName">The app setting name that
        /// contains the app secret.</param>
        public AppRegistration(string id = default(string), string name = default(string), string kind = default(string), string type = default(string), string appId = default(string), string appSecretSettingName = default(string))
            : base(id, name, kind, type)
        {
            AppId = appId;
            AppSecretSettingName = appSecretSettingName;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the App ID of the app used for login.
        /// </summary>
        [JsonProperty(PropertyName = "properties.appId")]
        public string AppId { get; set; }

        /// <summary>
        /// Gets or sets the app setting name that contains the app secret.
        /// </summary>
        [JsonProperty(PropertyName = "properties.appSecretSettingName")]
        public string AppSecretSettingName { get; set; }

    }
}


text:
/** @module state */ /** for typedoc */
import {extend, inherit, pluck, equalForKeys} from "../common/common";
import {isString} from "../common/predicates";
import {StateDeclaration} from "./interface";
import {State} from "./stateObject";
import {StateBuilder} from "./stateBuilder";
import {StateService} from "./stateService";
import {UrlRouterProvider} from "../url/urlRouter";
import {RawParams} from "../params/interface";
import {StateRegistry, StateRegistryListener} from "./stateRegistry";

export class StateQueueManager {
  queue: State[];
  private $state: StateService;

  constructor(
      public states: { [key: string]: State; },
      public builder: StateBuilder,
      public $urlRouterProvider: UrlRouterProvider,
      public listeners: StateRegistryListener[]) {
    this.queue = [];
  }

  register(config: StateDeclaration) {
    let {states, queue, $state} = this;
    // Wrap a new object around the state so we can store our private details easily.
    // @TODO: state = new State(extend({}, config, { ... }))
    let state = inherit(new State(), extend({}, config, {
      self: config,
      resolve: config.resolve || [],
      toString: () => config.name
    }));

    if (!isString(state.name)) throw new Error("State must have a valid name");
    if (states.hasOwnProperty(state.name) || pluck(queue, 'name').indexOf(state.name) !== -1)
      throw new Error(`State '${state.name}' is already defined`);

    queue.push(state);

    if (this.$state) {
      this.flush($state);
    }
    return state;
  }

  flush($state: StateService) {
    let {queue, states, builder} = this;
    let registered: State[] = [], // states that got registered
        orphans: State[] = [], // states that dodn't yet have a parent registered
        previousQueueLength = {}; // keep track of how long the queue when an orphan was first encountered

    while (queue.length > 0) {
      let state: State = queue.shift();
      let result: State = builder.build(state);
      let orphanIdx: number = orphans.indexOf(state);

      if (result) {
        if (states.hasOwnProperty(state.name))
          throw new Error(`State '${name}' is already defined`);
        states[state.name] = state;
        this.attachRoute($state, state);
        if (orphanIdx >= 0) orphans.splice(orphanIdx, 1);
        registered.push(state);
        continue;
      }

      let prev = previousQueueLength[state.name];
      previousQueueLength[state.name] = queue.length;
      if (orphanIdx >= 0 && prev === queue.length) {
        // Wait until two consecutive iterations where no additional states were dequeued successfully.
        // throw new Error(`Cannot register orphaned state '${state.name}'`);
        queue.push(state);
        return states;
      } else if (orphanIdx < 0) {
        orphans.push(state);
      }

      queue.push(state);
    }

    if (registered.length) {
      this.listeners.forEach(listener => listener("registered", registered.map(s => s.self)));
    }

    return states;
  }

  autoFlush($state: StateService) {
    this.$state = $state;
    this.flush($state);
  }

  attachRoute($state: StateService, state: State) {
    let {$urlRouterProvider} = this;
    if (state.abstract || !state.url) return;

    $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match: RawParams, $stateParams: RawParams) {
      if ($state.$current.navigable !== state || !equalForKeys($match, $stateParams)) {
        $state.transitionTo(state, $match, { inherit: true, source: "url" });
      }
    }], (rule) => state._urlRule = rule);
  }
}


text:
require 'forecast_io'

ForecastIO.configure do |configuration|
  configuration.api_key = ENV["FORECAST_IO_APIKEY"]
end


text:
#ifndef __ARCH_ARM_PREDECODER_HH__
#define __ARCH_ARM_PREDECODER_HH__

#include "arch/arm/types.hh"
#include "base/misc.hh"
#include "base/types.hh"

class ThreadContext;

namespace ArmISA
{
    class Predecoder
    {
      protected:
        ThreadContext * tc;
        //The extended machine instruction being generated
        ExtMachInst emi;

      public:
        Predecoder(ThreadContext * _tc) : tc(_tc)
        {}

        ThreadContext * getTC()
        {
            return tc;
        }

        void setTC(ThreadContext * _tc)
        {
            tc = _tc;
        }

        void process()
        {}

        void reset()
        {}

        //Use this to give data to the predecoder. This should be used
        //when there is control flow.
        void moreBytes(Addr pc, Addr fetchPC, MachInst inst)
        {
            emi = inst;
            emi.sevenAndFour = bits(inst, 7) && bits(inst, 4);
            emi.isMisc = (bits(inst, 24, 23) == 0x2 && bits(inst, 20) == 0);
        }

        //Use this to give data to the predecoder. This should be used
        //when instructions are executed in order.
        void moreBytes(MachInst machInst)
        {
            moreBytes(0, 0, machInst);
        }

        bool needMoreBytes()
        {
            return true;
        }

        bool extMachInstReady()
        {
            return true;
        }

        //This returns a constant reference to the ExtMachInst to avoid a copy
        const ExtMachInst & getExtMachInst()
        {
            return emi;
        }
    };
};

#endif // __ARCH_ARM_PREDECODER_HH__


text:
/**
 *    @file
 *      Declaration of SetUp Code Pairer, a class that parses a given
 *      setup code and uses the extracted informations to discover and
 *      filter commissionables nodes, before initiating the pairing process.
 *
 */

#pragma once

#include <controller/DevicePairingDelegate.h>
#include <lib/core/CHIPError.h>
#include <lib/core/NodeId.h>
#include <lib/support/DLLUtil.h>
#include <platform/CHIPDeviceConfig.h>
#include <protocols/secure_channel/RendezvousParameters.h>
#include <setup_payload/ManualSetupPayloadParser.h>
#include <setup_payload/QRCodeSetupPayloadParser.h>

#if CONFIG_NETWORK_LAYER_BLE
#include <ble/BleLayer.h>
#endif // CONFIG_NETWORK_BLE

#include <controller/DeviceDiscoveryDelegate.h>

#include <queue>

namespace chip {
namespace Controller {

class DeviceCommissioner;

enum class SetupCodePairerBehaviour : uint8_t
{
    kCommission,
    kPaseOnly,
};

class DLL_EXPORT SetUpCodePairer : public DevicePairingDelegate
{
public:
    SetUpCodePairer(DeviceCommissioner * commissioner) : mCommissioner(commissioner) { ResetDiscoveryState(); }
    virtual ~SetUpCodePairer() {}

    CHIP_ERROR PairDevice(chip::NodeId remoteId, const char * setUpCode,
                          SetupCodePairerBehaviour connectionType = SetupCodePairerBehaviour::kCommission);

    // Called by the DeviceCommissioner to notify that we have discovered a new device.
    void NotifyCommissionableDeviceDiscovered(const chip::Dnssd::DiscoveredNodeData & nodeData);

    void SetSystemLayer(System::Layer * systemLayer) { mSystemLayer = systemLayer; };

#if CONFIG_NETWORK_LAYER_BLE
    void SetBleLayer(Ble::BleLayer * bleLayer) { mBleLayer = bleLayer; };
#endif // CONFIG_NETWORK_LAYER_BLE

    // Called to notify us that the DeviceCommissioner is shutting down and we
    // should not try to do any more new work.
    void CommissionerShuttingDown();

private:
    // DevicePairingDelegate implementation.
    void OnStatusUpdate(DevicePairingDelegate::Status status) override;
    void OnPairingComplete(CHIP_ERROR error) override;
    void OnPairingDeleted(CHIP_ERROR error) override;
    void OnCommissioningComplete(NodeId deviceId, CHIP_ERROR error) override;

    CHIP_ERROR Connect(SetupPayload & paload);
    CHIP_ERROR StartDiscoverOverBle(SetupPayload & payload);
    CHIP_ERROR StopConnectOverBle();
    CHIP_ERROR StartDiscoverOverIP(SetupPayload & payload);
    CHIP_ERROR StopConnectOverIP();
    CHIP_ERROR StartDiscoverOverSoftAP(SetupPayload & payload);
    CHIP_ERROR StopConnectOverSoftAP();

    // Returns whether we have kicked off a new connection attempt.
    bool ConnectToDiscoveredDevice();

    // Reset our mWaitingForDiscovery/mDiscoveredParameters state to indicate no
    // pending work.
    void ResetDiscoveryState();

    // Get ready to start PASE establishment via mCommissioner.  Sets up
    // whatever state is needed for that.
    void ExpectPASEEstablishment();

    // PASE establishment by mCommissioner has completed: we either have a PASE
    // session now or we failed to set one up, but we are done waiting on
    // mCommissioner.
    void PASEEstablishmentComplete();

    // Called when PASE establishment fails.
    //
    // May start a new PASE establishment.
    //
    // Will return whether we might in fact have more rendezvous parameters to
    // try (e.g. because we started a new PASE establishment or are waiting on
    // more device discovery).
    //
    // The commissioner can use the return value to decide whether pairing has
    // actually failed or not.
    bool TryNextRendezvousParameters();

    // True if we are still waiting on discovery to possibly produce new
    // RendezvousParameters in the future.
    bool DiscoveryInProgress() const;

    // Not an enum class because we use this for indexing into arrays.
    enum TransportTypes
    {
        kBLETransport = 0,
        kIPTransport,
        kSoftAPTransport,
        kTransportTypeCount,
    };

    static void OnDeviceDiscoveredTimeoutCallback(System::Layer * layer, void * context);

#if CONFIG_NETWORK_LAYER_BLE
    Ble::BleLayer * mBleLayer = nullptr;
    void OnDiscoveredDeviceOverBle(BLE_CONNECTION_OBJECT connObj);
    void OnBLEDiscoveryError(CHIP_ERROR err);
    /////////// BLEConnectionDelegate Callbacks /////////
    static void OnDiscoveredDeviceOverBleSuccess(void * appState, BLE_CONNECTION_OBJECT connObj);
    static void OnDiscoveredDeviceOverBleError(void * appState, CHIP_ERROR err);
#endif // CONFIG_NETWORK_LAYER_BLE

    bool NodeMatchesCurrentFilter(const Dnssd::DiscoveredNodeData & nodeData) const;
    Dnssd::DiscoveryFilter currentFilter;

    DeviceCommissioner * mCommissioner = nullptr;
    System::Layer * mSystemLayer       = nullptr;
    chip::NodeId mRemoteId;
    uint32_t mSetUpPINCode                   = 0;
    SetupCodePairerBehaviour mConnectionType = SetupCodePairerBehaviour::kCommission;

    // While we are trying to pair, we intercept the DevicePairingDelegate
    // notifications from mCommissioner.  We want to make sure we send them on
    // to the original pairing delegate, if any.
    DevicePairingDelegate * mPairingDelegate = nullptr;

    // Boolean will be set to true if we currently have an async discovery
    // process happening via the relevant transport.
    bool mWaitingForDiscovery[kTransportTypeCount] = { false };

    // Queue of things we have discovered but not tried connecting to yet.  The
    // general discovery/pairing process will terminate once this queue is empty
    // and all the booleans in mWaitingForDiscovery are false.
    std::queue<RendezvousParameters> mDiscoveredParameters;

    // mWaitingForPASE is true if we have called either
    // EstablishPASEConnection or PairDevice on mCommissioner and are now just
    // waiting to see whether that works.
    bool mWaitingForPASE = false;

    // mLastPASEError is the error from the last OnPairingComplete call we got.
    CHIP_ERROR mLastPASEError = CHIP_NO_ERROR;
};

} // namespace Controller
} // namespace chip


text:
package com.xeiam.xchange.examples.bitcoinium;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.ExchangeFactory;
import com.xeiam.xchange.ExchangeSpecification;
import com.xeiam.xchange.bitcoinium.BitcoiniumExchange;
import com.xeiam.xchange.bitcoinium.dto.marketdata.BitcoiniumTicker;
import com.xeiam.xchange.bitcoinium.dto.marketdata.BitcoiniumTickerHistory;
import com.xeiam.xchange.bitcoinium.service.polling.BitcoiniumMarketDataServiceRaw;
import com.xeiam.xchange.currency.Currencies;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.ChartBuilder;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartType;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.XChartPanel;

/**
 * Demonstrates plotting an OrderBook with XChart
 *
 * @author timmolter
 */
public class BitcoiniumRealtimeTickerDemo {

  BitcoiniumMarketDataServiceRaw bitcoiniumMarketDataService;
  List<Date> xAxisData;
  List<Float> yAxisData;
  public static final String SERIES_NAME = "Bitcoinium USD/BTC";

  public static void main(String[] args) throws Exception {

    final BitcoiniumRealtimeTickerDemo bitcoiniumRealtimeTickerDemo = new BitcoiniumRealtimeTickerDemo();
    bitcoiniumRealtimeTickerDemo.go();
  }

  private void go() throws IOException {

    ExchangeSpecification exchangeSpecification = new ExchangeSpecification(BitcoiniumExchange.class.getName());
    // exchangeSpecification.setPlainTextUri("http://openexchangerates.org");
    exchangeSpecification.setApiKey("42djci5kmbtyzrvglfdw3e2dgmh5mr37");
    System.out.println(exchangeSpecification.toString());
    Exchange bitcoiniumExchange = ExchangeFactory.INSTANCE.createExchange(exchangeSpecification);

    // Interested in the public polling market data feed (no authentication)
    bitcoiniumMarketDataService = (BitcoiniumMarketDataServiceRaw) bitcoiniumExchange.getPollingMarketDataService();

    // Setup the panel
    final XChartPanel chartPanel = buildPanel();
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {

      @Override
      public void run() {

        // Create and set up the window.
        JFrame frame = new JFrame("XChart");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(chartPanel);

        // Display the window.
        frame.pack();
        frame.setVisible(true);
      }
    });

    // Simulate a data feed
    TimerTask chartUpdaterTask = new TimerTask() {

      @Override
      public void run() {

        try {
          BitcoiniumTicker bitcoiniumTicker = bitcoiniumMarketDataService.getBitcoiniumTicker(Currencies.BTC, "BITSTAMP_USD");
          System.out.println(bitcoiniumTicker.toString());
          Date timestamp = new Date(bitcoiniumTicker.getTimestamp());
          float price = bitcoiniumTicker.getLast().floatValue();
          if (xAxisData.get(xAxisData.size() - 1).getTime() != timestamp.getTime()) {
            xAxisData.add(timestamp);
            yAxisData.add(price);
            Series series = chartPanel.updateSeries(SERIES_NAME, xAxisData, yAxisData);
            System.out.println(series.getXData());
            System.out.println(series.getYData());
          } else {
            System.out.println("No new data.");
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    };

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(chartUpdaterTask, 0, 10000); // every ten seconds

  }

  public XChartPanel buildPanel() throws IOException {

    System.out.println("fetching data...");

    // Get the latest order book data for BTC/USD - BITSTAMP
    BitcoiniumTickerHistory bitcoiniumTickerHistory = bitcoiniumMarketDataService.getBitcoiniumTickerHistory(Currencies.BTC, "BITSTAMP_USD",
        "THREE_HOURS");

    System.out.println(bitcoiniumTickerHistory.toString());

    // build ticker history chart series data
    xAxisData = new ArrayList<Date>();
    yAxisData = new ArrayList<Float>();
    for (int i = 0; i < bitcoiniumTickerHistory.getCondensedTickers().length; i++) {

      BitcoiniumTicker bitcoiniumTicker = bitcoiniumTickerHistory.getCondensedTickers()[i];

      Date timestamp = new Date(bitcoiniumTicker.getTimestamp());
      float price = bitcoiniumTicker.getLast().floatValue();
      System.out.println(timestamp + ": " + price);
      xAxisData.add(timestamp);
      yAxisData.add(price);
    }

    // create chart
    Chart chart = new ChartBuilder().chartType(ChartType.Area).width(800).height(400).title("Real-time Bitstamp Price vs. Time").xAxisTitle("Time")
        .yAxisTitle("Price").build();
    chart.getStyleManager().setLegendPosition(LegendPosition.InsideNE);

    // add series
    Series series = chart.addSeries(SERIES_NAME, xAxisData, yAxisData);
    series.setMarker(SeriesMarker.NONE);

    return new XChartPanel(chart);
  }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>No Stress for Vets</title>

    <link rel="stylesheet" href="https://npmcdn.com/leaflet@1.0.0-rc.3/dist/leaflet.css" />
    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Merriweather:700" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Candal" rel="stylesheet">

    <link rel="stylesheet" href="app/css/normalize.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/yeti/bootstrap.min.css">
    <link rel="stylesheet" href="app/font-awesome-4.6.3/css/font-awesome.min.css">
    <link rel="stylesheet" href="app/css/coverr.css">
    <link rel="stylesheet" href="app/css/styles.css">


text:
import sys

import pytest

from google.api import http_pb2
from google.api_core import protobuf_helpers
from google.longrunning import operations_pb2
from google.protobuf import any_pb2
from google.protobuf import message
from google.protobuf import source_context_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import type_pb2
from google.protobuf import wrappers_pb2
from google.type import color_pb2
from google.type import date_pb2
from google.type import timeofday_pb2

def test_from_any_pb_success():
    in_message = date_pb2.Date(year=1990)
    in_message_any = any_pb2.Any()
    in_message_any.Pack(in_message)
    out_message = protobuf_helpers.from_any_pb(date_pb2.Date, in_message_any)

    assert in_message == out_message

def test_from_any_pb_wrapped_success():
    # Declare a message class conforming to wrapped messages.
    class WrappedDate(object):
        def __init__(self, **kwargs):
            self._pb = date_pb2.Date(**kwargs)

        def __eq__(self, other):
            return self._pb == other

        @classmethod
        def pb(cls, msg):
            return msg._pb

    # Run the same test as `test_from_any_pb_success`, but using the
    # wrapped class.
    in_message = date_pb2.Date(year=1990)
    in_message_any = any_pb2.Any()
    in_message_any.Pack(in_message)
    out_message = protobuf_helpers.from_any_pb(WrappedDate, in_message_any)

    assert out_message == in_message

def test_from_any_pb_failure():
    in_message = any_pb2.Any()
    in_message.Pack(date_pb2.Date(year=1990))

    with pytest.raises(TypeError):
        protobuf_helpers.from_any_pb(timeofday_pb2.TimeOfDay, in_message)

def test_check_protobuf_helpers_ok():
    assert protobuf_helpers.check_oneof() is None
    assert protobuf_helpers.check_oneof(foo="bar") is None
    assert protobuf_helpers.check_oneof(foo="bar", baz=None) is None
    assert protobuf_helpers.check_oneof(foo=None, baz="bacon") is None
    assert protobuf_helpers.check_oneof(foo="bar", spam=None, eggs=None) is None

def test_check_protobuf_helpers_failures():
    with pytest.raises(ValueError):
        protobuf_helpers.check_oneof(foo="bar", spam="eggs")
    with pytest.raises(ValueError):
        protobuf_helpers.check_oneof(foo="bar", baz="bacon", spam="eggs")
    with pytest.raises(ValueError):
        protobuf_helpers.check_oneof(foo="bar", spam=0, eggs=None)

def test_get_messages():
    answer = protobuf_helpers.get_messages(date_pb2)

    # Ensure that Date was exported properly.
    assert answer["Date"] is date_pb2.Date

    # Ensure that no non-Message objects were exported.
    for value in answer.values():
        assert issubclass(value, message.Message)

def test_get_dict_absent():
    with pytest.raises(KeyError):
        assert protobuf_helpers.get({}, "foo")

def test_get_dict_present():
    assert protobuf_helpers.get({"foo": "bar"}, "foo") == "bar"

def test_get_dict_default():
    assert protobuf_helpers.get({}, "foo", default="bar") == "bar"

def test_get_dict_nested():
    assert protobuf_helpers.get({"foo": {"bar": "baz"}}, "foo.bar") == "baz"

def test_get_dict_nested_default():
    assert protobuf_helpers.get({}, "foo.baz", default="bacon") == "bacon"
    assert protobuf_helpers.get({"foo": {}}, "foo.baz", default="bacon") == "bacon"

def test_get_msg_sentinel():
    msg = timestamp_pb2.Timestamp()
    with pytest.raises(KeyError):
        assert protobuf_helpers.get(msg, "foo")

def test_get_msg_present():
    msg = timestamp_pb2.Timestamp(seconds=42)
    assert protobuf_helpers.get(msg, "seconds") == 42

def test_get_msg_default():
    msg = timestamp_pb2.Timestamp()
    assert protobuf_helpers.get(msg, "foo", default="bar") == "bar"

def test_invalid_object():
    with pytest.raises(TypeError):
        protobuf_helpers.get(object(), "foo", "bar")

def test_set_dict():
    mapping = {}
    protobuf_helpers.set(mapping, "foo", "bar")
    assert mapping == {"foo": "bar"}

def test_set_msg():
    msg = timestamp_pb2.Timestamp()
    protobuf_helpers.set(msg, "seconds", 42)
    assert msg.seconds == 42

def test_set_dict_nested():
    mapping = {}
    protobuf_helpers.set(mapping, "foo.bar", "baz")
    assert mapping == {"foo": {"bar": "baz"}}

def test_set_invalid_object():
    with pytest.raises(TypeError):
        protobuf_helpers.set(object(), "foo", "bar")

def test_set_list():
    list_ops_response = operations_pb2.ListOperationsResponse()

    protobuf_helpers.set(
        list_ops_response,
        "operations",
        [{"name": "foo"}, operations_pb2.Operation(name="bar")],
    )

    assert len(list_ops_response.operations) == 2

    for operation in list_ops_response.operations:
        assert isinstance(operation, operations_pb2.Operation)

    assert list_ops_response.operations[0].name == "foo"
    assert list_ops_response.operations[1].name == "bar"

def test_set_list_clear_existing():
    list_ops_response = operations_pb2.ListOperationsResponse(
        operations=[{"name": "baz"}]
    )

    protobuf_helpers.set(
        list_ops_response,
        "operations",
        [{"name": "foo"}, operations_pb2.Operation(name="bar")],
    )

    assert len(list_ops_response.operations) == 2
    for operation in list_ops_response.operations:
        assert isinstance(operation, operations_pb2.Operation)
    assert list_ops_response.operations[0].name == "foo"
    assert list_ops_response.operations[1].name == "bar"

def test_set_msg_with_msg_field():
    rule = http_pb2.HttpRule()
    pattern = http_pb2.CustomHttpPattern(kind="foo", path="bar")

    protobuf_helpers.set(rule, "custom", pattern)

    assert rule.custom.kind == "foo"
    assert rule.custom.path == "bar"

def test_set_msg_with_dict_field():
    rule = http_pb2.HttpRule()
    pattern = {"kind": "foo", "path": "bar"}

    protobuf_helpers.set(rule, "custom", pattern)

    assert rule.custom.kind == "foo"
    assert rule.custom.path == "bar"

def test_set_msg_nested_key():
    rule = http_pb2.HttpRule(custom=http_pb2.CustomHttpPattern(kind="foo", path="bar"))

    protobuf_helpers.set(rule, "custom.kind", "baz")

    assert rule.custom.kind == "baz"
    assert rule.custom.path == "bar"

def test_setdefault_dict_unset():
    mapping = {}
    protobuf_helpers.setdefault(mapping, "foo", "bar")
    assert mapping == {"foo": "bar"}

def test_setdefault_dict_falsy():
    mapping = {"foo": None}
    protobuf_helpers.setdefault(mapping, "foo", "bar")
    assert mapping == {"foo": "bar"}

def test_setdefault_dict_truthy():
    mapping = {"foo": "bar"}
    protobuf_helpers.setdefault(mapping, "foo", "baz")
    assert mapping == {"foo": "bar"}

def test_setdefault_pb2_falsy():
    operation = operations_pb2.Operation()
    protobuf_helpers.setdefault(operation, "name", "foo")
    assert operation.name == "foo"

def test_setdefault_pb2_truthy():
    operation = operations_pb2.Operation(name="bar")
    protobuf_helpers.setdefault(operation, "name", "foo")
    assert operation.name == "bar"

def test_field_mask_invalid_args():
    with pytest.raises(ValueError):
        protobuf_helpers.field_mask("foo", any_pb2.Any())
    with pytest.raises(ValueError):
        protobuf_helpers.field_mask(any_pb2.Any(), "bar")
    with pytest.raises(ValueError):
        protobuf_helpers.field_mask(any_pb2.Any(), operations_pb2.Operation())

def test_field_mask_equal_values():
    assert protobuf_helpers.field_mask(None, None).paths == []

    original = struct_pb2.Value(number_value=1.0)
    modified = struct_pb2.Value(number_value=1.0)
    assert protobuf_helpers.field_mask(original, modified).paths == []

    original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0))
    modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0))
    assert protobuf_helpers.field_mask(original, modified).paths == []

    original = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=1.0)])
    modified = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=1.0)])
    assert protobuf_helpers.field_mask(original, modified).paths == []

    original = struct_pb2.Struct(fields={"bar": struct_pb2.Value(number_value=1.0)})
    modified = struct_pb2.Struct(fields={"bar": struct_pb2.Value(number_value=1.0)})
    assert protobuf_helpers.field_mask(original, modified).paths == []

def test_field_mask_zero_values():
    # Singular Values
    original = color_pb2.Color(red=0.0)
    modified = None
    assert protobuf_helpers.field_mask(original, modified).paths == []

    original = None
    modified = color_pb2.Color(red=0.0)
    assert protobuf_helpers.field_mask(original, modified).paths == []

    # Repeated Values
    original = struct_pb2.ListValue(values=[])
    modified = None
    assert protobuf_helpers.field_mask(original, modified).paths == []

    original = None
    modified = struct_pb2.ListValue(values=[])
    assert protobuf_helpers.field_mask(original, modified).paths == []

    # Maps
    original = struct_pb2.Struct(fields={})
    modified = None
    assert protobuf_helpers.field_mask(original, modified).paths == []

    original = None
    modified = struct_pb2.Struct(fields={})
    assert protobuf_helpers.field_mask(original, modified).paths == []

    # Oneofs
    original = struct_pb2.Value(number_value=0.0)
    modified = None
    assert protobuf_helpers.field_mask(original, modified).paths == []

    original = None
    modified = struct_pb2.Value(number_value=0.0)
    assert protobuf_helpers.field_mask(original, modified).paths == []

def test_field_mask_singular_field_diffs():
    original = type_pb2.Type(name="name")
    modified = type_pb2.Type()
    assert protobuf_helpers.field_mask(original, modified).paths == ["name"]

    original = type_pb2.Type(name="name")
    modified = type_pb2.Type()
    assert protobuf_helpers.field_mask(original, modified).paths == ["name"]

    original = None
    modified = type_pb2.Type(name="name")
    assert protobuf_helpers.field_mask(original, modified).paths == ["name"]

    original = type_pb2.Type(name="name")
    modified = None
    assert protobuf_helpers.field_mask(original, modified).paths == ["name"]

def test_field_mask_message_diffs():
    original = type_pb2.Type()
    modified = type_pb2.Type(
        source_context=source_context_pb2.SourceContext(file_name="name")
    )
    assert protobuf_helpers.field_mask(original, modified).paths == [
        "source_context.file_name"
    ]

    original = type_pb2.Type(
        source_context=source_context_pb2.SourceContext(file_name="name")
    )
    modified = type_pb2.Type()
    assert protobuf_helpers.field_mask(original, modified).paths == ["source_context"]

    original = type_pb2.Type(
        source_context=source_context_pb2.SourceContext(file_name="name")
    )
    modified = type_pb2.Type(
        source_context=source_context_pb2.SourceContext(file_name="other_name")
    )
    assert protobuf_helpers.field_mask(original, modified).paths == [
        "source_context.file_name"
    ]

    original = None
    modified = type_pb2.Type(
        source_context=source_context_pb2.SourceContext(file_name="name")
    )
    assert protobuf_helpers.field_mask(original, modified).paths == [
        "source_context.file_name"
    ]

    original = type_pb2.Type(
        source_context=source_context_pb2.SourceContext(file_name="name")
    )
    modified = None
    assert protobuf_helpers.field_mask(original, modified).paths == ["source_context"]

def test_field_mask_wrapper_type_diffs():
    original = color_pb2.Color()
    modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0))
    assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"]

    original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0))
    modified = color_pb2.Color()
    assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"]

    original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0))
    modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=2.0))
    assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"]

    original = None
    modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=2.0))
    assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"]

    original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0))
    modified = None
    assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"]

def test_field_mask_repeated_diffs():
    original = struct_pb2.ListValue()
    modified = struct_pb2.ListValue(
        values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]
    )
    assert protobuf_helpers.field_mask(original, modified).paths == ["values"]

    original = struct_pb2.ListValue(
        values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]
    )
    modified = struct_pb2.ListValue()
    assert protobuf_helpers.field_mask(original, modified).paths == ["values"]

    original = None
    modified = struct_pb2.ListValue(
        values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]
    )
    assert protobuf_helpers.field_mask(original, modified).paths == ["values"]

    original = struct_pb2.ListValue(
        values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]
    )
    modified = None
    assert protobuf_helpers.field_mask(original, modified).paths == ["values"]

    original = struct_pb2.ListValue(
        values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]
    )
    modified = struct_pb2.ListValue(
        values=[struct_pb2.Value(number_value=2.0), struct_pb2.Value(number_value=1.0)]
    )
    assert protobuf_helpers.field_mask(original, modified).paths == ["values"]

def test_field_mask_map_diffs():
    original = struct_pb2.Struct()
    modified = struct_pb2.Struct(fields={"foo": struct_pb2.Value(number_value=1.0)})
    assert protobuf_helpers.field_mask(original, modified).paths == ["fields"]

    original = struct_pb2.Struct(fields={"foo": struct_pb2.Value(number_value=1.0)})
    modified = struct_pb2.Struct()
    assert protobuf_helpers.field_mask(original, modified).paths == ["fields"]

    original = None
    modified = struct_pb2.Struct(fields={"foo": struct_pb2.Value(number_value=1.0)})
    assert protobuf_helpers.field_mask(original, modified).paths == ["fields"]

    original = struct_pb2.Struct(fields={"foo": struct_pb2.Value(number_value=1.0)})
    modified = None
    assert protobuf_helpers.field_mask(original, modified).paths == ["fields"]

    original = struct_pb2.Struct(fields={"foo": struct_pb2.Value(number_value=1.0)})
    modified = struct_pb2.Struct(fields={"foo": struct_pb2.Value(number_value=2.0)})
    assert protobuf_helpers.field_mask(original, modified).paths == ["fields"]

    original = struct_pb2.Struct(fields={"foo": struct_pb2.Value(number_value=1.0)})
    modified = struct_pb2.Struct(fields={"bar": struct_pb2.Value(number_value=1.0)})
    assert protobuf_helpers.field_mask(original, modified).paths == ["fields"]

def test_field_mask_different_level_diffs():
    original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0))
    modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=2.0), red=1.0)
    assert sorted(protobuf_helpers.field_mask(original, modified).paths) == [
        "alpha",
        "red",
    ]

@pytest.mark.skipif(
    sys.version_info.major == 2,
    reason="Field names with trailing underscores can only be created"
    "through proto-plus, which is Python 3 only.",
)
def test_field_mask_ignore_trailing_underscore():
    import proto

    class Foo(proto.Message):
        type_ = proto.Field(proto.STRING, number=1)
        input_config = proto.Field(proto.STRING, number=2)

    modified = Foo(type_="bar", input_config="baz")

    assert sorted(protobuf_helpers.field_mask(None, Foo.pb(modified)).paths) == [
        "input_config",
        "type",
    ]

@pytest.mark.skipif(
    sys.version_info.major == 2,
    reason="Field names with trailing underscores can only be created"
    "through proto-plus, which is Python 3 only.",
)
def test_field_mask_ignore_trailing_underscore_with_nesting():
    import proto

    class Bar(proto.Message):
        class Baz(proto.Message):
            input_config = proto.Field(proto.STRING, number=1)

        type_ = proto.Field(Baz, number=1)

    modified = Bar()
    modified.type_.input_config = "foo"

    assert sorted(protobuf_helpers.field_mask(None, Bar.pb(modified)).paths) == [
        "type.input_config",
    ]


text:
import mongoengine as me

from st2common.models.db import stormbase

class NotificationSubSchema(me.EmbeddedDocument):
    """
        Schema for notification settings to be specified for action success/failure.
    """
    message = me.StringField()
    data = stormbase.EscapedDynamicField(
        default={},
        help_text='Payload to be sent as part of notification.')
    channels = me.ListField(
        default=['notify.default'],
        help_text='Channels to post notifications to.')

    def __str__(self):
        result = []
        result.append('NotificationSubSchema@')
        result.append(str(id(self)))
        result.append('(message="%s", ' % str(self.message))
        result.append('data="%s", ' % str(self.data))
        result.append('channels="%s")' % str(self.channels))
        return ''.join(result)

class NotificationSchema(me.EmbeddedDocument):
    """
        Schema for notification settings to be specified for actions.
    """
    on_success = me.EmbeddedDocumentField(NotificationSubSchema)
    on_failure = me.EmbeddedDocumentField(NotificationSubSchema)
    on_complete = me.EmbeddedDocumentField(NotificationSubSchema)

    def __str__(self):
        result = []
        result.append('NotifySchema@')
        result.append(str(id(self)))
        result.append('(on_complete="%s", ' % str(self.on_complete))
        result.append('on_success="%s", ' % str(self.on_success))
        result.append('on_failure="%s")' % str(self.on_failure))
        return ''.join(result)


text:
package MIP::List;

use 5.026;
use Carp;
use charnames qw{ :full :short };
use English qw{ -no_match_vars };
use open qw{ :encoding(UTF-8) :std };
use Params::Check qw{ allow check last_error };
use utf8;
use warnings;
use warnings qw{ FATAL utf8 };

## CPANM
use autodie qw{ :all };

BEGIN {
    require Exporter;
    use base qw{ Exporter };

    # Functions and variables which can be optionally exported
    our @EXPORT_OK =
      qw{ check_allowed_array_values check_element_exist_hash_of_array get_splitted_lists };
}

sub check_allowed_array_values {

## Function : Check that the array values are allowed
## Returns  :
## Arguments: $allowed_values_ref => Allowed values for parameter {REF}
##          : $values_ref         => Values for parameter {REF}

    my ($arg_href) = @_;

    ## Flatten argument(s)
    my $allowed_values_ref;
    my $values_ref;

    my $tmpl = {
        allowed_values_ref => {
            default     => [],
            defined     => 1,
            required    => 1,
            store       => \$allowed_values_ref,
            strict_type => 1,
        },
        values_ref => {
            default     => [],
            defined     => 1,
            required    => 1,
            store       => \$values_ref,
            strict_type => 1,
        },
    };

    check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!};

    use Array::Utils qw{ array_minus };

    # Check if arrays contains allowed values
    return 0 if ( array_minus( @{$values_ref}, @{$allowed_values_ref} ) );

    # All ok
    return 1;
}

sub check_element_exist_hash_of_array {

## Function : Test element for being part of hash of array at supplied key.
## Returns  : Return "1" if element is not part of array
## Arguments: $element  => Element to look for in hash of array
##          : $hash_ref => Hash {REF}
##          : $key      => The key pointing to the array in the $hash_ref

    my ($arg_href) = @_;

    ## Flatten argument(s)
    my $element;
    my $hash_ref;
    my $key;

    my $tmpl = {
        element => {
            defined     => 1,
            required    => 1,
            store       => \$element,
            strict_type => 1,
        },
        hash_ref => {
            default     => {},
            defined     => 1,
            required    => 1,
            store       => \$hash_ref,
            strict_type => 1,
        },
        key => { required => 1, defined => 1, strict_type => 1, store => \$key },
    };

    check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!};

    use List::Util qw{ any };

    return 0 if ( not exists ${$hash_ref}{$key} );

    return 1 if ( any { $_ eq $element } @{ $hash_ref->{$key} } );

    return;
}

sub get_splitted_lists {

## Function : Split list on regexp
## Returns  : \@match_list, \@no_match_list
## Arguments: $list_ref => List to split
##          : $regexp   => Regexp to split list on

    my ($arg_href) = @_;

    ## Flatten argument(s)
    my $list_ref;
    my $regexp;

    my $tmpl = {
        list_ref => {
            default     => [],
            defined     => 1,
            required    => 1,
            store       => \$list_ref,
            strict_type => 1,
        },
        regexp => {
            default     => qr//,
            defined     => 1,
            required    => 1,
            store       => \$regexp,
            strict_type => 1,
        },
    };

    check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!};

    my @match_list    = grep { m/$regexp/xms } @{$list_ref};
    my @no_match_list = grep { not m/$regexp/xms } @{$list_ref};

    return \@match_list, \@no_match_list;
}

1;


text:
const productUtil = require('../../utils/product.js')
var app = getApp()
Page({
  data: {
    title: '',
    id: 0,
    quantity: 1,
    product: {},
    windowWidth: 375,
    windowHeight: 667,
    pixelRatio: 2,
    accountType: '',
    from_share: false,
    addProductAnimation: {}
  },

  onShareAppMessage: function () {
    return {
      title: this.data.product.name,
      desc: "巴爷供销社 - 高品质购物",
      path: `pages/show_product/show_product?id=${this.data.product.id}&share=1`
    }
  },

  onLoad (params) {
    var that = this
    var id = params.id

    try {
      var res = wx.getSystemInfoSync()
      this.setData({
        windowWidth:  res.windowWidth,
        windowHeight: res.windowHeight,
        pixelRatio:   res.pixelRatio
      })
      app.globalData.windowWidth  = res.windowWidth
      app.globalData.windowHeight = res.windowHeight
      app.globalData.pixelRatio   = res.pixelRatio
    } catch (e) {
    }

    if (params.share) {
      productUtil.getProduct(id, function(result){
        var data = app.store.sync(result.data)
        that.setData({
          from_share: true,
          id: data.id,
          product: data,
          title: data.name
        })
      })
    } else {
      var allProducts
      if (params.type) {
        allProducts = wx.getStorageSync(`cate_${params.type}`)
      } else {
        allProducts = wx.getStorageSync('products')
      }
      var id = params.id
      var product = allProducts.filter(function(i){
        return i.id === id
      })[0]

      this.setData({
        from_share: false,
        id: id,
        product: product,
        title: product.name
      })
    }
  },

  onShow() {
    if (app.globalData.currentCustomer) {
      var accountType = app.globalData.currentCustomer.account_type
      this.setData({accountType: accountType})
    }
  },

  onReady() {
    wx.setNavigationBarTitle({ title: this.data.title })
  },

  bindAddToCart (e) {
    var that = this

    //管到屏蔽
    if (!app.globalData.featureManager.enableGuanDao) {
      if (this.data.product && (parseInt(this.data.product['category-id']) === 18)) {
        wx.showModal({
          title: '管到商品暂未开放',
          content: '目前无法在小程序上购买管到商品,如有需要,可以在巴爷微信商城上进行购买。',
          showCancel: false,
          success: function(res) {}
        })
        return
      }
    }

    this.popAddProduct()

    var cartItems = wx.getStorageSync('cartItems') || []

    var exist = cartItems.filter(function(ele){
      return ele.id === that.data.id
    })[0]

    if (exist) {
      exist.quantity = parseInt(exist.quantity) + 1
    } else {
      cartItems.push({
        id: this.data.id,
        quantity: 1,
        product: this.data.product
      })
    }
    wx.showToast({
      title: '成功加入',
      icon: 'success',
      duration: 1000
    })
    wx.setStorage({
      key: 'cartItems',
      data: cartItems
    })

    if (this.data.from_share) {
      wx.switchTab({
        url: '../cart/cart'
      })
    }
  },

  popAddProduct: function () {
    if (this.count) {
      this.count = this.count + 1
    } else {
      this.count = 1
    }
    var animation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease',
    })
    var y = this.count % 2 === 0 ? 200 : -200
    animation.translateY(y).step()

    this.setData({
      addProductAnimation: animation.export()
    })
  }
})


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotVVM.Framework.Hosting;

namespace DotVVM.Framework.ResourceManagement
{
    /// <summary>
    /// Represents a resource located at remote server identified by a url.
    /// </summary>
    public class UrlResourceLocation: IResourceLocation
    {
        public string Url { get; }
        public string DebugUrl { get; set; }
        public UrlResourceLocation(string url, string? debugUrl = null)
        {
            this.Url = url;
            this.DebugUrl = debugUrl ?? url;
        }

        public string GetUrl(IDotvvmRequestContext context, string name)
        {
            return context.TranslateVirtualPath(context.Configuration.Debug ? DebugUrl : Url);
        }
    }
}


text:
<?php

/**
 * JournalEntry form.
 *
 * @package    sf_sandbox
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class JournalEntryForm extends BaseJournalEntryForm
{
  public function configure()
  {
  }
}


text:
package ru.yandex.qatools.matchers.decorators;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import static ru.yandex.qatools.matchers.decorators.ActionMatcherDecorator.decorateMatcherWithAction;
import static ru.yandex.qatools.matchers.decorators.ConditionMatcherDecorator.decorateMatcherWithCondition;

/**
 * @author Alexander Tolmachev starlight@yandex-team.ru
 *         Date: 28.02.13
 */
public final class MatcherDecoratorsBuilder<T> extends TypeSafeMatcher<T> {
    private Matcher<? super T> matcher;

    @Factory
    public static <T> MatcherDecoratorsBuilder<T> should(final Matcher<? super T> matcher) {
        return new MatcherDecoratorsBuilder<T>(matcher);
    }

    private MatcherDecoratorsBuilder(Matcher<? super T> matcher) {
        this.matcher = matcher;
    }

    @Override
    protected boolean matchesSafely(T item) {
        return matcher.matches(item);
    }

    @Override
    public void describeTo(Description description) {
        matcher.describeTo(description);
    }

    @Override
    protected void describeMismatchSafely(T item, Description mismatchDescription) {
        matcher.describeMismatch(item, mismatchDescription);
    }

    public MatcherDecoratorsBuilder<T> after(final Action action) {
        matcher = decorateMatcherWithAction(matcher, action);
        return this;
    }

    public <E> MatcherDecoratorsBuilder<T> inCase(final E itemToMatchCondition, final Matcher<? super E> condition) {
        matcher = decorateMatcherWithCondition(matcher, itemToMatchCondition, condition);
        return this;
    }

    public MatcherDecoratorsBuilder<T> whileWaitingUntil(final Waiter waiter) {
        matcher = WaiterMatcherDecorator.decorateMatcherWithWaiter(matcher, waiter);
        return this;
    }
}


text:
import Color from 'color';
import ColorHash from 'color-hash';
import find from 'lodash/find';
import get from 'lodash/get';
import memoize from 'lodash/memoize';
import { ThemeType } from '..';
import { Coloring, Theme } from '../common-types';

const colorHash = new ColorHash();
export type ColorShade = 'main' | 'light' | 'dark';

const shadeCustomColor = (color: string, shade: 'main' | 'light' | 'dark') => {
	if (shade === 'main') {
		return color;
	}

	if (shade === 'light') {
		return lighten(color);
	}

	return darken(color);
};

// Returns a color that is legible if put on the passed background.
export const getLegibleTextColor = memoize((bg: string, contrast = 4.5) => {
	const bgColor = new Color(bg);
	const findWithContrast = (darken: number): string => {
		// Darkening goes from 0 to 1. This makes sure the recursive function terminates.
		if (darken >= 1) {
			return bgColor.darken(1).hex();
		}

		const textColor = bgColor.darken(darken);
		if (textColor.contrast(bgColor) >= contrast) {
			return textColor.hex();
		}

		// We can do divide-and-conquer strategy here, but this is simpler and still guaranteed to finish in < 20 iterations.
		return findWithContrast(darken + 0.05);
	};

	// It is pointless to start with 0, so we start with some trivially larger value
	return findWithContrast(0.1);
});

export const generateColorFromString = memoize((text: string): string => {
	return colorHash.hex(text.replace(/\s/g, ''));
});

export const isLight = (color?: string) => {
	return Color(color).luminosity() > 0.65;
};

export const opaque = (color: string, opacity: number) =>
	new Color([...Color(color).array(), opacity]).string();

export const lighten = (color: string) => Color(color).fade(0.3).string();

export const darken = (color: string, amount?: number) =>
	Color(color)
		.darken(amount || 0.2)
		.string();

export const getColoringType = (props: {
	theme: Theme;
	[key: string]: any;
}): string | undefined => {
	// get primary, tertiary, secondary etc
	const type = find<string>(
		Object.keys(props),
		(b: any) =>
			!!props[b] && !!find(Object.keys(props.theme.colors), (k) => k === b),
	);
	return type;
};

export const getColor = (
	props: { theme: Theme; [key: string]: any },
	key: string,
	shade: ColorShade,
) => {
	if (get(props, key)) {
		return shadeCustomColor(get(props, key), shade);
	}

	const type = getColoringType(props);
	if (type) {
		const color = get(props.theme, `colors.${type}`) as Theme['colors']['key'];
		if (color != null && typeof color === 'object') {
			return color[shade];
		} else {
			// We checked that this is not an object color, so we can ignore the typescript error
			return shadeCustomColor(color, shade);
		}
	}
};

export const getThemeColoring = (
	theme: ThemeType,
	props: { [key: string]: any },
	shade: ColorShade = 'main',
) => {
	// get primary, tertiary, secondary etc
	const type = find(
		Object.keys(props) as Array<keyof Coloring>,
		(b) => !!props[b] && !!theme.colors[b],
	);
	if (type) {
		return getColor({ ...props, theme }, type, shade);
	}
	return '';
};