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 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)); }
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 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; }
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 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]); } } }
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 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 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 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); } }
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 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)); } } }
/// <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 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 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)); }
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 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); }
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); }
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> /// 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; }
/// <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; }
/// <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; }
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); }
public DeploymentDetail(Func<string> name, Func<DeploymentResult> verify, Func<DeploymentResult> execute, Func<DeploymentResult> trace) { _name = name; _verify = verify; _execute = execute; _trace = trace; }
public static ConfiguredCall Returns <TArg, TResult>(this object obj, Func <TArg, TResult> func) => obj.Returns(args => func(args.Arg <TArg>()));
public static IMqttClient UseApplicationMessageReceivedHandler(this IMqttClient client, Func<MqttApplicationMessageReceivedEventArgs, Task> handler) { if (client == null) throw new ArgumentNullException(nameof(client)); if (handler == null) { return client.UseApplicationMessageReceivedHandler((IMqttApplicationMessageReceivedHandler)null); } return client.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(handler)); }
protected Func<RedisKey, RedisKey> GetMapFunction() { // create as a delegate when first required, then re-use return mapFunction ?? (mapFunction = new Func<RedisKey, RedisKey>(ToInner)); }
/// <summary> /// Creates new thread which runs the given action and starts it after creation. The given action will be wrapped so /// that any exception will be caught and logged. /// </summary> /// <param name="action">The enumerable action which the new thread should run.</param> /// <returns>The instance of the created thread class.</returns> public static CustomThread CreateThread(Func <CustomThread, IEnumerator> action) { return(CreateThread(action, true)); }
public IQueryable<AutoGenNoSetting> GetAll(Expression<Func<AutoGenNoSetting, bool>> filter = null, Func<IQueryable<AutoGenNoSetting>, IOrderedQueryable<AutoGenNoSetting>> orderBy = null, int? skip = null, int? take = null, params string[] includeProperties) { var list = new List<AutoGenNoSetting>() { new AutoGenNoSetting() { EntityName="JournalVoucher", NoOfDigits=6, PostFix=null, PreFix="JV", Separator="-", IsActive=true }, //CreatedBy=1, DateCreated=DateTime.Now }, new AutoGenNoSetting() { EntityName="PaymentVoucher", NoOfDigits=6, PostFix=null, PreFix="PV", Separator="-", IsActive=true }, //CreatedBy=1, DateCreated=DateTime.Now }, new AutoGenNoSetting() { EntityName="ReceiptVoucher", NoOfDigits=6, PostFix=null, PreFix="RV", Separator="-", IsActive=true } //,CreatedBy=1, DateCreated=DateTime.Now } }; return list.AsQueryable().Where(filter); }
public static List <DependencyList <T> > Group <T, D, TKey>(DependencyList <T> depList, Func <T, IEnumerable <D> > getDependencies, Func <D, T> getDependencyDetail, GenericEqualityComparer <T, TKey> comparer = null) { Dictionary <T, int> visited = new Dictionary <T, int>(comparer); List <DependencyList <T> > sorted = new List <DependencyList <T> >(); foreach (var v in depList) { Visit(v, getDependencies, getDependencyDetail, visited, sorted); } return(sorted); }
protected SolverNodeFactoryBaseDefault(Func<IBitmap, IBitmap> factoryClone, Func<VectorInt2, IBitmap> factoryBySize) { this.factoryClone = factoryClone; this.factoryBySize = factoryBySize; }
internal static Task <List <Into> > SelectAsync <Into, From>(this IDbCommand dbCmd, Func <SqlExpression <From>, SqlExpression <From> > expression, CancellationToken token) { var q = dbCmd.GetDialectProvider().SqlExpression <From>(); string sql = expression(q).SelectInto <Into>(); return(dbCmd.ExprConvertToListAsync <Into>(sql, q.Params, q.OnlyFields, token)); }
public static int Visit <T, D>(T item, Func <T, IEnumerable <D> > getDependencies, Func <D, T> getDependencyDetail, Dictionary <T, int> visited, List <DependencyList <T> > sorted) { const int inProcess = -1; int level; var alreadyVisited = visited.TryGetValue(item, out level); if (alreadyVisited) { if (level == inProcess) { throw new ArgumentException("Circular dependency detected"); } } else { visited[item] = (level = inProcess); var dependencies = getDependencies(item); foreach (var dependency in dependencies) { var depLevel = Visit(getDependencyDetail(dependency), getDependencies, getDependencyDetail, visited, sorted); level = Math.Max(depLevel, level); } visited[item] = ++level; while (level >= sorted.Count) { sorted.Add(new DependencyList <T>()); } sorted[level].Add(item); } return(level); }
internal static Task <T> SingleAsync <T>(this IDbCommand dbCmd, Func <SqlExpression <T>, SqlExpression <T> > expression, CancellationToken token) { var expr = dbCmd.GetDialectProvider().SqlExpression <T>(); return(dbCmd.SingleAsync(expression(expr), token)); }
/// <summary> /// Gets the orders generated starting from the provided <see cref="ITransactionHandler.OrderEvents"/> position /// </summary> /// <returns>The delta orders</returns> protected virtual Dictionary <int, Order> GetDeltaOrders(int orderEventsStartPosition, Func <int, bool> shouldStop) { var deltaOrders = new Dictionary <int, Order>(); foreach (var orderId in TransactionHandler.OrderEvents.Skip(orderEventsStartPosition).Select(orderEvent => orderEvent.OrderId)) { LastDeltaOrderPosition++; if (deltaOrders.ContainsKey(orderId)) { // we can have more than 1 order event per order id continue; } var order = Algorithm.Transactions.GetOrderById(orderId); if (order == null) { // this shouldn't happen but just in case continue; } // for charting order.Price = order.Price.SmartRounding(); deltaOrders[orderId] = order; if (shouldStop(deltaOrders.Count)) { break; } } return(deltaOrders); }
public int Count(Func <ViewTeamGradeMetaData, bool> predicate) { return(EntityList.Count()); }
public virtual IQueryable ApplyTo(IQueryable query, ODataQuerySettings querySettings) { if (query == null) { throw Error.ArgumentNull("query"); } if (querySettings == null) { throw Error.ArgumentNull("querySettings"); } IQueryable result = query; // First apply $apply // Section 3.15 of the spec http://docs.oasis-open.org/odata/odata-data-aggregation-ext/v4.0/cs01/odata-data-aggregation-ext-v4.0-cs01.html#_Toc378326311 if (IsAvailableODataQueryOption(Apply, AllowedQueryOptions.Apply)) { result = Apply.ApplyTo(result, querySettings, _assembliesResolver); Request.ODataProperties().ApplyClause = Apply.ApplyClause; this.Context.ElementClrType = Apply.ResultClrType; } // Construct the actual query and apply them in the following order: filter, orderby, skip, top if (IsAvailableODataQueryOption(Filter, AllowedQueryOptions.Filter)) { result = Filter.ApplyTo(result, querySettings, _assembliesResolver); } if (IsAvailableODataQueryOption(Count, AllowedQueryOptions.Count)) { if (Request.ODataProperties().TotalCountFunc == null) { Func <long> countFunc = Count.GetEntityCountFunc(result); if (countFunc != null) { Request.ODataProperties().TotalCountFunc = countFunc; } } if (ODataCountMediaTypeMapping.IsCountRequest(Request)) { return(result); } } OrderByQueryOption orderBy = OrderBy; // $skip or $top require a stable sort for predictable results. // Result limits require a stable sort to be able to generate a next page link. // If either is present in the query and we have permission, // generate an $orderby that will produce a stable sort. if (querySettings.EnsureStableOrdering && (IsAvailableODataQueryOption(Skip, AllowedQueryOptions.Skip) || IsAvailableODataQueryOption(Top, AllowedQueryOptions.Top) || querySettings.PageSize.HasValue)) { // If there is no OrderBy present, we manufacture a default. // If an OrderBy is already present, we add any missing // properties necessary to make a stable sort. // Instead of failing early here if we cannot generate the OrderBy, // let the IQueryable backend fail (if it has to). orderBy = orderBy == null ? GenerateDefaultOrderBy(Context) : EnsureStableSortOrderBy(orderBy, Context); } if (IsAvailableODataQueryOption(orderBy, AllowedQueryOptions.OrderBy)) { result = orderBy.ApplyTo(result, querySettings); } if (IsAvailableODataQueryOption(Skip, AllowedQueryOptions.Skip)) { result = Skip.ApplyTo(result, querySettings); } if (IsAvailableODataQueryOption(Top, AllowedQueryOptions.Top)) { result = Top.ApplyTo(result, querySettings); } AddAutoExpandProperties(); if (SelectExpand != null) { var tempResult = ApplySelectExpand(result, querySettings); if (tempResult != default(IQueryable)) { result = tempResult; } } if (querySettings.PageSize.HasValue) { bool resultsLimited; result = LimitResults(result, querySettings.PageSize.Value, out resultsLimited); if (resultsLimited && Request.RequestUri != null && Request.RequestUri.IsAbsoluteUri && Request.ODataProperties().NextLink == null) { Uri nextPageLink = Request.GetNextPageLink(querySettings.PageSize.Value); Request.ODataProperties().NextLink = nextPageLink; } } return(result); }
public static void Visit <T, D>(T item, Func <T, IEnumerable <D> > getDependencies, Func <D, T> getDependecyDetail, DependencyList <T> sorted, Dictionary <T, bool> visited) { bool inProcess; var alreadyVisited = visited.TryGetValue(item, out inProcess); if (alreadyVisited) { if (inProcess) { throw new ArgumentException("Cyclic dependency found."); } } else { visited[item] = true; var dependencies = getDependencies(item); if (dependencies != null) { foreach (var dependency in dependencies) { Visit(getDependecyDetail(dependency), getDependencies, getDependecyDetail, sorted, visited); } } visited[item] = false; sorted.Add(item); } }
public override TLimit Get(IComponentContext context, IEnumerable<Parameter> parameters, Func<TLimit> getFromPool) { Interlocked.Increment(ref _outOfPool); return getFromPool(); }
public static DependencyList <T> Sort <T, D, TKey>(DependencyList <T> source, Func <T, IEnumerable <D> > getDependencies, Func <D, T> getDependecyDetail, GenericEqualityComparer <T, TKey> comparer) { var sorted = new DependencyList <T>(); var visited = new Dictionary <T, bool>(comparer); foreach (var item in source) { Visit(item, getDependencies, getDependecyDetail, sorted, visited); } return(sorted); }
/// <summary> /// 返回5个结果集 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sqlKey"></param> /// <param name="paramDic"></param> /// <param name="total"></param> /// <param name="isUseTrans"></param> /// <returns></returns> public IEnumerable<TReturn> QueryMultiple<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(string sqlKey, Dictionary<string, object> paramDic, Func<IEnumerable<TFirst>, IEnumerable<TSecond>, IEnumerable<TThird>, IEnumerable<TFourth>, IEnumerable<TFifth>, IEnumerable<TReturn>> func, bool isUseTrans = false, int maxretry = MaxRetry) { var sqlAnaly = CacheSqlConfig.Instance.GetSqlAnalyByKey(sqlKey, paramDic); try { var t = GetSQLHelper(sqlAnaly).QueryMultiple(sqlAnaly.SqlText, CommandType.Text, paramDic, func, isUseTrans); return t; } catch (MySql.Data.MySqlClient.MySqlException ex) { if (maxretry > 0 && RetryMessage.Contains(ex.Message)) { return QueryMultiple(sqlKey, paramDic, func, isUseTrans, --maxretry); } else { throw ex; } } catch (Exception ex) { throw ex; } }
/// <summary> /// Creates new thread which runs the given action. The given action will be wrapped so that any exception will be /// caught and logged. /// </summary> /// <param name="action">The enumerable action which the new thread should run.</param> /// <param name="autoStartThread">True when the thread should start immediately after creation.</param> /// <returns>The instance of the created thread class.</returns> public static CustomThread CreateThread(Func <IEnumerator> action, bool autoStartThread) { Func <CustomThread, IEnumerator> wrappedAction = thread => action(); return(CreateThread(wrappedAction, autoStartThread)); }
public MyCodeAction( Func <CancellationToken, Task <Document> > createChangedDocument) : base(FeaturesResources.Use_throw_expression, createChangedDocument) { }
internal void BindConverter(string targetName, Func <object, object> func) { _customTypeConverters[targetName] = func; }
/// <summary> /// Creates new thread which runs the given action and starts it after creation. The given action will be wrapped so /// that any exception will be caught and logged. /// </summary> /// <param name="action">The action which the new thread should run.</param> /// <returns>The instance of the created thread class.</returns> public static CustomThread CreateThread(Func <IEnumerator> action) { Func <CustomThread, IEnumerator> wrappedAction = thread => action(); return(CreateThread(wrappedAction, true)); }
/// <summary> /// Creates a new transformed record. The Kinesis Firehose Base64 data is decided using the provided encoding parameter before being passed to the /// transform function. /// </summary> /// <param name="record">The Kinesis Firehose record</param> /// <param name="transform">The function that will transform the data from the Kinesis Firehose record</param> /// <param name="encoding">The encoding used to convert the bytes from the Base64 string into a readable string</param> /// <returns>The transformed record</returns> public static async Task <KinesisFirehoseTransformedRecord> BuildAsync(KinesisFirehoseRecord record, Func <string, Task <TransformationResult> > transform, Encoding encoding) { ParameterTests.NonNull(record, "record"); ParameterTests.NonNull(transform, "transform"); ParameterTests.NonNull(encoding, "encoding"); try { TransformationResult Result = await transform.Invoke(record.DecodeData(encoding)); return(new KinesisFirehoseTransformedRecord(record.RecordId, Result.Data, Result.Result)); } catch (AggregateException e) { return(new KinesisFirehoseTransformedRecord(record.RecordId, Convert.ToBase64String(Encoding.UTF8.GetBytes($"{e.InnerException.GetType().FullName} : {e.InnerException.Message}")), TransformationResultStatus.PROCESSING_FAILED)); } catch (Exception e) { return(new KinesisFirehoseTransformedRecord(record.RecordId, Convert.ToBase64String(Encoding.UTF8.GetBytes($"{e.GetType().FullName} : {e.Message}")), TransformationResultStatus.PROCESSING_FAILED)); } }
private void TestRoundTrip(IEnumerable<ISymbol> symbols, Compilation compilation, Func<ISymbol, object> fnId = null) { foreach (var symbol in symbols) { TestRoundTrip(symbol, compilation, fnId: fnId); } }
/// <summary> /// Returns am empty <see cref="IReadOnlyList{T}"/>. /// </summary> /// <typeparam name="T">Element ype</typeparam> /// <param name="cons">Ignored</param> public override IReadOnlyList <T> Cast <T>(Func <DeserializerState, T> cons) => new EmptyList <T>();
public static DependencyList <T> Sort <T, D, TKey>(DependencyList <T> source, Func <T, IEnumerable <D> > getDependencies, Func <D, T> getDependecyDetail, Func <T, TKey> getKey) { return(Sort(source, getDependencies, getDependecyDetail, new GenericEqualityComparer <T, TKey>(getKey))); }
public IEnumerable<Annotation> GetMatches(Func<Annotation, string, bool> predicate, string parameter) { return from a in _doc.Root.Elements() where predicate(new Annotation(a), parameter) //enhance... very ineffienct making these constantly select new Annotation(a); }
public ObjectDecorationEvaluator(string objectDecoration, Func <string, IEnvelope, string> evaluateVariables) { _objectDecoration = objectDecoration; _evaluateVariables = evaluateVariables; }
public override void AddRequiredEntitiesToLoad (Func<TAtypeEntityId, bool> a, Func<TBtypeEntityId, bool> b) { a (AId); }
/// <summary> /// Creates a new transformed record. By default the Kinesis Firehose Base64 data is decoded into UTF8 before being passed to the tranform function. /// </summary> /// <param name="record">The Kinesis Firehose record</param> /// <param name="transform">The function that will transform the data from the Kinesis Firehose record</param> /// <param name="useDefaultEncoding">Specifies if the data in the Kinesis Firehose record should be decoded using /// the default text encoding, UTF8. If this is false, the data will be passed to the transform function as a Base64 encoded string</param> /// <returns>The transformed record</returns> public static KinesisFirehoseTransformedRecord Build(KinesisFirehoseRecord record, Func <string, TransformationResult> transform, bool useDefaultEncoding = true) { ParameterTests.NonNull(record, "record"); ParameterTests.NonNull(transform, "transform"); try { string Data = record.Data; if (useDefaultEncoding) { Data = record.DecodeData(); } TransformationResult Result = transform.Invoke(Data); return(new KinesisFirehoseTransformedRecord(record.RecordId, Result.Data, Result.Result)); } catch (Exception e) { return(new KinesisFirehoseTransformedRecord(record.RecordId, Convert.ToBase64String(Encoding.UTF8.GetBytes($"{e.GetType().FullName} : {e.Message}")), TransformationResultStatus.PROCESSING_FAILED)); } }
public static async Task <TRoot> ReplaceSyntaxAsync <TRoot>( this TRoot root, IEnumerable <SyntaxNode> nodes, Func <SyntaxNode, SyntaxNode, CancellationToken, Task <SyntaxNode> > computeReplacementNodeAsync, IEnumerable <SyntaxToken> tokens, Func <SyntaxToken, SyntaxToken, CancellationToken, Task <SyntaxToken> > computeReplacementTokenAsync, IEnumerable <SyntaxTrivia> trivia, Func <SyntaxTrivia, SyntaxTrivia, CancellationToken, Task <SyntaxTrivia> > computeReplacementTriviaAsync, CancellationToken cancellationToken) where TRoot : SyntaxNode { // index all nodes, tokens and trivia by the full spans they cover var nodesToReplace = nodes != null?nodes.ToDictionary(n => n.FullSpan) : new Dictionary <TextSpan, SyntaxNode>(); var tokensToReplace = tokens != null?tokens.ToDictionary(t => t.FullSpan) : new Dictionary <TextSpan, SyntaxToken>(); var triviaToReplace = trivia != null?trivia.ToDictionary(t => t.FullSpan) : new Dictionary <TextSpan, SyntaxTrivia>(); var nodeReplacements = new Dictionary <SyntaxNode, SyntaxNode>(); var tokenReplacements = new Dictionary <SyntaxToken, SyntaxToken>(); var triviaReplacements = new Dictionary <SyntaxTrivia, SyntaxTrivia>(); var retryAnnotations = new AnnotationTable <object>("RetryReplace"); var spans = new List <TextSpan>(nodesToReplace.Count + tokensToReplace.Count + triviaToReplace.Count); spans.AddRange(nodesToReplace.Keys); spans.AddRange(tokensToReplace.Keys); spans.AddRange(triviaToReplace.Keys); while (spans.Count > 0) { // sort the spans of the items to be replaced so we can tell if any overlap spans.Sort((x, y) => { // order by end offset, and then by length var d = x.End - y.End; if (d == 0) { d = x.Length - y.Length; } return(d); }); // compute replacements for all nodes that will go in the same batch // only spans that do not overlap go in the same batch. TextSpan previous = default; foreach (var span in spans) { // only add to replacement map if we don't intersect with the previous node. This taken with the sort order // should ensure that parent nodes are not processed in the same batch as child nodes. if (previous == default || !previous.IntersectsWith(span)) { if (nodesToReplace.TryGetValue(span, out var currentNode)) { var original = (SyntaxNode)retryAnnotations.GetAnnotations(currentNode).SingleOrDefault() ?? currentNode; var newNode = await computeReplacementNodeAsync(original, currentNode, cancellationToken).ConfigureAwait(false); nodeReplacements[currentNode] = newNode; } else if (tokensToReplace.TryGetValue(span, out var currentToken)) { var original = (SyntaxToken)retryAnnotations.GetAnnotations(currentToken).SingleOrDefault(); if (original == default) { original = currentToken; } var newToken = await computeReplacementTokenAsync(original, currentToken, cancellationToken).ConfigureAwait(false); tokenReplacements[currentToken] = newToken; } else if (triviaToReplace.TryGetValue(span, out var currentTrivia)) { var original = (SyntaxTrivia)retryAnnotations.GetAnnotations(currentTrivia).SingleOrDefault(); if (original == default) { original = currentTrivia; } var newTrivia = await computeReplacementTriviaAsync(original, currentTrivia, cancellationToken).ConfigureAwait(false); triviaReplacements[currentTrivia] = newTrivia; } } previous = span; } bool retryNodes = false; bool retryTokens = false; bool retryTrivia = false; // replace nodes in batch // submit all nodes so we can annotate the ones we don't replace root = root.ReplaceSyntax( nodes: nodesToReplace.Values, computeReplacementNode: (original, rewritten) => { if (rewritten != original || !nodeReplacements.TryGetValue(original, out var replaced)) { // the subtree did change, or we didn't have a replacement for it in this batch // so we need to add an annotation so we can find this node again for the next batch. replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original); retryNodes = true; } return(replaced); }, tokens: tokensToReplace.Values, computeReplacementToken: (original, rewritten) => { if (rewritten != original || !tokenReplacements.TryGetValue(original, out var replaced)) { // the subtree did change, or we didn't have a replacement for it in this batch // so we need to add an annotation so we can find this node again for the next batch. replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original); retryTokens = true; } return(replaced); }, trivia: triviaToReplace.Values, computeReplacementTrivia: (original, rewritten) => { if (!triviaReplacements.TryGetValue(original, out var replaced)) { // the subtree did change, or we didn't have a replacement for it in this batch // so we need to add an annotation so we can find this node again for the next batch. replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original); retryTrivia = true; } return(replaced); }); nodesToReplace.Clear(); tokensToReplace.Clear(); triviaToReplace.Clear(); spans.Clear(); // prepare next batch out of all remaining annotated nodes if (retryNodes) { nodesToReplace = retryAnnotations.GetAnnotatedNodes(root).ToDictionary(n => n.FullSpan); spans.AddRange(nodesToReplace.Keys); } if (retryTokens) { tokensToReplace = retryAnnotations.GetAnnotatedTokens(root).ToDictionary(t => t.FullSpan); spans.AddRange(tokensToReplace.Keys); } if (retryTrivia) { triviaToReplace = retryAnnotations.GetAnnotatedTrivia(root).ToDictionary(t => t.FullSpan); spans.AddRange(triviaToReplace.Keys); } } return(root); }