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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>AbstractNetworkProtocol</title>
<meta name="date" content="2015-02-24">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

de.mash1t.networklib

Class AbstractNetworkProtocol

java.lang.Object

de.mash1t.networklib.AbstractNetworkProtocol

All Implemented Interfaces:

de.mash1t.networklib.methods.NetworkProtocol

Direct Known Subclasses:

ExtendedTCP

public abstract class AbstractNetworkProtocol
extends java.lang.Object
implements de.mash1t.networklib.methods.NetworkProtocol

Abstract class for mainly handling static method call of send(packet, thread, nwpType) Methods have to be implemented by childs

Constructor Summary

Constructors

Constructor and Description

AbstractNetworkProtocol()

Method Summary

Methods

Modifier and Type
Method and Description

boolean
close()

java.lang.String
getIP()

de.mash1t.networklib.packets.Packet
read()

boolean
send(de.mash1t.networklib.packets.Packet packet)

static boolean
send(de.mash1t.networklib.packets.Packet packet,
    ClientThread clientThread,
    de.mash1t.networklib.methods.NetworkProtocolType nwpType)

Sends a message to a specific thread

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AbstractNetworkProtocol

public AbstractNetworkProtocol()

Method Detail

send

public static boolean send(de.mash1t.networklib.packets.Packet packet,
           ClientThread clientThread,
           de.mash1t.networklib.methods.NetworkProtocolType nwpType)

Sends a message to a specific thread

Parameters:

packet -

clientThread -

nwpType -

Returns:

getIP

public java.lang.String getIP()

Specified by:

getIP in interface de.mash1t.networklib.methods.NetworkProtocol

send

public boolean send(de.mash1t.networklib.packets.Packet packet)

Specified by:

send in interface de.mash1t.networklib.methods.NetworkProtocol

read

public de.mash1t.networklib.packets.Packet read()

Specified by:

read in interface de.mash1t.networklib.methods.NetworkProtocol

close

public boolean close()

Specified by:

