private Func<object> BuildFactoryForService(Type type) { if (type.IsClass) { foreach (var ctor in type.GetConstructors().Where(it => it.IsPublic)) { var ctorParams = ctor.GetParameters(); if (ctorParams.Length == 0) return () => Activator.CreateInstance(type); if (ctorParams.Length == 1) { if (ctorParams[0].ParameterType == typeof(IServiceProvider) || ctorParams[0].ParameterType == typeof(IObjectFactory)) return () => Activator.CreateInstance(type, this); } var argFactories = new Func<object>[ctorParams.Length]; for (int i = 0; i < ctorParams.Length; i++) { var arg = GetFactory(ctorParams[i].ParameterType); if (arg == null) return null; argFactories[i] = arg; } return () => { var args = new object[argFactories.Length]; for (int i = 0; i < argFactories.Length; i++) args[i] = argFactories[i](); return Activator.CreateInstance(type, args); }; } } return null; }

public void DepthFirstSearchTest() { Func<Vertex[], int, bool[]>[] functions = new Func<Vertex[], int, bool[]>[] { DepthFirstSearchTestClass.RunDepthFirstSearch, DepthFirstSearchTestClass.RunBreadthFirstSearch, DepthFirstSearchTestClass.RunBellmanFord, DepthFirstSearchTestClass.RunDjikstra, DepthFirstSearchTestClass.RunFloydWarshall, }; Vertex[] vertices = new Vertex[10]; for (int i = 0; i < vertices.Length; i++) vertices[i] = new Vertex(); for (int i = 0; i <= vertices.Length * (vertices.Length - 1); i++) { for (int j = 0; j < vertices.Length; j++) { bool[][] results = new bool[vertices.Length][]; for (int k = 0; k < functions.Length; k++) { foreach (Vertex vertex in vertices) vertex.Reset(); results[k] = functions[k](vertices, j); Assert.IsTrue(ArrayUtilities.AreEqual(results[0], results[k])); } } GraphUtilities.SetRandomEdge(vertices); } }

public void ReverseSingleSublistTest() { Func<ListNode<int>, int, int, ListNode<int>>[] functions = new Func<ListNode<int>, int, int, ListNode<int>>[] { ReverseSingleSublist.BruteForce, ReverseSingleSublist.SinglePass }; for(int i = 0; i < 10; i++) { int[] data = ArrayUtilities.CreateRandomArray(10, 0, 10); for (int start = 1; start <= 10; start++) { for(int end = start; end <= 10; end++) { ListNode<int>[] results = new ListNode<int>[functions.Length]; for (int j = 0; j < results.Length; j++) { ListNode<int> head = LinkedListUtilities.Initialize(data); results[j] = functions[j](head, start, end); Assert.IsTrue(LinkedListUtilities.AreEqual(results[0], results[j])); } } } } }

public static ParameterSpecification Type(this ParameterSpecification @this, Func<ParameterInfo, TypeSpecification, TypeSpecification> typeSpecification) { Guard.NotNull(@this, "this"); Guard.NotNull(typeSpecification, "typeSpecification"); return @this.Combine(p => typeSpecification(p, TypeSpecificationBuilder.Any)(p.ParameterType)); }

public void FirstMissingElementTest() { Func<int[], int>[] functions = new Func<int[], int>[] { FirstMissingElement.BruteForce, FirstMissingElement.Iterative }; for(int i = 0; i < 10; i++) { int[][] data = new int[functions.Length][]; int[] original = ArrayUtilities.CreateRandomArray(20, -10, 10); for (int j = 0; j < functions.Length; j++) { data[j] = new int[original.Length]; Array.Copy(original, data[j], original.Length); } int[] results = new int[functions.Length]; for(int j = 0; j < functions.Length; j++) { results[j] = functions[j](data[j]); Assert.AreEqual(results[j], results[0]); } } }

