/// <summary> /// Validates the specified BindEvent<string> object and gets the /// tuples representing the error information. /// </summary> /// <param name="ev"> /// The BindEvent<string> object. /// </param> /// <param name="invalidBooleanValueError"> /// The error message when it is unable to parse a boolean value. /// </param> /// <returns> /// <see cref="NoError"/> if the specified BindEvent<string> /// object can be parsed successfully. Otherwise, the errors. /// </returns> public static IEnumerable <WhereWhy> ValidateBoolean( BindEvent <string>?ev, string invalidBooleanValueError) { if (ev is null) { return(NoError); } var v = ParseBoolean(ev.Value); return(!v.HasValue ? Enumerables.Of(ToError(ev, invalidBooleanValueError)) : NoError); }
public override void MouseMove(Vector2Double mousePosition) { base.MouseMove(mousePosition); if (IsDragging) { foreach (SpecificationComponent component in Enumerables.Create(leftComponent, rightComponent).OfType <SpecificationComponent>()) { component.Point += DragVector * SlowDownFactor; } OnSpecificationChanged(); } }
// Generation. public override UnitSystemCore Generate(int seed, CancellationToken?cancellationToken = null) { var unitSystem = new UnitSystemCore(); int added = 0; cancellationToken?.ThrowIfCancellationRequested(); // Initialize random. var random = new System.Random(seed); // Count free nodes. int freeNodes = 0; foreach (var position in Enumerables.InRange2(Map.Size)) { if (Map[position].Type == MapNode.NodeType.Common) { ++freeNodes; } } if (freeNodes <= UnitCount) { foreach (var position in Enumerables.InRange2(Map.Size)) { if (Map[position].Type == MapNode.NodeType.Common) { unitSystem.AddUnit(BuildUnit(random, position, Map, ref added), position); } cancellationToken?.ThrowIfCancellationRequested(); } return(unitSystem); } cancellationToken?.ThrowIfCancellationRequested(); // Place units at free nodes. int toAdd = UnitCount; while (added < UnitCount) { Vector2Int position; do { position = new Vector2Int(random.Next(Map.Size.x), random.Next(Map.Size.y)); cancellationToken?.ThrowIfCancellationRequested(); } while (Map[position].Type != MapNode.NodeType.Common || unitSystem[position] != null); unitSystem.AddUnit(BuildUnit(random, position, Map, ref added), position); cancellationToken?.ThrowIfCancellationRequested(); } return(unitSystem); }
public static void Run() { IEnumerable <MonteCarloIteration> stream = Enumerables .RandomPoints() .Scan( seed: new MonteCarloIteration(), func: NextIteration ); while (true) { stream = stream.Skip(1_000_000); Console.WriteLine(stream.First().PiApproximation); } }
private void RegisterFromAssembly(ContainerBuilder builder, Assembly assembly) { var registerers = Enumerables.List <IRegisterer>( new ComponentRegisterer(builder, _options), new ConfigurationRegisterer(builder, _options) ); foreach (var type in assembly.ExportedTypes) { foreach (var registerer in registerers) { registerer.Register(type); } } }
void AddCurve() { BasicSpecification basicSpecification = new BasicSpecification ( 100, 1, new PolynomialFunctionTermCurveTemplate(10), Enumerables.Create ( new PointCurveSpecification(0.0, new Vector2Double(300, 300)), new PointCurveSpecification(1.0, new Vector2Double(400, 300)) ) ); AddCurve(new CurveComponent(this, optimizationWorker, new Specification(basicSpecification))); }
private static void LoadSettings() { var lines = File.ReadAllLines(FilePath); var dic = Enumerables.ToDictionary(Enumerables.Select(lines, GetKeyValuePair), KeySelector, ValueSelector); TotalSeconds = int.Parse(dic["TotalSeconds"]); string value; Message = dic.TryGetValue("Message", out value) ? value : "Stand Up Now ..."; AllowEscapingMessage = dic.TryGetValue("AllowEscapingMessage", out value) ? value.Equals("true", StringComparison.InvariantCultureIgnoreCase) : false; RedSeconds = dic.TryGetValue("RedSeconds", out value) ? int.Parse(value) : 60; StandUpSeconds = dic.TryGetValue("StandUpSeconds", out value) ? int.Parse(value) : 30; AllowSnooze = dic.TryGetValue("AllowSnooze", out value) ? !value.Equals("false", StringComparison.InvariantCultureIgnoreCase) : true; AllowPrepareNotification = dic.TryGetValue("AllowPrepareNotification", out value) ? !value.Equals("false", StringComparison.InvariantCultureIgnoreCase) : true; MessageFadeInSeconds = dic.TryGetValue("MessageFadeInSeconds", out value) ? int.Parse(value) : 3; SnoozeSeconds = dic.TryGetValue("SnoozeSeconds", out value) ? int.Parse(value) : 60; }
/// <summary> /// Validates the specified BindEvent<string> object and gets the /// tuples representing the error information. /// </summary> /// <param name="ev"> /// The BindEvent<string> object. /// </param> /// <param name="isValidValue"> /// The function that returns whether a value of the argument is valid /// or not. /// </param> /// <param name="invalidIntegerValueError"> /// The error message when it is unable to parse an integer value. /// </param> /// <param name="invalidValueRangeError"> /// The error message when the parsed value is invalid. /// </param> /// <returns> /// <see cref="NoError"/> if the specified BindEvent<string> /// object can be parsed successfully. Otherwise, the errors. /// </returns> public static IEnumerable <WhereWhy> ValidateInt( BindEvent <string>?ev, Func <int, bool> isValidValue, string invalidIntegerValueError, string invalidValueRangeError) { if (ev is null) { return(NoError); } var v = ParseInt(ev.Value); return(!v.HasValue ? Enumerables.Of(ToError(ev, invalidIntegerValueError)) : !isValidValue(v.Value) ? Enumerables.Of(ToError(ev, invalidValueRangeError)) : NoError); }
public override void Draw(Context context) { if (curve != null) { foreach (Tuple <double, double> positions in Scalars.GetIntermediateValuesSymmetric(0, 1, SegmentCount + 1).GetRanges()) { double position = Enumerables.Average(positions.Item1, positions.Item2); Vector2Double curvatureVector = CurveOptimizer.CurvatureMarkersFactor * curve.GetCurvature(position) * curve.GetNormalVector(position); Krach.Graphics.Color lineColor = StretchColor(curve.GetSpeed(position) / basicSpecification.CurveLength); Drawing.DrawLine(context, curve.GetPoint(position), curve.GetPoint(position) + curvatureVector, 0.5, Colors.Blue); Drawing.DrawLine(context, curve.GetPoint(positions.Item1), curve.GetPoint(positions.Item2), 2, lineColor); } } base.Draw(context); }
// Constructor. public VisionStencil(float visionRadius, float bodyRadius, float toleranceRadius) { // Initialize fields. this.visionRadius = Mathf.Max(visionRadius, 0); this.bodyRadius = Mathf.Clamp(bodyRadius, 0, 0.5f); this.toleranceRadius = Mathf.Clamp(toleranceRadius, 0, 0.49f); possiblyVisible = new List <Vector2Int>(); int arrayDimension = Mathf.FloorToInt(this.visionRadius) + 1; visionPaths = new List <Vector2Int> [arrayDimension, arrayDimension]; // Calculate stencil. foreach (var position in Enumerables.Index(visionPaths)) { TrackVision(position); } /*WriteDebugInFile();*/ }
public override T Rewrite <T>(T term) { if (!(term is Application)) { return(null); } Application application = (Application)(BaseTerm)term; if (!(application.Function is Product)) { return(null); } if (!(application.Parameter is Vector)) { return(null); } Vector vector = (Vector)application.Parameter; if (vector.Terms.Count() != 2) { return(null); } ValueTerm parameter0 = vector.Terms.ElementAt(0); ValueTerm parameter1 = vector.Terms.ElementAt(1); if (parameter0 is Application && ((Application)parameter0).Function is Product) { return(null); } if (!ShouldSwap(parameter0, parameter1)) { return(null); } return((T)(BaseTerm) new Application(new Product(), new Vector(Enumerables.Create(parameter1, parameter0)))); }
public override FunctionTerm Substitute(Variable variable, ValueTerm substitute) { if (variables.Contains(variable)) { return(this); } IEnumerable <Variable> newVariables = FindUnusedVariables ( variables, Enumerables.Concatenate ( GetFreeVariables(), Enumerables.Create(variable), substitute.GetFreeVariables() ) ); ValueTerm newTerm = term.Substitute(variables, newVariables); return(new Abstraction(newVariables, newTerm.Substitute(variable, substitute))); }
static void Main(string[] args) { //Network net = new Network(new int[] { 5, 10, 5 }); //net.BackPropagate(new Vector<double> targetOutputValues); // Loading training data from CSVs List <int> yUnrolled = Enumerables <int> .Unroll2DEnumerable(CSVReader.ReadCSVInt("E:/dev/misc/handwriting_labelled/y.csv")); int[] y = yUnrolled.ToArray(); Matrix <double> X = Matrix <double> .Build.DenseOfColumns(CSVReader.ReadCSVDouble("E:/dev/misc/handwriting_labelled/X.csv")).Transpose(); NetworkManager <int> man = new NetworkManager <int>(X, y, new int[] { 400, 50, 200, 10 }); Vector <double> oneExample = man.GetDataSet().KeepRows(new int[] { 0 }).ToVector(); man.Net.ForwardPropagate(oneExample); Vector <double> oneExampleExpectedOutput = man.GetExpectedOutput(0); man.Net.BackPropagate(oneExampleExpectedOutput); int aaa = 2; }
public override MapCore Generate(int seed, CancellationToken?cancellationToken = null) { cancellationToken?.ThrowIfCancellationRequested(); var map = new MapCore(Size, HeightLimit); foreach (var position in Enumerables.InRange2(Size)) { float noiseValue = noise.cellular2x2(0.05f * new float2(position.x, position.y)).x; float normalizedHeight = (noiseValue - 0.4f) / (1 - 0.4f); if (normalizedHeight >= 0) { float height = 2 * ShiftedErf(normalizedHeight); var node = new MapNode(MapNode.NodeType.Common, height); map[position] = node; } cancellationToken?.ThrowIfCancellationRequested(); } return(map); }
public void Practice(string[] args) { var task = Task.Run(() => GetDateTime()); var continuationTasks = new List <Task <DateTime> >(); Enumerables.For(1, 10, i => { var utf32 = 'A' - 1 + i; Thread.Sleep(200); task = task.ContinueWith((x, y) => GetDateTime(), new Person { Id = i, Name = $"{(char)(utf32)}{(char)(utf32 + 1)}{(char)(utf32 + 2)}{(char)(utf32 + 3)}{(char)(utf32 + 4)}{i}" }); continuationTasks.Add(task); }); task.Wait(); continuationTasks.ForEach(c => { var person = c.AsyncState as Person; Console.WriteLine($"Task finished at {c.Result}. {person}"); }); }
// Building methods. private async Task ReadNodes(MapPresentation map, CancellationToken cancellation) { if (map is null) { throw new ArgumentNullException(nameof(map)); } cancellation.ThrowIfCancellationRequested(); // Place nodes. await Task.Run(() => { nodes = new LayoutNode[map.Size.x, map.Size.y]; foreach (var position in Enumerables.InRange2(NodeCount)) { if (map[position].Type != MapNode.NodeType.Common) { continue; } nodes[position.x, position.y] = new LayoutNode(position); } cancellation.ThrowIfCancellationRequested(); }); }
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { if (tabControl1.SelectedIndex == 0) { Loops newFrm = new Loops { MdiParent = this, // This set the form parent as the tabClicked Parent = tabControl1.TabPages[0] }; newFrm.Show(); } else if (tabControl1.SelectedIndex == 1) { Enumerables newFrm = new Enumerables { MdiParent = this, // This set the form parent as the tabClicked Parent = tabControl1.TabPages[1] }; newFrm.Show(); } }
public void It_can_make_some_new_employees() { var sampleNames = new[] { "Aaron", "Adam", "Alan", "Alex", "Andrew", "Anthony", "Austin", "Brendan", "Brent", "Bryan", "Charlie", "Chris", "Doug", "Emory", "Jace", "James", "Jason", "Jennifer", "Jessica", "Jim", "John", "Kene", "Kenny", "Keshav", "Kevin", "Kyle", "Lynette", "Mark", "Matthew", "Michael", "Mit", "Prabu", "Randall", "Ricardo", "Richard", "Robert", "Rodney", "Roya", "Ryan", "Sharique", "Shawn", "Skipp", "Steve", "Steven", "Tavares", "Tej", "Tim", "Todd", "Tom", "Trent", "Will", "Wright", "Yakov" }; this.BuildWords(2, 3, true, sampleNames); this.Expect(this.wordBuilder.ChoiceArrayMemorySize, this.EqualTo(1936)); var names = Enumerables.Infinite().Select(i => this.wordBuilder.BuildNextWord()).Except(sampleNames).Distinct().Take(55).ToArray(); this.Expect(names, this.EquivalentTo(new[] { "Jennif", "Emoryan", "Ricardoug", "Rique", "Bryandrew", "Trennifer", "Tavare", "Tavardo", "Michar", "Emor", "Tavarique", "Matthony", "Randal", "Lynett", "Richae", "Jessic", "Jame", "Micha", "Ya", "Austi", "Rabu", "Tavar", "Michae", "Lynetteven", "Matthe", "Shaw", "Rober", "Riqu", "Adameshav", "Sharicha", "Brendall", "Jessicardo", "Jameshav", "Chard", "Matthon", "Wrigh", "Trenthony", "Andalan", "Michard", "Sharight", "Jamessicard", "Rodne", "Lynetthew", "Keshariq", "Randre", "Anthon", "Charon", "Prab", "Rodnette", "Ryanthon", "Bren", "Andall", "Tavariqu", "Micharlie", "Lynetteve" })); }
// Information methods. public List <Vector2Int> TryFindShortestPath(Vector2Int originPosition, Vector2Int destinationPosition) { if (!Enumerables.IsIndex(originPosition, nodes) || !Enumerables.IsIndex(destinationPosition, nodes)) { return(null); } var originNode = nodes[originPosition.x, originPosition.y]; var destinationNode = nodes[destinationPosition.x, destinationPosition.y]; if (originNode is null || destinationNode is null) { return(null); } var nodePath = AStarSparse.TryFindShortestPath( originNode.AsVision, destinationNode.AsVision, destinationNode.AsVision.CalculateDistance); if (nodePath == null) { return(null); } var path = new List <Vector2Int>(nodePath.ConvertAll((node) => node.Position)); return(path); }
OptimizationProblem(OptimizationSegments optimizationSegments, IEnumerable <CurveSpecification> curveSpecifications) { if (optimizationSegments == null) { throw new ArgumentNullException("segmentManager"); } if (curveSpecifications == null) { throw new ArgumentNullException("curveSpecifications"); } this.optimizationSegments = optimizationSegments; this.curveSpecifications = curveSpecifications; this.curveLength = Terms.Variable("curveLength"); this.pointSpecificationTemplates = ( from pointSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is PointCurveSpecification)) select SpecificationTemplate.CreatePointSpecificationTemplate(optimizationSegments.Segments, pointSpecificationIndex) ) .ToArray(); this.directionSpecificationTemplates = ( from directionSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is DirectionCurveSpecification)) select SpecificationTemplate.CreateDirectionSpecificationTemplate(optimizationSegments.Segments, curveLength, directionSpecificationIndex) ) .ToArray(); this.curvatureSpecificationTemplates = ( from curvatureSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is CurvatureCurveSpecification)) select SpecificationTemplate.CreateCurvatureSpecificationTemplate(optimizationSegments.Segments, curveLength, curvatureSpecificationIndex) ) .ToArray(); IEnumerable <ValueTerm> variables = optimizationSegments.Parameters; ValueTerm segmentLength = Terms.Quotient(curveLength, Terms.Constant(optimizationSegments.Segments.Count())); ValueTerm speedError = Terms.Sum ( from segment in optimizationSegments.Segments let position = Terms.Variable("t") let curve = segment.LocalCurve let speed = curve.Speed.Apply(position) let error = Terms.Square(Terms.Difference(speed, segmentLength)) select Terms.IntegrateTrapezoid(error.Abstract(position), new OrderedRange <double>(0, 1), 100) ); ValueTerm fairnessError = Terms.Sum ( from segment in optimizationSegments.Segments let position = Terms.Variable("t") let curve = segment.LocalCurve let jerk = curve.Jerk.Apply(position) let normal = Terms.Normal(curve.Velocity.Apply(position)) let error = Terms.Square(Terms.DotProduct(jerk, normal)) select Terms.IntegrateTrapezoid(error.Abstract(position), new OrderedRange <double>(0, 1), 100) ); // ValueTerm pointSpecificationError = Terms.Sum // ( // Enumerables.Concatenate // ( // Enumerables.Create(Terms.Constant(0)), // from specificationTemplate in Enumerables.Concatenate(pointSpecificationTemplates) // select Terms.NormSquared // ( // Terms.Difference // ( // specificationTemplate.Constraint.Item, // Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start)) // ) // ) // ) // ); // ValueTerm directionSpecificationError = Terms.Sum // ( // Enumerables.Concatenate // ( // Enumerables.Create(Terms.Constant(0)), // from specificationTemplate in Enumerables.Concatenate(directionSpecificationTemplates) // select Terms.NormSquared // ( // Terms.Difference // ( // specificationTemplate.Constraint.Item, // Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start)) // ) // ) // ) // ); // ValueTerm curvatureSpecificationError = Terms.Sum // ( // Enumerables.Concatenate // ( // Enumerables.Create(Terms.Constant(0)), // from specificationTemplate in Enumerables.Concatenate(curvatureSpecificationTemplates) // select Terms.NormSquared // ( // Terms.Difference // ( // specificationTemplate.Constraint.Item, // Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start)) // ) // ) // ) // ); ValueTerm objectiveValue = Terms.Sum ( Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(-2)), Terms.Constant(100000.0), speedError), Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(-4)), Terms.Constant(1), fairnessError) // Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(0)), Terms.Constant(0.1), pointSpecificationError), // Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(1)), Terms.Constant(10), directionSpecificationError), // Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(2)), Terms.Constant(100), curvatureSpecificationError) ) .Simplify(); IEnumerable <Constraint <ValueTerm> > constraintValues = ( Enumerables.Concatenate ( from pointSpecificationTemplate in pointSpecificationTemplates select pointSpecificationTemplate.Constraint, from directionSpecificationTemplate in directionSpecificationTemplates select directionSpecificationTemplate.Constraint, from curvatureSpecificationTemplate in curvatureSpecificationTemplates select curvatureSpecificationTemplate.Constraint, from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1) let segment0CurvePoint = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Point let segment1CurvePoint = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Point select Constraints.CreateEquality ( segment0CurvePoint.Apply(Terms.Constant(1)), segment1CurvePoint.Apply(Terms.Constant(0)) ), from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1) let segment0CurveVelocity = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Velocity let segment1CurveVelocity = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Velocity select Constraints.CreateEquality ( segment0CurveVelocity.Apply(Terms.Constant(1)), segment1CurveVelocity.Apply(Terms.Constant(0)) ), from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1) let segment0CurveAcceleration = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Acceleration let segment1CurveAcceleration = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Acceleration select Constraints.CreateEquality ( segment0CurveAcceleration.Apply(Terms.Constant(1)), segment1CurveAcceleration.Apply(Terms.Constant(0)) ) ) ) .ToArray(); Constraint <ValueTerm> constraint = Constraints.Merge(constraintValues); FunctionTerm objectiveFunction = objectiveValue.Abstract(variables); FunctionTerm constraintFunction = constraint.Item.Abstract(variables); this.problem = IpoptProblem.Create(objectiveFunction, constraintFunction, constraint.Ranges); }
private void GetComboTipo() { Enumerables e = new Enumerables(); ViewBag.Type = e.GetComboTipo(); }
public BasicSpecification() : this(1, 1, new PolynomialFunctionTermCurveTemplate(2), Enumerables.Create <CurveSpecification>()) { }
public override int GetHashCode() { return(curveLength.GetHashCode() ^ segmentCount.GetHashCode() ^ segmentTemplate.GetHashCode() ^ Enumerables.GetSequenceHashCode(curveSpecifications)); }
private void GetComboPeriodo() { Enumerables e = new Enumerables(); ViewBag.Per = e.GetPeriodo(); }
private void GetEstado() { Enumerables e = new Enumerables(); ViewBag.Est = e.GetEstadoFacturaProveedores(); }
private void GetTipoFactura() { Enumerables e = new Enumerables(); ViewBag.TipoFac = e.GetTipoFactura(); }
public override int GetHashCode() { return(basicSpecification.GetHashCode() ^ Enumerables.GetSequenceHashCode(position)); }
public CompositeAssemblySelector() { _assemblySelectors = Enumerables.List <IAssemblySelector>(); _includes = Enumerables.List <string>(); _excludes = Enumerables.List <string>(); }
public override T Rewrite <T>(T term) { if (!(term is Application)) { return(null); } Application application0 = (Application)(BaseTerm)term; if (!(application0.Function is Product)) { return(null); } if (!(application0.Parameter is Vector)) { return(null); } Vector vector0 = (Vector)application0.Parameter; if (vector0.Terms.Count() != 2) { return(null); } ValueTerm parameter00 = vector0.Terms.ElementAt(0); ValueTerm parameter01 = vector0.Terms.ElementAt(1); if (!(parameter00 is Application)) { return(null); } Application application00 = (Application)parameter00; if (!(application00.Function is Product)) { return(null); } if (!(application00.Parameter is Vector)) { return(null); } Vector vector00 = (Vector)application00.Parameter; if (vector00.Terms.Count() != 2) { return(null); } ValueTerm parameter000 = vector00.Terms.ElementAt(0); ValueTerm parameter001 = vector00.Terms.ElementAt(1); // ((parameter000 . parameter001) . parameter01) if (!ShouldSwap(parameter001, parameter01)) { return(null); } return((T)(BaseTerm) new Application(new Product(), new Vector(Enumerables.Create(new Application(new Product(), new Vector(Enumerables.Create(parameter000, parameter01))), parameter001)))); }
private void GetComboUnidadMedida() { Enumerables e = new Enumerables(); ViewBag.UM = e.GetUM(); }