close in interface de.mash1t.networklib.methods.NetworkProtocol

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.codelibs</groupId>
	<artifactId>elasticsearch-taste</artifactId>
	<version>2.4.0-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>Elasticsearch Mahout Taste Plugin</name>
	<description>Mahout Taste Implementation for Elasticsearch</description>
	<inceptionYear>2011</inceptionYear>
	<licenses>
		<license>
			<name>The Apache Software License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>
	<scm>
		<connection>scm:git:git@github.com:codelibs/elasticsearch-taste.git</connection>
		<developerConnection>scm:git:git@github.com:codelibs/elasticsearch-taste.git</developerConnection>
		<url>git@github.com:codelibs/elasticsearch-taste.git</url>
	</scm>
	<parent>
		<groupId>org.sonatype.oss</groupId>
		<artifactId>oss-parent</artifactId>
		<version>9</version>
	</parent>
	<properties>
		<elasticsearch.version>2.4.0</elasticsearch.version>
		<elasticsearch.plugin.classname>org.codelibs.elasticsearch.taste.TastePlugin</elasticsearch.plugin.classname>
		<lucene.version>5.5.2</lucene.version>
		<slf4j.version>1.7.7</slf4j.version>
		<mahout.version>0.9</mahout.version>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>${maven.compiler.source}</source>
					<target>${maven.compiler.target}</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.19</version>
				<configuration>
					<includes>
						<include>**/*Test.java</include>
					</includes>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.4</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<configuration>
					<additionalparam>-Xdoclint:none</additionalparam>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<appendAssemblyId>false</appendAssemblyId>
					<outputDirectory>${project.build.directory}/releases/</outputDirectory>
					<descriptors>
						<descriptor>${basedir}/src/main/assemblies/plugin.xml</descriptor>
					</descriptors>
				</configuration>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>elasticsearch</artifactId>
			<version>${elasticsearch.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.lucene</groupId>
			<artifactId>lucene-analyzers-common</artifactId>
			<version>${lucene.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.mahout</groupId>
			<artifactId>mahout-math</artifactId>
			<version>${mahout.version}</version>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>19.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>
		<dependency>
			<groupId>org.codelibs</groupId>
			<artifactId>elasticsearch-cluster-runner</artifactId>
			<version>2.4.0.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

redpajama_set_name: RedPajamaGithub


text:
Imports NETGeographicLib

Module example_Geocentric
    Sub Main()
        Try
            Dim earth As Geocentric = New Geocentric(Constants.WGS84.MajorRadius,
                                                     Constants.WGS84.Flattening)
            ' Alternatively: Geocentric earth = new Geocentric();
            ' Sample forward calculation
            Dim lat As Double = 27.99, lon = 86.93, h = 8820 ' Mt Everest
            Dim X, Y, Z As Double
            earth.Forward(lat, lon, h, X, Y, Z)
            Console.WriteLine(String.Format("{0} {1} {2}",
                Math.Floor(X / 1000 + 0.5),
                Math.Floor(Y / 1000 + 0.5),
                Math.Floor(Z / 1000 + 0.5)))
            ' Sample reverse calculation
            X = 302000.0 : Y = 5636000.0 : Z = 2980000.0
            earth.Reverse(X, Y, Z, lat, lon, h)
            Console.WriteLine(String.Format("{0} {1} {2}", lat, lon, h))
        Catch ex As GeographicErr
            Console.WriteLine(String.Format("Caught exception: {0}", ex.Message))
        End Try
    End Sub
End Module


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.addCommentBefore = addCommentBefore;
exports.default = addComment;

function addCommentBefore(str, indent, comment) {
  if (!comment) return str;
  const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`);
  return `#${cc}\n${indent}${str}`;
}

function addComment(str, indent, comment) {
  return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`);
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Exporters.Csv;
using BenchmarkDotNet.Exporters.Json;
using BenchmarkDotNet.Exporters.Xml;
using BenchmarkDotNet.Extensions;
using BenchmarkDotNet.Filters;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Portability;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Toolchains.NativeAot;
using BenchmarkDotNet.Toolchains.CoreRun;
using BenchmarkDotNet.Toolchains.CsProj;
using BenchmarkDotNet.Toolchains.DotNetCli;
using BenchmarkDotNet.Toolchains.InProcess.Emit;
using BenchmarkDotNet.Toolchains.MonoWasm;
using BenchmarkDotNet.Toolchains.MonoAotLLVM;
using CommandLine;
using Perfolizer.Horology;
using Perfolizer.Mathematics.OutlierDetection;
using Perfolizer.Mathematics.SignificanceTesting;
using Perfolizer.Mathematics.Thresholds;

namespace BenchmarkDotNet.ConsoleArguments
{
    public static class ConfigParser
    {
        private const int MinimumDisplayWidth = 80;
        private const char EnvVarKeyValueSeparator = ':';

        private static readonly IReadOnlyDictionary<string, Job> AvailableJobs = new Dictionary<string, Job>(StringComparer.InvariantCultureIgnoreCase)
        {
            { "default", Job.Default },
            { "dry", Job.Dry },
            { "short", Job.ShortRun },
            { "medium", Job.MediumRun },
            { "long", Job.LongRun },
            { "verylong", Job.VeryLongRun }
        };

        [SuppressMessage("ReSharper", "StringLiteralTypo")]
        [SuppressMessage("ReSharper", "CoVariantArrayConversion")]
        private static readonly IReadOnlyDictionary<string, IExporter[]> AvailableExporters =
            new Dictionary<string, IExporter[]>(StringComparer.InvariantCultureIgnoreCase)
            {
                { "csv", new[] { CsvExporter.Default } },
                { "csvmeasurements", new[] { CsvMeasurementsExporter.Default } },
                { "html", new[] { HtmlExporter.Default } },
                { "markdown", new[] { MarkdownExporter.Default } },
                { "atlassian", new[] { MarkdownExporter.Atlassian } },
                { "stackoverflow", new[] { MarkdownExporter.StackOverflow } },
                { "github", new[] { MarkdownExporter.GitHub } },
                { "plain", new[] { PlainExporter.Default } },
                { "rplot", new[] { CsvMeasurementsExporter.Default, RPlotExporter.Default } }, // R Plots depends on having the full measurements available
                { "json", new[] { JsonExporter.Default } },
                { "briefjson", new[] { JsonExporter.Brief } },
                { "fulljson", new[] { JsonExporter.Full } },
                { "asciidoc", new[] { AsciiDocExporter.Default } },
                { "xml", new[] { XmlExporter.Default } },
                { "briefxml", new[] { XmlExporter.Brief } },
                { "fullxml", new[] { XmlExporter.Full } }
            };

        public static (bool isSuccess, IConfig config, CommandLineOptions options) Parse(string[] args, ILogger logger, IConfig globalConfig = null)
        {
            (bool isSuccess, IConfig config, CommandLineOptions options) result = default;

            using (var parser = CreateParser(logger))
            {
                parser
                    .ParseArguments<CommandLineOptions>(args)
                    .WithParsed(options => result = Validate(options, logger) ? (true, CreateConfig(options, globalConfig, args), options) : (false, default, default))
                    .WithNotParsed(errors => result = (false, default, default));
            }

            return result;
        }

        private static Parser CreateParser(ILogger logger)
            => new Parser(settings =>
            {
                settings.CaseInsensitiveEnumValues = true;
                settings.CaseSensitive = false;
                settings.EnableDashDash = true;
                settings.IgnoreUnknownArguments = false;
                settings.HelpWriter = new LoggerWrapper(logger);
                settings.MaximumDisplayWidth = Math.Max(MinimumDisplayWidth, GetMaximumDisplayWidth());
            });

        private static bool Validate(CommandLineOptions options, ILogger logger)
        {
            if (!AvailableJobs.ContainsKey(options.BaseJob))
            {
                logger.WriteLineError($"The provided base job \"{options.BaseJob}\" is invalid. Available options are: {string.Join(", ", AvailableJobs.Keys)}.");
                return false;
            }

            foreach (string runtime in options.Runtimes)
            {
                if (!TryParse(runtime, out RuntimeMoniker runtimeMoniker))
                {
                    logger.WriteLineError($"The provided runtime \"{runtime}\" is invalid. Available options are: {string.Join(", ", Enum.GetNames(typeof(RuntimeMoniker)).Select(name => name.ToLower()))}.");
                    return false;
                }
                else if (runtimeMoniker == RuntimeMoniker.MonoAOTLLVM && (options.AOTCompilerPath == null || options.AOTCompilerPath.IsNotNullButDoesNotExist()))
                {
                     logger.WriteLineError($"The provided {nameof(options.AOTCompilerPath)} \"{ options.AOTCompilerPath }\" does NOT exist. It MUST be provided.");
                }
            }

            foreach (string exporter in options.Exporters)
                if (!AvailableExporters.ContainsKey(exporter))
                {
                    logger.WriteLineError($"The provided exporter \"{exporter}\" is invalid. Available options are: {string.Join(", ", AvailableExporters.Keys)}.");
                    return false;
                }

            if (options.CliPath.IsNotNullButDoesNotExist())
            {
                logger.WriteLineError($"The provided {nameof(options.CliPath)} \"{options.CliPath}\" does NOT exist.");
                return false;
            }

            foreach (var coreRunPath in options.CoreRunPaths)
                if (coreRunPath.IsNotNullButDoesNotExist())
                {
                    if (Directory.Exists(coreRunPath.FullName))
                    {
                        logger.WriteLineError($"The provided path to CoreRun: \"{coreRunPath}\" exists but it's a directory, not an executable. You need to include CoreRun.exe (corerun on Unix) in the path.");
                    }
                    else
                    {
                        logger.WriteLineError($"The provided path to CoreRun: \"{coreRunPath}\" does NOT exist.");
                    }

                    return false;
                }

            if (options.MonoPath.IsNotNullButDoesNotExist())
            {
                logger.WriteLineError($"The provided {nameof(options.MonoPath)} \"{options.MonoPath}\" does NOT exist.");
                return false;
            }

            if (options.WasmJavascriptEngine.IsNotNullButDoesNotExist())
            {
                logger.WriteLineError($"The provided {nameof(options.WasmJavascriptEngine)} \"{options.WasmJavascriptEngine}\" does NOT exist.");
                return false;
            }

            if (options.IlcPackages.IsNotNullButDoesNotExist())
            {
                logger.WriteLineError($"The provided {nameof(options.IlcPackages)} \"{options.IlcPackages}\" does NOT exist.");
                return false;
            }

            if (options.HardwareCounters.Count() > 3)
            {
                logger.WriteLineError("You can't use more than 3 HardwareCounters at the same time.");
                return false;
            }

            foreach (var counterName in options.HardwareCounters)
                if (!Enum.TryParse(counterName, ignoreCase: true, out HardwareCounter _))
                {
                    logger.WriteLineError($"The provided hardware counter \"{counterName}\" is invalid. Available options are: {string.Join("+", Enum.GetNames(typeof(HardwareCounter)))}.");
                    return false;
                }

            if (!string.IsNullOrEmpty(options.StatisticalTestThreshold) && !Threshold.TryParse(options.StatisticalTestThreshold, out _))
            {
                logger.WriteLineError("Invalid Threshold for Statistical Test. Use --help to see examples.");
                return false;
            }

            if (options.EnvironmentVariables.Any(envVar => envVar.IndexOf(EnvVarKeyValueSeparator) <= 0))
            {
                logger.WriteLineError($"Environment variable value must be separated from the key using '{EnvVarKeyValueSeparator}'. Use --help to see examples.");
                return false;
            }

            return true;
        }

        private static IConfig CreateConfig(CommandLineOptions options, IConfig globalConfig, string[] args)
        {
            var config = new ManualConfig();

            var baseJob = GetBaseJob(options, globalConfig);
            var expanded = Expand(baseJob.UnfreezeCopy(), options, args).ToArray(); // UnfreezeCopy ensures that each of the expanded jobs will have it's own ID
            if (expanded.Length > 1)
                expanded[0] = expanded[0].AsBaseline(); // if the user provides multiple jobs, then the first one should be a baseline
            config.AddJob(expanded);
            if (config.GetJobs().IsEmpty() && baseJob != Job.Default)
                config.AddJob(baseJob);

            config.AddExporter(options.Exporters.SelectMany(exporter => AvailableExporters[exporter]).ToArray());

            config.AddHardwareCounters(options.HardwareCounters
                .Select(counterName => (HardwareCounter)Enum.Parse(typeof(HardwareCounter), counterName, ignoreCase: true))
                .ToArray());

            if (options.UseMemoryDiagnoser)
                config.AddDiagnoser(MemoryDiagnoser.Default);
            if (options.UseThreadingDiagnoser)
                config.AddDiagnoser(ThreadingDiagnoser.Default);
            if (options.UseDisassemblyDiagnoser)
                config.AddDiagnoser(new DisassemblyDiagnoser(new DisassemblyDiagnoserConfig(maxDepth: options.DisassemblerRecursiveDepth, exportDiff: options.DisassemblerDiff)));
            if (!string.IsNullOrEmpty(options.Profiler))
                config.AddDiagnoser(DiagnosersLoader.GetImplementation<IProfiler>(profiler => profiler.ShortName.EqualsWithIgnoreCase(options.Profiler)));

            if (options.DisplayAllStatistics)
                config.AddColumn(StatisticColumn.AllStatistics);
            if (!string.IsNullOrEmpty(options.StatisticalTestThreshold) && Threshold.TryParse(options.StatisticalTestThreshold, out var threshold))
                config.AddColumn(new StatisticalTestColumn(StatisticalTestKind.MannWhitney, threshold));

            if (options.ArtifactsDirectory != null)
                config.ArtifactsPath = options.ArtifactsDirectory.FullName;

            var filters = GetFilters(options).ToArray();
            if (filters.Length > 1)
                config.AddFilter(new UnionFilter(filters));
            else
                config.AddFilter(filters);

            config.WithOption(ConfigOptions.JoinSummary, options.Join);
            config.WithOption(ConfigOptions.KeepBenchmarkFiles, options.KeepBenchmarkFiles);
            config.WithOption(ConfigOptions.DontOverwriteResults, options.DontOverwriteResults);
            config.WithOption(ConfigOptions.StopOnFirstError, options.StopOnFirstError);
            config.WithOption(ConfigOptions.DisableLogFile, options.DisableLogFile);
            config.WithOption(ConfigOptions.LogBuildOutput, options.LogBuildOutput);
            config.WithOption(ConfigOptions.GenerateMSBuildBinLog, options.GenerateMSBuildBinLog);

            if (options.MaxParameterColumnWidth.HasValue)
                config.WithSummaryStyle(SummaryStyle.Default.WithMaxParameterColumnWidth(options.MaxParameterColumnWidth.Value));

            if (options.TimeOutInSeconds.HasValue)
                config.WithBuildTimeout(TimeSpan.FromSeconds(options.TimeOutInSeconds.Value));

            return config;
        }

        private static Job GetBaseJob(CommandLineOptions options, IConfig globalConfig)
        {
            var baseJob =
                globalConfig?.GetJobs().SingleOrDefault(job => job.Meta.IsDefault) // global config might define single custom Default job
                ?? AvailableJobs[options.BaseJob.ToLowerInvariant()];

            if (baseJob != Job.Dry && options.Outliers != OutlierMode.RemoveUpper)
                baseJob = baseJob.WithOutlierMode(options.Outliers);

            if (options.Affinity.HasValue)
                baseJob = baseJob.WithAffinity((IntPtr) options.Affinity.Value);

            if (options.LaunchCount.HasValue)
                baseJob = baseJob.WithLaunchCount(options.LaunchCount.Value);
            if (options.WarmupIterationCount.HasValue)
                baseJob = baseJob.WithWarmupCount(options.WarmupIterationCount.Value);
            if (options.MinWarmupIterationCount.HasValue)
                baseJob = baseJob.WithMinWarmupCount(options.MinWarmupIterationCount.Value);
            if (options.MaxWarmupIterationCount.HasValue)
                baseJob = baseJob.WithMaxWarmupCount(options.MaxWarmupIterationCount.Value);
            if (options.IterationTimeInMilliseconds.HasValue)
                baseJob = baseJob.WithIterationTime(TimeInterval.FromMilliseconds(options.IterationTimeInMilliseconds.Value));
            if (options.IterationCount.HasValue)
                baseJob = baseJob.WithIterationCount(options.IterationCount.Value);
            if (options.MinIterationCount.HasValue)
                baseJob = baseJob.WithMinIterationCount(options.MinIterationCount.Value);
            if (options.MaxIterationCount.HasValue)
                baseJob = baseJob.WithMaxIterationCount(options.MaxIterationCount.Value);
            if (options.InvocationCount.HasValue)
                baseJob = baseJob.WithInvocationCount(options.InvocationCount.Value);
            if (options.UnrollFactor.HasValue)
                baseJob = baseJob.WithUnrollFactor(options.UnrollFactor.Value);
            if (options.RunStrategy.HasValue)
                baseJob = baseJob.WithStrategy(options.RunStrategy.Value);
            if (options.Platform.HasValue)
                baseJob = baseJob.WithPlatform(options.Platform.Value);
            if (options.RunOncePerIteration)
                baseJob = baseJob.RunOncePerIteration();
            if (options.MemoryRandomization)
                baseJob = baseJob.WithMemoryRandomization();

            if (options.EnvironmentVariables.Any())
            {
                baseJob = baseJob.WithEnvironmentVariables(options.EnvironmentVariables.Select(text =>
                {
                    var separated = text.Split(new[] { EnvVarKeyValueSeparator }, 2);
                    return new EnvironmentVariable(separated[0], separated[1]);
                }).ToArray());
            }

            if (AvailableJobs.Values.Contains(baseJob)) // no custom settings
                return baseJob;

            return baseJob
                .AsDefault(false) // after applying all settings from console args the base job is not default anymore
                .AsMutator(); // we mark it as mutator so it will be applied to other jobs defined via attributes and merged later in GetRunnableJobs method
        }

        private static IEnumerable<Job> Expand(Job baseJob, CommandLineOptions options, string[] args)
        {
            if (options.RunInProcess)
            {
                yield return baseJob.WithToolchain(InProcessEmitToolchain.Instance);
            }
            else if (!string.IsNullOrEmpty(options.ClrVersion))
            {
                yield return baseJob.WithRuntime(ClrRuntime.CreateForLocalFullNetFrameworkBuild(options.ClrVersion)); // local builds of .NET Runtime
            }
            else if (options.CliPath != null && options.Runtimes.IsEmpty() && options.CoreRunPaths.IsEmpty())
            {
                yield return CreateCoreJobWithCli(baseJob, options);
            }
            else
            {
                // in case both --runtimes and --corerun are specified, the first one is returned first and becomes a baseline job
                string first = args.FirstOrDefault(arg =>
                    arg.Equals("--runtimes", StringComparison.OrdinalIgnoreCase)
                    || arg.Equals("-r", StringComparison.OrdinalIgnoreCase)

                    || arg.Equals("--corerun", StringComparison.OrdinalIgnoreCase));

                if (first is null || first.Equals("--corerun", StringComparison.OrdinalIgnoreCase))
                {
                    foreach (var coreRunPath in options.CoreRunPaths)
                        yield return CreateCoreRunJob(baseJob, options, coreRunPath); // local dotnet/runtime builds

                    foreach (string runtime in options.Runtimes) // known runtimes
                        yield return CreateJobForGivenRuntime(baseJob, runtime, options);
                }
                else
                {
                    foreach (string runtime in options.Runtimes) // known runtimes
                        yield return CreateJobForGivenRuntime(baseJob, runtime, options);

                    foreach (var coreRunPath in options.CoreRunPaths)
                        yield return CreateCoreRunJob(baseJob, options, coreRunPath); // local dotnet/runtime builds
                }
            }
        }

        private static Job CreateJobForGivenRuntime(Job baseJob, string runtimeId, CommandLineOptions options)
        {
            if (!TryParse(runtimeId, out RuntimeMoniker runtimeMoniker))
            {
                throw new InvalidOperationException("Impossible, already validated by the Validate method");
            }

            switch (runtimeMoniker)
            {
                case RuntimeMoniker.Net461:
                case RuntimeMoniker.Net462:
                case RuntimeMoniker.Net47:
                case RuntimeMoniker.Net471:
                case RuntimeMoniker.Net472:
                case RuntimeMoniker.Net48:
                    return baseJob
                        .WithRuntime(runtimeMoniker.GetRuntime())
                        .WithToolchain(CsProjClassicNetToolchain.From(runtimeId, options.RestorePath?.FullName));
                case RuntimeMoniker.NetCoreApp20:
                case RuntimeMoniker.NetCoreApp21:
                case RuntimeMoniker.NetCoreApp22:
                case RuntimeMoniker.NetCoreApp30:
                case RuntimeMoniker.NetCoreApp31:
#pragma warning disable CS0618 // Type or member is obsolete
                case RuntimeMoniker.NetCoreApp50:
#pragma warning restore CS0618 // Type or member is obsolete
                case RuntimeMoniker.Net50:
                case RuntimeMoniker.Net60:
                case RuntimeMoniker.Net70:
                    return baseJob
                        .WithRuntime(runtimeMoniker.GetRuntime())
                        .WithToolchain(CsProjCoreToolchain.From(new NetCoreAppSettings(runtimeId, null, runtimeId, options.CliPath?.FullName, options.RestorePath?.FullName)));
                case RuntimeMoniker.Mono:
                    return baseJob.WithRuntime(new MonoRuntime("Mono", options.MonoPath?.FullName));
                case RuntimeMoniker.NativeAot60:
                    return CreateAotJob(baseJob, options, runtimeMoniker, "6.0.0-*", "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-experimental/nuget/v3/index.json");
                case RuntimeMoniker.NativeAot70:
                    return CreateAotJob(baseJob, options, runtimeMoniker, "7.0.0-*", "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet7/nuget/v3/index.json");
                case RuntimeMoniker.Wasm:
                    return MakeWasmJob(baseJob, options, RuntimeInformation.IsNetCore ? CoreRuntime.GetCurrentVersion().MsBuildMoniker : "net5.0", runtimeMoniker);
                case RuntimeMoniker.WasmNet50:
                    return MakeWasmJob(baseJob, options, "net5.0", runtimeMoniker);
                case RuntimeMoniker.WasmNet60:
                    return MakeWasmJob(baseJob, options, "net6.0", runtimeMoniker);
                case RuntimeMoniker.WasmNet70:
                    return MakeWasmJob(baseJob, options, "net7.0", runtimeMoniker);
                case RuntimeMoniker.MonoAOTLLVM:
                    return MakeMonoAOTLLVMJob(baseJob, options, RuntimeInformation.IsNetCore ? CoreRuntime.GetCurrentVersion().MsBuildMoniker : "net6.0");
                case RuntimeMoniker.MonoAOTLLVMNet60:
                    return MakeMonoAOTLLVMJob(baseJob, options, "net6.0");
                case RuntimeMoniker.MonoAOTLLVMNet70:
                    return MakeMonoAOTLLVMJob(baseJob, options, "net7.0");
                default:
                    throw new NotSupportedException($"Runtime {runtimeId} is not supported");
            }
        }

        private static Job CreateAotJob(Job baseJob, CommandLineOptions options, RuntimeMoniker runtimeMoniker, string ilCompilerVersion, string nuGetFeedUrl)
        {
            var builder = NativeAotToolchain.CreateBuilder();

            if (options.CliPath != null)
                builder.DotNetCli(options.CliPath.FullName);
            if (options.RestorePath != null)
                builder.PackagesRestorePath(options.RestorePath.FullName);

            if (options.IlcPackages != null)
                builder.UseLocalBuild(options.IlcPackages);
            else if (!string.IsNullOrEmpty(options.ILCompilerVersion))
                builder.UseNuGet(options.ILCompilerVersion, nuGetFeedUrl);
            else
                builder.UseNuGet(ilCompilerVersion, nuGetFeedUrl);

            var runtime = runtimeMoniker.GetRuntime();
            builder.TargetFrameworkMoniker(runtime.MsBuildMoniker);

            return baseJob.WithRuntime(runtime).WithToolchain(builder.ToToolchain());
        }

        private static Job MakeMonoAOTLLVMJob(Job baseJob, CommandLineOptions options, string msBuildMoniker)
        {
            var monoAotLLVMRuntime = new MonoAotLLVMRuntime(aotCompilerPath: options.AOTCompilerPath, aotCompilerMode: options.AOTCompilerMode, msBuildMoniker: msBuildMoniker);

            var toolChain = MonoAotLLVMToolChain.From(
            new NetCoreAppSettings(
                targetFrameworkMoniker: monoAotLLVMRuntime.MsBuildMoniker,
                runtimeFrameworkVersion: null,
                name: monoAotLLVMRuntime.Name,
                customDotNetCliPath: options.CliPath?.FullName,
                packagesPath: options.RestorePath?.FullName,
                customRuntimePack: options.CustomRuntimePack,
                aotCompilerPath: options.AOTCompilerPath.ToString(),
                aotCompilerMode: options.AOTCompilerMode));

            return baseJob.WithRuntime(monoAotLLVMRuntime).WithToolchain(toolChain);
        }

        private static Job MakeWasmJob(Job baseJob, CommandLineOptions options, string msBuildMoniker, RuntimeMoniker moniker)
        {
            bool wasmAot = options.AOTCompilerMode == MonoAotCompilerMode.wasm;

            var wasmRuntime = new WasmRuntime(
                msBuildMoniker: msBuildMoniker,
                javaScriptEngine: options.WasmJavascriptEngine?.FullName ?? "v8",
                javaScriptEngineArguments: options.WasmJavaScriptEngineArguments,
                aot: wasmAot,
                wasmDataDir: options.WasmDataDirectory?.FullName,
                moniker: moniker);

            var toolChain = WasmToolChain.From(new NetCoreAppSettings(
                targetFrameworkMoniker: wasmRuntime.MsBuildMoniker,
                runtimeFrameworkVersion: null,
                name: wasmRuntime.Name,
                customDotNetCliPath: options.CliPath?.FullName,
                packagesPath: options.RestorePath?.FullName,
                customRuntimePack: options.CustomRuntimePack,
                aotCompilerMode: options.AOTCompilerMode));

            return baseJob.WithRuntime(wasmRuntime).WithToolchain(toolChain);
        }

        private static IEnumerable<IFilter> GetFilters(CommandLineOptions options)
        {
            if (options.Filters.Any())
                yield return new GlobFilter(options.Filters.ToArray());
            if (options.AllCategories.Any())
                yield return new AllCategoriesFilter(options.AllCategories.ToArray());
            if (options.AnyCategories.Any())
                yield return new AnyCategoriesFilter(options.AnyCategories.ToArray());
            if (options.AttributeNames.Any())
                yield return new AttributesFilter(options.AttributeNames.ToArray());
        }

        private static int GetMaximumDisplayWidth()
        {
            try
            {
                return Console.WindowWidth;
            }
            catch (IOException)
            {
                return MinimumDisplayWidth;
            }
        }

        private static Job CreateCoreRunJob(Job baseJob, CommandLineOptions options, FileInfo coreRunPath)
            => baseJob
                .WithToolchain(new CoreRunToolchain(
                    coreRunPath,
                    createCopy: true,
                    targetFrameworkMoniker:
                        RuntimeInformation.IsNetCore
                            ? RuntimeInformation.GetCurrentRuntime().MsBuildMoniker
                            : CoreRuntime.Latest.MsBuildMoniker, // use most recent tfm, as the toolchain is being used only by dotnet/runtime contributors
                    customDotNetCliPath: options.CliPath,
                    restorePath: options.RestorePath,
                    displayName: GetCoreRunToolchainDisplayName(options.CoreRunPaths, coreRunPath)));

        private static Job CreateCoreJobWithCli(Job baseJob, CommandLineOptions options)
            => baseJob
                .WithToolchain(CsProjCoreToolchain.From(
                    new NetCoreAppSettings(
                        targetFrameworkMoniker: RuntimeInformation.GetCurrentRuntime().MsBuildMoniker,
                        customDotNetCliPath: options.CliPath?.FullName,
                        runtimeFrameworkVersion: null,
                        name: RuntimeInformation.GetCurrentRuntime().Name,
                        packagesPath: options.RestorePath?.FullName)));

        /// <summary>
        /// we have a limited amount of space when printing the output to the console, so we try to keep things small and simple
        ///
        /// for following paths:
        ///  C:\Projects\coreclr_upstream\bin\tests\Windows_NT.x64.Release\Tests\Core_Root\CoreRun.exe
        ///  C:\Projects\coreclr_upstream\bin\tests\Windows_NT.x64.Release\Tests\Core_Root_beforeMyChanges\CoreRun.exe
        ///
        /// we get:
        ///
        /// \Core_Root\CoreRun.exe
        /// \Core_Root_beforeMyChanges\CoreRun.exe
        /// </summary>
        private static string GetCoreRunToolchainDisplayName(IReadOnlyList<FileInfo> paths, FileInfo coreRunPath)
        {
            if (paths.Count <= 1)
                return "CoreRun";

            int commonLongestPrefixIndex = paths[0].FullName.Length;
            for (int i = 1; i < paths.Count; i++)
            {
                commonLongestPrefixIndex = Math.Min(commonLongestPrefixIndex, paths[i].FullName.Length);
                for (int j = 0; j < commonLongestPrefixIndex; j++)
                    if (paths[i].FullName[j] != paths[0].FullName[j])
                    {
                        commonLongestPrefixIndex = j;
                        break;
                    }
            }

            if (commonLongestPrefixIndex <= 1)
                return coreRunPath.FullName;

            var lastCommonDirectorySeparatorIndex = coreRunPath.FullName.LastIndexOf(Path.DirectorySeparatorChar, commonLongestPrefixIndex - 1);

            return coreRunPath.FullName.Substring(lastCommonDirectorySeparatorIndex);
        }

        private static bool TryParse(string runtime, out RuntimeMoniker runtimeMoniker)
        {
            int index = runtime.IndexOf('-');

            return index < 0
                ? Enum.TryParse<RuntimeMoniker>(runtime.Replace(".", string.Empty), ignoreCase: true, out runtimeMoniker)
                : Enum.TryParse<RuntimeMoniker>(runtime.Substring(0, index).Replace(".", string.Empty), ignoreCase: true, out runtimeMoniker);
        }
    }
}


text:
#ifndef GRPC_CORE_LIB_SECURITY_CREDENTIALS_SSL_SSL_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_SSL_SSL_CREDENTIALS_H

#include "src/core/lib/security/credentials/credentials.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
  grpc_channel_credentials base;
  grpc_ssl_config config;
} grpc_ssl_credentials;

struct grpc_ssl_server_certificate_config {
  grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs;
  size_t num_key_cert_pairs;
  char* pem_root_certs;
};

typedef struct {
  grpc_ssl_server_certificate_config_callback cb;
  void* user_data;
} grpc_ssl_server_certificate_config_fetcher;

typedef struct {
  grpc_server_credentials base;
  grpc_ssl_server_config config;
  grpc_ssl_server_certificate_config_fetcher certificate_config_fetcher;
} grpc_ssl_server_credentials;

tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs(
    const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
    size_t num_key_cert_pairs);

void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair* kp,
                                             size_t num_key_cert_pairs);

#ifdef __cplusplus
}
#endif

#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_SSL_SSL_CREDENTIALS_H */