/// <summary> /// A bicubic spline interpolation. /// </summary> /// <param name="points">The known data points.</param> /// <param name="x0">The first X.</param> /// <param name="y0">The first Y.</param> /// <param name="xDelta">The delta X.</param> /// <param name="yDelta">The delta Y.</param> /// <returns>An interpolation function.</returns> public static Func<double, Func<double, double>> Bicubic(double[,] points, double x0, double y0, double xDelta, double yDelta) { if (points.GetLength(0) < 2 || points.GetLength(1) < 2) return null; double[][] pointsAlt = new double[points.GetLength(1)][]; for (int x = 0; x < points.GetLength(1); x++) { pointsAlt[x] = new double[points.GetLength(0)]; for (int y = 0; y < points.GetLength(0); y++) { pointsAlt[x][y] = points[y, x]; } } Func<double, double>[] splines = new Func<double, double>[points.GetLength(1)]; for (int x = 0; x < pointsAlt.Length; x++) { splines[x] = Interpolation.Cubic(Interpolation.ConvertToPoints(pointsAlt[x], x0, xDelta)); } return x => { double[] interpolated = new double[splines.Length]; for (int i = 0; i < splines.Length; i++) { interpolated[i] = splines[i](x); } return Interpolation.Cubic(Interpolation.ConvertToPoints(interpolated, y0, yDelta)); }; }

public void IntersectSortedArraysTest() { Func<int[], int[], int[]>[] functions = new Func<int[], int[], int[]>[] { IntersectSortedArrays.BruteForce, IntersectSortedArrays.Search, IntersectSortedArrays.Iterate }; for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { int[] a = ArrayUtilities.CreateRandomArray(i, 0, 8); int[] b = ArrayUtilities.CreateRandomArray(j, 0, 8); Array.Sort(a); Array.Sort(b); int[][] results = new int[functions.Length][]; for (int k = 0; k < functions.Length; k++) { results[k] = functions[k](a, b); Assert.IsTrue(ArrayUtilities.AreEqual(results[0], results[k])); } } } }

public static TypeArgumentSpecification Type(this TypeArgumentSpecification @this, Func<Type, TypeSpecification, TypeSpecification> typeSpecification) { Guard.NotNull(@this, "this"); Guard.NotNull(typeSpecification, "typeSpecification"); return @this.Combine(ta => typeSpecification(ta, TypeSpecificationBuilder.Any)(ta)); }

public void GenerateStringTypeTests() { FastRandom fr = new FastRandom(); CharacterType[] types = new CharacterType[] { CharacterType.LowerCase, CharacterType.UpperCase, CharacterType.Numeric }; Func<char, bool>[] actions = new Func<char, bool>[] { Char.IsLower, Char.IsUpper, Char.IsNumber }; for(int i = 0; i < types.Length; i++) { for(int j = 0; j < 1000; j++) { var s = fr.NextString(5, types[i]); Assert.Equal(5, s.Length); foreach(var c in s) { Assert.True(actions[i](c)); } } } { var s = fr.NextString(5, CharacterType.Special); Assert.Equal(5, s.Length); foreach(var c in s) { Assert.True(FastRandom.SpecialCharacters.Contains(c)); } } }

public void MergeTwoSortedListsTest() { Func<ListNode<int>, ListNode<int>, ListNode<int>>[] functions = new Func<ListNode<int>, ListNode<int>, ListNode<int>>[] { MergeTwoSortedLists.AppendAndSort, MergeTwoSortedLists.SinglePass }; for(int i = 0; i < 10; i++) { int[] data1 = ArrayUtilities.CreateRandomArray(10, 0, 25); int[] data2 = ArrayUtilities.CreateRandomArray(10, 0, 25); Array.Sort(data1); Array.Sort(data2); int[] expected = new int[data1.Length + data2.Length]; Array.Copy(data1, expected, data1.Length); Array.Copy(data2, 0, expected, data1.Length, data2.Length); Array.Sort(expected); for (int j = 0; j < functions.Length; j++) { ListNode<int> result = functions[j](LinkedListUtilities.Initialize(data1), LinkedListUtilities.Initialize(data2)); int[] actual = LinkedListUtilities.ToArray(result); Assert.IsTrue(ArrayUtilities.AreEqual(expected, actual)); } } }

public void ShortestPathTest() { Func<Vertex[], int[,]>[] functions = new Func<Vertex[], int[,]>[] { ShortestPathTestClass.RunBellmanFord, ShortestPathTestClass.RunDjikstra, ShortestPathTestClass.RunFloydWarshall, }; Vertex[] vertices = new Vertex[10]; for (int i = 0; i < vertices.Length; i++) vertices[i] = new Vertex(); for (int i = 0; i <= vertices.Length * (vertices.Length - 1); i++) { for (int j = 0; j < vertices.Length; j++) { int[][,] results = new int[vertices.Length][,]; for (int k = 0; k < functions.Length; k++) { foreach (Vertex vertex in vertices) vertex.Reset(); results[k] = functions[k](vertices); Assert.IsTrue(ArrayUtilities.AreEqual(results[0], results[k])); } } GraphUtilities.SetRandomEdge(vertices); } }