text: "$CLOUD_REBUILD" LockFreeQueue 32 dll release same


text:
namespace content {

class CONTENT_EXPORT WebKeyboardEventBuilder {
 public:
  static blink::WebKeyboardEvent Build(HWND hwnd,
                                       UINT message,
                                       WPARAM wparam,
                                       LPARAM lparam,
                                       double time_stamp);
};

class CONTENT_EXPORT WebMouseEventBuilder {
 public:
  static blink::WebMouseEvent Build(
      HWND hwnd,
      UINT message,
      WPARAM wparam,
      LPARAM lparam,
      double time_stamp,
      blink::WebPointerProperties::PointerType pointer_type);
};

class CONTENT_EXPORT WebMouseWheelEventBuilder {
 public:
  static blink::WebMouseWheelEvent Build(
      HWND hwnd,
      UINT message,
      WPARAM wparam,
      LPARAM lparam,
      double time_stamp,
      blink::WebPointerProperties::PointerType pointer_type);
};

} // namespace content

#endif  // CONTENT_BROWSER_RENDERER_HOST_INPUT_WEB_INPUT_EVENT_BUILDERS_WIN_H_


text:
/**
 * Copyright (c) 2009 Carnegie Mellon University.
 *     All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS
 *  IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 *  express or implied.  See the License for the specific language
 *  governing permissions and limitations under the License.
 *
 * For more about this software visit:
 *
 *      http://www.graphlab.ml.cmu.edu
 *
 */

#ifndef GRAPHLAB_QUEUED_FIFO_SCHEDULER_HPP
#define GRAPHLAB_QUEUED_FIFO_SCHEDULER_HPP

#include <algorithm>
#include <queue>

#include <graph/graph_basic_types.hpp>
#include <parallel/pthread_tools.hpp>
#include <parallel/atomic.hpp>

#include <util/dense_bitset.hpp>

#include <random/random.hpp>
#include <graphlab/scheduler/ischeduler.hpp>
#include <graphlab/options/graphlab_options.hpp>

#include <graphlab/macros_def.hpp>
namespace graphlab {

  /**
   * \ingroup group_schedulers
   *
   * This class defines a multiple queue approximate fifo scheduler.
   * Each processor has its own in_queue which it puts new tasks in
   * and out_queue which it pulls tasks from.  Once a processors
   * in_queue gets too large, the entire queue is placed at the end of
   * the shared master queue.  Once a processors out queue is empty it
   * grabs the next out_queue from the master.
   */
  class queued_fifo_scheduler: public ischeduler {

  public:

    typedef std::deque<lvid_type> queue_type;

  private:
    size_t ncpus;
    size_t num_vertices;
    size_t multi;
    dense_bitset vertex_is_scheduled;
    std::deque<queue_type> master_queue;
    mutex master_lock;
    size_t sub_queue_size;
    std::vector<queue_type> in_queues;
    std::vector<mutex> in_queue_locks;
    std::vector<queue_type> out_queues;
    std::vector<mutex> out_queue_locks;