public string GetPublicIp() { var ipServices = new Func<string>[] { () => new IpInfoIpService().GetPublicIp(), () => new DynDnsIpService().GetPublicIp(), () => new IpifyIpService().GetPublicIp(), () => new ICanHazIpService().GetPublicIp(), () => new FreeGeoIpService().GetPublicIp() }; for (int i = 0; i < ipServices.Count(); i++) { if (lastUsedIndex >= ipServices.Count()) lastUsedIndex = 0; else lastUsedIndex++; try { return ipServices[lastUsedIndex](); } catch { } } return null; }

private static int Stack(string rpn) { string operators = "+-*/"; Func<int, int, int>[] functions = new Func<int, int, int>[] { (x, y) => x + y, (x, y) => x - y, (x, y) => x * y, (x, y) => x / y, }; string[] tokens = rpn.Split(','); Stack<int> values = new Stack<int>(); foreach(string token in tokens) { int index = operators.IndexOf(token); if (index == -1) { values.Push(int.Parse(token)); continue; } int y = values.Pop(); int x = values.Pop(); values.Push(functions[index](x, y)); } return values.Pop(); }

public static void Transfer(SupermarketsEntities sqlserver) { using (var mysql = new MySqlSupermarket()) { // SET IDENTITY_INSERT (Transact-SQL) http://msdn.microsoft.com/en-us/library/ms188059.aspx sqlserver.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Vendors ON"); sqlserver.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Measures ON"); sqlserver.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Products ON"); var mysqlTables = new IEnumerable[] { mysql.Vendors, mysql.Measures, mysql.Products }; var sqlserverEntityFactories = new Func<object>[] { () => new Vendor(), () => new Measure(), () => new Product() }; var sqlserverTables = new DbSet[] { sqlserver.Vendors, sqlserver.Measures, sqlserver.Products }; for (int ii = 0; ii < mysqlTables.Length; ii++) { foreach (var mysqlObject in mysqlTables[ii]) { var sqlserverObject = sqlserverEntityFactories[ii](); sqlserverObject.LoadPropertiesFrom(mysqlObject); sqlserverTables[ii].Add(sqlserverObject); } } sqlserver.SaveChanges(); sqlserver.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Vendors OFF"); sqlserver.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Measures OFF"); sqlserver.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Products OFF"); } }

public void ExecuteTests(TestTraceOutput output, Component originalComponent, Component transformedComponent, MethodInfo originalMethod, MethodInfo transformedMethod) { var parameters = originalMethod.GetParameters(); var originalArguments = new object[parameters.Length]; var transformedArguments = new object[parameters.Length]; var valueFactories = new Func<object>[parameters.Length]; for (var i = 0; i < parameters.Length; ++i) { if (parameters[i].ParameterType == typeof(int) || parameters[i].ParameterType == typeof(int).MakeByRefType()) valueFactories[i] = RandomInt32; else if (parameters[i].ParameterType == typeof(double) || parameters[i].ParameterType == typeof(double).MakeByRefType()) valueFactories[i] = RandomDouble; else if (parameters[i].ParameterType == typeof(bool) || parameters[i].ParameterType == typeof(bool).MakeByRefType()) valueFactories[i] = RandomBoolean; else Assert.NotReached("Unknown parameter type '{0}'.", parameters[i].ParameterType); } output.Log("Testing '{0}'", originalMethod); for (var i = 0; i < _testCount * 2; ++i) { output.Trace("----- Inputs -----"); for (var j = 0; j < originalArguments.Length; ++j) { originalArguments[j] = valueFactories[j](); transformedArguments[j] = originalArguments[j]; output.Trace("{0} = {1}", parameters[j].Name, originalArguments[j]); } var originalResult = originalMethod.Invoke(originalComponent, originalArguments); var transformedResult = transformedMethod.Invoke(transformedComponent, transformedArguments); if (originalResult != null && originalResult.GetType().IsEnum) { originalResult = ((IConvertible)originalResult).ToInt32(CultureInfo.InvariantCulture); transformedResult = ((IConvertible)transformedResult).ToInt32(CultureInfo.InvariantCulture); } transformedResult.ShouldBe(originalResult); transformedArguments.ShouldBe(originalArguments); for (var j = 0; j < originalComponent.Metadata.Fields.Length; ++j) { var originalField = originalComponent.Metadata.Fields[j]; output.Trace("Comparing field '{0}'", originalField.FieldInfo); var transformedField = transformedComponent.Metadata.Fields.Single(f => f.Name == originalField.Name); transformedField.FieldInfo.GetValue(transformedComponent).ShouldBe(originalField.FieldInfo.GetValue(originalComponent)); } } }

/// <summary> /// /// </summary> /// <param name="coeffs"></param> /// <returns></returns> private static Func<double, double> MakeFromCoeffs(double y0, double y1, double[] coeffs) { var n = coeffs.Length; var haar2 = new Func<double, double>[n]; for (int k = 0; k < n; k++) { haar2[k] = MixedHaar2(2, k + 1 + 2); } return t => y0 + y1 * t + coeffs.Select((yk, k) => yk * haar2[k](t)).Sum(); }

/// <summary> /// 引数に指定された基底とデータ長に対応したデザイン行列を作る。<br /> /// データは 0 ～ 1 の範囲をデータ長で等分した位置で取る。 /// </summary> /// <param name="dataLength">デザイン行列のデータ長。</param> /// <param name="basis">デザイン行列に用いる基底。</param> public static double[,] DesignMatrix(int dataLength, Func<double, double>[] basis) { int dimension = basis.Length; double[,] matrix = new double[dataLength, dimension]; for (int m = 0; m < dimension; m++) { for (int n = 0; n < dataLength; n++) { matrix[n, m] = basis[m]((double)n / dataLength); } } return matrix; }

//calculates the f(x) value from each lamda expression int array //@param x a value for the func //@param maxValue the greatest calculated f(x) value //@param currentValue is the current calculated value to check for max public void max(Func<float, float>[] l, float x) { float maxValue = 0; for (int i = 0; i < l.Length; i++) { currentValue = l[i](x); if (currentValue > maxValue) { maxValue = currentValue; } } Console.WriteLine("the max is --> "+maxValue); }

public void TestDifferentIterateVariables() { const int Length = 3; Func<int>[] diffVarFuncs = new Func<int>[Length]; for (int i = 0; i < Length; ++i) { int temp = i; diffVarFuncs[i] = () => { return temp; }; } for (int i = 0; i < Length; ++i) Assert.AreEqual(i, diffVarFuncs[i]()); }

internal static void svdfit(double[][] x, double[][] y, double[][] a, out double chisq, Func<double[], double>[] funcs) { int i, j, k; double wmax, tmp, thresh, sum, TOL = 1e-13; //Allocated memory for svd matrices double[,] u = new double[x.Length, funcs.Length]; double[,] v = new double[funcs.Length, funcs.Length]; double[] w = new double[funcs.Length]; //Fill input matrix with values based on fitting functions and input coordinates for (i = 0; i < x.Length; i++) { for (j = 0; j < funcs.Length; j++) u[i, j] = funcs[j](x[i]); } //Perform decomposition svdcmp(u, w, v); //Check for w values that are close to zero and replace them with zeros such that they are ignored in backsub wmax = 0; for (j = 0; j < funcs.Length; j++) if (w[j] > wmax) wmax = w[j]; thresh = TOL * wmax; for (j = 0; j < funcs.Length; j++) if (w[j] < thresh) w[j] = 0; //Perform back substitution to get result svdbksb(u, w, v, y, a); //Calculate chi squared for the fit chisq = 0; for (k = 0; k < y[0].Length; k++) { for (i = 0; i < y.Length; i++) { sum = 0.0; for (j = 0; j < funcs.Length; j++) sum += a[j][k] * funcs[j](x[i]); tmp = (y[i][k] - sum); chisq += tmp * tmp; } } chisq = Math.Sqrt(chisq / (y.Length * y[0].Length)); }

private async Task VerifyFixInternalAsync(string language, ImmutableArray<DiagnosticAnalyzer> analyzers, CodeFixProvider codeFixProvider, string oldSource, string newSource, int? codeFixIndex, bool allowNewCompilerDiagnostics, int maxNumberOfIterations, Func<ImmutableArray<DiagnosticAnalyzer>, CodeFixProvider, int?, CancellationToken, Document, int, Task<Document>> getFixedDocument, CancellationToken cancellationToken) { var document = this.CreateDocument(oldSource, language); var compilerDiagnostics = await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false); document = await getFixedDocument(analyzers, codeFixProvider, codeFixIndex, cancellationToken, document, maxNumberOfIterations).ConfigureAwait(false); var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false)); // check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false)); string message = string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())), (await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).ToFullString()); Assert.True(false, message); } // after applying all of the code fixes, compare the resulting string to the inputted one var actual = await GetStringFromDocumentAsync(document, cancellationToken).ConfigureAwait(false); Assert.Equal(newSource, actual); }

public Dictionary<string, object> Read(byte [] data, string rsaPrivKey, Dictionary<string, Type> objTypeMap, Func<byte[], byte[]> xmlFilter = null) { using (var ms = new MemoryStream(data)) { return DecryptFileList(Util.Compression.UnZip(ms), rsaPrivKey, objTypeMap, xmlFilter); } }

private void LifestyleMany(Func<BasedOnDescriptor, IRegistration> assingLifestyle, LifestyleType expectedLifestyle) { var registration = Classes.FromThisAssembly().BasedOn<A>(); Kernel.Register(assingLifestyle(registration)); var handler = Kernel.GetHandler(typeof(A)); Assert.AreEqual(expectedLifestyle, handler.ComponentModel.LifestyleType); }

private void LifestyleSingle(Func<ComponentRegistration<A>, IRegistration> assingLifestyle, LifestyleType expectedLifestyle) { var registration = Component.For<A>(); Kernel.Register(assingLifestyle(registration)); var handler = Kernel.GetHandler(typeof(A)); Assert.AreEqual(expectedLifestyle, handler.ComponentModel.LifestyleType); }

/// <summary> /// Creates a new command. /// </summary> /// <param name="execute">The execution logic.</param> /// <param name="canExecute">The execution status logic.</param> public RelayCommand(Action<object> execute, Func<bool> canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; }

public ExtendedFrameNavigationService(IFrameFacade frame, Func<string, Type> navigationResolver, ISessionStateService sessionStateService) : base(frame, navigationResolver, sessionStateService) { _frame = frame; _navigationResolver = navigationResolver; _sessionStateService = sessionStateService; }

public RecordsetGroup(IBinaryDataListEntry sourceEntry, IList<IDev2Definition> definitions, Func<IDev2Definition, string> inputExpressionExtractor, Func<IDev2Definition, string> outputExpressionExtractor) { if(sourceEntry == null) { throw new ArgumentNullException("sourceEntry"); } if(definitions == null) { throw new ArgumentNullException("definitions"); } if(inputExpressionExtractor == null) { throw new ArgumentNullException("inputExpressionExtractor"); } if(outputExpressionExtractor == null) { throw new ArgumentNullException("outputExpressionExtractor"); } SourceEntry = sourceEntry; Definitions = definitions; InputExpressionExtractor = inputExpressionExtractor; OutputExpressionExtractor = outputExpressionExtractor; }

/// <summary> /// Adds an additional Instance constructed by a Func using IContext /// </summary> /// <param name="description">User friendly description for diagnostic purposes</param> /// <param name="func"></param> /// <returns></returns> public LambdaInstance<object> Add(string description, Func<IContext, object> func) { var instance = new LambdaInstance<object>(description, func); Add(instance); return instance; }

/// <summary> /// Gets the or load. /// </summary> /// <param name="testRun">The test run.</param> /// <param name="substitutions"></param> /// <param name="loadRunner">The action.</param> /// <returns></returns> public NDistribUnitProcessRunner GetOrLoad(TestRun testRun, DistributedConfigurationSubstitutions substitutions, Func<NDistribUnitProcessRunner> loadRunner) { var key = GetKey(testRun); //var timeSpan = TimeSpan.FromHours(4); var cacheByParameters = cache.GetOrAdd(key, guid => new ConcurrentDictionary<int, TestRunnerMetadata>()); int hashCode = GetKeyForSubstitutions(substitutions); var metadata = cacheByParameters.GetOrAdd(hashCode, hash => { var runner = loadRunner(); // var timer = new Timer(obj=> // { // TestRunnerMetadata removed; // if (cacheByParameters.TryRemove(hashCode, out removed)) // removed.Runner.Unload(); // }, null, timeSpan, TimeSpan.FromMilliseconds(-1)); return new TestRunnerMetadata { Runner = runner, // Timer = timer }; }); // metadata.Timer.Change(timeSpan, TimeSpan.FromMilliseconds(-1)); return metadata.Runner; }

public DeploymentDetail(Func<string> name, Func<DeploymentResult> verify, Func<DeploymentResult> execute, Func<DeploymentResult> trace) { _name = name; _verify = verify; _execute = execute; _trace = trace; }