    void set_options(const graphlab_options& opts);

    void initialize_data_structures();
  public:

    queued_fifo_scheduler(size_t num_vertices,
                          const graphlab_options& opts);

    void set_num_vertices(const lvid_type numv);

    void schedule(const lvid_type vid, double priority = 1 /* ignored */);

    /** Get the next element in the queue */
    sched_status::status_enum get_next(const size_t cpuid,
                                       lvid_type& ret_vid);

    bool empty();

    /**
     * Print a help string describing the options that this scheduler
     * accepts.
     */
    static void print_options_help(std::ostream& out) {
      out << "\t queuesize: [the size at which a subqueue is "
          << "placed in the master queue. default = 100]\n";
      out << "\t multi = [number of queues per thread. Default = 3].\n";
    }

  };

} // end of namespace graphlab
#include <graphlab/macros_undef.hpp>

#endif


text:
"""
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].
"""
__author__ = 'Danyang'
class Solution:
    def removeDuplicates(self, A):
        """
        Algorithms: Two Pointers, open & closed
        Data structure: array
        Shifting the array

        del, pop(), or remove() are not allowed.
        return the length of "shrunk" array
        The array remains the same length

        :param A: list
        :return: "shrunk" list
        """
        length = len(A)

        # trivial
        if length==0 or length==1:
            return length

        # closed pointer, open pointer
        closed_ptr = 0
        open_ptr = 1
        while open_ptr<length:
            # find the next non-duplicate:
            if A[closed_ptr]==A[open_ptr]:
                open_ptr += 1
                continue  # go to the next iteration

            non_duplicate = A[open_ptr]
            A[closed_ptr+1] = non_duplicate
            closed_ptr += 1

        return closed_ptr+1 # length is index+1

    def removeDuplicates_another_loop_style(self, A):
        """
        Yet another looping style - double while loops
        :param A: list
        :return: "shrunk" list
        """
        length = len(A)

        if length==0 or length==1:
            return length

        closed_ptr = 0
        open_ptr = 1
        while open_ptr<length:
            while open_ptr<length and A[closed_ptr]==A[open_ptr]:
                open_ptr += 1

            if open_ptr<length:
                non_duplicate = A[open_ptr]
                A[closed_ptr+1] = non_duplicate
                closed_ptr += 1

        return closed_ptr+1 # length is index+1


text:
<?php

namespace App\Http\Controllers\Module\Authentication;

use App\Http\Controllers\Controller;
use App\Http\Requests\Module\Auth\LoginRequest;
use App\Models\Vendor\Facades\AuthenticationHistory;
use App\Models\Vendor\Facades\Token;
use App\Models\Vendor\Facades\User;
use Exception;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\URL;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/dashboard';
    private $previousRouteKey = 'WBPreviousURL';
    private $previousRouteName = null;

    public function __construct()
    {
        parent::__construct();
        $this->middleware('guest')->except('logoutAction');
        $this->previousRouteName = app('router')
            ->getRoutes()
            ->match(app('request')->create(URL::previous()))
            ->getName();
    }

    /**
     * Show the application's login form.
     *
     * @return Response
     */
    public function loginAction()
    {
        if (!in_array($this->previousRouteName, [
            'auth.login', 'auth.login.process', 'auth.logout', 'auth.facebook', 'auth.facebook.callback',
            'auth.register', 'auth.register.process',
            'auth.password.forgot', 'auth.password.process.forgot', 'auth.password.recover', 'auth.password.process.recover',
            'auth.verify.email', 'auth.verify.phone'
        ])) {
            request()->session()->put($this->previousRouteKey, URL::previous());
        }

        return $this->view('auth.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param LoginRequest $request
     * @return bool|RedirectResponse
     */
    public function processAction(LoginRequest $request)
    {
        // redirect to previous url
        $previous_url = session($this->previousRouteKey, $this->redirectTo);
        if ($previous_url && $previous_url != url('/')) {
            $this->redirectTo = $previous_url;
        }

        // too many attempt
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            $seconds = $this->limiter()->availableIn(
                $this->throttleKey($request)
            );

            return $this->_authenticationError(
                $request,
                'Too many attempts to login, please try again later after ' . $seconds . ' seconds.'
            );
        }

        // authenticate
        if ($this->_authenticate($request)) {
            return $this->_authenticated($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);
        return $this->_authenticationError($request, 'Invalid username or password.');
    }

    /**
     * Authentication error
     *
     * @param $request
     * @param $error
     * @return RedirectResponse
     */
    private function _authenticationError($request, $error)
    {
        if ($request->ajax()) {
            return failedJSONResponse(['username' => $error], 422, false);
        } else {
            return $this->redirect()->withErrors([
                'username' => $error,
            ]);
        }
    }

    /**
     * Authenticate using username or email
     *
     * @param $request
     * @return bool
     */
    private function _authenticate($request)
    {
        // authenticate using email
        if (auth()->attempt($this->_requestInputs($request), $request->filled('remember'))) {
            return true;
        }

        // authenticate using username
        if (auth()->attempt($this->_requestInputs($request, 'username'), $request->filled('remember'))) {
            return true;
        }

        return false;
    }

    /**
     * Default request inputs for login
     *
     * @param $request
     * @param string $type
     * @return array
     */
    private function _requestInputs($request, $type = 'email')
    {
        return [
            $type => $request->get('username'),
            'password' => $request->get('password'),
            'is_email_verified' => 1,
            'is_account_enabled' => 1
        ];
    }

    /**
     * Authenticated user
     *
     * @param $request
     * @return bool
     */
    private function _authenticated($request)
    {
        $request->session()->regenerate();
        $this->clearLoginAttempts($request);
        __initializeSettings();

        // login history
        $this->_logAuthentication();

        // create session log
        $this->_createTokenLog();

        if ($this->request->ajax()) {
            return successJSONResponse([
                'redirect' => $this->redirectPath()
            ]);
        }

        return $this->redirect($this->redirectPath());
    }

    /**
     * Log the authentication
     * @param string $type
     */
    private function _logAuthentication($type = 'login')
    {
        if (!__me()) {
            return;
        }

        try {
            $userAgent = userAgent();

            AuthenticationHistory::store([
                'user_id' => __me()->id,
                'ip' => ipAddress(),
                'platform' => $userAgent->platform . ', ' . $userAgent->browserName,
                'type' => $type
            ]);
        } catch (Exception $e) {
            logErrors('LoginController._logAuthentication: ' . $e->getMessage());
        }
    }

    /**
     * Create token log
     */
    private function _createTokenLog()
    {
        User::crateToken(__me(), 'client', session()->getId(), config('session.lifetime'));
    }

    /**
     * Log the user out of the application.
     *
     * @return Response
     */
    public function logoutAction()
    {
        // login history
        $this->_logAuthentication('logout');

        // destroy token log
        $this->_destroyTokenLog();

        return $this->logout($this->request);
    }

    /**
     * Delete the current token log
     */
    private function _destroyTokenLog()
    {
        Token::remove([
            'user_id' => __me()->id,
            'token' => session()->getId(),
            'source' => 'client'
        ]);
    }
}


text:
package exercise.p02_ExtendedDatabase;

import javax.naming.OperationNotSupportedException;
import java.util.ArrayList;
import java.util.List;

public class Database {

    private Person[] elements;
    private int elementsCount = 0;
    private int index;

    public Database(Person... people) throws OperationNotSupportedException {
        this.elementsCount = people.length;
        this.setElements(people);
        this.index = elementsCount - 1;
    }

    public void add(Person person) throws OperationNotSupportedException {
        if (person == null) {
            throw new OperationNotSupportedException();
        }

        this.elements[++index] = person;
        this.elementsCount++;
    }

    public void remove() throws OperationNotSupportedException {
        try {
			this.elements[index--] = null;
			this.elementsCount--;
		} catch (ArrayIndexOutOfBoundsException ex) {
			throw new OperationNotSupportedException();
		}
    }

    public Person[] getElements() {
        Person[] buffer = new Person[elementsCount];
        int bufferIndex = 0;

        for (Person person : elements) {
            if (person != null) {
                buffer[bufferIndex++] = person;
            }
        }

        return buffer;
    }

    public Person findByUsername(String username) throws OperationNotSupportedException {
        List<Person> people = new ArrayList<>();

        if (username == null) {
            throw new OperationNotSupportedException();
        }

        for (Person person : elements) {

            if (person == null) {
                continue;
            }

            if (person.getUsername().equals(username)) {
                people.add(person);
            }
        }

        if (people.size() != 1) {
            throw new OperationNotSupportedException();
        }

        return people.get(0);
    }

    public Person findById(long id) throws OperationNotSupportedException {
        List<Person> people = new ArrayList<>();

        for (Person person : elements) {

            if (person == null) {
                continue;
            }

            if (person.getId() == id) {
                people.add(person);
            }
        }

        if (people.size() != 1) {
            throw new OperationNotSupportedException();
        }

        return people.get(0);
    }

    private void setElements(Person... elements) throws OperationNotSupportedException {
        if (elements.length > 16 ||
                elements.length < 1) {
            throw new OperationNotSupportedException();
        }

        this.elements = new Person[16];
        int bufferIndex = 0;

        for (Person person : elements) {
            this.elements[bufferIndex++] = person;
        }

        this.index = elements.length - 1;
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Aloha, Images!</title>

	<link href="../vendor/ui/ui-lightness/jquery-ui-1.8.10.cropnresize.css" rel="stylesheet" type="text/css" />
	<link rel="stylesheet" href="../../../../demo/common/index.css"	type="text/css">
	<link rel="stylesheet" href="test.css"	type="text/css">


text:
using System;
using System.Threading;
using System.Threading.Tasks;
// ReSharper disable CheckNamespace

namespace TWCore.Services.Messaging
{
    /// <inheritdoc />
    /// <summary>
    /// Defines a message processor async version
    /// </summary>
    public interface IMessageProcessorAsync : IDisposable
    {
        /// <summary>
        /// Initialize message processor
        /// </summary>
        void Init();
        /// <summary>
        /// Invokes the processing a message
        /// </summary>
        /// <param name="message">Message to process</param>
        /// <param name="cancellationToken">Cancellation token for process message timeout</param>
        /// <returns>Process response</returns>
        Task<object> ProcessAsync(object message, CancellationToken cancellationToken);
    }
}


text:
package com.jaredrummler.android.processes;

/**
 * @deprecated Use {@link com.jaredrummler.android.processes.AndroidProcesses} instead.
 */
@Deprecated
public class ProcessManager extends AndroidProcesses {

}


text:
using System;
namespace Com.Viperstudio.Geom
{
		public class ColorTransform
		{
			public float AlphaOffset = 0f;
			public float RedOffset = 0f;
			public float GreenOffset = 0f;
			public float BlueOffset = 0f;

			public float AlphaMultiplier = 0f;
			public float RedMultiplier = 0f;
			public float GreenMultiplier = 0f;
			public float BlueMultiplier = 0f;

				public ColorTransform ()
				{
				}
		}
}


text:
<?php

/**
 * $model.description$
 *
 * NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
 *
 */
class TravelDirectionPath
{

    static $swaggerTypes = array(
        'Direction' => 'string',
        'Path' => 'string'

    );

    /**
     * The Route's direction of travel, eg Inbound, Upward, etc. North = 0, South = 1, East = 2, West = 3, Inbound = 4, Outbound = 5, Inward = 6, Outward = 7, Upward = 8, Downward = 9, Clockwise = 10, Counterclockwise = 11, Direction1 = 12, Direction2 = 13, Null = 14
     */
    public $Direction; // string
    /**
     * The pattern map points for the route in each direction as a Polyline
     */
    public $Path; // string
}


text:
module.exports = {
  description: 'Install helpful components and the ember-velocity-mixin',

  normalizeEntityName: function() {},

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  afterInstall: function() {
     this.addAddonToProject('ember-velocity-mixin');
  }

};